From 46accc8edc2ffad064e70903367bb5d0fdc27891 Mon Sep 17 00:00:00 2001 From: mcocdaa Date: Mon, 23 Nov 2026 06:43:39 +0100 Subject: [PATCH] fix(storyteller): isolate Altar chat cooldown & scenario, fix Fallback scope/events, and clean dead code refactor: consolidate storyteller identities, policies, and localization Extract shared identity constants into StorytellerRequestIds (OwnerModId, ChatModId, ChatScenarioId, DefaultNpcId, IncidentOutputSchemaKey/Json) and replace scattered literals across agent, coordinator, notification, and UI. Split Altar chat onto its own StorytellerChat scenario and ChatModId so interactive turns bypass the incident MTB cooldown, and drop the IsStorytellerChat hint plumbing in favor of explicit scenario guards. Centralize tension deltas and fallback profiles in IncidentSelectionPolicy with a FallbackProfile/ChooseCategorySlot model, and restrict the fallback comp to Map_PlayerHome via XML and runtime target checks. Publish StorytellerStateChangedEvent from every memory mutation, add CancelCurrent so cancellations skip the failure backoff, and replace the autotest's destructive dialogue clear with a scoped removal. Route all UI and context text through RimMindAPI.Text.TrOr with English fallbacks, prefer the live difficultyDef label, and add contract tests covering schema registration, chat isolation, and zero raw .Translate(). Remove the unused PawnLookup helpers, ISkipCheck registration, and the in-csproj deploy target; rewrite deploy-single.ps1 for multi-version builds with runtime DLL exclusions and drop the redundant shell script. --- .../skills/rimworld-mod-dev/SKILL.md | 616 ------------------ .github/workflows/test.yml | 3 + AGENTS.md | 69 +- About/About.xml | 10 +- Defs/StorytellerDefs/RimMindDirector.xml | 6 +- INTRODUCTION.txt | 97 --- README.md | 2 +- README_zh.md | 2 +- Source/Agent/StorytellerAgentController.cs | 4 +- Source/Comps/CompStorytellerAltar.cs | 11 +- .../Debug/StorytellerBehaviorAutotestSuite.cs | 18 +- Source/Debug/StorytellerDebugActions.cs | 7 +- Source/Extensions/PawnLookup.cs | 19 - Source/Extensions/PawnLookupCore.cs | 46 -- .../Extensions/StorytellerContextBuilder.cs | 186 ++++-- .../StorytellerIncidentSkipCheck.cs | 18 - Source/Extensions/StorytellerModCooldown.cs | 4 +- ...ab.cs => StorytellerSettingsTabAdapter.cs} | 2 +- Source/Memory/IncidentHistoryRecord.cs | 9 +- Source/Memory/StorytellerMemory.cs | 76 ++- Source/RimMindStoryteller.csproj | 13 - Source/RimMindStorytellerMod.cs | 3 - Source/Settings/StorytellerSettingsTab.cs | 180 +++-- Source/Storyteller/IncidentSelectionPolicy.cs | 109 +++- Source/Storyteller/README.md | 4 +- Source/Storyteller/RimMindIncidentSelector.cs | 6 +- ...orytellerCompProperties_RimMindDirector.cs | 2 - .../StorytellerComp_RimMindFallback.cs | 56 +- .../StorytellerContextProviderRegistrar.cs | 217 +++--- .../StorytellerNotificationService.cs | 2 +- .../StorytellerRequestCoordinator.cs | 17 +- Source/Storyteller/StorytellerRequestIds.cs | 54 +- Source/Storyteller/StorytellerRequestState.cs | 9 + Source/UI/Window_StorytellerAgentControl.cs | 52 +- Source/UI/Window_StorytellerDialogue.cs | 18 +- .../StorytellerCoreAdoptionContracts.cs | 66 +- .../StorytellerIncidentPolicyContracts.cs | 167 +++-- .../StorytellerQueueIdentityContracts.cs | 39 +- .../StorytellerRequestContextContracts.cs | 45 +- .../StorytellerWorldProviderContracts.cs | 26 +- Tests/README.md | 34 +- Tests/RimMindStoryteller.Tests.csproj | 2 - Tests/VerseStubs.cs | 15 +- .../Storyteller/RimMindDirector_BackUp.png | 3 - script/deploy-single.ps1 | 121 ++-- script/deploy-single.sh | 95 --- 46 files changed, 1070 insertions(+), 1490 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/Extensions/PawnLookup.cs delete mode 100644 Source/Extensions/PawnLookupCore.cs delete mode 100644 Source/Extensions/StorytellerIncidentSkipCheck.cs rename Source/Extensions/{StorytellerSettingsTab.cs => StorytellerSettingsTabAdapter.cs} (86%) delete mode 100644 Textures/Storyteller/RimMindDirector_BackUp.png 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 f303ae1..fa8f610 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,10 +25,10 @@ AI叙事者模块,替换RimWorld Storyteller系统,LLM决定事件选择。 | 项 | 值 | |----|-----| -| Target | net48, C#9.0, Nullable enable | -| Output | `../1.6/Assemblies/` | +| Target | net48 (1.6) / net10.0 (1.7), C# 9.0, Nullable enable | +| Output | `../$(GameVersion)/Assemblies/` | | Assembly | RimMindStoryteller | -| 依赖 | RimMindCore.dll, Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json | +| 依赖 | `0_RimMindDomain.dll`, `1_RimMindApplication.dll`, `2_RimMindCore.dll` (`false`), Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json | ## 源码结构 @@ -38,35 +38,37 @@ Source/ ├── Agent/StorytellerAgentController.cs Storyteller-owned Agent 控制器 ├── Storyteller/ │ ├── README.md 事件请求与 Context Provider 阅读地图 -│ ├── StorytellerContextProviderRegistrar.cs 5个 Context Provider 注册 +│ ├── StorytellerRequestIds.cs ModId/ScenarioId/NpcId/IncidentOutput Schema 常量中心 +│ ├── StorytellerContextProviderRegistrar.cs 7个 Context Provider + 2个 Scenario + IncidentOutput Schema 注册 │ ├── StorytellerComp_RimMindDirector.cs RimWorld入口 + 间隔触发门控 │ ├── StorytellerRequestCoordinator.cs 请求派发、回调终态与事件链记录 -│ ├── StorytellerRequestState.cs Token、pending请求和pending结果状态 +│ ├── StorytellerRequestState.cs Token、pending请求、取消状态与pending结果状态 │ ├── StorytellerNotificationService.cs 玩家反应通知与张力回调 -│ ├── IncidentSelectionPolicy.cs 点数倍率范围与威胁通知策略 -│ ├── StorytellerComp_RimMindFallback.cs 回退事件生成器 +│ ├── IncidentSelectionPolicy.cs 点数倍率范围、张力增量表、FallbackProfile 表与威胁通知策略 +│ ├── StorytellerComp_RimMindFallback.cs 回退事件生成器(仅 Map_PlayerHome) │ ├── StorytellerCompProperties_RimMindDirector.cs Director Def属性 │ ├── StorytellerCompProperties_RimMindFallback.cs Fallback Def属性 │ ├── RimMindIncidentSelector.cs 响应解析入口(委托给 StorytellerResponseParserPure) │ └── StorytellerResponseParserPure.cs JSON解析+修复统一入口(纯逻辑,可单测) ├── Memory/ -│ ├── StorytellerMemory.cs WorldComponent(事件/对话/反应/张力/链) +│ ├── StorytellerMemory.cs WorldComponent(事件/对话/反应/张力/链 + StorytellerStateChangedEvent) │ ├── IncidentHistoryRecord.cs 事件历史记录(含存档兼容字段) │ ├── TensionMath.cs 张力衰减/Clamp01 纯逻辑(可单测) │ └── IncidentResponse.cs IncidentResponse DTO ├── Extensions/ │ ├── StorytellerContextPolicy.cs 自定义指令与生成任务指令组合 -│ ├── StorytellerContextBuilder.cs 难度/威胁/张力文本构建(6个helper,3个纯逻辑可单测) -│ ├── StorytellerIncidentSkipCheck.cs ISkipCheck 实现 -│ ├── StorytellerModCooldown.cs IModCooldown 实现 -│ └── StorytellerSettingsTab.cs ISettingsTab Adapter +│ ├── StorytellerContextBuilder.cs 难度/威胁/张力文本构建(纯逻辑可单测) +│ ├── StorytellerModCooldown.cs IModCooldown 实现(仅作用于事件选择 ModId) +│ └── StorytellerSettingsTabAdapter.cs ISettingsTab Adapter ├── Settings/RimMindStorytellerSettings.cs + StorytellerSettingsTab.cs ├── UI/ -│ ├── Window_StorytellerDialogue.cs 祭坛对话窗口 +│ ├── Window_StorytellerDialogue.cs 祭坛对话窗口(独立 ChatScenarioId & ChatModId) │ └── Window_StorytellerAgentControl.cs Agent控制台窗口 ├── Comps/CompStorytellerAltar.cs 祭坛建筑组件 ├── Patch/Patch_IncidentWorker_TryExecute.cs 事件执行后置补丁 -└── Debug/StorytellerDebugActions.cs +└── Debug/ + ├── StorytellerDebugActions.cs + └── StorytellerBehaviorAutotestSuite.cs 游戏内自动化行为测试套件 ``` ## 事件选择流程 @@ -101,28 +103,38 @@ StorytellerComp_RimMindDirector.MakeIntervalIncidents | Randy | 1.35 | 30%Big/30%Small/40%Misc | | Phoebe | 8.0 | 40%FactionArrival/60%Small | -## ContextKey 注册(全部使用新 API + 场景守卫) +## ContextKey 与 Schema 注册(全部使用新 API + 场景守卫) -| Key | Layer | Priority | 内容 | -|-----|-------|----------|------| -| storyteller_task | L0_Static | 0.95 | TaskInstruction(12段事件选择指令) | -| storyteller_context | L1_Baseline | 0.85 | 难度+威胁+张力+近期事件+活跃链 | -| storyteller_reactions | L1_Baseline | 0.8 | 玩家情感反应(ConsumedReactionsText) | -| storyteller_dialogue | L3_State | 0.5 | 近期对话摘要 | -| storyteller_recent_incidents | L4_History | 0.7 | Memory模组近期叙述(`RimMindAPI.Memory`) | +`StorytellerContextProviderRegistrar.RegisterAll()` 在初始化时注册 `IncidentOutput` Schema(`RimMindAPI.Context.RegisterSchema`)、两个场景(`ScenarioIds.Storyteller` 事件选择与 `StorytellerRequestIds.ChatScenarioId = "StorytellerChat"` 祭坛对话)以及 7 个 Context Provider: -所有注册均以 `ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller` 返回 `null`。这五个 provider 读取世界级数据,不查找 Pawn,也不要求正数 `PawnId`;地图 NPC 与 `NPC-storyteller` 后备身份的 `PawnId=0` 是有效输入。 +| Key | Layer | Priority | 适用场景 | 内容 | +|-----|-------|----------|----------|------| +| `storyteller_system` | L0_Static | 1.0 | `Storyteller` / `StorytellerChat` | 叙事者系统提示词(按场景区分事件选择/祭坛对话)+ `CustomSystemPrompt` | +| `storyteller_rules` | L0_Static | 0.98 | `Storyteller` | 叙事者事件选择世界规则(祭坛对话自动排除) | +| `storyteller_task` | L0_Static | 0.95 | `Storyteller` | TaskInstruction(12段事件选择指令,已与 `CustomSystemPrompt` 解耦避免重复注入) | +| `storyteller_context` | L1_Baseline | 0.85 | `Storyteller` / `StorytellerChat` | 难度(`difficultyDef.LabelCap`)+威胁+张力+近期事件+活跃链 | +| `storyteller_reactions` | L1_Baseline | 0.8 | `Storyteller` / `StorytellerChat` | 玩家情感反应(`ConsumedReactionsText`) | +| `storyteller_dialogue` | L3_State | 0.5 | `Storyteller` / `StorytellerChat` | 近期对话摘要 | +| `storyteller_recent_incidents` | L4_History | 0.7 | `Storyteller` / `StorytellerChat` | Memory模组近期叙述(`RimMindAPI.Memory`) | + +所有注册均含显式场景守卫,非目标场景返回 `null`。这些 provider 读取世界级数据,不查找 Pawn,也不要求正数 `PawnId`;地图 NPC 与 `NPC-storyteller` 后备身份的 `PawnId=0` 是有效输入。祭坛对话使用独立 `StorytellerRequestIds.ChatModId = "RimMind.StorytellerChat"` 与 `StorytellerRequestIds.ChatScenarioId`,避免命中 `StorytellerModCooldown` 的事件选择冷却。 ## 上下文注入流程 ``` ContextEngine.BuildContext(Scenario=Storyteller) - ├── L0_Static: storyteller_task (TaskInstruction 12段指令) + ├── L0_Static: storyteller_system + storyteller_rules + storyteller_task (TaskInstruction 12段指令) ├── L1_Baseline: storyteller_context (难度+威胁+张力+事件+链) ├── L1_Baseline: storyteller_reactions (玩家反应) ├── L2_Environment: Core自动注入 (地图状态、殖民者状态等) ├── L3_State: storyteller_dialogue (对话摘要) └── L4_History: storyteller_recent_incidents (Memory叙述) + Core自动注入 (NarrativeMemory) + +ContextEngine.BuildContext(Scenario=StorytellerChat) + ├── L0_Static: storyteller_system (祭坛对话模式 + CustomSystemPrompt) + ├── L1_Baseline: storyteller_context + storyteller_reactions + ├── L3_State: storyteller_dialogue + └── L4_History: storyteller_recent_incidents ``` ## 跨模组 Memory 路径 @@ -141,12 +153,13 @@ Storyteller 不访问 Memory 的具体 Store、WorldComponent 或设置单例。 - Harmony ID: `mcocdaa.RimMindStoryteller` - `mtbDays` 运行时以Settings为准(覆盖Def) - 间隔检查顺序保持为 target → maintenance → pending result → pending request (含 15000 tick 超时自动取消) → failure backoff (`LastFailTick` 2500 tick 冷却) → API → setting → skip check → MTB -- 过期请求Token必须忽略;成功/失败Tick只由 `StorytellerRequestState` 更新 +- 过期请求Token必须忽略;成功/失败/取消状态只由 `StorytellerRequestState` 更新(取消不触发 2500 tick 失败冷却) - `StorytellerResponseParserPure` 在提取 JSON 子串时必须统计字符串外的花括号平衡(截断 JSON 不得在内部嵌套 `}` 处截断),并在修复阶段先闭合未结束的字符串字面量再配平括号 -- `PawnLookup.FindPawnById` 优先通过 `RimMindPawnLookup.FindPawnByNumber` 与当前地图 `FreeColonists` 查找,最后回退到 `WorldPawns.AllPawnsAlive` -- `StorytellerMemory` 持有事件历史、对话、反应、张力和事件链的持久状态 +- `StorytellerComp_RimMindFallback` 与 XML Def 均限定 `Map_PlayerHome` 且校验 `target is Map`,关闭 `enableIntervalTrigger` 时不阻断 Fallback +- `StorytellerMemory` 持有事件历史、对话、反应、张力和事件链的持久状态,所有变更/清理入口必须发布 `StorytellerStateChangedEvent.Publish()` +- 所有翻译调用统一使用 `RimMindAPI.Text.TrOr(key, englishFallback, ...)`,禁止裸 `.Translate()` 或 `TrOr(key, key)` - 所有ContextKey注册必须包含场景守卫 -- `RimMindIncidentSelector` 直接守卫解析失败、未知 Def 和 `CanFireNow=false`;参数倍率范围与威胁通知条件仍由 `IncidentSelectionPolicy` 负责。 +- `RimMindIncidentSelector` 直接守卫解析失败、未知 Def、`CanFireNow=false` 与 `!f.IsPlayer && !f.defeated` 敌对派系匹配;参数倍率范围、张力增量表、FallbackProfile 表与威胁通知条件由 `IncidentSelectionPolicy` 负责。 - 禁止使用 `[Obsolete]` 的 `RegisterPawnContextProvider` / `RegisterStaticProvider` - 禁止直接访问 `Core.Internal` 命名空间 diff --git a/About/About.xml b/About/About.xml index 99d25d1..4946694 100644 --- a/About/About.xml +++ b/About/About.xml @@ -30,15 +30,16 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [tr][td]RimMind-Dialogue[/td][td]Contextual spoken dialogue via express_dialogue ToolCall & speech bubbles[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Dialogue]Link[/url][/td][/tr] [tr][td]RimMind-Memory[/td][td]3-Tier cognitive memory hierarchy, work aggregation & temporal decay[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Memory]Link[/url][/td][/tr] [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][b]RimMind-Storyteller[/b][/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][b]RimMind-Storyteller[/b][/td][td]AI Story Director, dramatic tension curve, chained arcs & Storyteller Altar[/td][td]Core (Memory optional)[/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]RimMind-Bridge-RimTalk[/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] [/table] [code]Core ──┬── Actions ── Advisor ├── Dialogue - ├── Memory ── Storyteller + ├── Memory ├── Personality + ├── Storyteller (optional Memory integration) ├── Extension-ModelService ├── Bridge-RimChat └── Bridge-RimTalk[/code] @@ -79,11 +80,6 @@ A: [code]StorytellerRequestCoordinator[/code] automatically recovers from timeou RimMind - Core https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Core -
  • - mcocdaa.RimMindMemory - RimMind - Memory - https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Memory -
  • brrainz.harmony
  • diff --git a/Defs/StorytellerDefs/RimMindDirector.xml b/Defs/StorytellerDefs/RimMindDirector.xml index 1dc404f..3166abc 100644 --- a/Defs/StorytellerDefs/RimMindDirector.xml +++ b/Defs/StorytellerDefs/RimMindDirector.xml @@ -11,7 +11,11 @@
  • -
  • +
  • + +
  • Map_PlayerHome
  • + +
  • DiseaseHuman diff --git a/INTRODUCTION.txt b/INTRODUCTION.txt deleted file mode 100644 index 4c64adb..0000000 --- a/INTRODUCTION.txt +++ /dev/null @@ -1,97 +0,0 @@ -[h1]RimMind - Storyteller[/h1] -你的殖民地,值得一个会讲故事的叙事者。 -[h1]RimMind - Storyteller (智能叙事导演)[/h1] - -[h2]原版叙事者只会掷骰子[/h2] -Cassandra 按表来,Randy 看心情,Phoebe 偶尔露面。它们不知道你的殖民地刚经历了一场惨烈的围攻,不知道你已经三个季度没见过商队,不知道你的粮食只够撑过这个冬天。它们只是……掷骰子。 -[i]告别冷冰冰的随机数掷骰——让 AI 成为洞悉殖民地一切悲欢的叙事导演。[/i] -[i]Move beyond cold RNG dice rolls — An AI Storyteller that crafts deliberate, emergent narrative arcs.[/i] - -RimMind Director 不同。它知道一切。然后,它做出选择——不是为了随机,而是为了故事。 -[hr] -[h2]📖 中文介绍 / Chinese Overview[/h2] - -[h2]AI 编织连贯叙事[/h2] -每一次事件选择,AI 都会审视殖民地的完整历史:上次袭击是什么时候?殖民地富裕还是贫穷?张力是高还是低?然后它选择最能推进当前叙事的事件。 -[b]RimMind-Storyteller[/b] 为 RimWorld 引入了具有戏剧把控力的 AI 叙事者。原版的卡珊德拉按时间表出招、兰迪全凭运气,而 RimMind Director 能够理解殖民地的历史脉络、物资短缺与心理创伤,为你量身编织波澜起伏的故事弧线。 - -悲剧之后迎来希望。长期平静后酝酿风暴。你的殖民地不再是一串随机数的受害者——它是一个有起承转合的故事。 -[h3]🌟 核心特性[/h3] -[list] -[*] [b]戏剧张力平衡系统 (Tension Tracking)[/b]:实时量化殖民地的紧张度。惨烈血战后提供适度的休整喘息,长期安稳懈怠时酝酿危机挑战。 -[*] [b]连贯多步事件链 (Incident Chains)[/b]:事件不再是孤立碎片。先遣小队的骚扰、后续增援的反扑、乃至战败后的外交斡旋,环环相扣。 -[*] [b]全局上下文理解[/b]:知晓殖民地刚刚经历的瘟疫或饥荒,做出兼顾挑战性与叙事逻辑的事件派发。 -[/list] - -[h2]事件链:从试探到决战[/h2] -一波小规模海盗袭击可能只是试探。几天后,同一批海盗带着增援卷土重来。你击退了他们?他们可能派人来谈判——也可能选择更疯狂的报复。 -[hr] -[h2]🌐 English Overview[/h2] - -AI 可以设计多步连锁事件,让 RimWorld 的随机事件变成有弧线的故事。每一个事件都不是孤立的,而是前一个的后果、后一个的伏笔。 -[b]RimMind-Storyteller[/b] reimagines colony events through an AI Director who comprehends drama, pacing, and emotional weight. - -[h2]张力系统:张弛有度[/h2] -叙事者追踪殖民地的紧张程度。大型威胁让张力飙升,商队来访让张力缓解,日常琐事轻轻放下。AI 根据张力水平调整事件强度——高张力时给你喘息,低张力时制造挑战。 - -你的殖民地不会一直被碾压,也不会一直无聊。节奏,是故事的生命。 - -[h2]你的反应改变叙事[/h2] -当 AI 选择了一个威胁事件,你会收到通知——"叙事者宣告"或"叙事者低语"。你可以选择你的情感反应: - -[h3]🌟 Key Highlights[/h3] -[list] -[*] [b]"不是吧!"[/b] — 你紧张了,叙事者知道。它可能会给你喘息的机会。 -[*] [b]"来的好!"[/b] — 你渴望挑战,叙事者记住了。下次会更刺激。 -[*] [b]"了解"[/b] — 默默接受命运。 -[*] [b]Adaptive Dramatic Tension[/b]: Monitors colony stress levels to ensure meaningful balance between high-stakes pressure and well-earned recovery. -[*] [b]Connected Event Chains[/b]: Incidents link together as cause and effect—scouting raids lead to fortified assaults or unexpected treaties. -[*] [b]Context-Driven Selection[/b]: Selects incidents that reflect the ongoing story rather than arbitrary dice rolls. -[/list] - -你不是被动的旁观者。你的态度,影响叙事者的决策。 - -[h2]与叙事者对话[/h2] -建造一座叙事者祭坛,就可以和掌控你命运的 AI 对话。叙事者以神秘睿智的口吻回应——它知道接下来会发生什么,但不会直接告诉你。 - -"我们安全吗?" -"安全?在这片边缘世界上,安全不过是两次灾难间的喘息。不过眼下……倒也还算平静。" - -你可以从它的暗示中窥探一二,但它绝不会泄露机密。 - -[h2]AI 挂了也不怕[/h2] -网络断了?API 挂了?没问题。RimMind Director 自动切换到你选择的经典叙事者模式(Cassandra / Randy / Phoebe),游戏不会中断。API 恢复后 AI 自动接管,无缝切换。 - -[h2]难度自适应[/h2] -AI 根据游戏难度调整行为——和平模式温和友善,极限模式冷酷无情。六个难度档位,从"优先选择非威胁性事件"到"不给殖民地喘息的机会"。 - -[h2]自定义叙事风格[/h2] -通过设置页的"叙事者风格 Prompt"自定义 AI 行为。你可以让叙事者变成冷酷的暴君、温柔的守护者、或者任何你想象得到的角色。你的叙事者,你的故事。 - -[h2]RimMind 是什么[/h2] -RimMind 是一套 AI 驱动的 RimWorld 模组套件,通过接入大语言模型 (LLM),让殖民者拥有人格、记忆、对话和自主决策能力。 - -[h2]快速开始[/h2] -[hr] -[h2]⚙️ 依赖与顺序 / Requirements & Order[/h2] -[list] -[*] 安装 [Harmony](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077) 和 RimMind-Core -[*] 在 Core 设置中填写 API Key 和端点 -[*] 新建游戏或载入存档,选择叙事者 [b]"RimMind Director"[/b] -[*] 建造叙事者祭坛,与你的叙事者对话 -[*] [b]必需前置 (Required)[/b]: Harmony, [b]RimMind-Core[/b] -[*] [b]推荐搭配 (Recommended)[/b]: [b]RimMind-Memory[/b](提供宏观编年史上下文) -[/list] - -[h2]常见问题[/h2] -[b]Q: 必须新建游戏吗?[/b] -A: 不需要。载入已有存档后,在叙事者选择界面切换为 RimMind Director 即可。 - -[b]Q: AI 不可用时会怎样?[/b] -A: 自动切换到 Fallback 模式(默认 Cassandra),游戏不会中断。 - -[b]Q: AI 会选择过于极端的事件吗?[/b] -A: 张力系统确保不会连续触发灾难性事件。你也可以通过自定义 Prompt 限制 AI 行为。 - -[b]Q: 配合 Memory 模组效果更好吗?[/b] -A: 是的。Memory 提供殖民地历史记忆,Storyteller 参考这些记忆做出更有叙事连贯性的事件选择。 diff --git a/README.md b/README.md index d8c05a1..268fa26 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@

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

    diff --git a/README_zh.md b/README_zh.md index 584e541..bd3aed7 100644 --- a/README_zh.md +++ b/README_zh.md @@ -8,7 +8,7 @@

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

    diff --git a/Source/Agent/StorytellerAgentController.cs b/Source/Agent/StorytellerAgentController.cs index d47833c..7a22b20 100644 --- a/Source/Agent/StorytellerAgentController.cs +++ b/Source/Agent/StorytellerAgentController.cs @@ -5,8 +5,8 @@ namespace RimMind.Storyteller.Agent { public static class StorytellerAgentController { - public const string ScopeType = "storyteller"; - public const string ScopeId = "NPC-storyteller"; + public const string ScopeType = StorytellerRequestIds.AgentScopeType; + public const string ScopeId = StorytellerRequestIds.DefaultNpcId; public static IScopedAgent? Find() => RimMindAPI.Agents.FindScoped(ScopeType, ScopeId); diff --git a/Source/Comps/CompStorytellerAltar.cs b/Source/Comps/CompStorytellerAltar.cs index 0360fdf..2db3a4d 100644 --- a/Source/Comps/CompStorytellerAltar.cs +++ b/Source/Comps/CompStorytellerAltar.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using RimMind.Presentation.Api; using RimMind.Storyteller.UI; using Verse; @@ -10,9 +11,13 @@ public override IEnumerable CompGetGizmosExtra() { yield return new Command_Action { - defaultLabel = "RimMind.Storyteller.Altar.Communicate".Translate(), - defaultDesc = "RimMind.Storyteller.Altar.CommunicateDesc".Translate(), - icon = Verse.ContentFinder.Get("UI/StorytellerAltarIcon", reportFailure: false), + defaultLabel = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Altar.Communicate", + "Communicate with Storyteller"), + defaultDesc = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Altar.CommunicateDesc", + "Open dialogue with the AI storyteller"), + icon = ContentFinder.Get("UI/StorytellerAltarIcon", reportFailure: false), action = () => { var map = parent.Map; diff --git a/Source/Debug/StorytellerBehaviorAutotestSuite.cs b/Source/Debug/StorytellerBehaviorAutotestSuite.cs index 2b98ced..4045abb 100644 --- a/Source/Debug/StorytellerBehaviorAutotestSuite.cs +++ b/Source/Debug/StorytellerBehaviorAutotestSuite.cs @@ -1,9 +1,7 @@ using System; -using System.Linq; using LudeonTK; using RimMind.Presentation.Api; using RimMind.Storyteller.Memory; -using RimWorld; using Verse; namespace RimMind.Storyteller.Debug @@ -30,14 +28,16 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) { context.Assert(memory.TensionLevel >= 0f && memory.TensionLevel <= 1f, $"Current storyteller tension level is valid 0-1 range ({memory.TensionLevel:F2})"); - // 2. DialogueRecord Addition and Cleanup + // 2. DialogueRecord Addition and Scoped Self-Cleanup (preserves pre-existing save history) int beforeCount = memory.DialogueRecords.Count; - memory.RecordDialogue("assistant", "Storyteller autotest greeting", Find.TickManager.TicksGame); - context.Assert(memory.DialogueRecords.Count == beforeCount + 1, "DialogueRecord added successfully to StorytellerMemory"); - - // Self-cleanup - memory.ClearDialogueRecords(); - context.Assert(memory.DialogueRecords.Count == 0, "Dialogue records cleanly cleared after test"); + int probeTick = Find.TickManager?.TicksGame ?? 0; + const string probeRole = "assistant"; + const string probeContent = "Storyteller autotest greeting"; + memory.RecordDialogue(probeRole, probeContent, probeTick); + context.Assert(memory.DialogueRecords.Count >= Math.Min(beforeCount + 1, memory.MaxDialogueRecords), "DialogueRecord added successfully to StorytellerMemory"); + + bool removed = memory.RemoveLastDialogueIfMatches(probeRole, probeContent, probeTick); + context.Assert(removed, "Autotest dialogue record cleanly removed without wiping save history"); } // 3. TensionMath Calculations diff --git a/Source/Debug/StorytellerDebugActions.cs b/Source/Debug/StorytellerDebugActions.cs index 5e391d3..095b8a2 100644 --- a/Source/Debug/StorytellerDebugActions.cs +++ b/Source/Debug/StorytellerDebugActions.cs @@ -103,7 +103,12 @@ private static void FireIncidentManual() private static void TestFallbackMode() { var settings = RimMindStorytellerMod.Settings; - var modes = new[] { FallbackMode.Cassandra, FallbackMode.Randy, FallbackMode.Phoebe, FallbackMode.None }; + if (settings == null) + { + RimMindErrors.Warn("[RimMind-Storyteller] Settings not initialized."); + return; + } + var modes = (FallbackMode[])System.Enum.GetValues(typeof(FallbackMode)); int idx = System.Array.IndexOf(modes, settings.fallbackMode); settings.fallbackMode = modes[(idx + 1) % modes.Length]; Log.Message($"[RimMind-Storyteller] Fallback mode switched to: {settings.fallbackMode}"); diff --git a/Source/Extensions/PawnLookup.cs b/Source/Extensions/PawnLookup.cs deleted file mode 100644 index c85c085..0000000 --- a/Source/Extensions/PawnLookup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using RimMind.Presentation.Api; -using Verse; - -namespace RimMind.Storyteller.Extensions -{ - /// - /// Legacy compatibility forwarder. Delegates directly to Core . - /// - [Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup directly.")] - public static class PawnLookup - { - public static Pawn? FindPawnById(int pawnId) - => pawnId <= 0 ? null : RimMindPawnLookup.FindPawnByNumber(pawnId); - - public static Pawn? FindById(string? pawnId) - => RimMindPawnLookup.FindPawnById(pawnId); - } -} diff --git a/Source/Extensions/PawnLookupCore.cs b/Source/Extensions/PawnLookupCore.cs deleted file mode 100644 index 588cd57..0000000 --- a/Source/Extensions/PawnLookupCore.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace RimMind.Storyteller.Extensions -{ - [Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup directly.")] - public static class PawnLookupCore - { - public static T? FindById( - int id, - Func> worldFactory, - Func?> mapFactory, - Func getId) - where T : class - { - if (id <= 0) - return null; - if (worldFactory == null) - throw new ArgumentNullException(nameof(worldFactory)); - if (mapFactory == null) - throw new ArgumentNullException(nameof(mapFactory)); - if (getId == null) - throw new ArgumentNullException(nameof(getId)); - - IEnumerable world = worldFactory() - ?? throw new InvalidOperationException("World Pawn source returned null."); - foreach (T candidate in world) - { - if (getId(candidate) == id) - return candidate; - } - - IEnumerable? map = mapFactory(); - if (map == null) - return null; - - foreach (T candidate in map) - { - if (getId(candidate) == id) - return candidate; - } - - return null; - } - } -} diff --git a/Source/Extensions/StorytellerContextBuilder.cs b/Source/Extensions/StorytellerContextBuilder.cs index bd02485..7f832b7 100644 --- a/Source/Extensions/StorytellerContextBuilder.cs +++ b/Source/Extensions/StorytellerContextBuilder.cs @@ -7,121 +7,183 @@ namespace RimMind.Storyteller.Extensions { /// /// Builds storyteller context text sections (difficulty, threat, tension). - /// Extracted from RimMindStorytellerMod for reuse and testing. - /// - /// 3 个纯逻辑解析器(ResolveDifficultyTier / ResolveDifficultyName / ResolveDifficultyGuidanceKey) - /// 可在 net10.0 测试项目中直接单元测试;3 个 Append 方法依赖 RimWorld 运行时 API - /// (Find.Storyteller / TaggedString.Translate),通过 ArchTest 模式验证。 + /// Pure tier resolution helpers are unit-tested directly; Append helpers read Find.Storyteller + /// and format text via with English fallbacks. /// public static class StorytellerContextBuilder { + private readonly struct DifficultyTierDescriptor + { + public readonly float MaxExclusiveThreatScale; + public readonly string FallbackName; + public readonly string GuidanceKey; + public readonly string GuidanceFallback; + + public DifficultyTierDescriptor( + float maxExclusiveThreatScale, + string fallbackName, + string guidanceKey, + string guidanceFallback) + { + MaxExclusiveThreatScale = maxExclusiveThreatScale; + FallbackName = fallbackName; + GuidanceKey = guidanceKey; + GuidanceFallback = guidanceFallback; + } + } + + private static readonly DifficultyTierDescriptor[] DifficultyTiers = + { + new DifficultyTierDescriptor( + 0.1f, + "Peaceful", + "RimMind.Storyteller.Prompt.DifficultyPeaceful", + "Peaceful — Prioritize non-threatening events, avoid bringing serious crisis to the colony, maintain a relaxed atmosphere"), + new DifficultyTierDescriptor( + 0.5f, + "Community Builder", + "RimMind.Storyteller.Prompt.DifficultyEasy", + "Easy — Moderately reduce threat event frequency and intensity, occasionally provide small challenges"), + new DifficultyTierDescriptor( + 0.8f, + "Adventure Story", + "RimMind.Storyteller.Prompt.DifficultyMedium", + "Medium — Balance threat and peaceful events, maintain story rhythm"), + new DifficultyTierDescriptor( + 1.2f, + "Strive to Survive", + "RimMind.Storyteller.Prompt.DifficultyRough", + "Rough — Select events at a normal pace, provide appropriate challenges"), + new DifficultyTierDescriptor( + 1.8f, + "Blood and Dust", + "RimMind.Storyteller.Prompt.DifficultyHard", + "Hard — Increase threat event intensity and frequency, test the colony's survival ability"), + new DifficultyTierDescriptor( + float.PositiveInfinity, + "Losing is Fun", + "RimMind.Storyteller.Prompt.DifficultyExtreme", + "Extreme — Select the most challenging events, give the colony no room to breathe"), + }; + /// - /// 根据 threatScale 解析为 6 档难度 tier(0-5)。 + /// Resolves threatScale into a 0..5 difficulty tier. /// public static int ResolveDifficultyTier(float threatScale) { - return threatScale switch + for (int i = 0; i < DifficultyTiers.Length; i++) { - < 0.1f => 0, - < 0.5f => 1, - < 0.8f => 2, - < 1.2f => 3, - < 1.8f => 4, - _ => 5 - }; + if (threatScale < DifficultyTiers[i].MaxExclusiveThreatScale) + return i; + } + return DifficultyTiers.Length - 1; } /// - /// 根据 difficultyLevel 返回对应的难度指导翻译 key;无效值返回 null。 + /// Returns the translation key for the given difficulty tier, or null if out of range. /// public static string? ResolveDifficultyGuidanceKey(int difficultyLevel) { - return difficultyLevel switch - { - 0 => "RimMind.Storyteller.Prompt.DifficultyPeaceful", - 1 => "RimMind.Storyteller.Prompt.DifficultyEasy", - 2 => "RimMind.Storyteller.Prompt.DifficultyMedium", - 3 => "RimMind.Storyteller.Prompt.DifficultyRough", - 4 => "RimMind.Storyteller.Prompt.DifficultyHard", - 5 => "RimMind.Storyteller.Prompt.DifficultyExtreme", - _ => null - }; + if (difficultyLevel < 0 || difficultyLevel >= DifficultyTiers.Length) + return null; + return DifficultyTiers[difficultyLevel].GuidanceKey; } /// - /// 根据 difficultyLevel 返回 RimWorld 原生难度名;未知值返回 Custom 格式。 + /// Returns the fallback vanilla difficulty name for the given tier. /// public static string ResolveDifficultyName(int difficultyLevel) { - return difficultyLevel switch - { - 0 => "Peaceful", - 1 => "Community Builder", - 2 => "Adventure Story", - 3 => "Strive to Survive", - 4 => "Blood and Dust", - 5 => "Losing is Fun", - _ => $"Custom ({difficultyLevel})" - }; + if (difficultyLevel < 0 || difficultyLevel >= DifficultyTiers.Length) + return $"Custom ({difficultyLevel})"; + return DifficultyTiers[difficultyLevel].FallbackName; } /// - /// 向 StringBuilder 追加当前难度上下文(难度名、threatScale、限制开关、难度指导)。 - /// 依赖 Find.Storyteller 运行时 API。 + /// Appends difficulty name (preferring RimWorld's live difficultyDef label), threat scale, + /// threat-restriction flags, and behavioral guidance. /// public static void AppendDifficultyContext(StringBuilder sb) { - var diff = Find.Storyteller?.difficulty; + var storyteller = Find.Storyteller; + var diff = storyteller?.difficulty; if (diff == null) return; + int tier = ResolveDifficultyTier(diff.threatScale); - string difficultyName = ResolveDifficultyName(tier); - sb.AppendLine("RimMind.Storyteller.Prompt.DifficultyContext".Translate()); - sb.AppendLine("RimMind.Storyteller.Prompt.DifficultyDetail".Translate( - difficultyName, $"{diff.threatScale:F2}")); + string? liveLabel = storyteller?.difficultyDef?.LabelCap.ToString(); + string difficultyName = !string.IsNullOrWhiteSpace(liveLabel) + ? liveLabel! + : ResolveDifficultyName(tier); + + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.DifficultyContext", + "[Difficulty Settings]")); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.DifficultyDetail", + " {0} (threat multiplier={1})", + difficultyName, + $"{diff.threatScale:F2}")); + if (!diff.allowBigThreats) - sb.AppendLine("RimMind.Storyteller.Prompt.NoBigThreats".Translate()); + { + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.NoBigThreats", + " Major threats disabled -> do not select ThreatBig category events")); + } if (!diff.allowIntroThreats) - sb.AppendLine("RimMind.Storyteller.Prompt.NoIntroThreats".Translate()); + { + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.NoIntroThreats", + " Intro threats disabled")); + } if (!diff.allowViolentQuests) - sb.AppendLine("RimMind.Storyteller.Prompt.NoViolentQuests".Translate()); - string? guidanceKey = ResolveDifficultyGuidanceKey(tier); - if (guidanceKey != null) { - string guidanceText = RimMindAPI.Text.TrOr(guidanceKey, guidanceKey); - sb.AppendLine("RimMind.Storyteller.Prompt.DifficultyGuidance".Translate(guidanceText)); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.NoViolentQuests", + " Violent quests disabled")); + } + + if (tier >= 0 && tier < DifficultyTiers.Length) + { + var descriptor = DifficultyTiers[tier]; + string guidanceText = RimMindAPI.Text.TrOr(descriptor.GuidanceKey, descriptor.GuidanceFallback); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.DifficultyGuidance", + "Difficulty behavior guidance: {0}", + guidanceText)); } } /// - /// 向 StringBuilder 追加威胁等级标签(4 档:None/Low/Medium/High)。 - /// 依赖 Find.Storyteller 运行时 API。 + /// Appends threat level label (None/Low/Medium/High) from current difficulty threatScale. /// public static void AppendThreatLevel(StringBuilder sb) { var diff = Find.Storyteller?.difficulty; if (diff == null) return; + string threatLabel = diff.threatScale switch { - < 0.1f => "RimMind.Storyteller.Prompt.ThreatNone".Translate(), - < 0.5f => "RimMind.Storyteller.Prompt.ThreatLow".Translate(), - < 0.8f => "RimMind.Storyteller.Prompt.ThreatMedium".Translate(), - _ => "RimMind.Storyteller.Prompt.ThreatHigh".Translate() + < 0.1f => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.ThreatNone", "None"), + < 0.5f => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.ThreatLow", "Low"), + < 0.8f => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.ThreatMedium", "Medium"), + _ => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.ThreatHigh", "High") }; sb.AppendLine($"[Threat Level] {threatLabel}"); } /// - /// 向 StringBuilder 追加张力分类标签(5 档:VeryLow/Low/Medium/High/VeryHigh)。 + /// Appends narrative tension bucket label (VeryLow/Low/Medium/High/VeryHigh). /// public static void AppendTensionLabel(StringBuilder sb, float tension) { string tensionLabel = tension switch { - < 0.2f => "RimMind.Storyteller.Prompt.TensionVeryLow".Translate(), - < 0.4f => "RimMind.Storyteller.Prompt.TensionLow".Translate(), - < 0.6f => "RimMind.Storyteller.Prompt.TensionMedium".Translate(), - < 0.8f => "RimMind.Storyteller.Prompt.TensionHigh".Translate(), - _ => "RimMind.Storyteller.Prompt.TensionVeryHigh".Translate() + < 0.2f => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.TensionVeryLow", "Very Low"), + < 0.4f => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.TensionLow", "Low"), + < 0.6f => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.TensionMedium", "Medium"), + < 0.8f => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.TensionHigh", "High"), + _ => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.TensionVeryHigh", "Very High") }; sb.AppendLine($"[Tension Category] {tensionLabel}"); } diff --git a/Source/Extensions/StorytellerIncidentSkipCheck.cs b/Source/Extensions/StorytellerIncidentSkipCheck.cs deleted file mode 100644 index c0afd3d..0000000 --- a/Source/Extensions/StorytellerIncidentSkipCheck.cs +++ /dev/null @@ -1,18 +0,0 @@ -using RimMind.Application.Common.Interfaces.Extension; -using RimMind.Storyteller.Settings; - -namespace RimMind.Storyteller -{ - internal sealed class StorytellerIncidentSkipCheck : ISkipCheck - { - private readonly RimMindStorytellerSettings _settings; - public StorytellerIncidentSkipCheck(RimMindStorytellerSettings settings) { _settings = settings; } - public string Id => "storyteller.incident"; - public string OwnerModId => "RimMind.Storyteller"; - public SkipCheckKind Kind => SkipCheckKind.StorytellerIncident; - public bool ShouldSkip(in SkipCheckArgs args) => !_settings.enableIntervalTrigger; - - public static bool ShouldSkipStorytellerIncident() - => RimMind.Presentation.Api.RimMindAPI.Ext.ShouldSkipStorytellerIncident(); - } -} diff --git a/Source/Extensions/StorytellerModCooldown.cs b/Source/Extensions/StorytellerModCooldown.cs index 7388fef..766f99d 100644 --- a/Source/Extensions/StorytellerModCooldown.cs +++ b/Source/Extensions/StorytellerModCooldown.cs @@ -7,9 +7,9 @@ internal sealed class StorytellerModCooldown : IModCooldown { private readonly RimMindStorytellerSettings _settings; public StorytellerModCooldown(RimMindStorytellerSettings settings) { _settings = settings; } - // Must equal the envelope ModId: Core resolves and stores queue cooldowns by that key. + // Must equal the incident-selection envelope ModId: Core stores queue cooldowns by that key. public string Id => StorytellerRequestIds.RequestModId; - public string OwnerModId => StorytellerRequestIds.RequestModId; + public string OwnerModId => StorytellerRequestIds.OwnerModId; public int CooldownTicks => (int)(_settings.mtbDays * 60000f); } } diff --git a/Source/Extensions/StorytellerSettingsTab.cs b/Source/Extensions/StorytellerSettingsTabAdapter.cs similarity index 86% rename from Source/Extensions/StorytellerSettingsTab.cs rename to Source/Extensions/StorytellerSettingsTabAdapter.cs index ff21232..dda9a31 100644 --- a/Source/Extensions/StorytellerSettingsTab.cs +++ b/Source/Extensions/StorytellerSettingsTabAdapter.cs @@ -7,7 +7,7 @@ namespace RimMind.Storyteller internal sealed class StorytellerSettingsTabAdapter : ISettingsTab { public string Id => "storyteller"; - public string OwnerModId => "RimMind.Storyteller"; + public string OwnerModId => StorytellerRequestIds.OwnerModId; public string Label => RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.TabLabel", "Storyteller"); public void Draw(Rect rect) => Settings.StorytellerSettingsTab.Draw(rect); } diff --git a/Source/Memory/IncidentHistoryRecord.cs b/Source/Memory/IncidentHistoryRecord.cs index f70fe53..50f516d 100644 --- a/Source/Memory/IncidentHistoryRecord.cs +++ b/Source/Memory/IncidentHistoryRecord.cs @@ -1,5 +1,5 @@ +using RimMind.Presentation.Api; using RimWorld; -using RimWorld.Planet; using Verse; namespace RimMind.Storyteller.Memory @@ -14,9 +14,12 @@ public IncidentHistoryRecord() { } public static IncidentHistoryRecord Create(IncidentDef def, IIncidentTarget target, int tick) { - string mapName = "RimMind.Storyteller.UI.UnknownMap".Translate(); + string mapName = RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.UnknownMap", "Unknown"); if (target is Map map) - mapName = map.Parent?.Label ?? "RimMind.Storyteller.UI.MainBase".Translate(); + { + mapName = map.Parent?.Label + ?? RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.MainBase", "Main Base"); + } return new IncidentHistoryRecord { diff --git a/Source/Memory/StorytellerMemory.cs b/Source/Memory/StorytellerMemory.cs index cf815c5..3997edf 100644 --- a/Source/Memory/StorytellerMemory.cs +++ b/Source/Memory/StorytellerMemory.cs @@ -141,14 +141,19 @@ public void RecordIncident(IncidentDef def, IIncidentTarget target, int tick) _maxRecords = settings.maxEventRecords; var record = IncidentHistoryRecord.Create(def, target, tick); _records.Add(record); - if (_records.Count > _maxRecords) + while (_records.Count > _maxRecords) _records.RemoveAt(0); + StorytellerStateChangedEvent.Publish(); } public string GetRecentSummary(int count) => StorytellerMemoryPromptFormatter.FormatRecentIncidents(_records, count); - public void ClearRecords() => _records.Clear(); + public void ClearRecords() + { + _records.Clear(); + StorytellerStateChangedEvent.Publish(); + } public void RecordDialogue(string role, string content, int tick) { @@ -158,12 +163,32 @@ public void RecordDialogue(string role, string content, int tick) _dialogueRecords.Add(DialogueRecord.Create(role, content, tick)); while (_dialogueRecords.Count > _maxDialogueRecords) _dialogueRecords.RemoveAt(0); + StorytellerStateChangedEvent.Publish(); + } + + internal bool RemoveLastDialogueIfMatches(string role, string content, int tick) + { + for (int i = _dialogueRecords.Count - 1; i >= 0; i--) + { + var r = _dialogueRecords[i]; + if (r.role == role && r.content == content && r.tick == tick) + { + _dialogueRecords.RemoveAt(i); + StorytellerStateChangedEvent.Publish(); + return true; + } + } + return false; } public string GetRecentDialogueSummary(int count) => StorytellerMemoryPromptFormatter.FormatRecentDialogues(_dialogueRecords, count); - public void ClearDialogueRecords() => _dialogueRecords.Clear(); + public void ClearDialogueRecords() + { + _dialogueRecords.Clear(); + StorytellerStateChangedEvent.Publish(); + } public void RecordPlayerReaction(string incidentDefName, string incidentLabel, string reaction, string reactionLabel, int tick) { @@ -180,6 +205,7 @@ public void RecordPlayerReaction(string incidentDefName, string incidentLabel, s }); while (_playerReactions.Count > _maxPlayerReactions) _playerReactions.RemoveAt(0); + StorytellerStateChangedEvent.Publish(); } public string PeekReactions(int maxCount) @@ -187,11 +213,16 @@ public string PeekReactions(int maxCount) string formatted = StorytellerMemoryPromptFormatter.FormatPlayerReactions(_playerReactions, maxCount); if (string.IsNullOrEmpty(formatted)) { - _consumedReactionsText = null; + if (_consumedReactionsText != null) + { + _consumedReactionsText = null; + StorytellerStateChangedEvent.Publish(); + } return string.Empty; } _consumedReactionsText = formatted; + StorytellerStateChangedEvent.Publish(); return formatted; } @@ -199,28 +230,33 @@ public string ConsumeReactions(int maxCount) { if (_playerReactions.Count == 0 || maxCount <= 0) { - _consumedReactionsText = null; + if (_consumedReactionsText != null) + { + _consumedReactionsText = null; + StorytellerStateChangedEvent.Publish(); + } return string.Empty; } - string text = PeekReactions(maxCount); + string text = StorytellerMemoryPromptFormatter.FormatPlayerReactions(_playerReactions, maxCount); int takeCount = System.Math.Min(maxCount, _playerReactions.Count); _playerReactions.RemoveRange(0, takeCount); + _consumedReactionsText = null; + StorytellerStateChangedEvent.Publish(); return text; } - public void UpdateTension(IncidentCategoryDef category) + public void UpdateTension(IncidentCategoryDef? category) { - var factionArrival = DefDatabase.GetNamedSilentFail("FactionArrival"); - float delta = category switch - { - var c when c == IncidentCategoryDefOf.ThreatBig => 0.25f, - var c when c == IncidentCategoryDefOf.ThreatSmall => 0.12f, - var c when c == IncidentCategoryDefOf.Misc => -0.05f, - var c when c == factionArrival => -0.08f, - _ => 0f - }; + if (category == null) + return; + + float delta = IncidentSelectionPolicy.GetTensionDeltaForCategory(category.defName); + if (delta == 0f) + return; + _tensionLevel = TensionMath.ApplyDelta(_tensionLevel, delta); + StorytellerStateChangedEvent.Publish(); } public void ApplyDecayAndCleanup() @@ -228,9 +264,15 @@ public void ApplyDecayAndCleanup() int now = Find.TickManager.TicksGame; if (_lastTensionDecayTick <= 0) _lastTensionDecayTick = now; + float beforeTension = _tensionLevel; + int beforeChains = _activeChains.Count; DecayTension(now - _lastTensionDecayTick); _lastTensionDecayTick = now; CleanupExpiredChains(); + if (_tensionLevel != beforeTension || _activeChains.Count != beforeChains) + { + StorytellerStateChangedEvent.Publish(); + } } private void DecayTension(int ticksElapsed) @@ -256,6 +298,7 @@ public override void WorldComponentTick() public void ApplyTensionDelta(float delta) { _tensionLevel = TensionMath.ApplyDelta(_tensionLevel, delta); + StorytellerStateChangedEvent.Publish(); } public void RecordChainStep(string chainId, int chainStep, int chainTotal, string nextHint, string incidentDefName, int tick, float points, string factionDefName) @@ -286,6 +329,7 @@ public void RecordChainStep(string chainId, int chainStep, int chainTotal, strin chain.steps.Add(new ChainStep { incidentDefName = incidentDefName, triggeredTick = tick, completed = true }); _activeChains.Add(chain); } + StorytellerStateChangedEvent.Publish(); } private void CleanupExpiredChains() diff --git a/Source/RimMindStoryteller.csproj b/Source/RimMindStoryteller.csproj index 6f79f74..0d64063 100644 --- a/Source/RimMindStoryteller.csproj +++ b/Source/RimMindStoryteller.csproj @@ -42,17 +42,4 @@ - - - $(RIMWORLD_DIR)\Mods\RimMind-Storyteller\ - - - - - - - - - diff --git a/Source/RimMindStorytellerMod.cs b/Source/RimMindStorytellerMod.cs index 238ecd6..091e82a 100644 --- a/Source/RimMindStorytellerMod.cs +++ b/Source/RimMindStorytellerMod.cs @@ -1,9 +1,7 @@ -using HarmonyLib; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Presentation; using RimMind.Presentation.Api; using RimMind.Presentation.Settings; -using RimMind.Storyteller.Extensions; using RimMind.Storyteller.Settings; using UnityEngine; using Verse; @@ -23,7 +21,6 @@ public RimMindStorytellerMod(ModContentPack content) : base(content) RimMindAPI.Extensions().Register(new StorytellerSettingsTabAdapter()); RimMindAPI.Extensions().Register(new StorytellerModCooldown(Settings)); - RimMindAPI.Extensions().Register(new StorytellerIncidentSkipCheck(Settings)); StorytellerContextProviderRegistrar.RegisterAll(); diff --git a/Source/Settings/StorytellerSettingsTab.cs b/Source/Settings/StorytellerSettingsTab.cs index 8f2a116..d77bcfd 100644 --- a/Source/Settings/StorytellerSettingsTab.cs +++ b/Source/Settings/StorytellerSettingsTab.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using RimMind.Presentation.Api; using RimMind.Presentation.UI; using RimMind.Storyteller.Memory; using UnityEngine; @@ -8,6 +9,9 @@ namespace RimMind.Storyteller.Settings { public static class StorytellerSettingsTab { + private static readonly FallbackMode[] AllFallbackModes = + (FallbackMode[])Enum.GetValues(typeof(FallbackMode)); + private static Vector2 _scrollPos = Vector2.zero; private static float _measuredHeight = 760f; private static string _promptText = string.Empty; @@ -17,6 +21,7 @@ public static void Draw(Rect inRect) { SyncPromptWithActiveMemory(); var settings = RimMindStorytellerMod.Settings; + if (settings == null) return; SettingsUIDrawer.DrawScrollableSettingsPage( inRect, @@ -24,88 +29,153 @@ public static void Draw(Rect inRect) ref _measuredHeight, listing => { - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.TriggerSources".Translate()); - listing.CheckboxLabeled("RimMind.Storyteller.UI.EnableIntervalTrigger".Translate(), ref settings.enableIntervalTrigger, - "RimMind.Storyteller.UI.EnableIntervalTrigger.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Storyteller.UI.EnableEventNotification".Translate(), ref settings.enableEventNotification, - "RimMind.Storyteller.UI.EnableEventNotification.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Fallback".Translate()); - listing.LabelWithTooltip("RimMind.Storyteller.UI.FallbackModeLabel".Translate(settings.fallbackMode.ToString()), - "RimMind.Storyteller.UI.FallbackModeDesc".Translate()); - if (Widgets.ButtonText(listing.GetRect(30f), "RimMind.Storyteller.UI.SwitchFallback".Translate())) + SettingsUIDrawer.DrawSectionHeader(listing, RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.TriggerSources", "Trigger Sources")); + listing.CheckboxLabeled( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.EnableIntervalTrigger", "Interval Trigger"), + ref settings.enableIntervalTrigger, + RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.EnableIntervalTrigger.Desc", + "Request AI to select events at random intervals based on MTB (Mean Time Between). When disabled, the storyteller won't auto-trigger AI requests, but manual trigger still works.")); + listing.CheckboxLabeled( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.EnableEventNotification", "Event Notification"), + ref settings.enableEventNotification, + RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.EnableEventNotification.Desc", + "When the storyteller selects a threat event, send a notification to the request overlay. Players can choose an emotional reaction, which affects narrative tension and future event selection.")); + + SettingsUIDrawer.DrawSectionHeader(listing, RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.Section.Fallback", "Fallback Mode")); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.FallbackModeLabel", + "Fallback Mode (behavior when AI unavailable): {0}", + settings.fallbackMode.ToString()), + RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.FallbackModeDesc", + "When AI request is cooling down, fails, or the Director is unhealthy (no recent success or recent failure), use vanilla storyteller logic to select events")); + if (Widgets.ButtonText( + listing.GetRect(30f), + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.SwitchFallback", "Switch Fallback Mode"))) { - var modes = new List - { - FallbackMode.Cassandra, - FallbackMode.Randy, - FallbackMode.Phoebe, - FallbackMode.None, - }; - int idx = modes.IndexOf(settings.fallbackMode); - settings.fallbackMode = modes[(idx + 1) % modes.Count]; + int idx = Array.IndexOf(AllFallbackModes, settings.fallbackMode); + settings.fallbackMode = AllFallbackModes[(idx + 1) % AllFallbackModes.Length]; GUI.changed = true; } - SettingsUIDrawer.DrawCustomPromptSection(listing, - "RimMind.Storyteller.UI.StylePromptLabel".Translate(), - ref _promptText, 72f); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Request".Translate()); - string mtbTip = "RimMind.Storyteller.UI.MTBDays.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MTBDays".Translate($"{settings.mtbDays:F1}"), mtbTip); + SettingsUIDrawer.DrawCustomPromptSection( + listing, + RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.StylePromptLabel", + "Storyteller Style Prompt (prepended to system prompt, leave empty to skip):"), + ref _promptText, + 72f); + + SettingsUIDrawer.DrawSectionHeader(listing, RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.Section.Request", "Request Settings")); + string mtbTip = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.MTBDays.Desc", + "Average interval in game days for the AI storyteller to trigger events, using MTB random trigger mechanism similar to vanilla storytellers. Lower values mean more frequent events."); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.MTBDays", "Average event interval: {0} game days", $"{settings.mtbDays:F1}"), + mtbTip); settings.mtbDays = listing.SliderWithTooltip(settings.mtbDays, 0.5f, 10f, mtbTip); - settings.mtbDays = (float)System.Math.Round(settings.mtbDays, 1); - - string reqExpireTip = "RimMind.Storyteller.UI.RequestExpire.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.RequestExpire".Translate($"{settings.requestExpireTicks / 60000f:F2}"), reqExpireTip); + settings.mtbDays = (float)Math.Round(settings.mtbDays, 1); + + string reqExpireTip = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.RequestExpire.Desc", + "Storyteller AI requests that don't receive a response within this time are automatically cancelled."); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.RequestExpire", "Request expiry: {0} game days", $"{settings.requestExpireTicks / 60000f:F2}"), + reqExpireTip); settings.requestExpireTicks = (int)listing.SliderWithTooltip(settings.requestExpireTicks, 3600f, 120000f, reqExpireTip); settings.requestExpireTicks = (settings.requestExpireTicks / 1500) * 1500; - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Debug".Translate()); - listing.CheckboxLabeled("RimMind.Storyteller.UI.DebugLogging".Translate(), ref settings.debugLogging, - "RimMind.Storyteller.UI.DebugLogging.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Memory".Translate()); - string eventRecTip = "RimMind.Storyteller.UI.MaxEventRecords.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxEventRecords".Translate(settings.maxEventRecords), eventRecTip); + SettingsUIDrawer.DrawSectionHeader(listing, RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.Section.Debug", "Debug")); + listing.CheckboxLabeled( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.DebugLogging", "Verbose Logging"), + ref settings.debugLogging, + RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.DebugLogging.Desc", + "Output detailed AI request and response info to Player.log for troubleshooting.")); + + SettingsUIDrawer.DrawSectionHeader(listing, RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.Section.Memory", "Memory Settings")); + string eventRecTip = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.MaxEventRecords.Desc", + "Number of recent event records kept for AI reference when selecting events."); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.MaxEventRecords", "Max event records: {0}", settings.maxEventRecords), + eventRecTip); settings.maxEventRecords = (int)listing.SliderWithTooltip(settings.maxEventRecords, 10f, 100f, eventRecTip); - string dialRecTip = "RimMind.Storyteller.UI.MaxDialogueRecords.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxDialogueRecords".Translate(settings.maxDialogueRecords), dialRecTip); + string dialRecTip = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.MaxDialogueRecords.Desc", + "Number of recent dialogue records kept for AI reference when responding to players."); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.MaxDialogueRecords", "Max dialogue records: {0}", settings.maxDialogueRecords), + dialRecTip); settings.maxDialogueRecords = (int)listing.SliderWithTooltip(settings.maxDialogueRecords, 5f, 60f, dialRecTip); - string reactionTip = "RimMind.Storyteller.UI.MaxPlayerReactions.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxPlayerReactions".Translate(settings.maxPlayerReactions), reactionTip); + string reactionTip = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.MaxPlayerReactions.Desc", + "Maximum number of player emotional reaction records kept."); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.MaxPlayerReactions", "Max player reactions: {0}", settings.maxPlayerReactions), + reactionTip); settings.maxPlayerReactions = (int)listing.SliderWithTooltip(settings.maxPlayerReactions, 5f, 50f, reactionTip); - string chainExpireTip = "RimMind.Storyteller.UI.ChainExpireDays.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.ChainExpireDays".Translate($"{settings.chainExpireDays:F1}"), chainExpireTip); + string chainExpireTip = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.ChainExpireDays.Desc", + "Event chains not advanced within this time are automatically removed."); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.ChainExpireDays", "Chain expiry: {0} days", $"{settings.chainExpireDays:F1}"), + chainExpireTip); settings.chainExpireDays = listing.SliderWithTooltip(settings.chainExpireDays, 3f, 30f, chainExpireTip); - settings.chainExpireDays = (float)System.Math.Round(settings.chainExpireDays * 2f) / 2f; - - string tensionDecayTip = "RimMind.Storyteller.UI.TensionDecayPerDay.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.TensionDecayPerDay".Translate($"{settings.tensionDecayPerDay:F3}"), tensionDecayTip); + settings.chainExpireDays = (float)Math.Round(settings.chainExpireDays * 2f) / 2f; + + string tensionDecayTip = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.TensionDecayPerDay.Desc", + "Amount of narrative tension that decays per game day. Higher values mean tension drops faster."); + listing.LabelWithTooltip( + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.TensionDecayPerDay", "Tension decay: {0}/day", $"{settings.tensionDecayPerDay:F3}"), + tensionDecayTip); settings.tensionDecayPerDay = listing.SliderWithTooltip(settings.tensionDecayPerDay, 0.01f, 0.10f, tensionDecayTip); - settings.tensionDecayPerDay = (float)System.Math.Round(settings.tensionDecayPerDay * 200f) / 200f; + settings.tensionDecayPerDay = (float)Math.Round(settings.tensionDecayPerDay * 200f) / 200f; - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.MemoryTitle".Translate()); + SettingsUIDrawer.DrawSectionHeader(listing, RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.MemoryTitle", "Storyteller Memory (read-only):")); var memory = StorytellerMemory.Instance; if (memory == null) { - listing.Label("RimMind.Storyteller.UI.MemoryNeedLoad".Translate()); + listing.Label(RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.MemoryNeedLoad", " Load a game to view")); } else { - listing.Label("RimMind.Storyteller.UI.MemoryRecordCount".Translate(memory.Records.Count, settings.maxEventRecords)); - listing.Label("RimMind.Storyteller.UI.DialogueRecordCount".Translate(memory.DialogueRecords.Count)); + listing.Label(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.MemoryRecordCount", + " Records: {0}/{1}", + memory.Records.Count, + settings.maxEventRecords)); + listing.Label(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.DialogueRecordCount", + " Dialogue records: {0}", + memory.DialogueRecords.Count)); for (int i = memory.Records.Count - 1; i >= 0 && i >= memory.Records.Count - 10; i--) { var r = memory.Records[i]; int day = TensionMath.TicksToDay(r.TriggeredTick); - listing.Label("RimMind.Storyteller.UI.MemoryDayEntry".Translate(day, r.Label, r.MapName)); + listing.Label(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.MemoryDayEntry", + " Day {0}: {1} ({2})", + day, + r.Label, + r.MapName)); } - if (Widgets.ButtonText(listing.GetRect(30f), "RimMind.Storyteller.UI.ClearMemory".Translate())) + if (Widgets.ButtonText( + listing.GetRect(30f), + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.ClearMemory", "Clear Memory"))) { memory.ClearRecords(); memory.ClearDialogueRecords(); diff --git a/Source/Storyteller/IncidentSelectionPolicy.cs b/Source/Storyteller/IncidentSelectionPolicy.cs index 89bd18b..3df14c5 100644 --- a/Source/Storyteller/IncidentSelectionPolicy.cs +++ b/Source/Storyteller/IncidentSelectionPolicy.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace RimMind.Storyteller { @@ -9,8 +10,91 @@ public enum StorytellerIncidentKind ThreatBig, } + public enum FallbackCategorySlot + { + ThreatBig, + ThreatSmall, + Misc, + FactionArrival, + } + + public sealed class FallbackProfile + { + public FallbackProfile( + float mtbDays, + float threatBigWeight, + float threatSmallWeight, + float miscWeight, + float factionArrivalWeight) + { + MtbDays = mtbDays; + ThreatBigWeight = threatBigWeight; + ThreatSmallWeight = threatSmallWeight; + MiscWeight = miscWeight; + FactionArrivalWeight = factionArrivalWeight; + } + + public float MtbDays { get; } + public float ThreatBigWeight { get; } + public float ThreatSmallWeight { get; } + public float MiscWeight { get; } + public float FactionArrivalWeight { get; } + + public FallbackCategorySlot ChooseCategorySlot(float sample01) + { + float clamped = sample01 < 0f ? 0f : (sample01 > 1f ? 1f : sample01); + float total = ThreatBigWeight + ThreatSmallWeight + MiscWeight + FactionArrivalWeight; + if (total <= 0f) + return FallbackCategorySlot.ThreatBig; + + float threshold = clamped * total; + float cumulative = ThreatBigWeight; + if (ThreatBigWeight > 0f && threshold < cumulative) + return FallbackCategorySlot.ThreatBig; + + cumulative += ThreatSmallWeight; + if (ThreatSmallWeight > 0f && threshold < cumulative) + return FallbackCategorySlot.ThreatSmall; + + cumulative += MiscWeight; + if (MiscWeight > 0f && threshold < cumulative) + return FallbackCategorySlot.Misc; + + if (FactionArrivalWeight > 0f) + return FallbackCategorySlot.FactionArrival; + + return FallbackCategorySlot.ThreatBig; + } + } + public static class IncidentSelectionPolicy { + public const string ThreatBigCategoryDefName = "ThreatBig"; + public const string ThreatSmallCategoryDefName = "ThreatSmall"; + public const string MiscCategoryDefName = "Misc"; + public const string FactionArrivalCategoryDefName = "FactionArrival"; + public const string RaidFriendlyDefName = "RaidFriendly"; + + private static readonly Dictionary CategoryTensionDeltas = + new Dictionary(StringComparer.Ordinal) + { + [ThreatBigCategoryDefName] = 0.25f, + [ThreatSmallCategoryDefName] = 0.12f, + [MiscCategoryDefName] = -0.05f, + [FactionArrivalCategoryDefName] = -0.08f, + }; + + private static readonly Dictionary FallbackProfilesByModeName = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["Cassandra"] = new FallbackProfile(4.6f, threatBigWeight: 1.0f, threatSmallWeight: 0f, miscWeight: 0f, factionArrivalWeight: 0f), + ["Randy"] = new FallbackProfile(1.35f, threatBigWeight: 0.3f, threatSmallWeight: 0.3f, miscWeight: 0.4f, factionArrivalWeight: 0f), + ["Phoebe"] = new FallbackProfile(8.0f, threatBigWeight: 0f, threatSmallWeight: 0.6f, miscWeight: 0f, factionArrivalWeight: 0.4f), + }; + + private static readonly FallbackProfile DisabledFallbackProfile = + new FallbackProfile(999f, threatBigWeight: 1.0f, threatSmallWeight: 0f, miscWeight: 0f, factionArrivalWeight: 0f); + public static float ClampPointsMultiplier(float multiplier) => Math.Clamp(multiplier, 0.3f, 2.0f); @@ -24,8 +108,27 @@ public static bool ShouldNotify( public static bool RequiresHostileFaction( string? incidentDefName, string? categoryDefName) - => (string.Equals(categoryDefName, "ThreatBig", StringComparison.Ordinal) - || string.Equals(categoryDefName, "ThreatSmall", StringComparison.Ordinal)) - && !string.Equals(incidentDefName, "RaidFriendly", StringComparison.Ordinal); + => (string.Equals(categoryDefName, ThreatBigCategoryDefName, StringComparison.Ordinal) + || string.Equals(categoryDefName, ThreatSmallCategoryDefName, StringComparison.Ordinal)) + && !string.Equals(incidentDefName, RaidFriendlyDefName, StringComparison.Ordinal); + + public static float GetTensionDeltaForCategory(string? categoryDefName) + { + if (string.IsNullOrEmpty(categoryDefName)) + return 0f; + + return CategoryTensionDeltas.TryGetValue(categoryDefName!, out float delta) ? delta : 0f; + } + + public static FallbackProfile ResolveFallbackProfile(string? modeName) + { + if (!string.IsNullOrEmpty(modeName) && + FallbackProfilesByModeName.TryGetValue(modeName!, out var profile)) + { + return profile; + } + + return DisabledFallbackProfile; + } } } diff --git a/Source/Storyteller/README.md b/Source/Storyteller/README.md index 56f8750..0056a11 100644 --- a/Source/Storyteller/README.md +++ b/Source/Storyteller/README.md @@ -13,9 +13,9 @@ Start with `StorytellerComp_RimMindDirector.cs`. It is the RimWorld adapter and ## Context Provider path -Start at `../RimMindStorytellerMod.cs` to see the module composition entry. It delegates all five Context Provider registrations to `StorytellerContextProviderRegistrar.cs`. When you need provider details, read `StorytellerContextProviderRegistrar.cs`, then `../Extensions/StorytellerContextPolicy.cs`, `../Extensions/StorytellerContextBuilder.cs`, `../Memory/StorytellerMemory.cs`, and `RimMindAPI.Memory` in that order. The Mod entry composes the module; it does not own provider content. +Start at `../RimMindStorytellerMod.cs` to see the module composition entry. It delegates `IncidentOutput` schema registration, both scenarios (`ScenarioIds.Storyteller` and `StorytellerRequestIds.ChatScenarioId`), and all seven Context Provider registrations to `StorytellerContextProviderRegistrar.cs`. When you need provider details, read `StorytellerRequestIds.cs`, `StorytellerContextProviderRegistrar.cs`, `../Extensions/StorytellerContextPolicy.cs`, `../Extensions/StorytellerContextBuilder.cs`, `../Memory/StorytellerMemory.cs`, and `RimMindAPI.Memory` in that order. The Mod entry composes the module; it does not own provider content. -All five providers are world-scoped: the only identity guard is `ScenarioStoryteller`. Map NPCs and the `NPC-storyteller` fallback legitimately have `PawnId=0`; no Pawn lookup is needed. `StorytellerContextPolicy` only composes the custom instruction with the generated task instruction. Missing world memory or empty histories still produce no optional content. +All providers are world-scoped and guarded strictly by scenario (`Storyteller` for incident direction vs `StorytellerChat` for Altar dialogue). Map NPCs and the `NPC-storyteller` fallback legitimately have `PawnId=0`; no Pawn lookup is needed. Missing world memory or empty histories still produce no optional content. ## Automatic flow diff --git a/Source/Storyteller/RimMindIncidentSelector.cs b/Source/Storyteller/RimMindIncidentSelector.cs index 61fd691..7c17654 100644 --- a/Source/Storyteller/RimMindIncidentSelector.cs +++ b/Source/Storyteller/RimMindIncidentSelector.cs @@ -43,10 +43,12 @@ public static (FiringIncident? incident, IncidentResponse? response) ParseRespon incidentDef.defName, incidentDef.category?.defName); var faction = Find.FactionManager.AllFactions - .FirstOrDefault(f => f.def.defName == result.@params.faction_hint + .FirstOrDefault(f => f.def?.defName == result.@params.faction_hint + && !f.IsPlayer + && !f.defeated && (requiresHostile ? f.HostileTo(Faction.OfPlayer) - : !f.IsPlayer && !f.HostileTo(Faction.OfPlayer) && !f.defeated)); + : !f.HostileTo(Faction.OfPlayer))); if (faction != null) parms.faction = faction; } diff --git a/Source/Storyteller/StorytellerCompProperties_RimMindDirector.cs b/Source/Storyteller/StorytellerCompProperties_RimMindDirector.cs index bbc281d..1034b21 100644 --- a/Source/Storyteller/StorytellerCompProperties_RimMindDirector.cs +++ b/Source/Storyteller/StorytellerCompProperties_RimMindDirector.cs @@ -1,5 +1,3 @@ -using RimMind.Storyteller.Memory; - namespace RimMind.Storyteller { public class StorytellerCompProperties_RimMindDirector : RimWorld.StorytellerCompProperties diff --git a/Source/Storyteller/StorytellerComp_RimMindFallback.cs b/Source/Storyteller/StorytellerComp_RimMindFallback.cs index 67a607e..98b239a 100644 --- a/Source/Storyteller/StorytellerComp_RimMindFallback.cs +++ b/Source/Storyteller/StorytellerComp_RimMindFallback.cs @@ -9,21 +9,30 @@ namespace RimMind.Storyteller { public class StorytellerComp_RimMindFallback : RimWorld.StorytellerComp { - private static readonly IncidentCategoryDef FactionArrivalCat = - DefDatabase.GetNamedSilentFail("FactionArrival"); + private static IncidentCategoryDef? _factionArrivalCat; + + private static IncidentCategoryDef? FactionArrivalCat => + _factionArrivalCat ??= DefDatabase.GetNamedSilentFail( + IncidentSelectionPolicy.FactionArrivalCategoryDefName); public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { + if (target == null || !target.IncidentTargetTags().Contains(IncidentTargetTagDefOf.Map_PlayerHome)) + yield break; + + if (target is not Map) + yield break; + var settings = RimMindStorytellerMod.Settings; if (settings == null) yield break; var mode = settings.fallbackMode; if (mode == FallbackMode.None) yield break; - if (StorytellerIncidentSkipCheck.ShouldSkipStorytellerIncident()) + if (RimMindAPI.Ext.ShouldSkipStorytellerIncident()) yield break; - var aiComp = Find.Storyteller.storytellerComps + var aiComp = Find.Storyteller?.storytellerComps? .OfType() .FirstOrDefault(); @@ -32,7 +41,7 @@ public override IEnumerable MakeIntervalIncidents(IIncidentTarge if (RimMindAPI.Settings.IsConfigured() && settings.enableIntervalTrigger && aiComp != null) { - int now = Find.TickManager.TicksGame; + int now = Find.TickManager?.TicksGame ?? 0; float directorMtb = settings.mtbDays; int healthyThreshold = (int)(directorMtb * 60000f * 2f); @@ -40,10 +49,11 @@ public override IEnumerable MakeIntervalIncidents(IIncidentTarge yield break; } - if (!Rand.MTBEventOccurs(GetMTBDays(mode), 60000f, 1000f)) + FallbackProfile profile = IncidentSelectionPolicy.ResolveFallbackProfile(mode.ToString()); + if (!Rand.MTBEventOccurs(profile.MtbDays, 60000f, 1000f)) yield break; - IncidentCategoryDef category = ChooseCategory(mode); + IncidentCategoryDef category = ResolveCategory(profile.ChooseCategorySlot(Rand.Value)); IncidentParms parms = GenerateParms(category, target); var usable = UsableIncidentsInCategory(category, parms); @@ -53,31 +63,13 @@ public override IEnumerable MakeIntervalIncidents(IIncidentTarge yield return new FiringIncident(def, this, parms); } - private float GetMTBDays(FallbackMode mode) + private static IncidentCategoryDef ResolveCategory(FallbackCategorySlot slot) => slot switch { - return mode switch - { - FallbackMode.Cassandra => 4.6f, - FallbackMode.Randy => 1.35f, - FallbackMode.Phoebe => 8.0f, - _ => 999f, - }; - } - - private IncidentCategoryDef ChooseCategory(FallbackMode mode) - { - return mode switch - { - FallbackMode.Phoebe => Rand.Value < 0.4f && FactionArrivalCat != null - ? FactionArrivalCat - : IncidentCategoryDefOf.ThreatSmall, - FallbackMode.Randy => Rand.Value < 0.3f - ? IncidentCategoryDefOf.ThreatBig - : Rand.Value < 0.4286f - ? IncidentCategoryDefOf.ThreatSmall - : IncidentCategoryDefOf.Misc, - _ => IncidentCategoryDefOf.ThreatBig, - }; - } + FallbackCategorySlot.ThreatBig => IncidentCategoryDefOf.ThreatBig, + FallbackCategorySlot.ThreatSmall => IncidentCategoryDefOf.ThreatSmall, + FallbackCategorySlot.Misc => IncidentCategoryDefOf.Misc, + FallbackCategorySlot.FactionArrival => FactionArrivalCat ?? IncidentCategoryDefOf.ThreatSmall, + _ => IncidentCategoryDefOf.ThreatBig, + }; } } diff --git a/Source/Storyteller/StorytellerContextProviderRegistrar.cs b/Source/Storyteller/StorytellerContextProviderRegistrar.cs index d242e1f..f52a1fd 100644 --- a/Source/Storyteller/StorytellerContextProviderRegistrar.cs +++ b/Source/Storyteller/StorytellerContextProviderRegistrar.cs @@ -13,7 +13,7 @@ namespace RimMind.Storyteller { internal static class StorytellerContextProviderRegistrar { - private const string ModId = RimMind.Application.Common.Constants.RimMindOwnerConsts.StorytellerModId; + private const string ModId = StorytellerRequestIds.OwnerModId; private const string DefaultSystemInstruction = "You are the RimWorld storyteller AI. Based on the colony's current situation, select the most appropriate incident event. " + @@ -33,15 +33,29 @@ internal static class StorytellerContextProviderRegistrar "Respond in character as the narrator and director — perceptive, dramatic, and aware of colony history, narrative tension, and recent events. " + "Reply in concise natural prose (do NOT output JSON). Consider player wishes without blindly obeying them."; - private static string Tr(string key, params object[] args) - => RimMindAPI.Text.TrOr(key, key ?? string.Empty, args); + private static readonly string[] SharedPawnExcludeKeys = + { + "npc_identity", "pawn_base_info", "fixed_relations", + "ideology", "skills_summary", "health", "mood", "current_job", + "combat_status", "target_info", "task_progress", "npc_commands" + }; - private static bool IsStorytellerChat(IReadOnlyDictionary? hints) + private static readonly string[] ChatExcludeKeys = { - return hints != null - && hints.TryGetValue("IsStorytellerChat", out var isChat) - && (isChat is true || (isChat is string isChatStr && string.Equals(isChatStr, "true", StringComparison.OrdinalIgnoreCase))); - } + "npc_identity", "pawn_base_info", "fixed_relations", + "ideology", "skills_summary", "health", "mood", "current_job", + "combat_status", "target_info", "task_progress", "npc_commands", + "storyteller_rules", "storyteller_task" + }; + + private static bool IsIncidentScenario(string? scenario) + => string.Equals(scenario, RimMindAPI.Context.ScenarioStoryteller, StringComparison.Ordinal); + + private static bool IsChatScenario(string? scenario) + => string.Equals(scenario, StorytellerRequestIds.ChatScenarioId, StringComparison.Ordinal); + + private static bool IsAnyStorytellerScenario(string? scenario) + => IsIncidentScenario(scenario) || IsChatScenario(scenario); internal static void RegisterAll() { @@ -49,6 +63,41 @@ internal static void RegisterAll() // to a real event (unknown names never fall back to the base bus event). StorytellerStateChangedEvent.Register(); + // Register Storyteller-owned IncidentOutput schema into Core's SchemaRegistry. + RimMindAPI.Context.RegisterSchema( + StorytellerRequestIds.IncidentOutputSchemaKey, + StorytellerRequestIds.IncidentOutputSchemaJson); + + var sharedWeights = new Dictionary(StringComparer.Ordinal) + { + ["nearby_pawns"] = 0.5f, + ["colony_status"] = 0.9f, + ["current_area"] = 0.4f, + ["weather"] = 0.6f, + ["time_of_day"] = 0.5f, + ["season"] = 0.7f, + ["map_structure"] = 0.8f, + ["memory_pawn"] = 0.3f, + ["working_memory"] = 0.2f, + ["memory_narrator"] = 0.9f, + ["storyteller_system"] = 1.0f, + ["storyteller_dialogue"] = 0.6f, + ["storyteller_context"] = 0.95f, + ["storyteller_reactions"] = 0.9f, + ["storyteller_recent_incidents"] = 0.85f + }; + + var incidentWeights = new Dictionary(sharedWeights, StringComparer.Ordinal) + { + ["storyteller_rules"] = 0.98f, + ["storyteller_task"] = 0.95f + }; + + var chatWeights = new Dictionary(sharedWeights, StringComparer.Ordinal) + { + ["storyteller_dialogue"] = 0.95f + }; + RimMindAPI.Context.RegisterScenario(new ScenarioDescriptor { Id = ScenarioIds.Storyteller, @@ -56,69 +105,45 @@ internal static void RegisterAll() Description = "RimMind.Application.Scenario.Storyteller", DefaultBudget = 0.7f, L4Mode = L4Mode.NarrativeMemory, - DefaultExcludeKeys = new[] - { - "npc_identity", "pawn_base_info", "fixed_relations", - "ideology", "skills_summary", "health", "mood", "current_job", - "combat_status", "target_info", "task_progress", "npc_commands" - }, + DefaultExcludeKeys = SharedPawnExcludeKeys, OwnerModId = ModId, - RelevanceWeights = new Dictionary(StringComparer.Ordinal) - { - ["health"] = 0.3f, - ["mood"] = 0.4f, - ["current_job"] = 0.2f, - ["combat_status"] = 0.8f, - ["target_info"] = 0.7f, - ["task_progress"] = 0.3f, - ["nearby_pawns"] = 0.5f, - ["colony_status"] = 0.9f, - ["current_area"] = 0.4f, - ["weather"] = 0.6f, - ["time_of_day"] = 0.5f, - ["season"] = 0.7f, - ["map_structure"] = 0.8f, - ["pawn_base_info"] = 0.3f, - ["fixed_relations"] = 0.3f, - ["ideology"] = 0.4f, - ["skills_summary"] = 0.2f, - ["memory_pawn"] = 0.3f, - ["working_memory"] = 0.2f, - ["memory_narrator"] = 0.9f, - ["storyteller_system"] = 1.0f, - ["storyteller_rules"] = 0.98f, - ["storyteller_dialogue"] = 0.6f, - ["storyteller_task"] = 0.95f, - ["storyteller_context"] = 0.95f, - ["storyteller_reactions"] = 0.9f, - ["storyteller_recent_incidents"] = 0.85f - } + RelevanceWeights = incidentWeights + }); + + RimMindAPI.Context.RegisterScenario(new ScenarioDescriptor + { + Id = StorytellerRequestIds.ChatScenarioId, + DefaultBaseRounds = 8, + Description = "RimMind.Storyteller.Dialogue.Title", + DefaultBudget = 0.7f, + L4Mode = L4Mode.NarrativeMemory, + DefaultExcludeKeys = ChatExcludeKeys, + OwnerModId = ModId, + RelevanceWeights = chatWeights }); RimMindAPI.Context.ContextKeys.Register(new ContextProviderDef( "storyteller_system", ContextLayer.L0_Static, 1.0f, async (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) - { + if (!IsAnyStorytellerScenario(ctx.Scenario)) return null; - } - bool isChat = IsStorytellerChat(ctx.Hints); + + bool isChat = IsChatScenario(ctx.Scenario); return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { - if (isChat) - { - string chatPrompt = RimMindAPI.Text.TrOr( + string baseInstruction = isChat + ? RimMindAPI.Text.TrOr( "RimMind.Storyteller.Prompt.ChatSystemInstruction", - DefaultChatSystemInstruction); - return StorytellerContextPolicy.ComposeTaskInstruction( - StorytellerMemory.Instance?.CustomSystemPrompt, - chatPrompt); - } + DefaultChatSystemInstruction) + : RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.SystemInstruction", + DefaultSystemInstruction); - return RimMindAPI.Text.TrOr( - "RimMind.Storyteller.Prompt.SystemInstruction", - DefaultSystemInstruction); + // Inject player CustomSystemPrompt in one unified L0 provider for both modes. + return StorytellerContextPolicy.ComposeTaskInstruction( + StorytellerMemory.Instance?.CustomSystemPrompt, + baseInstruction); }, null, ct: ct).ConfigureAwait(false); }, ownerMod: ModId, stalenessTicks: 0, cacheScope: CacheScope.Static)); @@ -127,14 +152,9 @@ internal static void RegisterAll() "storyteller_rules", ContextLayer.L0_Static, 0.98f, async (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) - { + if (!IsIncidentScenario(ctx.Scenario)) return null; - } - if (IsStorytellerChat(ctx.Hints)) - { - return null; - } + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.WorldRules", DefaultWorldRules), null, ct: ct).ConfigureAwait(false); @@ -145,18 +165,21 @@ internal static void RegisterAll() "storyteller_dialogue", ContextLayer.L3_State, 0.5f, async (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) - { + if (!IsAnyStorytellerScenario(ctx.Scenario)) return null; - } + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { var mem = StorytellerMemory.Instance; if (mem == null) return null; string dialogue = mem.GetRecentDialogueSummary(5); - return string.IsNullOrEmpty(dialogue) - ? null - : $"{Tr("RimMind.Storyteller.Dialogue.StorytellerDialogueHeader")}\n{dialogue}"; + if (string.IsNullOrEmpty(dialogue)) + return null; + + string header = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Dialogue.StorytellerDialogueHeader", + "[RimMind Storyteller Dialogue]"); + return $"{header}\n{dialogue}"; }, null, ct: ct).ConfigureAwait(false); }, ownerMod: ModId, stalenessTicks: 750, invalidationTriggers: new[] { StorytellerStateChangedEvent.EventName }, cacheScope: CacheScope.Scenario)); @@ -165,29 +188,17 @@ internal static void RegisterAll() "storyteller_task", ContextLayer.L0_Static, 0.95f, async (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) - { + if (!IsIncidentScenario(ctx.Scenario)) return null; - } - if (IsStorytellerChat(ctx.Hints)) - { - return null; - } + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => - { - string taskInstruction = RimMindAPI.Prompt.BuildTaskInstruction( + RimMindAPI.Prompt.BuildTaskInstruction( "RimMind.Storyteller.Prompt.TaskInstruction", null, "Role", "Goal", "Process", "Constraint", "Example", "Output", "Fallback", "SystemJsonFormat", "SystemTensionGuidance", "SystemChainGuidance", - "SystemParamsGuidance", "SystemRequirements"); - - // 将 UI 中存储的 CustomSystemPrompt 前置注入到任务指令中, - // 使玩家自定义的系统层提示词作为最高优先级上下文生效。 - return StorytellerContextPolicy.ComposeTaskInstruction( - StorytellerMemory.Instance?.CustomSystemPrompt, - taskInstruction); - }, null, ct: ct).ConfigureAwait(false); + "SystemParamsGuidance", "SystemRequirements"), + null, ct: ct).ConfigureAwait(false); }, ownerMod: ModId, stalenessTicks: 0, cacheScope: CacheScope.Static)); @@ -195,20 +206,23 @@ internal static void RegisterAll() "storyteller_context", ContextLayer.L1_Baseline, 0.85f, async (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) - { + if (!IsAnyStorytellerScenario(ctx.Scenario)) return null; - } + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { var mem = StorytellerMemory.Instance; if (mem == null) return null; var sb = new StringBuilder(); - sb.AppendLine(Tr("RimMind.Storyteller.Prompt.StorytellerStateHeader")); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.StorytellerStateHeader", + "[RimMind Storyteller]")); StorytellerContextBuilder.AppendDifficultyContext(sb); StorytellerContextBuilder.AppendThreatLevel(sb); StorytellerContextBuilder.AppendTensionLabel(sb, mem.TensionLevel); - sb.AppendLine(Tr("RimMind.Storyteller.Prompt.TensionLevel", + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.TensionLevel", + "[Narrative Tension] Current tension: {0} ({1}/1.0)", $"{(int)(mem.TensionLevel * 100)}%", $"{mem.TensionLevel:F2}")); string summary = mem.GetRecentSummary(5); if (!string.IsNullOrEmpty(summary)) @@ -225,10 +239,9 @@ internal static void RegisterAll() "storyteller_reactions", ContextLayer.L1_Baseline, 0.8f, async (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) - { + if (!IsAnyStorytellerScenario(ctx.Scenario)) return null; - } + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { var mem = StorytellerMemory.Instance; @@ -243,17 +256,18 @@ internal static void RegisterAll() "storyteller_recent_incidents", ContextLayer.L4_History, 0.7f, async (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) - { + if (!IsAnyStorytellerScenario(ctx.Scenario)) return null; - } + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { var narrations = RimMindAPI.Memory.GetRecentNarrations(5); if (narrations.Count == 0) return null; var narrationText = new StringBuilder(); - narrationText.AppendLine(Tr("RimMind.Storyteller.Prompt.RecentIncidents")); + narrationText.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.RecentIncidents", + "[Recent Narrative Incidents]")); foreach (var narration in narrations) { int day = RimMind.Domain.Common.RimMindTime.TicksToDay(narration.Tick); @@ -264,6 +278,5 @@ internal static void RegisterAll() }, ownerMod: ModId, stalenessTicks: 3000, invalidationTriggers: new[] { StorytellerStateChangedEvent.EventName }, cacheScope: CacheScope.Scenario)); } - } } diff --git a/Source/Storyteller/StorytellerNotificationService.cs b/Source/Storyteller/StorytellerNotificationService.cs index c06ba05..7c05cb3 100644 --- a/Source/Storyteller/StorytellerNotificationService.cs +++ b/Source/Storyteller/StorytellerNotificationService.cs @@ -32,7 +32,7 @@ public void Register( string label = incident.def.LabelCap.ToString(); var entry = new RequestEntry { - source = "storyteller", + source = StorytellerRequestIds.NotificationSource, title = title, description = description, options = new[] { shock, excited, accept }, diff --git a/Source/Storyteller/StorytellerRequestCoordinator.cs b/Source/Storyteller/StorytellerRequestCoordinator.cs index f93d436..7a9abd1 100644 --- a/Source/Storyteller/StorytellerRequestCoordinator.cs +++ b/Source/Storyteller/StorytellerRequestCoordinator.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; @@ -102,7 +101,7 @@ private bool Dispatch(IIncidentTarget target, bool forced) "[RimMind-Storyteller] ForceRequest: sending structured AI request"); } - string npcId = RimMindAPI.GetNpcForMap(map) ?? "NPC-storyteller"; + string npcId = RimMindAPI.GetNpcForMap(map) ?? StorytellerRequestIds.DefaultNpcId; SendRequest(npcId, target, token); }, dispatchTick, @@ -123,9 +122,11 @@ private void SendRequest( IIncidentTarget target, long requestToken) { + string schema = RimMindAPI.Context.FindSchema(StorytellerRequestIds.IncidentOutputSchemaKey) + ?? StorytellerRequestIds.IncidentOutputSchemaJson; var envelope = StorytellerIncidentRequestFactory.Create( RimMindAPI.Context.ScenarioStoryteller, - RimMindAPI.Context.SchemaIncidentOutput, + schema, npcId); RimMindAPI.Request.Send( @@ -141,8 +142,14 @@ private void OnResponseReceived( if (!_requestState.IsCurrent(requestToken)) return; - int now = Find.TickManager.TicksGame; - if (result.IsErr && result.Error.Code == RimMindErrorCode.Cancelled) { _requestState.Fail(requestToken, now); return; } if (result.IsErr) + if (result.IsErr && result.Error.Code == RimMindErrorCode.Cancelled) + { + _requestState.CancelCurrent(requestToken); + return; + } + + int now = Find.TickManager?.TicksGame ?? 0; + if (result.IsErr) { _requestState.Fail(requestToken, now); RimMindErrors.Warn( diff --git a/Source/Storyteller/StorytellerRequestIds.cs b/Source/Storyteller/StorytellerRequestIds.cs index b540c74..cb99a31 100644 --- a/Source/Storyteller/StorytellerRequestIds.cs +++ b/Source/Storyteller/StorytellerRequestIds.cs @@ -1,19 +1,61 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Features.Llm; using RimMind.Domain.Llm; namespace RimMind.Storyteller { /// - /// Storyteller-owned identity used by Core's request queue. - /// The same id must be passed to LlmRequestEnvelopeBuilder.WithModId, to - /// RimMindAPI.Request.ClearModCooldown / GetModCooldownTicksLeft, and exposed by - /// StorytellerModCooldown: Core stores per-mod cooldowns under the envelope ModId, - /// so any other spelling silently targets a cooldown key that never exists. + /// Storyteller-owned identities and schema metadata shared across request queues, + /// context providers, altar chat, notifications, and scoped agents. /// public static class StorytellerRequestIds { - /// Envelope ModId and Core queue cooldown key for every Storyteller request. + /// Canonical extension owner ID for RimMind-Storyteller. + public const string OwnerModId = RimMindOwnerConsts.StorytellerModId; + + /// Envelope ModId and Core queue cooldown key for automatic/forced incident selection. public const string RequestModId = "RimMind.Storyteller"; + + /// + /// Dedicated ModId for interactive Altar chat. Does not prefix-match + /// under Core's QueueCircuitBreaker.MatchesModId, so interactive player turns are never + /// blocked by the 1.5-day incident MTB cooldown. + /// + public const string ChatModId = "RimMind.StorytellerChat"; + + /// Scenario ID for interactive Storyteller Altar dialogue. + public const string ChatScenarioId = "StorytellerChat"; + + /// Fallback world-level NPC identity when no map proxy NPC exists. + public const string DefaultNpcId = "NPC-storyteller"; + + /// Scoped agent type identifier for the Storyteller agent. + public const string AgentScopeType = "storyteller"; + + /// Pending-request notification source identifier. + public const string NotificationSource = "storyteller"; + + /// Schema registry key for structured incident selection responses. + public const string IncidentOutputSchemaKey = "IncidentOutput"; + + /// JSON Schema matching registered into Core's SchemaRegistry. + public const string IncidentOutputSchemaJson = + "{\"type\":\"object\",\"properties\":{" + + "\"defName\":{\"type\":\"string\"}," + + "\"reason\":{\"type\":\"string\"}," + + "\"announce\":{\"type\":\"string\"}," + + "\"params\":{\"type\":\"object\",\"properties\":{" + + "\"points_multiplier\":{\"type\":\"number\"}," + + "\"faction_hint\":{\"type\":\"string\"}," + + "\"raid_strategy_hint\":{\"type\":\"string\"}" + + "}}," + + "\"chain\":{\"type\":\"object\",\"properties\":{" + + "\"chain_id\":{\"type\":\"string\"}," + + "\"chain_step\":{\"type\":\"integer\"}," + + "\"chain_total\":{\"type\":\"integer\"}," + + "\"next_hint\":{\"type\":\"string\"}" + + "}}" + + "},\"required\":[\"defName\",\"reason\"]}"; } /// diff --git a/Source/Storyteller/StorytellerRequestState.cs b/Source/Storyteller/StorytellerRequestState.cs index 255f207..f1ee7c3 100644 --- a/Source/Storyteller/StorytellerRequestState.cs +++ b/Source/Storyteller/StorytellerRequestState.cs @@ -72,6 +72,15 @@ public void CancelRequest() _generation++; } + public bool CancelCurrent(long token) + { + if (!IsCurrent(token)) + return false; + + CancelRequest(); + return true; + } + public bool Fail(long token, int tick) { if (!IsCurrent(token)) diff --git a/Source/UI/Window_StorytellerAgentControl.cs b/Source/UI/Window_StorytellerAgentControl.cs index 502e1e0..0674132 100644 --- a/Source/UI/Window_StorytellerAgentControl.cs +++ b/Source/UI/Window_StorytellerAgentControl.cs @@ -7,7 +7,9 @@ namespace RimMind.Storyteller.UI { public sealed class Window_StorytellerAgentControl : Window { - public override Vector2 InitialSize => new(560f, 420f); + private Vector2 _debugScrollPos = Vector2.zero; + + public override Vector2 InitialSize => new Vector2(560f, 420f); public Window_StorytellerAgentControl() { @@ -20,52 +22,72 @@ public override void DoWindowContents(Rect inRect) { Text.Font = GameFont.Medium; Widgets.Label(new Rect(inRect.x, inRect.y, inRect.width, 32f), - "RimMind.Storyteller.UI.Agent.Title".Translate()); + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Agent.Title", "Storyteller Agent")); Text.Font = GameFont.Small; var agent = StorytellerAgentController.Find(); float y = inRect.y + 42f; + string notCreated = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.Agent.NotCreated", + "No Storyteller agent has been created yet."); + string stateDisplay; if (agent == null) { - stateDisplay = "RimMind.Storyteller.UI.Agent.NotCreated".Translate(); + stateDisplay = notCreated; } else { string stateKey = $"RimMind.Agent.State.{agent.State}"; stateDisplay = RimMindAPI.Text.TrOr(stateKey, agent.State.ToString()); } + Widgets.Label(new Rect(inRect.x, y, inRect.width, 24f), - "RimMind.Storyteller.UI.Agent.State".Translate(stateDisplay)); + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Agent.State", "State: {0}", stateDisplay)); y += 34f; - if (Widgets.ButtonText(new Rect(inRect.x, y, 120f, 32f), - "RimMind.Storyteller.UI.Agent.Start".Translate())) + const float gap = 8f; + float btnWidth = Mathf.Floor((inRect.width - gap * 3f) / 4f); + float bx = inRect.x; + + if (Widgets.ButtonText(new Rect(bx, y, btnWidth, 32f), + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Agent.Start", "Start"))) { StorytellerAgentController.Start(); } + bx += btnWidth + gap; - if (Widgets.ButtonText(new Rect(inRect.x + 130f, y, 120f, 32f), - "RimMind.Storyteller.UI.Agent.Pause".Translate())) + if (Widgets.ButtonText(new Rect(bx, y, btnWidth, 32f), + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Agent.Pause", "Pause"))) { StorytellerAgentController.Pause(); } + bx += btnWidth + gap; - if (Widgets.ButtonText(new Rect(inRect.x + 260f, y, 120f, 32f), - "RimMind.Storyteller.UI.Agent.ForceThink".Translate())) + if (Widgets.ButtonText(new Rect(bx, y, btnWidth, 32f), + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Agent.ForceThink", "Force Think"))) { StorytellerAgentController.ForceThink(); } + bx += btnWidth + gap; - if (Widgets.ButtonText(new Rect(inRect.x + 390f, y, 140f, 32f), - "RimMind.Storyteller.UI.Agent.OpenRequests".Translate())) + float lastBtnWidth = Mathf.Max(btnWidth, inRect.xMax - bx); + if (Widgets.ButtonText(new Rect(bx, y, lastBtnWidth, 32f), + RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Agent.OpenRequests", "Requests"))) { RimMindAPI.Debug.OpenAIRequests(); } - y += 48f; - Widgets.Label(new Rect(inRect.x, y, inRect.width, inRect.height - y), - agent?.GetDebugInfo() ?? "RimMind.Storyteller.UI.Agent.NotCreated".Translate()); + y += 42f; + Rect scrollOuter = new Rect(inRect.x, y, inRect.width, Mathf.Max(40f, inRect.yMax - y)); + string debugText = agent?.GetDebugInfo() ?? notCreated; + float contentWidth = Mathf.Max(20f, scrollOuter.width - 16f); + float contentHeight = Mathf.Max(scrollOuter.height, Text.CalcHeight(debugText, contentWidth) + 8f); + Rect scrollView = new Rect(0f, 0f, contentWidth, contentHeight); + + Widgets.BeginScrollView(scrollOuter, ref _debugScrollPos, scrollView); + Widgets.Label(scrollView, debugText); + Widgets.EndScrollView(); } } } diff --git a/Source/UI/Window_StorytellerDialogue.cs b/Source/UI/Window_StorytellerDialogue.cs index 2e13a1e..4c37267 100644 --- a/Source/UI/Window_StorytellerDialogue.cs +++ b/Source/UI/Window_StorytellerDialogue.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using RimMind.Application.Common.Models.Context; using RimMind.Application.Features.Llm; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -17,14 +16,12 @@ public class Window_StorytellerDialogue : RimMindChatWindowBase private const int MaxHistoryRounds = 6; private static readonly Color StorytellerHeaderColor = new Color(1f, 0.9f, 0.7f); - private readonly Map _map; - public override Vector2 InitialSize => new Vector2(520f, 560f); protected override Color HeaderColor => StorytellerHeaderColor; - public Window_StorytellerDialogue(Map map) : base() + public Window_StorytellerDialogue(Map? map = null) : base() { - _map = map; + _ = map; closeOnClickedOutside = true; var memory = StorytellerMemory.Instance; @@ -76,13 +73,11 @@ protected override void OnSubmitUserMessage(string trimmedInput) var envelope = LlmRequestEnvelopeBuilder .ForNpc( - "NPC-storyteller", + StorytellerRequestIds.DefaultNpcId, gameStateInfo: new GameStateInfo() - .AddSection("dialogue_input", trimmedInput) - .AddSection("IsStorytellerChat", "true")) - .ForScenarioId(ScenarioIds.Storyteller) - .WithModId(StorytellerRequestIds.RequestModId) - .WithHint("IsStorytellerChat", "true") + .AddSection("dialogue_input", trimmedInput)) + .ForScenarioId(StorytellerRequestIds.ChatScenarioId) + .WithModId(StorytellerRequestIds.ChatModId) .WithRequireAliveColonist(false) .WithMaxTokens(400) .WithTemperature(0.9f) @@ -130,7 +125,6 @@ private static void RecordDialogueToMemory(string role, string content) int tick = Find.TickManager?.TicksGame ?? 0; memory.RecordDialogue(role, content, tick); - // storyteller_dialogue context is cached; the new turn must reach the next prompt. StorytellerStateChangedEvent.Publish(); TryPushToMemoryMod(role, content, tick); diff --git a/Tests/Contracts/StorytellerCoreAdoptionContracts.cs b/Tests/Contracts/StorytellerCoreAdoptionContracts.cs index ac2edbb..183852e 100644 --- a/Tests/Contracts/StorytellerCoreAdoptionContracts.cs +++ b/Tests/Contracts/StorytellerCoreAdoptionContracts.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Newtonsoft.Json.Linq; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Context; using RimMind.Application.Common.Models.Context; @@ -20,9 +21,10 @@ namespace RimMind.Storyteller.Tests.Contracts public sealed class StorytellerCoreAdoptionContracts { [Fact] - public async Task Storyteller_OwnsItsOwnScenarioAndL0Prompts_ForBothIncidentAndAltarChatModes() + public async Task Storyteller_OwnsItsOwnScenariosSchemaAndL0Prompts_ForBothIncidentAndAltarChatModes() { RimMindAPI.Context.ContextKeys.Definitions.Clear(); + RimMindAPI.Context.RegisteredSchemas.Clear(); StorytellerMemory.Instance = new StorytellerMemory { CustomSystemPrompt = "Be mysterious and poetic." @@ -31,46 +33,74 @@ public async Task Storyteller_OwnsItsOwnScenarioAndL0Prompts_ForBothIncidentAndA { StorytellerContextProviderRegistrar.RegisterAll(); - var scenario = ScenarioRegistry.Get(ScenarioIds.Storyteller); - Assert.NotNull(scenario); - Assert.Equal(RimMindOwnerConsts.StorytellerModId, scenario!.OwnerModId); - Assert.Equal(L4Mode.NarrativeMemory, scenario.L4Mode); - Assert.True(scenario.RelevanceWeights != null && scenario.RelevanceWeights.ContainsKey("storyteller_system")); - Assert.True(scenario.RelevanceWeights!.ContainsKey("storyteller_rules")); + // Storyteller registers its own IncidentOutput JSON Schema + string? incidentSchema = RimMindAPI.Context.FindSchema(StorytellerRequestIds.IncidentOutputSchemaKey); + Assert.NotNull(incidentSchema); + var parsedSchema = JObject.Parse(incidentSchema!); + Assert.Equal("object", parsedSchema["type"]?.ToString()); + Assert.NotNull(parsedSchema["properties"]?["defName"]); + + var incidentScenario = ScenarioRegistry.Get(ScenarioIds.Storyteller); + Assert.NotNull(incidentScenario); + Assert.Equal(RimMindOwnerConsts.StorytellerModId, incidentScenario!.OwnerModId); + Assert.Equal(L4Mode.NarrativeMemory, incidentScenario.L4Mode); + Assert.True(incidentScenario.RelevanceWeights != null && incidentScenario.RelevanceWeights.ContainsKey("storyteller_system")); + Assert.True(incidentScenario.RelevanceWeights!.ContainsKey("storyteller_rules")); + // Pruned dead weights: no excluded key should also appear in RelevanceWeights + foreach (string excluded in incidentScenario.DefaultExcludeKeys) + { + Assert.False(incidentScenario.RelevanceWeights.ContainsKey(excluded), + $"Excluded key '{excluded}' must not remain in RelevanceWeights."); + } + + // Altar chat has its own registered scenario cleanly separated from incident selection + var chatScenario = ScenarioRegistry.Get(StorytellerRequestIds.ChatScenarioId); + Assert.NotNull(chatScenario); + Assert.Equal(RimMindOwnerConsts.StorytellerModId, chatScenario!.OwnerModId); + Assert.Contains("storyteller_rules", chatScenario.DefaultExcludeKeys); + Assert.Contains("storyteller_task", chatScenario.DefaultExcludeKeys); var systemProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_system"); var rulesProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_rules"); + var taskProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_task"); Assert.Equal(ContextLayer.L0_Static, systemProvider.Layer); Assert.Equal(ContextLayer.L0_Static, rulesProvider.Layer); + Assert.Equal(ContextLayer.L0_Static, taskProvider.Layer); - var incidentCtx = new ProviderContext(ScenarioIds.Storyteller, "t-inc") { NpcId = "NPC-storyteller" }; + var incidentCtx = new ProviderContext(ScenarioIds.Storyteller, "t-inc") { NpcId = StorytellerRequestIds.DefaultNpcId }; string? incidentSys = await systemProvider.Provider(incidentCtx, CancellationToken.None); string? incidentRules = await rulesProvider.Provider(incidentCtx, CancellationToken.None); + string? incidentTask = await taskProvider.Provider(incidentCtx, CancellationToken.None); Assert.NotNull(incidentSys); + Assert.Contains("Be mysterious and poetic.", incidentSys!); Assert.Contains("storyteller AI", incidentSys!); Assert.NotNull(incidentRules); Assert.Contains("Storyteller rules", incidentRules!); + Assert.NotNull(incidentTask); + // CustomSystemPrompt is composed once in storyteller_system, not duplicated in storyteller_task + Assert.DoesNotContain("Be mysterious and poetic.", incidentTask!); // Non-storyteller scenarios must receive null (strict scenario guard) Assert.Null(await systemProvider.Provider(incidentCtx with { Scenario = ScenarioIds.Dialogue }, CancellationToken.None)); Assert.Null(await rulesProvider.Provider(incidentCtx with { Scenario = ScenarioIds.AgentDecision }, CancellationToken.None)); - // Altar chat mode receives chat persona + CustomSystemPrompt, and omits incident JSON rules - var chatCtx = new ProviderContext(ScenarioIds.Storyteller, "t-chat") + // Altar chat scenario receives chat persona + CustomSystemPrompt, and omits incident JSON rules/task + var chatCtx = new ProviderContext(StorytellerRequestIds.ChatScenarioId, "t-chat") { - NpcId = "NPC-storyteller", - Hints = new Dictionary { ["IsStorytellerChat"] = "true" } + NpcId = StorytellerRequestIds.DefaultNpcId }; string? chatSys = await systemProvider.Provider(chatCtx, CancellationToken.None); Assert.NotNull(chatSys); Assert.Contains("Be mysterious and poetic.", chatSys!); Assert.Contains("Storyteller Altar", chatSys!); Assert.Null(await rulesProvider.Provider(chatCtx, CancellationToken.None)); + Assert.Null(await taskProvider.Provider(chatCtx, CancellationToken.None)); } finally { StorytellerMemory.Instance = null; RimMindAPI.Context.ContextKeys.Definitions.Clear(); + RimMindAPI.Context.RegisteredSchemas.Clear(); } } @@ -96,7 +126,7 @@ public void StorytellerResponseParserPure_HandlesThinkingTagsAndPseudoFunctionCa } [Fact] - public void Window_StorytellerDialogue_CancelsInFlightRequestOnPostClose_AndPersistsReplies() + public void Window_StorytellerDialogue_UsesDedicatedChatScenarioAndModId_CancelsOnPostClose_AndPersistsReplies() { RimMindAPI.Configured = true; RimMindAPI.Sent.Clear(); @@ -119,11 +149,15 @@ public void Window_StorytellerDialogue_CancelsInFlightRequestOnPostClose_AndPers window.DoWindowContents(new Rect(0, 0, 520, 560)); var sent = Assert.Single(RimMindAPI.Sent); - Assert.Equal(ScenarioIds.Storyteller, sent.Envelope.ScenarioId); - Assert.Equal(StorytellerRequestIds.RequestModId, sent.Envelope.ModId); + Assert.Equal(StorytellerRequestIds.ChatScenarioId, sent.Envelope.ScenarioId); + Assert.Equal(StorytellerRequestIds.ChatModId, sent.Envelope.ModId); + Assert.NotEqual(StorytellerRequestIds.RequestModId, sent.Envelope.ModId); Assert.Equal(false, sent.Envelope.RequireAliveColonist); Assert.True(sent.Envelope.Ct.CanBeCanceled); Assert.False(sent.Envelope.Ct.IsCancellationRequested); + // Control flags must never leak into GameStateInfo prompt text + string serializedGameState = sent.Envelope.GameStateInfo?.ToString() ?? string.Empty; + Assert.DoesNotContain("IsStorytellerChat", serializedGameState); // Deliver assistant reply and drain on next frame sent.Complete(Result.Ok(new LlmResponse { Content = "Fortune favors the bold." })); @@ -157,7 +191,7 @@ public void Window_StorytellerDialogue_CancelsInFlightRequestOnPostClose_AndPers [Fact] public void StorytellerIncidentRequestFactory_OptsOutOfColonistLivenessGate() { - var envelope = StorytellerIncidentRequestFactory.Create(ScenarioIds.Storyteller, "{}", "NPC-storyteller"); + var envelope = StorytellerIncidentRequestFactory.Create(ScenarioIds.Storyteller, "{}", StorytellerRequestIds.DefaultNpcId); Assert.Equal(false, envelope.RequireAliveColonist); Assert.Equal(false, envelope.EffectiveRequireAliveColonist); } diff --git a/Tests/Contracts/StorytellerIncidentPolicyContracts.cs b/Tests/Contracts/StorytellerIncidentPolicyContracts.cs index 5c54e62..2cf05f6 100644 --- a/Tests/Contracts/StorytellerIncidentPolicyContracts.cs +++ b/Tests/Contracts/StorytellerIncidentPolicyContracts.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.RegularExpressions; using System.Xml.Linq; -using RimMind.Storyteller.Extensions; -using RimMind.Storyteller.Memory; using RimMind.Testing; using RimWorld; using Verse; @@ -21,9 +19,10 @@ public void Stable_incident_policy_boundaries() ("valid incident responses retain parameters and chain metadata", ValidResponsesRetainMetadata), ("truncated and trailing comma responses are repaired", RecoverableResponsesAreRepaired), ("empty malformed and missing def names become no incident", InvalidResponsesBecomeNoIncident), - ("pawn lookup rejects invalid ids before world then map lookup", PawnLookupOrderRemainsStable), ("only threat categories notify the player", NotificationPolicyRemainsNarrow), - ("director xml includes vanilla trade visitors and random quest comps", DirectorDefIncludesVanillaEcosystemComps)); + ("tension deltas and fallback profiles stay centralized and bounded", TensionAndFallbackProfilesRemainConsistent), + ("director xml includes vanilla ecosystem comps and restricts fallback to Map_PlayerHome", DirectorDefIncludesVanillaEcosystemAndScopedFallback), + ("source code contains zero raw .Translate() calls", SourceContainsZeroRawTranslateCalls)); } private static void ValidResponsesRetainMetadata() @@ -142,7 +141,7 @@ public void Incident_parameters_are_bounded_before_worker_validation(float multi } [Fact] - public void Nonhostile_faction_and_unknown_strategy_hints_do_not_override_defaults() + public void Nonhostile_defeated_faction_and_unknown_strategy_hints_do_not_override_defaults() { var raidDef = new IncidentDef { defName = "RaidEnemy" }; raidDef.category.defName = "ThreatBig"; @@ -155,6 +154,8 @@ public void Nonhostile_faction_and_unknown_strategy_hints_do_not_override_defaul ally.def.defName = "OutlanderCivil"; var defeatedAlly = new Faction { IsHostile = false, defeated = true }; defeatedAlly.def.defName = "DefeatedCivil"; + var defeatedPirate = new Faction { IsHostile = true, defeated = true }; + defeatedPirate.def.defName = "DefeatedPirate"; var pirate = new Faction { IsHostile = true }; pirate.def.defName = "Pirate"; @@ -163,6 +164,7 @@ public void Nonhostile_faction_and_unknown_strategy_hints_do_not_override_defaul DefDatabase.Definitions[friendlyRaidDef.defName] = friendlyRaidDef; Find.FactionManager.AllFactions.Add(ally); Find.FactionManager.AllFactions.Add(defeatedAlly); + Find.FactionManager.AllFactions.Add(defeatedPirate); Find.FactionManager.AllFactions.Add(pirate); try { @@ -179,6 +181,13 @@ public void Nonhostile_faction_and_unknown_strategy_hints_do_not_override_defaul Assert.Null(raidIncident!.parms.faction); Assert.Null(raidIncident.parms.raidStrategy); + // Defeated hostile faction must also be rejected + var (defeatedHostileRaid, _) = RimMindIncidentSelector.ParseResponse( + "{\"defName\":\"RaidEnemy\",\"params\":{\"faction_hint\":\"DefeatedPirate\"}}", + new Map(), new StorytellerComp()); + Assert.NotNull(defeatedHostileRaid); + Assert.Null(defeatedHostileRaid!.parms.faction); + var (caravanIncident, _) = RimMindIncidentSelector.ParseResponse( "{\"defName\":\"TraderCaravanArrival\",\"params\":{\"faction_hint\":\"OutlanderCivil\"}}", new Map(), new StorytellerComp()); @@ -210,74 +219,6 @@ public void Nonhostile_faction_and_unknown_strategy_hints_do_not_override_defaul } } - private static void PawnLookupOrderRemainsStable() - { -#pragma warning disable CS0618 - int enumerations = 0; - IEnumerable Track(params TestPawn[] pawns) - { - enumerations++; - foreach (TestPawn pawn in pawns) - yield return pawn; - } - - Assert.Null(PawnLookupCore.FindById( - 0, - () => Track(new TestPawn(1, "world")), - () => Track(new TestPawn(1, "map")), - pawn => pawn.Id)); - Assert.Equal(0, enumerations); - - var world = new[] { new TestPawn(7, "world") }; - var map = new[] { new TestPawn(7, "map"), new TestPawn(8, "fallback") }; - int mapFactoryCalls = 0; - Assert.Equal( - "world", - PawnLookupCore.FindById( - 7, - () => world, - () => - { - mapFactoryCalls++; - return map; - }, - pawn => pawn.Id)!.Source); - Assert.Equal(0, mapFactoryCalls); - Assert.Equal( - "fallback", - PawnLookupCore.FindById( - 8, - () => world, - () => - { - mapFactoryCalls++; - return map; - }, - pawn => pawn.Id)!.Source); - Assert.Equal(1, mapFactoryCalls); - - var activeMap = new Map(); - var mapPawn = new Pawn { thingIDNumber = 42 }; - var worldOnlyPawn = new Pawn { thingIDNumber = 99 }; - activeMap.mapPawns.FreeColonists.Add(mapPawn); - Find.CurrentMap = activeMap; - Find.WorldPawns.AllPawnsAlive.Add(worldOnlyPawn); - try - { - Assert.Null(PawnLookup.FindPawnById(0)); - Assert.Same(mapPawn, PawnLookup.FindPawnById(42)); - Assert.Same(mapPawn, PawnLookup.FindById("Pawn_42")); - Assert.Null(PawnLookup.FindPawnById(99)); - Assert.Null(PawnLookup.FindById("Pawn_99")); - } - finally - { - Find.CurrentMap = null; - Find.WorldPawns.AllPawnsAlive.Clear(); - } -#pragma warning restore CS0618 - } - private static void NotificationPolicyRemainsNarrow() { Assert.True(IncidentSelectionPolicy.ShouldNotify( @@ -290,22 +231,34 @@ private static void NotificationPolicyRemainsNarrow() false, StorytellerIncidentKind.ThreatBig)); } - private static void DirectorDefIncludesVanillaEcosystemComps() + private static void TensionAndFallbackProfilesRemainConsistent() { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - while (dir != null && !File.Exists(Path.Combine(dir.FullName, "Defs", "StorytellerDefs", "RimMindDirector.xml"))) - { - string candidate = Path.Combine(dir.FullName, "RimMind-Storyteller", "Defs", "StorytellerDefs", "RimMindDirector.xml"); - if (File.Exists(candidate)) - { - dir = new DirectoryInfo(Path.Combine(dir.FullName, "RimMind-Storyteller")); - break; - } - dir = dir.Parent; - } + Assert.Equal(0.25f, IncidentSelectionPolicy.GetTensionDeltaForCategory("ThreatBig"), 3); + Assert.Equal(0.12f, IncidentSelectionPolicy.GetTensionDeltaForCategory("ThreatSmall"), 3); + Assert.Equal(-0.05f, IncidentSelectionPolicy.GetTensionDeltaForCategory("Misc"), 3); + Assert.Equal(-0.08f, IncidentSelectionPolicy.GetTensionDeltaForCategory("FactionArrival"), 3); + Assert.Equal(0f, IncidentSelectionPolicy.GetTensionDeltaForCategory(null), 3); - Assert.NotNull(dir); - string xmlPath = Path.Combine(dir!.FullName, "Defs", "StorytellerDefs", "RimMindDirector.xml"); + var cassandra = IncidentSelectionPolicy.ResolveFallbackProfile("Cassandra"); + Assert.Equal(4.6f, cassandra.MtbDays, 2); + Assert.Equal(FallbackCategorySlot.ThreatBig, cassandra.ChooseCategorySlot(0.5f)); + + var randy = IncidentSelectionPolicy.ResolveFallbackProfile("Randy"); + Assert.Equal(1.35f, randy.MtbDays, 2); + Assert.Equal(FallbackCategorySlot.ThreatBig, randy.ChooseCategorySlot(0.1f)); + Assert.Equal(FallbackCategorySlot.ThreatSmall, randy.ChooseCategorySlot(0.45f)); + Assert.Equal(FallbackCategorySlot.Misc, randy.ChooseCategorySlot(0.8f)); + + var phoebe = IncidentSelectionPolicy.ResolveFallbackProfile("Phoebe"); + Assert.Equal(8.0f, phoebe.MtbDays, 2); + Assert.Equal(FallbackCategorySlot.ThreatSmall, phoebe.ChooseCategorySlot(0.2f)); + Assert.Equal(FallbackCategorySlot.FactionArrival, phoebe.ChooseCategorySlot(0.9f)); + } + + private static void DirectorDefIncludesVanillaEcosystemAndScopedFallback() + { + string modRoot = FindStorytellerModRoot(); + string xmlPath = Path.Combine(modRoot, "Defs", "StorytellerDefs", "RimMindDirector.xml"); XDocument doc = XDocument.Load(xmlPath); var comps = doc.Root! .Elements("StorytellerDef") @@ -330,18 +283,44 @@ private static void DirectorDefIncludesVanillaEcosystemComps() Assert.Contains("OrbitalTraderArrival", incidents); Assert.Contains("StorytellerCompProperties_RandomQuest", classes); Assert.Contains("StorytellerCompProperties_ShipChunkDrop", classes); + + // Fallback comp must restrict target tags to Map_PlayerHome + var fallbackComp = comps.Single(c => c.Attribute("Class")?.Value == "RimMind.Storyteller.StorytellerCompProperties_RimMindFallback"); + var allowedTags = fallbackComp.Element("allowedTargetTags")?.Elements("li").Select(e => e.Value).ToList(); + Assert.NotNull(allowedTags); + Assert.Contains("Map_PlayerHome", allowedTags!); } - private sealed class TestPawn + private static void SourceContainsZeroRawTranslateCalls() { - public TestPawn(int id, string source) + string sourceRoot = Path.Combine(FindStorytellerModRoot(), "Source"); + var csFiles = Directory.EnumerateFiles(sourceRoot, "*.cs", SearchOption.AllDirectories) + .Where(p => !p.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar)) + .ToList(); + Assert.NotEmpty(csFiles); + + foreach (string file in csFiles) { - Id = id; - Source = source; + string code = Regex.Replace(File.ReadAllText(file), @"//[^\r\n]*|/\*.*?\*/", " ", RegexOptions.Singleline); + Assert.DoesNotContain(".Translate(", code, StringComparison.Ordinal); } + } + + private static string FindStorytellerModRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null) + { + if (File.Exists(Path.Combine(dir.FullName, "Defs", "StorytellerDefs", "RimMindDirector.xml"))) + return dir.FullName; - public int Id { get; } - public string Source { get; } + string candidate = Path.Combine(dir.FullName, "RimMind-Storyteller", "Defs", "StorytellerDefs", "RimMindDirector.xml"); + if (File.Exists(candidate)) + return Path.Combine(dir.FullName, "RimMind-Storyteller"); + + dir = dir.Parent; + } + throw new InvalidOperationException("RimMind-Storyteller root directory not found."); } } } diff --git a/Tests/Contracts/StorytellerQueueIdentityContracts.cs b/Tests/Contracts/StorytellerQueueIdentityContracts.cs index 78f01ea..9e071f7 100644 --- a/Tests/Contracts/StorytellerQueueIdentityContracts.cs +++ b/Tests/Contracts/StorytellerQueueIdentityContracts.cs @@ -8,23 +8,32 @@ namespace RimMind.Storyteller.Tests.Contracts { /// - /// Regression contract for B7: the cooldown key cleared by a forced request must be the - /// envelope ModId Core uses to store the Storyteller queue cooldown. + /// Regression contract for queue identity & cooldown separation: + /// - Incident selection uses matching StorytellerModCooldown. + /// - Altar chat uses which MUST NOT match or prefix-match + /// or + /// under Core's QueueCircuitBreaker.MatchesModId. /// public sealed class StorytellerQueueIdentityContracts { [Fact] - public void Queue_cooldown_key_is_the_envelope_mod_id() + public void Queue_cooldown_key_and_chat_mod_id_stay_isolated() { ContractCaseRunner.Run( - ("incident request envelope uses the module-owned request id", () => + ("incident request envelope uses the module-owned incident request id", () => { - var envelope = StorytellerIncidentRequestFactory.Create("Storyteller", "{}", "NPC-storyteller"); + var envelope = StorytellerIncidentRequestFactory.Create("Storyteller", "{}", StorytellerRequestIds.DefaultNpcId); Assert.Equal(StorytellerRequestIds.RequestModId, envelope.ModId); Assert.Equal("Storyteller", envelope.ScenarioId); - Assert.Equal("NPC-storyteller", envelope.NpcId); + Assert.Equal(StorytellerRequestIds.DefaultNpcId, envelope.NpcId); Assert.Equal(StorytellerIncidentRequestFactory.MaxTokens, envelope.MaxTokens); }), + ("altar chat ModId never collides with incident cooldown key or OwnerModId prefix", () => + { + Assert.False(MatchesQueueCooldownKey(StorytellerRequestIds.ChatModId, StorytellerRequestIds.RequestModId)); + Assert.False(MatchesQueueCooldownKey(StorytellerRequestIds.ChatModId, StorytellerRequestIds.OwnerModId)); + Assert.True(MatchesQueueCooldownKey(StorytellerRequestIds.RequestModId, StorytellerRequestIds.RequestModId)); + }), ("source never clears or reads a cooldown with a literal key or diverging ModId", () => { var literalCooldownKey = new Regex(@"(ClearModCooldown|GetModCooldownTicksLeft)\(\s*"""); @@ -39,12 +48,26 @@ public void Queue_cooldown_key_is_the_envelope_mod_id() string text = File.ReadAllText(file); Assert.False(literalCooldownKey.IsMatch(text), $"{Path.GetFileName(file)} passes a literal cooldown key; use StorytellerRequestIds.RequestModId."); - foreach (Match match in literalModId.Matches(text)) - Assert.Equal(StorytellerRequestIds.RequestModId, match.Groups["id"].Value); + Assert.False(literalModId.IsMatch(text), + $"{Path.GetFileName(file)} passes a raw literal ModId; use StorytellerRequestIds constants."); } })); } + private static bool MatchesQueueCooldownKey(string modId, string candidate) + { + if (string.Equals(modId, candidate, StringComparison.OrdinalIgnoreCase)) + return true; + + if (modId.StartsWith(candidate, StringComparison.OrdinalIgnoreCase) && modId.Length > candidate.Length) + { + char sep = modId[candidate.Length]; + if (sep == '.' || sep == '-' || sep == '_' || sep == ':' || sep == '/') + return true; + } + return false; + } + private static string SourceRoot() { var directory = new DirectoryInfo(AppContext.BaseDirectory); diff --git a/Tests/Contracts/StorytellerRequestContextContracts.cs b/Tests/Contracts/StorytellerRequestContextContracts.cs index 3347e8c..a92e7f5 100644 --- a/Tests/Contracts/StorytellerRequestContextContracts.cs +++ b/Tests/Contracts/StorytellerRequestContextContracts.cs @@ -1,6 +1,9 @@ +using System.Text; using RimMind.Storyteller.Extensions; using RimMind.Storyteller.Memory; using RimMind.Testing; +using RimWorld; +using Verse; using Xunit; namespace RimMind.Storyteller.Tests.Contracts @@ -13,7 +16,8 @@ public void Stable_request_context_and_memory_boundaries() ContractCaseRunner.Run( ("tension clamps decay and day conversion stay deterministic", TensionMathRemainsDeterministic), ("custom instruction is prepended only when nonblank", CustomInstructionComposition), - ("request state publishes one result for its current token", RequestStatePublishesOnce)); + ("request state publishes once and cancellation never marks director unhealthy", RequestStatePublishesOnceAndCancelPreservesHealth), + ("difficulty context prefers live difficultyDef label and falls back cleanly", DifficultyContextPrefersLiveLabel)); } private static void TensionMathRemainsDeterministic() @@ -48,7 +52,7 @@ private static void CustomInstructionComposition() StorytellerContextPolicy.ComposeTaskInstruction(" ", "generated")); } - private static void RequestStatePublishesOnce() + private static void RequestStatePublishesOnceAndCancelPreservesHealth() { var state = new StorytellerRequestState(); long token = 0; @@ -69,6 +73,14 @@ private static void RequestStatePublishesOnce() Assert.Equal("incident", incident); Assert.False(state.TryTake(out _)); + // Intentional cancellation clears pending state without advancing LastFailTick + long cancelToken = 0; + Assert.True(state.TryDispatch(captured => cancelToken = captured, failureTick: 200, out _)); + Assert.True(state.CancelCurrent(cancelToken)); + Assert.False(state.HasPendingRequest); + Assert.Equal(-99999, state.LastFailTick); + Assert.True(state.IsDirectorHealthy(currentTick: 250, healthyThresholdTicks: 120000)); + var freshAfterLoad = new StorytellerRequestState(); Assert.True(freshAfterLoad.IsDirectorHealthy(currentTick: 500000, healthyThresholdTicks: 120000)); @@ -77,5 +89,34 @@ private static void RequestStatePublishesOnce() Assert.False(freshAfterLoad.IsDirectorHealthy(currentTick: 500100, healthyThresholdTicks: 120000)); } + private static void DifficultyContextPrefersLiveLabel() + { + var prev = Find.Storyteller; + try + { + var st = new RimWorld.Storyteller + { + difficultyDef = new DifficultyDef { LabelCap = "Custom Modded Nightmare" } + }; + st.difficulty.threatScale = 1.5f; + Find.Storyteller = st; + + var sb = new StringBuilder(); + StorytellerContextBuilder.AppendDifficultyContext(sb); + string text = sb.ToString(); + Assert.Contains("Custom Modded Nightmare", text); + Assert.Contains("1.50", text); + + // Fallback to tier table when difficultyDef is absent + st.difficultyDef = null; + sb.Clear(); + StorytellerContextBuilder.AppendDifficultyContext(sb); + Assert.Contains("Blood and Dust", sb.ToString()); + } + finally + { + Find.Storyteller = prev; + } + } } } diff --git a/Tests/Contracts/StorytellerWorldProviderContracts.cs b/Tests/Contracts/StorytellerWorldProviderContracts.cs index 48d108c..cea88a6 100644 --- a/Tests/Contracts/StorytellerWorldProviderContracts.cs +++ b/Tests/Contracts/StorytellerWorldProviderContracts.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -24,7 +23,7 @@ public static IEnumerable WorldRequests() ["storyteller_reactions"] = "player reaction", ["storyteller_recent_incidents"] = "narrator memory" }; - foreach (string npcId in new[] { "NPC-map-7", "NPC-storyteller" }) + foreach (string npcId in new[] { "NPC-map-7", StorytellerRequestIds.DefaultNpcId }) foreach (var item in expectedContent) yield return new object[] { npcId, item.Key, item.Value }; } @@ -62,12 +61,13 @@ public async Task World_request_includes_registered_context_without_a_pawn(strin } [Fact] - public async Task Storyteller_providers_marshal_background_reads_via_MainThreadReader_and_respect_chat_hint() + public async Task Storyteller_providers_marshal_background_reads_via_MainThreadReader_and_isolate_chat_scenario() { RimMindAPI.Context.ContextKeys.Definitions.Clear(); StorytellerMemory.Instance = new StorytellerMemory { - IncidentSummary = "marshalled summary" + IncidentSummary = "marshalled summary", + Dialogue = "altar dialogue turn" }; int postCount = 0; RimMindAPI.MainThreadSnapshot.Reader = new MainThreadReader( @@ -83,25 +83,21 @@ public async Task Storyteller_providers_marshal_background_reads_via_MainThreadR StorytellerContextProviderRegistrar.RegisterAll(); var ctxProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_context"); var taskProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_task"); + var dialogueProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_dialogue"); - var context = new ProviderContext(ScenarioIds.Storyteller, "bg-test") { NpcId = "NPC-storyteller" }; + var context = new ProviderContext(ScenarioIds.Storyteller, "bg-test") { NpcId = StorytellerRequestIds.DefaultNpcId }; string? result = await ctxProvider.Provider(context, CancellationToken.None); Assert.Contains("marshalled summary", result); Assert.Equal(1, postCount); - var chatContext = new ProviderContext(ScenarioIds.Storyteller, "chat-test") + // Dedicated ChatScenarioId omits incident task while serving world/dialogue context + var chatContext = new ProviderContext(StorytellerRequestIds.ChatScenarioId, "chat-test") { - NpcId = "NPC-storyteller", - Hints = new Dictionary { ["IsStorytellerChat"] = true } + NpcId = StorytellerRequestIds.DefaultNpcId }; Assert.Null(await taskProvider.Provider(chatContext, CancellationToken.None)); - - var stringHintChatContext = new ProviderContext(ScenarioIds.Storyteller, "chat-string-test") - { - NpcId = "NPC-storyteller", - Hints = new Dictionary { ["IsStorytellerChat"] = "true" } - }; - Assert.Null(await taskProvider.Provider(stringHintChatContext, CancellationToken.None)); + Assert.Contains("marshalled summary", await ctxProvider.Provider(chatContext, CancellationToken.None)); + Assert.Contains("altar dialogue turn", await dialogueProvider.Provider(chatContext, CancellationToken.None)); } finally { diff --git a/Tests/README.md b/Tests/README.md index 13a44db..40e25b4 100644 --- a/Tests/README.md +++ b/Tests/README.md @@ -1,33 +1,31 @@ # RimMind Storyteller contract tests -The project compiles only the active behavior contracts and explicitly linked -production seams. Legacy files remain on disk but are excluded. +The project compiles the active behavior contracts (`Contracts/**/*.cs`) and explicitly linked production seams under `LangVersion 9.0` for `net48` + `net10.0` compatibility. ## Active contract manifest | Contract | Stable boundaries | Discovered cases | |---|---|---:| -| `Contracts/StorytellerIncidentPolicyContracts.cs` | response parsing, real incident selector guards and bounded parameters, faction/strategy hints, pawn lookup, notification policy | 8 | -| `Contracts/StorytellerRequestContextContracts.cs` | context scoping/composition, tension math, request state | 1 | +| `Contracts/StorytellerCoreAdoptionContracts.cs` | L0 prompt ownership, `IncidentOutput` schema registration, `RimMindChatWindowBase` adoption, `Map_PlayerHome` fallback guard, `FallbackProfile` policy, `CancelCurrent`, zero raw `.Translate()` | 5 | +| `Contracts/StorytellerIncidentPolicyContracts.cs` | response parsing, real incident selector guards and bounded parameters, undefeated hostile faction lookup, strategy hints, notification policy | 8 | +| `Contracts/StorytellerQueueIdentityContracts.cs` | distinct `RequestModId` vs `ChatModId` non-collision with `StorytellerModCooldown` / `QueueCircuitBreaker` | 1 | +| `Contracts/StorytellerRequestContextContracts.cs` | context scoping/composition, `DifficultyDef.LabelCap` context builder, tension math, request state | 1 | | `Contracts/StorytellerSaveErrorContracts.cs` | persistence codec, malformed-load normalization, request failure isolation | 1 | -| `Contracts/StorytellerWorldProviderContracts.cs` | five registered provider callbacks for map/fallback NPC identities with PawnId=0, plus foreign-scenario isolation | 10 | +| `Contracts/StorytellerWorldProviderContracts.cs` | registered provider callbacks for map/fallback NPC identities with `PawnId=0`, `MainThreadReader` marshalling, `StorytellerChat` scenario isolation, and foreign-scenario isolation | 11 | -Current discovery count: 20 cases. Across all Storyteller test projects, allow at most 999 discovered cases (less than 1000), counting each parameterized data row. Do not combine unrelated scenarios merely to reduce the count. +Current discovery count: 27 cases. Across all Storyteller test projects, allow at most 999 discovered cases (less than 1000), counting each parameterized data row. Do not combine unrelated scenarios merely to reduce the count. Tests must exercise real behavior, failure boundaries, and module collaboration. Substitutes isolate external dependencies; do not test only mocks, copy production algorithms, or lock private implementation shape. ## Provider and incident coverage -The project links the real `StorytellerContextProviderRegistrar`, `StorytellerContextBuilder`, and `RimMindIncidentSelector`. Provider contracts invoke the callbacks registered by production code, not a separately reconstructed guard. World-backed memory data, translation, Core public services, Def databases, and incident workers are external fixtures. These tests prove routing/content selection and safe incident parameters, not complete RimWorld world loading or provider scheduling. +The project links the real `StorytellerContextProviderRegistrar`, `StorytellerContextBuilder`, `IncidentSelectionPolicy`, and `RimMindIncidentSelector`. Provider contracts invoke the callbacks registered by production code, not a separately reconstructed guard. World-backed memory data, translation, Core public services, Def databases, and incident workers are external fixtures. These tests prove routing/content selection and safe incident parameters, not complete RimWorld world loading or provider scheduling. -The selector returns no incident for malformed input, unknown definitions, or `CanFireNow=false`; valid response metadata is preserved when appropriate. Parameter tests verify clamping before worker validation, hostile-faction lookup, and unknown-strategy fallback. The old bool-to-enum policy truth table and registrar source-order assertions are not used as integration evidence. +The selector returns no incident for malformed input, unknown definitions, or `CanFireNow=false`; valid response metadata is preserved when appropriate. Parameter tests verify clamping before worker validation, undefeated hostile-faction lookup, and unknown-strategy fallback. ## Persistence coverage level -`StorytellerSaveErrorContracts` executes the production persistence codec with a -behavior-capable Scribe recorder. It verifies stable keys/defaults/modes, null -collection recovery, request failure isolation and single-consumption success -state without compiling RimWorld adapters. +`StorytellerSaveErrorContracts` executes the production persistence codec with a behavior-capable Scribe recorder. It verifies stable keys/defaults/modes, null collection recovery, request failure isolation, and single-consumption success state without compiling RimWorld adapters. ## Active project entry and run @@ -40,15 +38,3 @@ dotnet test RimMind-Storyteller/Tests/RimMindStoryteller.Tests.csproj -c Release ``` This is not deployment or in-game verification. - -Legacy compile categories superseded by these contracts are: - -- incident response/parser, incident selector, pawn lookup, and notification tests; -- request envelope, context provider, prompt, tension, and decay tests; -- architecture-direction tests covered by the request/context contract. - -## Retired legacy tests - -Files outside `Contracts/` are retained on disk but excluded from compilation. -Their behavior mapping is recorded in the root contract mapping document. -Deletion requires explicit owner approval for each exact file path; directories are never deleted. diff --git a/Tests/RimMindStoryteller.Tests.csproj b/Tests/RimMindStoryteller.Tests.csproj index 1e40b82..f9fe885 100644 --- a/Tests/RimMindStoryteller.Tests.csproj +++ b/Tests/RimMindStoryteller.Tests.csproj @@ -38,8 +38,6 @@ - - diff --git a/Tests/VerseStubs.cs b/Tests/VerseStubs.cs index 647cffc..ebb622e 100644 --- a/Tests/VerseStubs.cs +++ b/Tests/VerseStubs.cs @@ -125,7 +125,15 @@ public sealed class Difficulty public bool allowIntroThreats = true; public bool allowViolentQuests = true; } - public sealed class Storyteller { public Difficulty difficulty { get; } = new(); } + public sealed class DifficultyDef + { + public string LabelCap = string.Empty; + } + public sealed class Storyteller + { + public Difficulty difficulty { get; } = new(); + public DifficultyDef? difficultyDef { get; set; } + } public sealed class IncidentCategoryDef { public string defName = "ThreatBig"; } public sealed class IncidentDef { @@ -369,8 +377,13 @@ public static class Context { public static string ScenarioStoryteller => RimMind.Application.Common.Models.Context.ScenarioIds.Storyteller; public static TestContextRegistry ContextKeys { get; } = new(); + public static Dictionary RegisteredSchemas { get; } = new(StringComparer.Ordinal); public static void RegisterScenario(ScenarioDescriptor descriptor) => ScenarioRegistry.Register(descriptor); + public static void RegisterSchema(string key, string schema) + => RegisteredSchemas[key] = schema; + public static string? FindSchema(string key) + => RegisteredSchemas.TryGetValue(key, out string? schema) ? schema : null; } public sealed class TestContextRegistry { diff --git a/Textures/Storyteller/RimMindDirector_BackUp.png b/Textures/Storyteller/RimMindDirector_BackUp.png deleted file mode 100644 index 44fbb25..0000000 --- a/Textures/Storyteller/RimMindDirector_BackUp.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:020d775e4c6a502bd96fa2babc83eed6aeacc40bce9998c43fe7a9337609bd49 -size 1010387 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