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 9eb43b0..534ba53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ ## 项目定位 -每日定时(含确定性抖动)或事件触发(受伤/技能/事件/死亡) → ContextEngine(RequestStructured, SchemaRegistry.PersonalityOutput) → AI评估 → `PersonalityThoughtMapper.Apply` 解析 → 写入 `PersonalityProfile`(narrative+identity) → 生成 `Thought_AIPersonality`(最多3槽位) → `MoodOffsetCalculator` 查表影响心情。含玩家塑造投票(强化/抑制/忽略)、AgentIdentity注册、Bio页人格按钮、WorldComponent定期清理无效Profile。 +每日定时(含确定性抖动)、概率状态跃迁或事件触发(受伤/技能/事件/死亡) → `PersonalityRequestBuilder` + `RimMindAPI.Request.Send`(使用自身注册的 `PersonalityOutput` JSON Schema) → AI评估 → `PersonalityThoughtMapper.Apply` 解析 → 写入 `PersonalityProfile`(narrative+identity,线程安全快照) → 生成 `Thought_AIPersonality`(最多3槽位) → `MoodOffsetCalculator` 查表影响心情。含玩家塑造投票(强化/抑制/忽略)、AgentIdentity注册、Bio页人格徽章(`IBioTabBadgeProvider`)、WorldComponent定期清理无效Profile。 依赖: Core(编译期),Personality上下文被Advisor/Dialogue通过Core系统自动消费。翻译自包含(事件触发key已迁入自身语言文件)。 @@ -16,45 +16,50 @@ | 项 | 值 | |----|-----| -| 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 | RimMindPersonality | | Harmony ID | mcocdaa.RimMindPersonality | -| 依赖 | RimMindCore.dll, Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json 13.0 | +| 依赖 | 0_RimMindDomain.dll, 1_RimMindApplication.dll, 2_RimMindCore.dll (`Private=false`), Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json 13.0 | ## 源码结构 ``` Source/ ├── README.md 入口到测试的运行时阅读地图 -├── RimMindPersonalityMod.cs 组合根与设置入口 +├── RimMindPersonalityMod.cs 组合根、Schema注册(`PersonalityOutput`)与Core扩展注册 ├── Personality/ -│ ├── PersonalityProviderRegistrar.cs Context 与 Agent Identity 注册 -│ ├── PersonalityThoughtMapper.cs 核心: AI响应→Thought映射+塑造投票+EvaluationSchema +│ ├── PersonalityProviderRegistrar.cs Context 与 Agent Identity 注册(直接委托 RimMindPawnLookup) +│ ├── PersonalityThoughtMapper.cs 核心: AI响应→Thought映射+塑造投票+PersonalityOutputSchema │ ├── PersonalityResultDto.cs JSON DTO(无RimWorld依赖) │ ├── Thought_AIPersonality.cs 自定义Thought(重写Label/MoodOffset/DurationTicks) │ ├── MoodOffsetCalculator.cs 强度→心情偏移查表(-3~+3) │ ├── ShapingAction.cs 塑造投票枚举(替代字符串魔法值) -│ ├── PersonalityRequestBuilder.cs 共享请求信封构建器 +│ ├── PersonalityRequestBuilder.cs 共享请求信封构建器(含CoalesceKey与TTL) +│ ├── PersonalityRequestDefaults.cs 共享ModId/Token/温度常量 │ ├── PersonalityContextScenarioPolicy.cs 人格上下文消费场景策略 │ ├── PersonalityContextText.cs 人格上下文格式化与截取纯函数 -│ └── PawnResolver.cs 共享Pawn查找辅助(按thingIDNumber) +│ ├── PersonalityThoughtPolicy.cs 槽位投影/时长裁剪/响应解析纯策略 +│ ├── PersonalityThoughtPersistence.cs Thought持久化辅助 +│ └── PersonalityTriggerPolicy.cs 纯触发判定策略(含ShouldTriggerDailyEvaluation) +├── Extensions/ Core扩展适配器(ActionSkipCheck/ModCooldown/SettingsTab/ToggleBehavior) ├── Settings/ -│ ├── AIPersonalitySettings.cs 17项设置(含4项时间参数) -│ └── PersonalitySettingsDrawer.cs 原生/Core设置页共享绘制实现 +│ ├── AIPersonalitySettings.cs 25项持久化设置(含概率状态跃迁与时间参数) +│ └── PersonalitySettingsDrawer.cs 原生/Core设置页共享绘制实现(委托 SettingsUIDrawer) ├── Data/ -│ ├── PersonalityProfile.cs 人格档案(IExposable) + AIPersonalityWorldComponent(含定期清理) +│ ├── PersonalityProfile.cs AIPersonalityWorldComponent(含定期清理与WorldScopedComponentCache) +│ ├── PersonalityProfileState.cs 线程安全人格档案(IExposable, `_sync` 锁 + 快照方法) │ └── ShapingRecord.cs 玩家塑造记录 -├── Comps/CompAIPersonality.cs ThingComp(Tick触发/事件触发/TriggerEventType枚举) +├── Comps/CompAIPersonality.cs ThingComp(Tick触发/事件触发/请求代际防陈旧回调) ├── UI/BioTabPersonalityPatch.cs + Dialog_PersonalityProfile.cs ├── Patches/ │ ├── AddCompToHumanlikePatch.cs ThingDef.ResolveReferences Postfix注入Comp -│ ├── Patch_PersonalityInjury.cs HediffSet.AddDirect Postfix(isBad+Severity>=0.2f+IsFreeNonSlaveColonist过滤) +│ ├── Patch_PersonalityInjury.cs HediffSet.AddDirect Postfix(isBad+Severity>=0.2f+IsEligible过滤) │ ├── Patch_PersonalityDeath.cs Pawn.Kill Postfix(检查DirectRelations) -│ ├── Patch_PersonalityIncident.cs IncidentWorker.TryExecuteWorker Postfix(ThreatBig/ThreatSmall过滤) +│ ├── Patch_PersonalityIncident.cs IncidentWorker.TryExecute Postfix(ThreatBig/ThreatSmall过滤) │ ├── Patch_PersonalitySkill.cs SkillRecord.Learn Prefix+Postfix(Harmony out int __state 捕获升级前等级 + __instance.Pawn) │ └── PersonalityTriggerHelper.cs 共享Patch触发辅助(TriggerForPawn/TriggerForColonists) -└── Debug/PersonalityDebugActions.cs 8个Debug动作 +└── Debug/PersonalityDebugActions.cs + PersonalityBehaviorAutotestSuite.cs ``` ## 触发机制 @@ -121,8 +126,8 @@ identity?: {motivations[], traits[], core_values[]} - `_compat1` 字段仅消费旧存档 `rimTalkSynced` key,值不使用 - ShapingAction 枚举替代 "reinforce"/"suppress"/"ignored" 字符串魔法值 - PersonalityRequestBuilder 统一 CompAIPersonality 和 DebugActions 的请求构建 -- PawnResolver 统一 3 个 ContextProvider 的 Pawn 查找逻辑 -- PersonalityContextScenarioPolicy 统一人格状态在 Personality / Decision / Dialogue 三类场景的注入边界 +- ContextProvider 直接使用 Core 公共 `RimMindPawnLookup.FindPawnByNumber` 与 `IsActiveSpawnedColonist` 查找并校验 Pawn +- PersonalityContextScenarioPolicy 统一人格状态在 Personality / Decision / Dialogue(含 `agent_decision`/`advisor_decision`/`CrisisDialogue`)场景的注入边界 - PersonalityTriggerHelper 统一 4 个 Patch 的 "查Comp→TriggerEvent" 模式 ## 操作边界 diff --git a/About/About.xml b/About/About.xml index 3b2b83a..7b789c9 100644 --- a/About/About.xml +++ b/About/About.xml @@ -9,13 +9,13 @@
  • 1.7
  • [h1]RimMind - Personality (v2.0)[/h1] -Big-Five psychological profiling and probabilistic state-transition reflection system for RimWorld colonists. Endows every colonist with a persistent inner world, generating dynamic personality Thoughts and introspective soliloquies that influence mood, behavior, and advisor decisions. +LLM-driven psychological profiling and probabilistic state-transition reflection system for RimWorld colonists. Endows every colonist with a persistent inner narrative and evolving agent identity, generating up to 3 dynamic personality Thoughts that influence mood, behavior, and advisor decisions. [b]v2.0 Clean Architecture & RimWorld 1.6 / 1.7 Dual-Version Support:[/b] [list] [*][b]RimWorld 1.6 & 1.7 (Waylith / .NET 10) Ready[/b]: Native multi-target compilation supporting both RimWorld 1.6 (.NET Framework 4.8) and RimWorld 1.7 (.NET 10 / Harmony 2.x & 3.x). -[*][b]v2.0 Big-Five Psychometric & Probabilistic State Engine[/b]: Replaces rigid timers with organic environmental triggers (06:00 Dawn Sunrise, Skygazing, Shared Recreation, Traumatic Mood Swings). Note: v1.x saves are not compatible with v2.0. -[*][b]Loose-Coupled Thought Event Bus[/b]: Broadcasts psychological shifts to [code]RimMind-Advisor[/code] and [code]RimMind-Core[/code] Zone 2 context without direct cross-mod coupling. +[*][b]v2.0 LLM Psychological Profiles & Probabilistic State Engine[/b]: Combines organic environmental state-transition triggers (06:00 Dawn Sunrise, Skygazing, Shared Recreation, Traumatic Mood Swings) with event triggers and staggered daily evaluations. Note: v1.x saves are not compatible with v2.0. +[*][b]Loose-Coupled Thought & Identity Bus[/b]: Broadcasts psychological narratives, traits/motivations/values, and Thoughts to [code]RimMind-Advisor[/code], [code]RimMind-Dialogue[/code], and [code]RimMind-Core[/code] context providers without direct cross-mod coupling. [/list] [h2]What Is RimMind[/h2] @@ -29,7 +29,7 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [tr][td]RimMind-Advisor[/td][td]Colonist self-reflective advice cards, 5-domain autonomy & player approval[/td][td]Core, Actions[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Advisor]Link[/url][/td][/tr] [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][b]RimMind-Personality[/b][/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-Personality[/b][/td][td]LLM psychological profiles, state-transition reflections & dynamic mood thoughts[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality]Link[/url][/td][/tr] [tr][td]RimMind-Storyteller[/td][td]AI Story Director, dramatic tension curve, chained arcs & Storyteller Altar[/td][td]Core, Memory[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Storyteller]Link[/url][/td][/tr] [tr][td]RimMind-Extension-ModelService[/td][td]Multi-provider routing, Anthropic KV cache, local gateways & load balancing[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Extension-ModelService]Link[/url][/td][/tr] [tr][td]RimMind-Bridge-RimChat[/td][td]RimChat compatibility bridge: dialogue/action mutual exclusion & context sync[/td][td]Core, RimChat[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimChat]Link[/url][/td][/tr] @@ -45,7 +45,7 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [h2]Core Features[/h2] [list] -[*][b]Big-Five Cognitive Profiling[/b] - Maps vanilla RimWorld traits (e.g., Bloodlust, Optimist, Neurotic) onto continuous psychometric axes ([i]Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism[/i]). +[*][b]LLM Psychological Profiles & Agent Identity[/b] - Builds a persistent narrative profile, work/social tendencies, and structured [code]AgentIdentity[/code] (motivations, traits, core values) grounded in each colonist's RimWorld traits and lived colony history. [*][b]Probabilistic State-Transition Reflections[/b] - Colonists reflect naturally during 06:00 Dawn Sunrise (30% chance), Skygazing/Solitude (40% chance), Shared Recreation (25% chance), and Traumatic Mood Swings (50% chance). [*][b]Dynamic Mood Thought Injection[/b] - Generates 1 to 3 contextual Personality Thoughts (intensity -3 to +3, mapping to -10 to +10 mood offset) injected into independent mood slots without overwriting one another. [*][b]Bio Personality Tab & Player Editing[/b] - View AI psychological narratives directly in the pawn Bio tab, customize personality descriptions, work preferences, and social tendencies, and use [b]Shape Voting[/b] to guide future AI evaluations. diff --git a/INTRODUCTION.txt b/INTRODUCTION.txt deleted file mode 100644 index ac949f5..0000000 --- a/INTRODUCTION.txt +++ /dev/null @@ -1,79 +0,0 @@ -[h1]RimMind - Personality[/h1] -让殖民者拥有内心世界。 -[h1]RimMind - Personality (动态人格与心流)[/h1] - -[h2] 他们不只是数据 [/h2] -RimWorld 的殖民者有背景、有技能、有特质——但他们没有[b]真正的情绪[/b]。受伤了不会沮丧,交到朋友不会开心,日复一日挖矿也不会厌倦。 -[i]让每个小人都拥有独特的内心世界——大五人格、情绪波澜与动态性格塑造。[/i] -[i]Give your colonists complex inner lives — Big Five profiles, situational thoughts, and character growth.[/i] - -RimMind-Personality 改变了这一点。AI 会审视每个殖民者的处境,生成[b]只有这个人在这个时刻才会有的想法[/b]。长期卧床的殖民者可能"对康复失去信心";刚交到朋友的殖民者可能"对新伙伴充满期待"。AI 阅读了殖民者的完整状态后,给出真正符合情境的心理反应。 -[hr] -[h2]📖 中文介绍 / Chinese Overview[/h2] - -[h2] 事情发生时,他们会反应 [/h2] -殖民者不只是每天被评估一次。当[b]真正重要的事情发生[/b]时,AI 会立即介入: -[b]RimMind-Personality[/b] 让殖民者告别同质化的数据白板。AI 会依据小人的原生特质、过往经历与处境,推导出立体的大五人格模型,并在面临突发事件时触发真正有血有肉的心态变化。 - -[h3]🌟 核心特性[/h3] -[list] -[*] [b]受伤或患病[/b] — 恐惧、痛苦、或者咬牙坚持 -[*] [b]技能突破[/b] — 自豪、新的志向、或者压力 -[*] [b]袭击来袭[/b] — 恐慌、勇气、或者绝望 -[*] [b]亲近者死亡[/b] — 悲痛,这是最强烈的心理冲击 -[*] [b]真实大五人格画像[/b]:为每个殖民者建立开放性、尽责性、外向性、宜人性与神经质等多维性格剖析。 -[*] [b]状态跃迁心理感知[/b]:在负伤、重病、丧友、仰望星空、技能突破或心情急跌时,智能投骰触发符合当事人性格的独创心理 Thought。 -[*] [b]心境直接驱动游戏数值[/b]:AI 生成的想法直接提供正向或负向心情加成,切实影响精神崩溃风险与工作效率。 -[*] [b]性格塑造投票机制 (Trait Shaping)[/b]:当 AI 提议新的性格特质演进时,玩家可选择“强化”、“抑制”或“顺其自然”,陪伴殖民者共同成长。 -[*] [b]殖民者人格卡片[/b]:在小人面板中清晰查阅 AI 生成的心态总结与工作/社交倾向。 -[/list] - -每种触发都可以独立开关。你可以只保留每日评估,也可以全部开启,让殖民者对每一个重要时刻都有心理反应。 -[hr] -[h2]🌐 English Overview[/h2] - -[h2] 心情真的会变 [/h2] -AI 生成的心理状态[b]直接影响心情值[/b]。经历了袭击、失去了朋友的殖民者,心情会真的跌入谷底。这不是装饰——它会[b]影响你的游戏决策[/b]。心情低落的殖民者精神崩溃风险更高,你需要认真对待他们的心理状态。 -[b]RimMind-Personality[/b] gives your colonists intricate psychological depth. Powered by the Big Five personality framework, pawns react emotionally and intellectually to triumphs, crises, and everyday life in the rim. - -[h2] 你可以塑造他们的人格 [/h2] -AI 提出新的人格特质时,你可以投票:[b]强化[/b]让特质更根深蒂固,[b]抑制[/b]让殖民者逐渐摆脱,[b]忽略[/b]则不干预。你的投票历史会被 AI 记住,久而久之生成更符合你期望的人格发展。 -[h3]🌟 Key Highlights[/h3] -[list] -[*] [b]Deep Personality Profiles[/b]: Generates nuanced Big Five psychological profiles based on traits, backstories, and environment. -[*] [b]State Transition Thought Generation[/b]: Triggered dynamically during injuries, losses, skill milestones, or dramatic mood swings to yield highly personalized thoughts. -[*] [b]Direct Gameplay Mood Impacts[/b]: Custom thoughts actively influence colonist mood meters and mental break thresholds. -[*] [b]Character Shaping & Voting[/b]: Guide your colonists' growth when new traits emerge by reinforcing or suppressing them. -[*] [b]Dedicated Personality Dossier[/b]: Inspect pawns' core values, motivations, and behavioral tendencies directly from their bio tab. -[/list] - -你也可以直接编辑每个殖民者的人格描述、工作倾向和社交倾向——就像给演员一份角色设定,AI 评估时会参考你写的内容。 - -[h2] 每个殖民者都是独特的 [/h2] -打开殖民者的"人格"面板,你会看到 AI 为他们生成的心理画像:AI 叙事描述近期心理变化,人格描述和工作/社交倾向由你编辑。AI 还会提取殖民者的动机、特质和价值观,形成完整的身份画像,被 RimMind 套件中的其他模块使用。 - -[h2] 配合其他 RimMind 模组效果更佳 [/h2] -[b]+ Memory[/b] — 殖民者记住过去的经历,人格评估更有深度 -[b]+ Advisor[/b] — AI 顾问参考人格档案做出更符合角色的决策 -[b]+ Dialogue[/b] — 对话风格受人格影响,内向者和外向者说话方式不同 - -[h2] 灵活可调 [/h2] -[hr] -[h2]⚙️ 依赖与推荐 / Requirements & Recommendations[/h2] -[list] -[*] 每种触发方式独立开关(每日/受伤/技能/事件/死亡) -[*] Thought 持续时长:AI 根据情境决定,或统一固定时长 -[*] 塑造投票:开启/关闭,自定义过期时间和历史保留数量 -[*] 通知和标签前缀:按你的喜好调整显示方式 -[*] [b]必需前置 (Required)[/b]: Harmony, [b]RimMind-Core[/b] -[*] [b]推荐搭配 (Recommended)[/b]: [b]RimMind-Memory[/b]、[b]RimMind-Dialogue[/b]、[b]RimMind-Advisor[/b] -[/list] - -[h2] 快速开始 [/h2] -1. 安装 [url=https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077]Harmony[/url] 和 RimMind-Core -2. 安装 RimMind-Personality -3. 在模组设置中填写 API Key(支持 OpenAI 兼容接口:DeepSeek、Ollama 等) -4. 进入游戏,选择殖民者,打开 Bio 页面点击"人格"按钮 -5. 等待 AI 自动评估,或使用 Dev 菜单强制触发 - -[b]让殖民者活过来。[/b] diff --git a/Languages/ChineseSimplified/Keyed/RimMind_Personality.xml b/Languages/ChineseSimplified/Keyed/RimMind_Personality.xml index 87b1ffd..a2c122f 100644 --- a/Languages/ChineseSimplified/Keyed/RimMind_Personality.xml +++ b/Languages/ChineseSimplified/Keyed/RimMind_Personality.xml @@ -12,10 +12,9 @@ Thought 持续时长: 设置 AI 生成的心理状态(Thought)的持续时间模式。 由 AI 决定每个 Thought 的时长 - 开启后,AI 会在 JSON 中输出 duration_hours 字段,根据情绪强度自动设定持续时间。 + 开启后,AI 会在 JSON 中输出 duration_hours(1~24)字段,根据情绪强度自动设定持续时间。 固定时长:{0} 游戏小时 所有 AI 生成的 Thought 统一使用此固定时长。 - AI 在 JSON 中输出 duration_hours(1~24),自动应用 触发来源 每日评估 每天自动对殖民者进行人格评估,生成心理状态。 @@ -79,6 +78,7 @@ 关闭后续的人格塑造投票弹窗(可在人格设置或角色人格档案窗口中重新开启)。 [玩家塑造历史] + [RimMind 塑造] 强化 抑制 忽略 diff --git a/Languages/English/Keyed/RimMind_Personality.xml b/Languages/English/Keyed/RimMind_Personality.xml index 5b6b183..b78c866 100644 --- a/Languages/English/Keyed/RimMind_Personality.xml +++ b/Languages/English/Keyed/RimMind_Personality.xml @@ -12,10 +12,9 @@ Thought duration: Set the duration mode for AI-generated psychological states (Thoughts). Let AI decide each Thought's duration - When enabled, AI outputs a duration_hours field in JSON, automatically setting duration based on emotional intensity. + When enabled, AI outputs duration_hours (1~24) in JSON, automatically setting duration based on emotional intensity. Fixed duration: {0} game hours All AI-generated Thoughts use this fixed duration uniformly. - AI outputs duration_hours (1~24) in JSON, applied automatically Trigger Sources Daily Evaluation Automatically evaluate colonist personality each day, generating psychological states. @@ -79,6 +78,7 @@ Disable future personality shaping vote popups (can be re-enabled in Personality settings or the colonist's Personality window). [Player Shaping History] + [RimMind Shaping] Reinforce Suppress Ignore diff --git a/Patches/AddAIPersonalityComp.xml b/Patches/AddAIPersonalityComp.xml deleted file mode 100644 index 13e6db9..0000000 --- a/Patches/AddAIPersonalityComp.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - diff --git a/README.md b/README.md index fca8e5e..70140c5 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,18 @@
    # RimMind-Personality 🎭 -### Big-Five Psychological Profiles & Probabilistic State-Transition Reflection for RimWorld 1.6 & 1.7 +### LLM Psychological Profiles, Dynamic Mood Thoughts & Probabilistic Reflections for RimWorld 1.6 & 1.7 **English** | [简体中文](README_zh.md)

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

    -

    Infuse colonists with multidimensional psychological depth, dawn soliloquies, and organic mood reflections.

    +

    Infuse colonists with persistent inner narratives, evolving agent identities, and organic mood reflections.

    @@ -20,16 +20,16 @@ ## 📖 Overview -**RimMind-Personality** models colonists with nuanced Big-Five personality dimensions (Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism). Instead of rigid timer loops, personality reflections occur dynamically through **probabilistic state transitions**. +**RimMind-Personality** builds a persistent LLM-driven psychological profile and structured `AgentIdentity` (motivations, traits, core values) for every colonist. Combining **probabilistic state-transition triggers**, major life events, and staggered daily evaluations, colonists continuously interpret their colony life and materialize 1 to 3 dynamic mood Thoughts. ### Key Highlights -- **Big-Five Cognitive Profiling**: Maps vanilla RimWorld traits (e.g., Bloodlust, Slothful, Optimist) onto continuous psychometric axes, guiding tone and decision rationale. -- **Probabilistic State-Transition Engine**: Colonists reflect on life during meaningful environmental moments: - - 🌅 **Sunrise (06:00 Dawn)**: Morning reflection as daylight returns (chance: 30%). - - 🌌 **Skygazing / Solitude**: Philosophical or poetic musings (chance: 40%). - - 🍷 **Shared Recreation**: Social warmth or witty cynicism (chance: 25%). - - 💔 **Traumatic Mood Swings**: Severe mental break risks trigger desperate internal rationales (chance: 50%). -- **Thought Injection**: AI-generated psychological reflections manifest directly as RimWorld `ThoughtDef` entries, influencing mood and mental break thresholds. +- **Persistent Psychological Profiles & Agent Identity**: Synthesizes an evolving AI narrative plus structured motivations, traits, and core values grounded in each colonist's vanilla traits, memories, and player customizations in the Bio tab. +- **Probabilistic State-Transition & Event Triggers**: Colonists reflect organically during meaningful moments: + - 🌅 **Sunrise (06:00 Dawn)**: Morning reflection as daylight returns (default chance: 30%). + - 🌌 **Skygazing / Solitude**: Quiet philosophical or introspective musings (default chance: 40%). + - 🍷 **Shared Recreation**: Reflections sparked during leisure activities (default chance: 25%). + - 💔 **Traumatic Mood Swings & Colony Events**: Sharp mood shifts (default chance: 50%), severe injuries, skill milestones, major threat incidents, and companion bereavement. +- **3-Slot Dynamic Thought Injection & Shape Voting**: Injects up to 3 independent `Thought_AIPersonality` entries (intensity `-3..+3`, mood offset `-10..+10`) and lets players reinforce, suppress, or edit personality traits via Bio tab Shape Voting. --- diff --git a/README_zh.md b/README_zh.md index 0453008..fd77802 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,18 +1,18 @@
    # RimMind-Personality 🎭 -### 专为 RimWorld 1.6 & 1.7 打造的大五人格特质画像、概率状态跃迁与心境反思系统 +### 专为 RimWorld 1.6 & 1.7 打造的 LLM 心理档案、动态心境 Thought 与概率反思系统 [English](README.md) | **简体中文**

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

    -

    为殖民者注入多维心理深度、晨曦哲学独白与自然随境而生的心境波动。

    +

    为殖民者赋予持续演化的内在心理档案、智能体身份画像与随境而生的动态心情 Thought。

    @@ -20,16 +20,16 @@ ## 📖 模块概览 -**RimMind-Personality** 通过大五人格心理学模型(开放性、尽责性、外向性、宜人性、神经质)对殖民者进行立体刻画。它彻底摒弃死板机械的定时器轮询,通过**基于概率的状态跃迁触发体系**让小人在富有意义的环境情境下自然反思。 +**RimMind-Personality** 为每位殖民者构建由大模型驱动的持久化心理档案与结构化 `AgentIdentity`(动机、特质与核心价值观)。它结合**基于概率的状态跃迁触发**、重大人生事件与每日交错评估,让小人持续消化殖民地经历并生成 1 至 3 条动态心境 Thought。 ### 核心特性 -- **立体大五人格画像**:将原版特质(嗜血、懒惰、乐天派等)映射为平滑的心理测量维度,决定其心理潜台词与行动逻辑。 -- **概率状态跃迁引擎**:在自然情境发生时机投骰感知: - - 🌅 **破晓晨曦 (06:00)**:清晨微光洒下时的内心独白(概率 30%)。 - - 🌌 **仰望星空 / 独处**:户外看天或漫步时的哲学与诗意遐思(概率 40%)。 - - 🍷 **娱乐聚会**:与同伴共处时的风趣幽默或冷峻审视(概率 25%)。 - - 💔 **心态剧变**:面临严重精神崩溃边缘时的绝望反思或心理自救(概率 50%)。 -- **心理 Thought 注入**:AI 生成的心理反思直接转化为 RimWorld 的原生 `ThoughtDef`,实质影响小人的心情与精神崩溃阈值。 +- **持久化心理档案与智能体身份**:结合原版特质、殖民地记忆与玩家在 Bio 页的自定义设定,持续演化 AI 心理叙事与动机/特质/价值观画像。 +- **概率状态跃迁与事件触发体系**:在富有意义的自然情境与重大变故时触发反思: + - 🌅 **破晓晨曦 (06:00)**:清晨微光洒下时的内心独白(默认概率 30%)。 + - 🌌 **仰望星空 / 独处**:户外看天或静思时的哲学与诗意遐思(默认概率 40%)。 + - 🍷 **娱乐休憩**:休闲活动中的心境流露(默认概率 25%)。 + - 💔 **心态剧变与重大事件**:剧烈情绪波动(默认概率 50%)、严重负伤、技能突破、重大威胁袭击与挚友离世。 +- **三槽位动态 Thought 与玩家塑造投票**:最多独立注入 3 个 `Thought_AIPersonality` 槽位(强度 `-3..+3`,映射 `-10..+10` 心情偏移),支持在 Bio 页通过塑造投票强化或抑制 AI 性格判断。 --- diff --git a/Source/Comps/CompAIPersonality.cs b/Source/Comps/CompAIPersonality.cs index 4bb2d9e..e4c13ef 100644 --- a/Source/Comps/CompAIPersonality.cs +++ b/Source/Comps/CompAIPersonality.cs @@ -2,7 +2,6 @@ using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; using RimWorld; -using UnityEngine; using Verse; namespace RimMind.Personality.Comps @@ -18,11 +17,11 @@ public CompProperties_AIPersonality() public class CompAIPersonality : ThingComp { private bool _hasPendingRequest; + private int _requestGeneration; private int _lastEventTick = -1200; private int _lastDailyDecayTick = -1; private int _pendingRequestTick; private string? _pendingEventContext; - private int _dailyJitter = -1; private string? _cachedThingId; private int _cachedThingIdNumber = -1; @@ -32,7 +31,6 @@ public class CompAIPersonality : ThingComp private bool _wasAwake = true; private Pawn? PawnOrNull => parent as Pawn; - private Pawn? Pawn => parent as Pawn; private AIPersonalitySettings Settings => RimMindPersonalityMod.Settings; private int GetDailyJitter() @@ -65,8 +63,10 @@ public override void CompTick() { if (Find.TickManager.TicksGame - _pendingRequestTick > Settings.requestTimeoutTicks) { - RimMindErrors.Warn($"[RimMind-Personality] Pending request timeout for {pawn.Name.ToStringShort}, resetting."); + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; + RimMindErrors.Warn($"[RimMind-Personality] Pending request timeout for {pawnName}, resetting."); _hasPendingRequest = false; + _requestGeneration++; } else { @@ -85,9 +85,15 @@ public override void CompTick() _lastDailyDecayTick = ticksGame; } - bool cooldownExpired = (ticksGame - _lastEventTick) >= Settings.eventCooldownTicks; - int dailyInterval = System.Math.Max(60, Settings.dailyIntervalTicks + GetDailyJitter()); - bool dailyFire = Settings.enableDailyEval && pawn.Awake() && (ticksGame - _lastDailyDecayTick >= 60000 || ticksGame - _lastDailyDecayTick >= dailyInterval); + int effectiveCooldown = RimMindAPI.Settings.ScaleCooldown(Settings.eventCooldownTicks); + bool cooldownExpired = (ticksGame - _lastEventTick) >= effectiveCooldown; + bool dailyFire = PersonalityTriggerPolicy.ShouldTriggerDailyEvaluation( + Settings.enableDailyEval, + pawn.Awake(), + ticksGame, + _lastDailyDecayTick, + Settings.dailyIntervalTicks, + GetDailyJitter()); bool eventFire = _pendingEventContext != null && cooldownExpired; if (!dailyFire && !eventFire) return; @@ -101,6 +107,7 @@ public override void CompTick() } _hasPendingRequest = true; _pendingRequestTick = ticksGame; + int requestGen = ++_requestGeneration; if (!string.IsNullOrEmpty(eventCtx)) { @@ -114,6 +121,7 @@ public override void CompTick() RimMindAPI.Request.Send(envelope, result => { + if (requestGen != _requestGeneration) return; _hasPendingRequest = false; PersonalityThoughtMapper.Apply(result, pawn); }); @@ -289,7 +297,8 @@ public override void PostExposeData() base.PostExposeData(); Scribe_Values.Look(ref _lastEventTick, "lastEventTick", -1200); Scribe_Values.Look(ref _lastDailyDecayTick, "lastDailyDecayTick", -1); - Scribe_Values.Look(ref _dailyJitter, "dailyJitter", -1); + int legacyDailyJitter = -1; + Scribe_Values.Look(ref legacyDailyJitter, "dailyJitter", -1); Scribe_Values.Look(ref _lastHour, "lastHour", -1); Scribe_Values.Look(ref _lastJobDefName, "lastJobDefName", null); Scribe_Values.Look(ref _lastMood, "lastMood", -1f); diff --git a/Source/Data/PersonalityProfile.cs b/Source/Data/PersonalityProfile.cs index a506c11..28764d7 100644 --- a/Source/Data/PersonalityProfile.cs +++ b/Source/Data/PersonalityProfile.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using RimMind.Presentation.Api; -using RimWorld; using RimWorld.Planet; using Verse; diff --git a/Source/Data/PersonalityProfileState.cs b/Source/Data/PersonalityProfileState.cs index fdf7ec0..2e7b771 100644 --- a/Source/Data/PersonalityProfileState.cs +++ b/Source/Data/PersonalityProfileState.cs @@ -10,6 +10,8 @@ namespace RimMind.Personality.Data /// public class PersonalityProfile : IExposable { + private readonly object _sync = new object(); + public string description = string.Empty; public string workTendencies = string.Empty; public string socialTendencies = string.Empty; @@ -22,11 +24,49 @@ public void AddShapingRecord(ShapingRecord record, int maxCount) { if (record == null) throw new ArgumentNullException(nameof(record)); - playerShapingHistory ??= new List(); - playerShapingHistory.Add(record); - int effectiveMax = Math.Max(maxCount, 1); - if (playerShapingHistory.Count > effectiveMax) - playerShapingHistory.RemoveRange(0, playerShapingHistory.Count - effectiveMax); + lock (_sync) + { + playerShapingHistory ??= new List(); + playerShapingHistory.Add(record); + int effectiveMax = Math.Max(maxCount, 1); + if (playerShapingHistory.Count > effectiveMax) + playerShapingHistory.RemoveRange(0, playerShapingHistory.Count - effectiveMax); + } + } + + public bool RemoveShapingRecord(ShapingRecord record) + { + if (record == null) return false; + lock (_sync) + { + return playerShapingHistory != null && playerShapingHistory.Remove(record); + } + } + + public ShapingRecord[] GetShapingHistorySnapshot() + { + lock (_sync) + { + return playerShapingHistory == null || playerShapingHistory.Count == 0 + ? Array.Empty() + : playerShapingHistory.ToArray(); + } + } + + public AgentIdentity? GetAgentIdentitySnapshot() + { + lock (_sync) + { + return agentIdentity; + } + } + + public void SetAgentIdentity(AgentIdentity identity) + { + lock (_sync) + { + agentIdentity = identity; + } } public bool IsEmpty => @@ -37,21 +77,24 @@ public void AddShapingRecord(ShapingRecord record, int maxCount) public void ExposeData() { + lock (_sync) + { #pragma warning disable CS8601 - Scribe_Values.Look(ref description, "description", string.Empty); - Scribe_Values.Look(ref workTendencies, "workTendencies", string.Empty); - Scribe_Values.Look(ref socialTendencies, "socialTendencies", string.Empty); - Scribe_Values.Look(ref aiNarrative, "aiNarrative", string.Empty); + Scribe_Values.Look(ref description, "description", string.Empty); + Scribe_Values.Look(ref workTendencies, "workTendencies", string.Empty); + Scribe_Values.Look(ref socialTendencies, "socialTendencies", string.Empty); + Scribe_Values.Look(ref aiNarrative, "aiNarrative", string.Empty); #pragma warning restore CS8601 - Scribe_Values.Look(ref lastNarrativeUpdateTick, "lastNarrativeUpdateTick"); + Scribe_Values.Look(ref lastNarrativeUpdateTick, "lastNarrativeUpdateTick"); - bool legacyRimTalkSynced = false; - Scribe_Values.Look(ref legacyRimTalkSynced, "rimTalkSynced"); + bool legacyRimTalkSynced = false; + Scribe_Values.Look(ref legacyRimTalkSynced, "rimTalkSynced"); - Scribe_Collections.Look(ref playerShapingHistory, "playerShapingHistory", LookMode.Deep); - playerShapingHistory ??= new List(); - Scribe_Deep.Look(ref agentIdentity, "agentIdentity"); - agentIdentity ??= new AgentIdentity(); + Scribe_Collections.Look(ref playerShapingHistory, "playerShapingHistory", LookMode.Deep); + playerShapingHistory ??= new List(); + Scribe_Deep.Look(ref agentIdentity, "agentIdentity"); + agentIdentity ??= new AgentIdentity(); + } } } diff --git a/Source/Debug/PersonalityBehaviorAutotestSuite.cs b/Source/Debug/PersonalityBehaviorAutotestSuite.cs index 3fd5b17..2d08502 100644 --- a/Source/Debug/PersonalityBehaviorAutotestSuite.cs +++ b/Source/Debug/PersonalityBehaviorAutotestSuite.cs @@ -4,7 +4,6 @@ using RimMind.Personality.Comps; using RimMind.Personality.Data; using RimMind.Presentation.Api; -using RimWorld; using Verse; namespace RimMind.Personality.Debug @@ -26,9 +25,10 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) Pawn? pawn = context.ActiveColonist; // 1. CompAIPersonality Attachment - if (context.CurrentMap?.mapPawns?.FreeColonists != null && context.CurrentMap.mapPawns.FreeColonists.Count > 0) + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(context.CurrentMap); + if (colonists.Count > 0) { - bool anyAttached = context.CurrentMap.mapPawns.FreeColonists.Any(p => p.GetComp() != null); + bool anyAttached = colonists.Any(p => p.GetComp() != null); context.Assert(anyAttached, "Free colonists on map have CompAIPersonality attached"); } else if (pawn != null) @@ -45,7 +45,7 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) try { var profile = worldComp.GetOrCreate(pawn); - context.Assert(profile != null, $"PersonalityProfile retrieved/created for {pawn.Name.ToStringShort}"); + context.Assert(profile != null, $"PersonalityProfile retrieved/created for {pawn.Name?.ToStringShort ?? pawn.LabelShort}"); if (profile != null) { @@ -56,15 +56,16 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) label = "Verified shaping history addition" }; - int countBefore = profile.playerShapingHistory.Count; + int countBefore = profile.GetShapingHistorySnapshot().Length; profile.AddShapingRecord(record, 20); + var afterAdd = profile.GetShapingHistorySnapshot(); - context.Assert(profile.playerShapingHistory.Count == countBefore + 1, "ShapingRecord appended successfully to playerShapingHistory"); - context.Assert(profile.playerShapingHistory.Last().action == "autotest_shaping", "Latest shaping record matches autotest action"); + context.Assert(afterAdd.Length == countBefore + 1, "ShapingRecord appended successfully to playerShapingHistory"); + context.Assert(afterAdd.Last().action == "autotest_shaping", "Latest shaping record matches autotest action"); // Self-cleanup - profile.playerShapingHistory.Remove(record); - context.Assert(profile.playerShapingHistory.Count == countBefore, "Test shaping record cleaned up cleanly"); + profile.RemoveShapingRecord(record); + context.Assert(profile.GetShapingHistorySnapshot().Length == countBefore, "Test shaping record cleaned up cleanly"); } } catch (Exception ex) diff --git a/Source/Debug/PersonalityDebugActions.cs b/Source/Debug/PersonalityDebugActions.cs index c511a5f..26ac75d 100644 --- a/Source/Debug/PersonalityDebugActions.cs +++ b/Source/Debug/PersonalityDebugActions.cs @@ -1,12 +1,8 @@ using LudeonTK; -using RimMind.Application.Features.Llm; -using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; -using RimMind.Application.Common.Models.Context; using RimMind.Personality.Comps; using RimMind.Personality.Data; -using RimWorld; using System; using System.Text; using Verse; @@ -16,6 +12,8 @@ namespace RimMind.Personality.Debug [StaticConstructorOnStartup] public static class PersonalityDebugActions { + private static string PawnName(Pawn pawn) => pawn.Name?.ToStringShort ?? pawn.LabelShort; + [DebugAction("RimMind Personality", "Force Evaluate Selected Pawn", actionType = DebugActionType.Action)] public static void ForceEvaluateSelected() @@ -29,7 +27,7 @@ public static void ForceEvaluateSelected() if (pawn.GetComp() == null) { - RimMindErrors.Warn($"[RimMind-Personality] {pawn.Name.ToStringShort} has no CompAIPersonality (non-humanlike?)."); + RimMindErrors.Warn($"[RimMind-Personality] {PawnName(pawn)} has no CompAIPersonality (non-humanlike?)."); return; } @@ -39,7 +37,7 @@ public static void ForceEvaluateSelected() return; } - Log.Message($"[RimMind-Personality] Sending evaluation request for {pawn.Name.ToStringShort}..."); + Log.Message($"[RimMind-Personality] Sending evaluation request for {PawnName(pawn)}..."); var envelope = PersonalityRequestBuilder.BuildForPawn(pawn.thingIDNumber, "[Debug] Force evaluate"); @@ -47,12 +45,12 @@ public static void ForceEvaluateSelected() { if (result.IsErr) { - if (result.Error.Code != RimMindErrorCode.Cancelled) RimMindErrors.Warn($"[RimMind-Personality] Evaluation failed ({pawn.Name.ToStringShort}): {result.Error}"); + if (result.Error.Code != RimMindErrorCode.Cancelled) RimMindErrors.Warn($"[RimMind-Personality] Evaluation failed ({PawnName(pawn)}): {result.Error}"); return; } var aiResult = result; - Log.Message($"[RimMind-Personality] Received response ({pawn.Name.ToStringShort}):\n{aiResult.Value.Content}"); + Log.Message($"[RimMind-Personality] Received response ({PawnName(pawn)}):\n{aiResult.Value.Content}"); PersonalityThoughtMapper.Apply(aiResult, pawn); }); } @@ -69,7 +67,7 @@ public static void ShowPersonalityState() } var sb = new StringBuilder(); - sb.AppendLine($"=== {pawn.Name.ToStringShort} Personality State ==="); + sb.AppendLine($"=== {PawnName(pawn)} Personality State ==="); sb.AppendLine($"[Diag] API configured: {RimMindAPI.Settings.IsConfigured()}"); var comp = pawn.GetComp(); @@ -131,7 +129,7 @@ public static void ClearPersonalityThoughts() PersonalityThoughtMapper.RemoveAllAIPersonalityThoughts(pawn); - Log.Message($"[RimMind-Personality] Cleared {before} personality thoughts for {pawn.Name.ToStringShort}."); + Log.Message($"[RimMind-Personality] Cleared {before} personality thoughts for {PawnName(pawn)}."); } [DebugAction("RimMind Personality", "List Personality-Enabled Pawns", @@ -154,7 +152,7 @@ public static void ListEnabledPawns() if (PersonalityThoughtMapper.IsAIPersonalityDef(t.def.defName)) thoughtCount++; - sb.AppendLine($" {p.Name.ToStringShort}: profile={(profile != null && !profile.IsEmpty)}, activeThoughts={thoughtCount}"); + sb.AppendLine($" {PawnName(p)}: profile={(profile != null && !profile.IsEmpty)}, activeThoughts={thoughtCount}"); count++; } sb.AppendLine($"API configured: {RimMindAPI.Settings.IsConfigured()} Total: {count} pawns"); @@ -173,7 +171,7 @@ public static void ResetPersonalityProfile() } AIPersonalityWorldComponent.Instance?.Remove(pawn); - Log.Message($"[RimMind-Personality] Reset personality profile for {pawn.Name.ToStringShort}."); + Log.Message($"[RimMind-Personality] Reset personality profile for {PawnName(pawn)}."); } [DebugAction("RimMind Personality", "Show Shaping History (selected)", @@ -187,19 +185,19 @@ public static void ShowShapingHistory() return; } - var profile = AIPersonalityWorldComponent.Instance?.TryGet(pawn); - if (profile == null || profile.playerShapingHistory.Count == 0) + var history = AIPersonalityWorldComponent.Instance?.TryGet(pawn)?.GetShapingHistorySnapshot(); + if (history == null || history.Length == 0) { - Log.Message($"[RimMind-Personality] {pawn.Name.ToStringShort} has no shaping history."); + Log.Message($"[RimMind-Personality] {PawnName(pawn)} has no shaping history."); return; } var sb = new StringBuilder(); - sb.AppendLine($"=== {pawn.Name.ToStringShort} Shaping History (last 20) ==="); - int start = Math.Max(0, profile.playerShapingHistory.Count - 20); - for (int i = start; i < profile.playerShapingHistory.Count; i++) + sb.AppendLine($"=== {PawnName(pawn)} Shaping History (last 20) ==="); + int start = Math.Max(0, history.Length - 20); + for (int i = start; i < history.Length; i++) { - var r = profile.playerShapingHistory[i]; + var r = history[i]; sb.AppendLine($" [{i}] label={r.label}, action={r.action}, tick={r.tick}"); } Log.Message(sb.ToString()); diff --git a/Source/Extensions/PersonalityActionSkipCheck.cs b/Source/Extensions/PersonalityActionSkipCheck.cs index 2f35635..330c9f7 100644 --- a/Source/Extensions/PersonalityActionSkipCheck.cs +++ b/Source/Extensions/PersonalityActionSkipCheck.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; namespace RimMind.Personality @@ -5,8 +6,10 @@ namespace RimMind.Personality internal sealed class PersonalityActionSkipCheck : ISkipCheck { public string Id => "personality.action"; - public string OwnerModId => "RimMindPersonality"; + public string OwnerModId => RimMindOwnerConsts.PersonalityModId; public SkipCheckKind Kind => SkipCheckKind.Action; - public bool ShouldSkip(in SkipCheckArgs args) => !RimMindPersonalityMod.Settings.enablePersonality; + // Personality never vetoes Advisor/Actions when personality evaluation is disabled; + // personality enablement only gates Personality's own triggers, evaluation, and context injection. + public bool ShouldSkip(in SkipCheckArgs args) => false; } } diff --git a/Source/Extensions/PersonalityModCooldown.cs b/Source/Extensions/PersonalityModCooldown.cs index 6be146f..cf27524 100644 --- a/Source/Extensions/PersonalityModCooldown.cs +++ b/Source/Extensions/PersonalityModCooldown.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Presentation.Api; @@ -5,9 +6,10 @@ namespace RimMind.Personality { internal sealed class PersonalityModCooldown : IModCooldown { - public string Id => "Personality"; - // Must match the envelope ModId: Core resolves queue cooldowns by that key. - public string OwnerModId => PersonalityRequestDefaults.ModId; + // Id matches envelope ModId so Core's QueueCircuitBreaker resolves cooldowns cleanly, + // while OwnerModId matches RimMindOwnerConsts for consistent UnregisterByOwner tracking. + public string Id => PersonalityRequestDefaults.ModId; + public string OwnerModId => RimMindOwnerConsts.PersonalityModId; public int CooldownTicks => RimMindAPI.Settings.ScaleCooldown(1200); } } diff --git a/Source/Extensions/PersonalitySettingsTab.cs b/Source/Extensions/PersonalitySettingsTab.cs index bfb5812..0fd507a 100644 --- a/Source/Extensions/PersonalitySettingsTab.cs +++ b/Source/Extensions/PersonalitySettingsTab.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Presentation.Api; using RimMind.Presentation.Settings; using UnityEngine; @@ -7,7 +8,7 @@ namespace RimMind.Personality internal sealed class PersonalitySettingsTab : ISettingsTab { public string Id => "personality"; - public string OwnerModId => "RimMindPersonality"; + public string OwnerModId => RimMindOwnerConsts.PersonalityModId; public string Label => RimMindAPI.Text.TrOr("RimMind.Personality.Settings.TabLabel", "Personality"); public void Draw(Rect rect) => PersonalitySettingsDrawer.Draw(rect); } diff --git a/Source/Extensions/PersonalityToggleBehavior.cs b/Source/Extensions/PersonalityToggleBehavior.cs index a717cbb..ae2d21e 100644 --- a/Source/Extensions/PersonalityToggleBehavior.cs +++ b/Source/Extensions/PersonalityToggleBehavior.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; namespace RimMind.Personality @@ -5,8 +6,12 @@ namespace RimMind.Personality internal sealed class PersonalityToggleBehavior : IToggleBehavior { public string Id => "personality.toggle"; - public string OwnerModId => "RimMindPersonality"; + public string OwnerModId => RimMindOwnerConsts.PersonalityModId; public bool IsActive => RimMindPersonalityMod.Settings.enablePersonality; - public void Toggle() => RimMindPersonalityMod.Settings.enablePersonality = !RimMindPersonalityMod.Settings.enablePersonality; + public void Toggle() + { + RimMindPersonalityMod.Settings.enablePersonality = !RimMindPersonalityMod.Settings.enablePersonality; + RimMindPersonalityMod.Settings.Write(); + } } } diff --git a/Source/Patches/AddCompToHumanlikePatch.cs b/Source/Patches/AddCompToHumanlikePatch.cs index 3e4339d..9aff1c7 100644 --- a/Source/Patches/AddCompToHumanlikePatch.cs +++ b/Source/Patches/AddCompToHumanlikePatch.cs @@ -2,7 +2,6 @@ using System.Linq; using HarmonyLib; using RimMind.Personality.Comps; -using RimWorld; using Verse; namespace RimMind.Personality.Patches diff --git a/Source/Patches/Patch_PersonalityDeath.cs b/Source/Patches/Patch_PersonalityDeath.cs index 58739b4..42e4ff3 100644 --- a/Source/Patches/Patch_PersonalityDeath.cs +++ b/Source/Patches/Patch_PersonalityDeath.cs @@ -1,8 +1,6 @@ -using System.Collections.Generic; using HarmonyLib; using RimMind.Personality.Comps; using RimMind.Presentation.Api; -using RimWorld; using Verse; namespace RimMind.Personality.Patches @@ -12,7 +10,9 @@ static class Patch_PersonalityDeath { static void Postfix(Pawn __instance, DamageInfo? dinfo, Hediff exactCulprit) { - if (!RimMindPersonalityMod.Settings.enableDeathTrigger) return; + var settings = RimMindPersonalityMod.Settings; + if (!settings.enablePersonality || !settings.enableDeathTrigger) return; + if (Find.Maps == null) return; // Iterate ALL maps, not just the killed pawn's current map: the killed // pawn's Map may be null after death, and related colonists on other @@ -30,8 +30,13 @@ static void Postfix(Pawn __instance, DamageInfo? dinfo, Hediff exactCulprit) { if (dr.otherPawn == killedPawn) { + string relLabel = dr.def?.LabelCap.RawText ?? dr.def?.defName ?? string.Empty; PersonalityTriggerHelper.TriggerForPawn(pawn, - $"{"RimMind.Personality.Trigger.RelationDeath".Translate(dr.def.LabelCap, killedName)}", + RimMindAPI.Text.TrOr( + "RimMind.Personality.Trigger.RelationDeath", + "{0} {1} died", + relLabel, + killedName), TriggerEventType.Death); break; } diff --git a/Source/Patches/Patch_PersonalityIncident.cs b/Source/Patches/Patch_PersonalityIncident.cs index e0863d3..e6837e4 100644 --- a/Source/Patches/Patch_PersonalityIncident.cs +++ b/Source/Patches/Patch_PersonalityIncident.cs @@ -15,6 +15,7 @@ static class Patch_PersonalityIncident static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __result) { + if (!RimMindPersonalityMod.Settings.enablePersonality) return; var def = __instance.def; bool targetIsMap = parms.target is Map; if (!PersonalityTriggerPolicy.ShouldTriggerIncident( diff --git a/Source/Patches/Patch_PersonalityInjury.cs b/Source/Patches/Patch_PersonalityInjury.cs index bda5077..b33125a 100644 --- a/Source/Patches/Patch_PersonalityInjury.cs +++ b/Source/Patches/Patch_PersonalityInjury.cs @@ -1,6 +1,6 @@ using HarmonyLib; using RimMind.Personality.Comps; -using RimWorld; +using RimMind.Presentation.Api; using Verse; namespace RimMind.Personality.Patches @@ -10,19 +10,31 @@ static class Patch_PersonalityInjury { static void Postfix(HediffSet __instance, Hediff hediff) { + var settings = RimMindPersonalityMod.Settings; + if (!settings.enablePersonality) return; + var pawn = __instance.pawn; if (!PersonalityTriggerPolicy.ShouldTriggerInjury( - RimMindPersonalityMod.Settings.enableInjuryTrigger, + settings.enableInjuryTrigger, hediff != null, - hediff?.def.isBad == true, + hediff?.def?.isBad == true, hediff?.Severity ?? 0f, PersonalityTriggerPolicy.IsEligible(pawn))) { return; } + string partLabel = hediff!.Part?.Label + ?? RimMindAPI.Text.TrOr("RimMind.Personality.Trigger.FullBody", "full body"); + string hediffLabel = hediff.LabelCap.NullOrEmpty() + ? (hediff.def?.defName ?? string.Empty) + : hediff.LabelCap; PersonalityTriggerHelper.TriggerForPawn(pawn!, - $"{"RimMind.Personality.Trigger.Contracted".Translate(hediff!.LabelCap, "RimMind.Personality.Trigger.FullBody".Translate())}", + RimMindAPI.Text.TrOr( + "RimMind.Personality.Trigger.Contracted", + "Suffered {0} ({1})", + hediffLabel, + partLabel), TriggerEventType.Injury); } } diff --git a/Source/Patches/Patch_PersonalitySkill.cs b/Source/Patches/Patch_PersonalitySkill.cs index 1e1dae3..c0f9e09 100644 --- a/Source/Patches/Patch_PersonalitySkill.cs +++ b/Source/Patches/Patch_PersonalitySkill.cs @@ -19,9 +19,12 @@ static void Postfix(SkillRecord __instance, float xp, int __state) { if (__state < 0) return; + var settings = RimMindPersonalityMod.Settings; + if (!settings.enablePersonality) return; + int currentLevel = __instance.Level; if (!PersonalityTriggerPolicy.ShouldTriggerSkill( - RimMindPersonalityMod.Settings.enableSkillTrigger, + settings.enableSkillTrigger, preLevelWasCaptured: true, __state, currentLevel)) @@ -32,15 +35,25 @@ static void Postfix(SkillRecord __instance, float xp, int __state) Pawn pawn = __instance.Pawn; if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return; + string defName = __instance.def?.defName ?? string.Empty; RimMindAPI.GameEvents.Publish(new SkillLevelUpGameEvent( pawn.thingIDNumber, - __instance.def.defName ?? string.Empty, + defName, __state, currentLevel)); + string skillLabel = (__instance.def?.LabelCap.RawText.NullOrEmpty() ?? true) + ? defName + : __instance.def!.LabelCap.RawText; PersonalityTriggerHelper.TriggerForPawn( pawn, - $"{"RimMind.Personality.Trigger.SkillUp".Translate(__instance.def.LabelCap, currentLevel, __state, currentLevel)}", + RimMindAPI.Text.TrOr( + "RimMind.Personality.Trigger.SkillUp", + "{0} skill increased to level {1} ({2}→{3})", + skillLabel, + currentLevel, + __state, + currentLevel), TriggerEventType.Skill); } } diff --git a/Source/Patches/PersonalityTriggerHelper.cs b/Source/Patches/PersonalityTriggerHelper.cs index 32f05f1..99e30d9 100644 --- a/Source/Patches/PersonalityTriggerHelper.cs +++ b/Source/Patches/PersonalityTriggerHelper.cs @@ -1,6 +1,5 @@ using RimMind.Personality.Comps; using RimMind.Presentation.Api; -using RimWorld; using Verse; namespace RimMind.Personality.Patches diff --git a/Source/Personality/MoodOffsetCalculator.cs b/Source/Personality/MoodOffsetCalculator.cs index 9e0ce00..2bb54cc 100644 --- a/Source/Personality/MoodOffsetCalculator.cs +++ b/Source/Personality/MoodOffsetCalculator.cs @@ -3,17 +3,17 @@ namespace RimMind.Personality { /// - /// å°?AI 返回çš?intensityï¼?3~+3)映射为 RimWorld 心情偏移值ã€? - /// 纯静态方法,æ—?RimWorld 依赖,可在单元测试中直接使用ã€? + /// Maps AI-returned intensity (-3..+3) to RimWorld mood offset values. + /// Pure static helper with no RimWorld dependencies for direct unit testing. /// public static class MoodOffsetCalculator { - // -3â†?10, -2â†?3, -1â†?1, 0â†?, 1â†?1, 2â†?3, 3â†?10 + // -3 => -10, -2 => -3, -1 => -1, 0 => 0, +1 => +1, +2 => +3, +3 => +10 private static readonly float[] MoodTable = { -10f, -3f, -1f, 0f, +1f, +3f, +10f }; /// - /// 根据 AI intensity 值计ç®?RimWorld 心情偏移量ã€? - /// intensity 超出 [-3, 3] 时自åŠ?clampã€? + /// Computes the RimWorld mood offset for the given AI intensity, clamping out-of-range + /// values to [-3, 3]. /// public static float CalcMoodOffset(float intensity) { diff --git a/Source/Personality/PawnResolver.cs b/Source/Personality/PawnResolver.cs deleted file mode 100644 index ec63ccc..0000000 --- a/Source/Personality/PawnResolver.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using RimMind.Presentation.Api; -using Verse; - -namespace RimMind.Personality -{ - /// - /// Thin backwards-compatible forwarding stub; new callers should use directly. - /// - [Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber directly.")] - public static class PawnResolver - { - public static Pawn? TryFindPawn(int pawnId) - => RimMindPawnLookup.FindPawnByNumber(pawnId); - } -} diff --git a/Source/Personality/PersonalityProviderRegistrar.cs b/Source/Personality/PersonalityProviderRegistrar.cs index 5ce8026..23d1631 100644 --- a/Source/Personality/PersonalityProviderRegistrar.cs +++ b/Source/Personality/PersonalityProviderRegistrar.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Context; using RimMind.Application.Common.Models.Context; using RimMind.Application.Features.Context; @@ -15,7 +16,7 @@ namespace RimMind.Personality { internal static class PersonalityProviderRegistrar { - private const string PublicProviderOwner = "RimMind.Personality"; + private const string PublicProviderOwner = RimMindOwnerConsts.PersonalityModId; private const int PublicProviderPriority = 100; internal static void RegisterAll() @@ -37,14 +38,17 @@ private static void RegisterPublicProviders() PublicProviderOwner, pawn => { - if (pawn == null) return null; + if (pawn == null || RimMindPersonalityMod.Settings?.enablePersonality != true) return null; // Read-only lookup: synchronous public providers may be called from any thread. var profile = AIPersonalityWorldComponent.Instance?.TryGet(pawn); - var history = profile?.playerShapingHistory?.ToArray(); + var history = profile?.GetShapingHistorySnapshot(); if (history == null || history.Length == 0) return string.Empty; + string header = RimMindText.TrOr( + "RimMind.Personality.Context.ShapingBriefHeader", + "[RimMind Shaping]"); return PersonalityContextText.FormatHeaderedLines( - "[RimMind Shaping]", + header, PersonalityContextText.TakeLast(history, 5) .Where(record => record != null) .Select(record => $"- [{record.action}] {record.label}")) ?? string.Empty; @@ -62,7 +66,7 @@ private static void RegisterProfileField( PublicProviderOwner, pawn => { - if (pawn == null) return null; + if (pawn == null || RimMindPersonalityMod.Settings?.enablePersonality != true) return null; var profile = AIPersonalityWorldComponent.Instance?.TryGet(pawn); return profile == null ? null : selector(profile); }, @@ -74,8 +78,9 @@ private static void RegisterAgentIdentityProvider() { RimMindAPI.Ext.RegisterAgentIdentityProvider(pawn => { + if (RimMindPersonalityMod.Settings?.enablePersonality != true) return null; var profile = AIPersonalityWorldComponent.Instance?.TryGet(pawn); - return profile?.agentIdentity; + return profile?.GetAgentIdentitySnapshot(); }); } @@ -93,7 +98,7 @@ private static string Tr(string key, params object[] args) // is inert in Core. Cached keys refresh through their 750-tick staleness window. private static void RegisterContextProviders() { - ScenarioRegistry.Register(new ScenarioDescriptor + RimMindAPI.Context.RegisterScenario(new ScenarioDescriptor { Id = ScenarioIds.Personality, DefaultBaseRounds = 3, @@ -135,7 +140,8 @@ private static void RegisterContextProviders() "personality_profile", ContextLayer.L3_State, 0.25f, (ctx, ct) => { - if (!PersonalityContextScenarioPolicy.IncludesPersonalityContext(ctx.Scenario)) + if (RimMindPersonalityMod.Settings?.enablePersonality != true + || !PersonalityContextScenarioPolicy.IncludesPersonalityContext(ctx.Scenario)) return Task.FromResult(null); int pawnId = ctx.PawnId; return OnMainThread(() => BuildProfileContext(pawnId), ct); @@ -145,7 +151,8 @@ private static void RegisterContextProviders() "personality_state", ContextLayer.L3_State, 0.2f, (ctx, ct) => { - if (!PersonalityContextScenarioPolicy.IncludesPersonalityContext(ctx.Scenario)) + if (RimMindPersonalityMod.Settings?.enablePersonality != true + || !PersonalityContextScenarioPolicy.IncludesPersonalityContext(ctx.Scenario)) return Task.FromResult(null); int pawnId = ctx.PawnId; return OnMainThread(() => BuildStateContext(pawnId), ct); @@ -155,7 +162,8 @@ private static void RegisterContextProviders() "personality_shaping", ContextLayer.L3_State, 0.15f, (ctx, ct) => { - if (!PersonalityContextScenarioPolicy.IncludesPersonalityContext(ctx.Scenario)) + if (RimMindPersonalityMod.Settings?.enablePersonality != true + || !PersonalityContextScenarioPolicy.IncludesPersonalityContext(ctx.Scenario)) return Task.FromResult(null); int pawnId = ctx.PawnId; return OnMainThread(() => BuildShapingContext(pawnId), ct); @@ -165,7 +173,8 @@ private static void RegisterContextProviders() "personality_task", ContextLayer.L0_Static, 0.95f, (ctx, ct) => { - if (ctx.Scenario != RimMindAPI.Context.ScenarioPersonality) + if (RimMindPersonalityMod.Settings?.enablePersonality != true + || ctx.Scenario != RimMindAPI.Context.ScenarioPersonality) return Task.FromResult(null); return OnMainThread(BuildTaskInstruction, ct); }, PublicProviderOwner, stalenessTicks: 0)); @@ -175,12 +184,12 @@ private static void RegisterContextProviders() private static string? BuildProfileContext(int pawnId) { var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); - if (pawn == null) return null; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return null; var profile = AIPersonalityWorldComponent.Instance?.TryGet(pawn); if (profile == null || profile.IsEmpty) return null; var sb = new System.Text.StringBuilder(); - sb.AppendLine(Tr("RimMind.Personality.Context.ProfileHeader", pawn.Name?.ToStringShort ?? "")); + sb.AppendLine(Tr("RimMind.Personality.Context.ProfileHeader", pawn!.Name?.ToStringShort ?? pawn.LabelShort)); if (!profile.description.NullOrEmpty()) sb.AppendLine(profile.description); if (!profile.workTendencies.NullOrEmpty()) @@ -196,14 +205,15 @@ private static void RegisterContextProviders() private static string? BuildStateContext(int pawnId) { var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); - var memories = pawn?.needs?.mood?.thoughts?.memories?.Memories; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return null; + var memories = pawn!.needs?.mood?.thoughts?.memories?.Memories; if (memories == null || memories.Count == 0) return null; - var lines = new System.Collections.Generic.List(); + var lines = new List(); for (int i = 0; i < memories.Count; i++) { var t = memories[i]; - if (t?.def == null || !Personality.PersonalityThoughtMapper.IsAIPersonalityDef(t.def.defName)) continue; + if (t?.def == null || !PersonalityThoughtMapper.IsAIPersonalityDef(t.def.defName)) continue; string desc = (t as Thought_AIPersonality)?.aiDescription ?? t.def.label; float hours = t.DurationTicks / (float)RimMind.Domain.Common.RimMindTime.TicksPerHour; @@ -216,9 +226,9 @@ private static void RegisterContextProviders() private static string? BuildShapingContext(int pawnId) { var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); - if (pawn == null) return null; - var history = AIPersonalityWorldComponent.Instance?.TryGet(pawn)?.playerShapingHistory; - if (history == null || history.Count == 0) return null; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return null; + var history = AIPersonalityWorldComponent.Instance?.TryGet(pawn)?.GetShapingHistorySnapshot(); + if (history == null || history.Length == 0) return null; int maxCount = RimMindPersonalityMod.Settings?.shapingHistoryMaxCount ?? 20; var lines = PersonalityContextText.TakeLast(history, maxCount) diff --git a/Source/Personality/PersonalityThoughtMapper.cs b/Source/Personality/PersonalityThoughtMapper.cs index 20f99e9..5a4bf6c 100644 --- a/Source/Personality/PersonalityThoughtMapper.cs +++ b/Source/Personality/PersonalityThoughtMapper.cs @@ -3,13 +3,9 @@ using System.Linq; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; -using RimMind.Application.Common.Interfaces.UI; using RimMind.Application.Common.Models.UI; using RimMind.Presentation.Api; -using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Models.Agent; -using RimMind.Application.Common.Models.Context; -using RimMind.Application.Common.Interfaces.Context; using RimMind.Personality.Data; using RimWorld; using Verse; @@ -18,7 +14,19 @@ namespace RimMind.Personality { public static class PersonalityThoughtMapper { - public static readonly string EvaluationSchema = RimMindAPI.Context.SchemaPersonalityOutput; + public const string SchemaKey = "PersonalityOutput"; + public const string PersonalityOutputSchema = + "{\"type\":\"object\",\"properties\":{\"thoughts\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\"},\"label\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"intensity\":{\"type\":\"number\"},\"duration_hours\":{\"type\":\"number\"}},\"required\":[\"label\",\"description\",\"intensity\"]}},\"narrative\":{\"type\":\"string\"},\"identity\":{\"type\":\"object\",\"properties\":{\"motivations\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"traits\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"core_values\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}}}},\"required\":[\"thoughts\",\"narrative\"]}"; + + public static string EvaluationSchema + { + get + { + string? registered = RimMindAPI.Context.FindSchema(SchemaKey); + return !string.IsNullOrEmpty(registered) ? registered! : PersonalityOutputSchema; + } + } + public const int DefaultMaxTokens = PersonalityRequestDefaults.MaxTokens; public const float DefaultTemperature = PersonalityRequestDefaults.Temperature; @@ -26,16 +34,18 @@ public static void Apply(Result result, Pawn pawn) { if (pawn == null || !RimMindPawnLookup.IsActiveSpawnedColonist(pawn) || pawn.needs?.mood == null) return; + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; if (result.IsErr) { - if (result.Error.Code != RimMindErrorCode.Cancelled) RimMindErrors.Warn($"[RimMind-Personality] Request failed ({pawn.Name.ToStringShort}): {result.Error}"); + if (result.Error.Code != RimMindErrorCode.Cancelled) + RimMindErrors.Warn($"[RimMind-Personality] Request failed ({pawnName}): {result.Error}"); return; } var dto = PersonalityThoughtPolicy.ParseResponse(result.Value.Content); if (dto == null) { - RimMindErrors.Warn($"[RimMind-Personality] Response parse failed ({pawn.Name.ToStringShort}):\n{result.Value.Content}"); + RimMindErrors.Warn($"[RimMind-Personality] Response parse failed ({pawnName}):\n{result.Value.Content}"); return; } @@ -59,14 +69,20 @@ private static void UpdateProfile(PersonalityProfile profile, PersonalityResultD if (dto.identity != null) { - if (profile.agentIdentity == null) - profile.agentIdentity = new AgentIdentity(); - if (dto.identity.motivations != null) - profile.agentIdentity.Motivations = new List(dto.identity.motivations); - if (dto.identity.traits != null) - profile.agentIdentity.PersonalityTraits = new List(dto.identity.traits); - if (dto.identity.core_values != null) - profile.agentIdentity.CoreValues = new List(dto.identity.core_values); + var existing = profile.GetAgentIdentitySnapshot(); + var updated = new AgentIdentity + { + Motivations = dto.identity.motivations != null + ? new List(dto.identity.motivations) + : (existing?.Motivations != null ? new List(existing.Motivations) : new List()), + PersonalityTraits = dto.identity.traits != null + ? new List(dto.identity.traits) + : (existing?.PersonalityTraits != null ? new List(existing.PersonalityTraits) : new List()), + CoreValues = dto.identity.core_values != null + ? new List(dto.identity.core_values) + : (existing?.CoreValues != null ? new List(existing.CoreValues) : new List()) + }; + profile.SetAgentIdentity(updated); } } @@ -174,8 +190,9 @@ private static void ApplyThoughts(Pawn pawn, PersonalityResultDto dto, AIPersona if (showNotifications && projections.Count > 0 && pawn.Spawned && pawn.Map != null) { + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; Messages.Message( - "RimMind.Personality.UI.PersonalityUpdated".Translate(pawn.Name.ToStringShort), + RimMindAPI.Text.TrOr("RimMind.Personality.UI.PersonalityUpdated", "[RimMind] {0}'s personality state has been updated.", pawnName), pawn, MessageTypeDefOf.SilentInput, historical: false); diff --git a/Source/Personality/PersonalityTriggerPolicy.cs b/Source/Personality/PersonalityTriggerPolicy.cs index d74c5d0..d954ac3 100644 --- a/Source/Personality/PersonalityTriggerPolicy.cs +++ b/Source/Personality/PersonalityTriggerPolicy.cs @@ -129,5 +129,18 @@ public static bool ShouldTriggerMoodSwing( float moodDelta, float threshold = 0.15f) => triggerEnabled && System.Math.Abs(moodDelta) >= threshold && roll < triggerChance; + + public static bool ShouldTriggerDailyEvaluation( + bool enableDailyEval, + bool isAwake, + int ticksGame, + int lastDailyDecayTick, + int dailyIntervalTicks, + int dailyJitterTicks) + { + if (!enableDailyEval || !isAwake) return false; + int dailyInterval = System.Math.Max(60, dailyIntervalTicks + dailyJitterTicks); + return ticksGame - lastDailyDecayTick >= dailyInterval; + } } } diff --git a/Source/README.md b/Source/README.md index bc2a991..a77e0dd 100644 --- a/Source/README.md +++ b/Source/README.md @@ -44,5 +44,5 @@ dotnet test RimMind-Personality/Tests/RimMindPersonality.Tests.csproj -c Release dotnet build RimMind-Personality/Source/RimMindPersonality.csproj -c Release ``` -The permanent suite contains eight aggregate Facts. The game Autotester remains -separate and is currently blocked by missing resources. +Count discovered cases with the root test-budget script (all projects per mod < 1000). +The game Autotester remains separate and is currently blocked by missing resources. diff --git a/Source/RimMindPersonalityMod.cs b/Source/RimMindPersonalityMod.cs index 919ed4e..264cac5 100644 --- a/Source/RimMindPersonalityMod.cs +++ b/Source/RimMindPersonalityMod.cs @@ -1,4 +1,3 @@ -using HarmonyLib; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Personality.UI; using RimMind.Presentation; @@ -18,6 +17,9 @@ public RimMindPersonalityMod(ModContentPack content) : base(content) Settings = base.Settings; InitializeHarmony(); + RimMindAPI.Context.RegisterSchema( + PersonalityThoughtMapper.SchemaKey, + PersonalityThoughtMapper.PersonalityOutputSchema); PersonalityProviderRegistrar.RegisterAll(); RimMindAPI.UI.RegisterBioTabBadge(new PersonalityBioTabBadgeProvider()); RimMindAPI.Extensions().Register(new PersonalitySettingsTab()); diff --git a/Source/Settings/PersonalitySettingsDrawer.cs b/Source/Settings/PersonalitySettingsDrawer.cs index 8f968fe..4d8f698 100644 --- a/Source/Settings/PersonalitySettingsDrawer.cs +++ b/Source/Settings/PersonalitySettingsDrawer.cs @@ -1,3 +1,4 @@ +using RimMind.Presentation.Api; using RimMind.Presentation.UI; using UnityEngine; using Verse; @@ -9,6 +10,9 @@ internal static class PersonalitySettingsDrawer private static Vector2 _scrollPos = Vector2.zero; private static float _measuredHeight = 760f; + private static string Tr(string key, string fallback, params object[] args) + => RimMindAPI.Text.TrOr(key, fallback, args); + internal static void Draw(Rect inRect) { SettingsUIDrawer.DrawScrollableSettingsPage( @@ -22,82 +26,114 @@ internal static void Draw(Rect inRect) private static void DrawContent(Listing_Standard listing) { - - listing.CheckboxLabeled("RimMind.Personality.Settings.EnablePersonality".Translate(), ref RimMindPersonalityMod.Settings.enablePersonality, - "RimMind.Personality.Settings.EnablePersonality.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Personality.Settings.TriggerSources".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.DailyEval".Translate(), ref RimMindPersonalityMod.Settings.enableDailyEval, - "RimMind.Personality.Settings.DailyEval.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.InjuryTrigger".Translate(), ref RimMindPersonalityMod.Settings.enableInjuryTrigger, - "RimMind.Personality.Settings.InjuryTrigger.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.SkillTrigger".Translate(), ref RimMindPersonalityMod.Settings.enableSkillTrigger, - "RimMind.Personality.Settings.SkillTrigger.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.IncidentTrigger".Translate(), ref RimMindPersonalityMod.Settings.enableIncidentTrigger, - "RimMind.Personality.Settings.IncidentTrigger.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.DeathTrigger".Translate(), ref RimMindPersonalityMod.Settings.enableDeathTrigger, - "RimMind.Personality.Settings.DeathTrigger.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Personality.Settings.Section.Thought".Translate()); - - listing.LabelWithTooltip("RimMind.Personality.Settings.ThoughtDuration".Translate(), - "RimMind.Personality.Settings.ThoughtDuration.Desc".Translate()); - bool aiDecides = RimMindPersonalityMod.Settings.durationMode == ThoughtDurationMode.AIDecides; - listing.CheckboxLabeled("RimMind.Personality.Settings.AIDecidesDuration".Translate(), ref aiDecides, - "RimMind.Personality.Settings.AIDecidesDuration.Desc".Translate()); - RimMindPersonalityMod.Settings.durationMode = aiDecides ? ThoughtDurationMode.AIDecides : ThoughtDurationMode.Fixed; + var s = RimMindPersonalityMod.Settings; + + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.EnablePersonality", "Enable AI Personality System"), + ref s.enablePersonality, + Tr("RimMind.Personality.Settings.EnablePersonality.Desc", "When enabled, AI dynamically generates psychological states (Thoughts) based on game events and colonist conditions.")); + + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Personality.Settings.TriggerSources", "Trigger Sources")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.DailyEval", "Daily Evaluation"), + ref s.enableDailyEval, + Tr("RimMind.Personality.Settings.DailyEval.Desc", "Automatically evaluate colonist personality each day, generating psychological states.")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.InjuryTrigger", "Injury / Illness"), + ref s.enableInjuryTrigger, + Tr("RimMind.Personality.Settings.InjuryTrigger.Desc", "Trigger personality evaluation when a colonist is injured.")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.SkillTrigger", "Skill Level Up"), + ref s.enableSkillTrigger, + Tr("RimMind.Personality.Settings.SkillTrigger.Desc", "Trigger personality evaluation when a colonist levels up a skill.")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.IncidentTrigger", "Major Incident"), + ref s.enableIncidentTrigger, + Tr("RimMind.Personality.Settings.IncidentTrigger.Desc", "Trigger personality evaluation when a major colony incident occurs.")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.DeathTrigger", "Close One Died"), + ref s.enableDeathTrigger, + Tr("RimMind.Personality.Settings.DeathTrigger.Desc", "Trigger personality evaluation for other colonists when someone dies.")); + + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Personality.Settings.Section.Thought", "Thought Settings")); + + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.ThoughtDuration", "Thought duration:"), + Tr("RimMind.Personality.Settings.ThoughtDuration.Desc", "Set the duration mode for AI-generated psychological states (Thoughts).")); + bool aiDecides = s.durationMode == ThoughtDurationMode.AIDecides; + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.AIDecidesDuration", "Let AI decide each Thought's duration"), + ref aiDecides, + Tr("RimMind.Personality.Settings.AIDecidesDuration.Desc", "When enabled, AI outputs duration_hours (1~24) in JSON, automatically setting duration based on emotional intensity.")); + s.durationMode = aiDecides ? ThoughtDurationMode.AIDecides : ThoughtDurationMode.Fixed; if (!aiDecides) { - string fixedTip = "RimMind.Personality.Settings.FixedDuration.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Personality.Settings.FixedDuration".Translate($"{RimMindPersonalityMod.Settings.thoughtDurationHours:F0}"), fixedTip); - RimMindPersonalityMod.Settings.thoughtDurationHours = listing.SliderWithTooltip(RimMindPersonalityMod.Settings.thoughtDurationHours, 1f, 24f, fixedTip); - } - else - { - listing.Label("RimMind.Personality.Settings.AIDurationHint".Translate()); + string fixedTip = Tr("RimMind.Personality.Settings.FixedDuration.Desc", "All AI-generated Thoughts use this fixed duration uniformly."); + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.FixedDuration", " Fixed duration: {0} game hours", $"{s.thoughtDurationHours:F0}"), + fixedTip); + s.thoughtDurationHours = listing.SliderWithTooltip(s.thoughtDurationHours, 1f, 24f, fixedTip); } - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Personality.Settings.Section.Display".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.ShowNotifications".Translate(), ref RimMindPersonalityMod.Settings.showNotifications, - "RimMind.Personality.Settings.ShowNotifications.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.ShowLabelPrefix".Translate(), ref RimMindPersonalityMod.Settings.showLabelPrefix, - "RimMind.Personality.Settings.ShowLabelPrefix.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Personality.Settings.Section.Request".Translate()); - listing.CheckboxLabeled("RimMind.Personality.Settings.EnableShapingVote".Translate(), ref RimMindPersonalityMod.Settings.enableShapingVote, - "RimMind.Personality.Settings.EnableShapingVote.Desc".Translate()); - - string reqExpireTip = "RimMind.Personality.Settings.RequestExpire.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Personality.Settings.RequestExpire".Translate($"{RimMindPersonalityMod.Settings.requestExpireTicks / 60000f:F2}"), reqExpireTip); - RimMindPersonalityMod.Settings.requestExpireTicks = (int)listing.SliderWithTooltip(RimMindPersonalityMod.Settings.requestExpireTicks, 3600f, 120000f, reqExpireTip); - RimMindPersonalityMod.Settings.requestExpireTicks = (RimMindPersonalityMod.Settings.requestExpireTicks / 1500) * 1500; - - string shapingHistoryTip = "RimMind.Personality.Settings.ShapingHistoryMax.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Personality.Settings.ShapingHistoryMax".Translate($"{RimMindPersonalityMod.Settings.shapingHistoryMaxCount}"), shapingHistoryTip); - RimMindPersonalityMod.Settings.shapingHistoryMaxCount = (int)listing.SliderWithTooltip(RimMindPersonalityMod.Settings.shapingHistoryMaxCount, 10f, 200f, shapingHistoryTip); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Personality.Settings.Section.Timing".Translate()); - - string dailyIntervalTip = "RimMind.Personality.Settings.DailyInterval.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Personality.Settings.DailyInterval".Translate($"{RimMindPersonalityMod.Settings.dailyIntervalTicks / 2500f:F1}"), dailyIntervalTip); - RimMindPersonalityMod.Settings.dailyIntervalTicks = (int)listing.SliderWithTooltip(RimMindPersonalityMod.Settings.dailyIntervalTicks, 12000f, 120000f, dailyIntervalTip); - RimMindPersonalityMod.Settings.dailyIntervalTicks = (RimMindPersonalityMod.Settings.dailyIntervalTicks / 3000) * 3000; - - string jitterTip = "RimMind.Personality.Settings.JitterRange.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Personality.Settings.JitterRange".Translate($"{RimMindPersonalityMod.Settings.jitterRangeTicks / 2500f:F1}"), jitterTip); - RimMindPersonalityMod.Settings.jitterRangeTicks = (int)listing.SliderWithTooltip(RimMindPersonalityMod.Settings.jitterRangeTicks, 0f, 12000f, jitterTip); - RimMindPersonalityMod.Settings.jitterRangeTicks = (RimMindPersonalityMod.Settings.jitterRangeTicks / 600) * 600; - - string eventCdTip = "RimMind.Personality.Settings.EventCooldown.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Personality.Settings.EventCooldown".Translate($"{RimMindPersonalityMod.Settings.eventCooldownTicks / 2500f:F1}"), eventCdTip); - RimMindPersonalityMod.Settings.eventCooldownTicks = (int)listing.SliderWithTooltip(RimMindPersonalityMod.Settings.eventCooldownTicks, 600f, 6000f, eventCdTip); - RimMindPersonalityMod.Settings.eventCooldownTicks = (RimMindPersonalityMod.Settings.eventCooldownTicks / 300) * 300; - - string timeoutTip = "RimMind.Personality.Settings.RequestTimeout.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Personality.Settings.RequestTimeout".Translate($"{RimMindPersonalityMod.Settings.requestTimeoutTicks / 2500f:F1}"), timeoutTip); - RimMindPersonalityMod.Settings.requestTimeoutTicks = (int)listing.SliderWithTooltip(RimMindPersonalityMod.Settings.requestTimeoutTicks, 12000f, 120000f, timeoutTip); - RimMindPersonalityMod.Settings.requestTimeoutTicks = (RimMindPersonalityMod.Settings.requestTimeoutTicks / 3000) * 3000; + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Personality.Settings.Section.Display", "Display")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.ShowNotifications", "Show Personality Change Notifications"), + ref s.showNotifications, + Tr("RimMind.Personality.Settings.ShowNotifications.Desc", "Display a notification on screen when AI generates a new psychological state.")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.ShowLabelPrefix", "Show [RimMind] Prefix"), + ref s.showLabelPrefix, + Tr("RimMind.Personality.Settings.ShowLabelPrefix.Desc", "Display a RimMind prefix before psychological state labels.")); + + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Personality.Settings.Section.Request", "Request Settings")); + listing.CheckboxLabeled( + Tr("RimMind.Personality.Settings.EnableShapingVote", "Enable Personality Shaping Vote"), + ref s.enableShapingVote, + Tr("RimMind.Personality.Settings.EnableShapingVote.Desc", "When enabled, AI proposes new personality traits during evaluation, and the player can vote.")); + + string reqExpireTip = Tr("RimMind.Personality.Settings.RequestExpire.Desc", "Shaping vote requests not responded to within this time are cancelled."); + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.RequestExpire", "Shaping vote expiry: {0} game days", $"{s.requestExpireTicks / 60000f:F2}"), + reqExpireTip); + s.requestExpireTicks = (int)listing.SliderWithTooltip(s.requestExpireTicks, 3600f, 120000f, reqExpireTip); + s.requestExpireTicks = (s.requestExpireTicks / 1500) * 1500; + + string shapingHistoryTip = Tr("RimMind.Personality.Settings.ShapingHistoryMax.Desc", "Keep the last N personality shaping vote records for AI evaluation reference."); + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.ShapingHistoryMax", "Shaping history limit: {0}", $"{s.shapingHistoryMaxCount}"), + shapingHistoryTip); + s.shapingHistoryMaxCount = (int)listing.SliderWithTooltip(s.shapingHistoryMaxCount, 10f, 200f, shapingHistoryTip); + + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Personality.Settings.Section.Timing", "Timing")); + + string dailyIntervalTip = Tr("RimMind.Personality.Settings.DailyInterval.Desc", "Time between automatic daily personality evaluations."); + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.DailyInterval", "Daily evaluation interval: {0} game hours", $"{s.dailyIntervalTicks / 2500f:F1}"), + dailyIntervalTip); + s.dailyIntervalTicks = (int)listing.SliderWithTooltip(s.dailyIntervalTicks, 12000f, 120000f, dailyIntervalTip); + s.dailyIntervalTicks = (s.dailyIntervalTicks / 3000) * 3000; + + string jitterTip = Tr("RimMind.Personality.Settings.JitterRange.Desc", "Variation added to daily interval to stagger colonist evaluations."); + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.JitterRange", "Jitter range: {0} game hours", $"{s.jitterRangeTicks / 2500f:F1}"), + jitterTip); + s.jitterRangeTicks = (int)listing.SliderWithTooltip(s.jitterRangeTicks, 0f, 12000f, jitterTip); + s.jitterRangeTicks = (s.jitterRangeTicks / 600) * 600; + + string eventCdTip = Tr("RimMind.Personality.Settings.EventCooldown.Desc", "Minimum time between event-triggered evaluations."); + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.EventCooldown", "Event cooldown: {0} game hours", $"{s.eventCooldownTicks / 2500f:F1}"), + eventCdTip); + s.eventCooldownTicks = (int)listing.SliderWithTooltip(s.eventCooldownTicks, 600f, 6000f, eventCdTip); + s.eventCooldownTicks = (s.eventCooldownTicks / 300) * 300; + + string timeoutTip = Tr("RimMind.Personality.Settings.RequestTimeout.Desc", "Cancel pending AI requests that exceed this duration."); + listing.LabelWithTooltip( + Tr("RimMind.Personality.Settings.RequestTimeout", "Request timeout: {0} game hours", $"{s.requestTimeoutTicks / 2500f:F1}"), + timeoutTip); + s.requestTimeoutTicks = (int)listing.SliderWithTooltip(s.requestTimeoutTicks, 12000f, 120000f, timeoutTip); + s.requestTimeoutTicks = (s.requestTimeoutTicks / 3000) * 3000; } private static void ResetDefaults() diff --git a/Source/UI/Dialog_PersonalityProfile.cs b/Source/UI/Dialog_PersonalityProfile.cs index 8343d64..15b57ea 100644 --- a/Source/UI/Dialog_PersonalityProfile.cs +++ b/Source/UI/Dialog_PersonalityProfile.cs @@ -9,13 +9,16 @@ namespace RimMind.Personality.UI public class Dialog_PersonalityProfile : Window { private readonly Pawn _pawn; - private PersonalityProfile _profile = null!; + private PersonalityProfile? _profile; private string _editDesc = ""; private string _editWork = ""; private string _editSocial = ""; private Vector2 _scrollNarrative; + private static string Tr(string key, string fallback, params object[] args) + => RimMindAPI.Text.TrOr(key, fallback, args); + public Dialog_PersonalityProfile(Pawn pawn) { _pawn = pawn; @@ -32,10 +35,10 @@ public Dialog_PersonalityProfile(Pawn pawn) public override void PreOpen() { base.PreOpen(); - _profile = AIPersonalityWorldComponent.Instance?.GetOrCreate(_pawn) ?? new PersonalityProfile(); - _editDesc = _profile.description ?? ""; - _editWork = _profile.workTendencies ?? ""; - _editSocial = _profile.socialTendencies ?? ""; + _profile = AIPersonalityWorldComponent.Instance?.TryGet(_pawn); + _editDesc = _profile?.description ?? ""; + _editWork = _profile?.workTendencies ?? ""; + _editSocial = _profile?.socialTendencies ?? ""; } public override void DoWindowContents(Rect inRect) @@ -43,29 +46,29 @@ public override void DoWindowContents(Rect inRect) float y = inRect.y; Text.Font = GameFont.Medium; - Widgets.Label(new Rect(inRect.x, y, inRect.width, 30f), "RimMind.Personality.UI.ProfileTitle".Translate(_pawn.LabelShort)); + Widgets.Label(new Rect(inRect.x, y, inRect.width, 30f), Tr("RimMind.Personality.UI.ProfileTitle", "{0}'s AI Personality", _pawn.LabelShort)); y += 34f; Text.Font = GameFont.Small; - Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), "RimMind.Personality.UI.DescriptionLabel".Translate()); + Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), Tr("RimMind.Personality.UI.DescriptionLabel", "Personality description (background, referenced by AI evaluation)")); y += 22f; _editDesc = Widgets.TextArea(new Rect(inRect.x, y, inRect.width, 64f), _editDesc); y += 68f; - Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), "RimMind.Personality.UI.WorkTendencies".Translate()); + Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), Tr("RimMind.Personality.UI.WorkTendencies", "Work tendencies")); y += 22f; _editWork = Widgets.TextArea(new Rect(inRect.x, y, inRect.width, 42f), _editWork); y += 46f; - Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), "RimMind.Personality.UI.SocialTendencies".Translate()); + Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), Tr("RimMind.Personality.UI.SocialTendencies", "Social tendencies")); y += 22f; _editSocial = Widgets.TextArea(new Rect(inRect.x, y, inRect.width, 42f), _editSocial); y += 46f; - Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), "RimMind.Personality.UI.AINarrative".Translate()); + Widgets.Label(new Rect(inRect.x, y, inRect.width, 20f), Tr("RimMind.Personality.UI.AINarrative", "AI recent narrative (read-only, updated daily by AI)")); y += 22f; - string narrative = _profile.aiNarrative.NullOrEmpty() - ? "RimMind.Personality.UI.NarrativeEmpty".Translate() + string narrative = _profile == null || _profile.aiNarrative.NullOrEmpty() + ? Tr("RimMind.Personality.UI.NarrativeEmpty", "(Not yet evaluated - AI will fill in automatically after running for a while)") : _profile.aiNarrative; float narrativeH = Mathf.Min(80f, Text.CalcHeight(narrative, inRect.width - 16f) + 4f); Rect narrativeOuterRect = new Rect(inRect.x, y, inRect.width, narrativeH); @@ -79,10 +82,10 @@ public override void DoWindowContents(Rect inRect) if (RimMindPersonalityMod.Settings != null) { - string voteToggleLabel = RimMindAPI.Text.TrOr( + string voteToggleLabel = Tr( "RimMind.Personality.UI.EnableShapingVoteToggle", "Enable personality shaping vote popups"); - string voteToggleTip = RimMindAPI.Text.TrOr( + string voteToggleTip = Tr( "RimMind.Personality.UI.EnableShapingVoteToggle.Tip", "When unchecked, new personality traits will not trigger shaping vote popups in the request overlay."); Rect toggleRect = new Rect(inRect.x, y, inRect.width, 24f); @@ -98,17 +101,22 @@ public override void DoWindowContents(Rect inRect) float btnW = (inRect.width - 8f) / 2f; float btnY = inRect.yMax - 36f; - if (Widgets.ButtonText(new Rect(inRect.x, btnY, btnW, 30f), "RimMind.Personality.UI.Save".Translate())) + if (Widgets.ButtonText(new Rect(inRect.x, btnY, btnW, 30f), Tr("RimMind.Personality.UI.Save", "Save"))) { - _profile.description = _editDesc.Trim(); - _profile.workTendencies = _editWork.Trim(); - _profile.socialTendencies = _editSocial.Trim(); - Messages.Message("RimMind.Personality.UI.ProfileSaved".Translate(_pawn.LabelShort), + var targetProfile = _profile ?? AIPersonalityWorldComponent.Instance?.GetOrCreate(_pawn); + if (targetProfile != null) + { + targetProfile.description = _editDesc.Trim(); + targetProfile.workTendencies = _editWork.Trim(); + targetProfile.socialTendencies = _editSocial.Trim(); + _profile = targetProfile; + } + Messages.Message(Tr("RimMind.Personality.UI.ProfileSaved", "[RimMind] {0}'s personality profile saved.", _pawn.LabelShort), MessageTypeDefOf.SilentInput, historical: false); Close(); } - if (Widgets.ButtonText(new Rect(inRect.x + btnW + 8f, btnY, btnW, 30f), "RimMind.Personality.UI.Cancel".Translate())) + if (Widgets.ButtonText(new Rect(inRect.x + btnW + 8f, btnY, btnW, 30f), Tr("RimMind.Personality.UI.Cancel", "Cancel"))) Close(); } } diff --git a/Tests/Contracts/PersonalityEvaluationContracts.cs b/Tests/Contracts/PersonalityEvaluationContracts.cs index 85ccb9c..1a376c5 100644 --- a/Tests/Contracts/PersonalityEvaluationContracts.cs +++ b/Tests/Contracts/PersonalityEvaluationContracts.cs @@ -76,12 +76,55 @@ public void Evaluation_math_dto_and_context_policy_are_stable() Assert.Equal("careful", Assert.Single(restored.identity.traits!)); Assert.Equal("community", Assert.Single(restored.identity.core_values!)); }), - ("profile defaults are empty and collection-safe", () => + ("profile defaults and thread-safe snapshot helpers preserve isolation", () => { var profile = new Data.PersonalityProfile(); Assert.True(profile.IsEmpty); Assert.NotNull(profile.playerShapingHistory); Assert.Empty(profile.playerShapingHistory); + + var rec1 = new Data.ShapingRecord { label = "brave" }; + var rec2 = new Data.ShapingRecord { label = "calm" }; + profile.AddShapingRecord(rec1, 5); + profile.AddShapingRecord(rec2, 5); + var snap = profile.GetShapingHistorySnapshot(); + Assert.Equal(2, snap.Length); + Assert.True(profile.RemoveShapingRecord(rec1)); + Assert.Equal(2, snap.Length); // snapshot isolated from later mutations + Assert.Single(profile.GetShapingHistorySnapshot()); + + var id = new RimMind.Application.Common.Models.Agent.AgentIdentity(); + profile.SetAgentIdentity(id); + Assert.Same(id, profile.GetAgentIdentitySnapshot()); + }), + ("daily evaluation honors configured interval and positive jitter without early 60k bypass", () => + { + Assert.False(Comps.PersonalityTriggerPolicy.ShouldTriggerDailyEvaluation( + enableDailyEval: true, isAwake: true, + ticksGame: 60000, lastDailyDecayTick: 0, + dailyIntervalTicks: 60000, dailyJitterTicks: 1500)); + Assert.True(Comps.PersonalityTriggerPolicy.ShouldTriggerDailyEvaluation( + enableDailyEval: true, isAwake: true, + ticksGame: 61500, lastDailyDecayTick: 0, + dailyIntervalTicks: 60000, dailyJitterTicks: 1500)); + // User configured >24h interval (90,000 ticks) must NOT fire early at 60,000 ticks + Assert.False(Comps.PersonalityTriggerPolicy.ShouldTriggerDailyEvaluation( + enableDailyEval: true, isAwake: true, + ticksGame: 60000, lastDailyDecayTick: 0, + dailyIntervalTicks: 90000, dailyJitterTicks: 0)); + Assert.True(Comps.PersonalityTriggerPolicy.ShouldTriggerDailyEvaluation( + enableDailyEval: true, isAwake: true, + ticksGame: 90000, lastDailyDecayTick: 0, + dailyIntervalTicks: 90000, dailyJitterTicks: 0)); + // Sleeping or disabled does not fire + Assert.False(Comps.PersonalityTriggerPolicy.ShouldTriggerDailyEvaluation( + enableDailyEval: true, isAwake: false, + ticksGame: 120000, lastDailyDecayTick: 0, + dailyIntervalTicks: 60000, dailyJitterTicks: 0)); + Assert.False(Comps.PersonalityTriggerPolicy.ShouldTriggerDailyEvaluation( + enableDailyEval: false, isAwake: true, + ticksGame: 120000, lastDailyDecayTick: 0, + dailyIntervalTicks: 60000, dailyJitterTicks: 0)); }), ("personality context covers personality, dialogue, and split decision scenarios only", () => { @@ -99,34 +142,17 @@ public void Evaluation_math_dto_and_context_policy_are_stable() { string source = ReadSource("Personality", "PersonalityProviderRegistrar.cs") .Replace("\r\n", "\n"); + string skipSource = ReadSource("Extensions", "PersonalityActionSkipCheck.cs"); - Assert.Contains( - "internal static void RegisterAll()\n" + - " {\n" + - " RegisterContextProviders();\n" + - " RegisterPublicProviders();\n" + - " RegisterAgentIdentityProvider();\n" + - " }", - source, - StringComparison.Ordinal); - Assert.Contains( - "private const string PublicProviderOwner = \"RimMind.Personality\";\n" + - " private const int PublicProviderPriority = 100;", - source, - StringComparison.Ordinal); - Assert.Contains( - "RegisterProfileField(\"personality.description\", profile => profile.description);\n" + - " RegisterProfileField(\"personality.work_tendencies\", profile => profile.workTendencies);\n" + - " RegisterProfileField(\"personality.social_tendencies\", profile => profile.socialTendencies);\n" + - " RegisterProfileField(\"personality.ai_narrative\", profile => profile.aiNarrative);", - source, - StringComparison.Ordinal); - Assert.Contains( - "RimMindAPI.Providers.RegisterPawnProvider(\n" + - " \"personality.shaping_history\",\n" + - " PublicProviderOwner,", - source, - StringComparison.Ordinal); + Assert.Contains("RegisterContextProviders();", source, StringComparison.Ordinal); + Assert.Contains("RegisterPublicProviders();", source, StringComparison.Ordinal); + Assert.Contains("RegisterAgentIdentityProvider();", source, StringComparison.Ordinal); + Assert.Contains("PublicProviderOwner = RimMindOwnerConsts.PersonalityModId;", source, StringComparison.Ordinal); + Assert.Contains("RegisterProfileField(\"personality.description\", profile => profile.description);", source, StringComparison.Ordinal); + Assert.Contains("RegisterProfileField(\"personality.work_tendencies\", profile => profile.workTendencies);", source, StringComparison.Ordinal); + Assert.Contains("RegisterProfileField(\"personality.social_tendencies\", profile => profile.socialTendencies);", source, StringComparison.Ordinal); + Assert.Contains("RegisterProfileField(\"personality.ai_narrative\", profile => profile.aiNarrative);", source, StringComparison.Ordinal); + Assert.Contains("\"personality.shaping_history\"", source, StringComparison.Ordinal); // Providers must never create profiles (GetOrCreate is main-thread only) and every // context provider body must read Verse state through the main-thread snapshot. @@ -135,6 +161,7 @@ public void Evaluation_math_dto_and_context_policy_are_stable() Assert.Contains("RimMindAPI.MainThreadSnapshot.GetAsync(", source, StringComparison.Ordinal); Assert.DoesNotContain("async (ctx, ct)", source, StringComparison.Ordinal); Assert.DoesNotContain("RimTalk", source, StringComparison.Ordinal); + Assert.Contains("ShouldSkip(in SkipCheckArgs args) => false;", skipSource, StringComparison.Ordinal); }), ("thought mapper checks IsActiveSpawnedColonist and profile cleanup delegates to Core retention & scoped cache", () => { diff --git a/Tests/Contracts/PersonalityPatchTargetContracts.cs b/Tests/Contracts/PersonalityPatchTargetContracts.cs index a1a3832..3ecd142 100644 --- a/Tests/Contracts/PersonalityPatchTargetContracts.cs +++ b/Tests/Contracts/PersonalityPatchTargetContracts.cs @@ -48,7 +48,8 @@ public void Incident_trigger_hooks_the_public_entry_point_and_queue_identity_sta } string cooldown = ReadSource("Extensions", "PersonalityModCooldown.cs"); - Assert.Contains("OwnerModId => PersonalityRequestDefaults.ModId", cooldown, StringComparison.Ordinal); + Assert.Contains("Id => PersonalityRequestDefaults.ModId", cooldown, StringComparison.Ordinal); + Assert.Contains("OwnerModId => RimMindOwnerConsts.PersonalityModId", cooldown, StringComparison.Ordinal); })); } diff --git a/Tests/README.md b/Tests/README.md index a9928f8..e12d791 100644 --- a/Tests/README.md +++ b/Tests/README.md @@ -1,12 +1,14 @@ # RimMind Personality contract tests -The retained suite is organized around three stable public boundaries: +The retained suite is organized around five stable public contract files: -- `PersonalityEvaluationContracts` — evaluation math, DTO/request behavior, context policy, and malformed-response isolation. -- `PersonalityThoughtInjectionContracts` — owned Thought slots, trigger eligibility, shaping actions, and bounded shaping history. +- `PersonalityEvaluationContracts` — evaluation math, DTO/request behavior, daily-evaluation interval/jitter policy, thread-safe profile snapshots, context policy, and malformed-response isolation. +- `PersonalityThoughtInjectionContracts` — owned Thought slots, trigger eligibility, shaping actions, peak shaping candidate selection, and bounded shaping history. - `PersonalityPersistenceContracts` — settings defaults, complete Scribe field mapping, legacy save keys, and malformed/partial save recovery. +- `PersonalityPatchTargetContracts` — `IncidentWorker.TryExecute` Harmony target regression and queue cooldown/ModId alignment. +- `PersonalityContextTextContracts` — headered context formatting and bounded tail selection. -The compact suite contains 8 Facts and no Theory rows, below the Personality budget of 40 discovered tests. +Count actual discovered cases with the root test-budget script (module budget: strictly below 1000). ## Cutover handoff diff --git a/Tests/RimMindPersonality.Tests.csproj b/Tests/RimMindPersonality.Tests.csproj index 9136a9d..2f73b4f 100644 --- a/Tests/RimMindPersonality.Tests.csproj +++ b/Tests/RimMindPersonality.Tests.csproj @@ -37,7 +37,6 @@ - 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