From dba706b72ed09877b2652d94482f1d4f6a5f491b Mon Sep 17 00:00:00 2001 From: mcocdaa Date: Mon, 23 Nov 2026 06:42:25 +0100 Subject: [PATCH] fix(memory): fix ActionSkipCheck P0, data-driven JobMemoryPolicy, tick throttling, and schema registration refactor: centralize job classification and harden memory lifecycle Extract job classification into a data-driven JobMemoryPolicy with runtime RegisterRule support, replacing the scattered blacklist, whitelist, and importance maps in WorkSessionAggregator. Other changes: - Route trigger writes through MemoryTriggerHelper and publish MemoryChangedEvent on decay, dark-memory, and manual edits - Register DarkMemoryOutput schema via RimMindAPI.Context and fall back to a local schema constant - Stagger dark-memory updates on 250-tick slots and guard async callbacks against stale world components - Fix TimeFormatter to use the event tick for older history dates - Replace archive-to-dark spill with TrimToLimit and return removed counts from ImportanceDecayManager.ApplyDecay - Use RimMindOwnerConsts for extension metadata; stop Memory from vetoing actions via skip check - Add TrOr fallbacks across settings, UI, and trigger text - Update deploy scripts for multi-version builds and runtime DLL exclusions; drop in-csproj deploy target - Expand contract tests for policy, decay counts, and store limits --- .../skills/rimworld-mod-dev/SKILL.md | 616 ------------------ .github/workflows/test.yml | 3 + AGENTS.md | 24 +- About/About.xml | 2 +- INTRODUCTION.txt | 85 --- Languages/English/Keyed/RimMind_Memory.xml | 2 +- README.md | 23 +- README_zh.md | 26 +- Source/Aggregation/JobMemoryPolicy.cs | 116 ++++ Source/Aggregation/Patch_StartJob_Memory.cs | 2 - Source/Aggregation/WorkSessionAggregator.cs | 139 ++-- Source/Core/PawnLookup.cs | 16 - Source/Core/TimeFormatter.cs | 4 +- .../DarkMemory/DarkMemoryResultParserPure.cs | 4 + Source/DarkMemory/DarkMemoryUpdater.cs | 144 ++-- Source/Data/MemoryEntry.cs | 1 + Source/Data/MemorySnapshotService.cs | 12 +- Source/Data/MemoryStoreBase.cs | 19 +- Source/Data/NarratorMemoryStore.cs | 2 - Source/Data/PawnMemoryStore.cs | 2 - Source/Data/RimMindMemoryWorldComponent.cs | 57 +- Source/Debug/MemoryBehaviorAutotestSuite.cs | 24 +- Source/Debug/MemoryDebugActions.cs | 50 +- Source/Decay/ImportanceDecayManager.cs | 9 +- Source/Extensions/MemoryActionSkipCheck.cs | 7 +- Source/Extensions/MemoryModCooldown.cs | 5 +- Source/Extensions/MemorySettingsTab.cs | 3 +- Source/Extensions/MemoryToggleBehavior.cs | 9 +- Source/Injection/MemoryContextProvider.cs | 16 +- Source/Injection/WorkingMemoryProvider.cs | 5 +- Source/Narrator/Patch_IncidentWorker.cs | 87 ++- Source/RimMindMemory.csproj | 13 - Source/RimMindMemoryMod.cs | 5 +- Source/Settings/MemorySettingsDrawer.cs | 147 +++-- Source/Triggers/MemoryTriggerHelper.cs | 18 +- Source/Triggers/Patch_AddHediff.cs | 57 +- Source/Triggers/Patch_AddRelation.cs | 48 +- Source/Triggers/Patch_MentalBreak.cs | 6 +- Source/Triggers/Patch_PawnKill.cs | 26 +- Source/Triggers/Patch_SkillLevelUp.cs | 13 +- Source/UI/BioTabMemoryPatch.cs | 1 + Source/UI/Dialog_MemoryLog.cs | 78 ++- .../MemoryParsingContextContracts.cs | 129 ++-- Tests/Contracts/MemoryStoreContracts.cs | 31 +- Tests/README.md | 8 +- Tests/RimMindMemory.Tests.csproj | 1 + script/deploy-single.ps1 | 121 ++-- script/deploy-single.sh | 95 --- 48 files changed, 933 insertions(+), 1378 deletions(-) delete mode 100644 .claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md delete mode 100644 INTRODUCTION.txt create mode 100644 Source/Aggregation/JobMemoryPolicy.cs delete mode 100644 Source/Core/PawnLookup.cs delete mode 100644 script/deploy-single.sh diff --git a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md b/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md deleted file mode 100644 index 1b3829a..0000000 --- a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md +++ /dev/null @@ -1,616 +0,0 @@ ---- -name: rimworld-mod-dev -description: This skill should be used when developing RimWorld mods, including creating C# Harmony patches, writing XML Defs, implementing AI integration for pawns or events, setting up mod structure, or debugging RimWorld mod issues. Activates for "rimworld mod", "harmony patch", "pawncomp", "incidentdef", "thinkTree", "storyteller", "jobgiver", "hediff", "defmodextension" topics. -version: 1.0.0 ---- - -# RimWorld Mod Development Skill - -This skill provides guidance for developing RimWorld mods, with a focus on C#/Harmony-based behavior modification and AI integration patterns. - ---- - -## Project Context - -- **Game version**: 1.5 / 1.6 -- **Target framework**: .NET Framework 4.8 (net48) -- **Required dependency**: Harmony (brrainz.harmony) - ---- - -## Mod Folder Structure - -``` -MyMod/ -├── About/ -│ ├── About.xml # Required: mod metadata, dependencies, supported versions -│ └── Preview.png # Required: 640x360 or 1280x720, < 1MB -├── Assemblies/ # Compiled DLL files -├── Defs/ # XML definitions (ThingDef, IncidentDef, etc.) -├── Patches/ # PatchOperations XML (safe cross-mod patching) -├── Languages/ # Localization files -│ └── English/ -│ └── Keyed/ -│ └── Keys.xml # Translation keys -├── Sounds/ # .ogg audio files -├── Textures/ # .png texture files (must be PoT: 32x32, 64x64, etc.) -├── Source/ # C# source code (not loaded by game) -│ └── MyMod/ -│ ├── MyModMain.cs -│ └── ... -└── LoadFolders.xml # Optional: conditional folder loading per version -``` - ---- - -## Core Technology Stack - -| Tech | Purpose | Notes | -|------|---------|-------| -| **Harmony** | Runtime method patching | Use PostFix over Prefix to reduce conflicts | -| **C# async/await** | AI API calls | Never block game main thread | -| **ConcurrentQueue** | Thread-safe result passing | Main thread consumes on next Tick | -| **ThingComp** | Per-pawn state storage | Serialized via ExposeData | -| **DefModExtension** | Extend XML Def fields | No C# subclassing needed | -| **Newtonsoft.Json** | JSON parsing | Already bundled in RimWorld | - ---- - -## AI Integration Pattern - -```csharp -// 1. Harmony patch on TickManager - runs every game tick -[HarmonyPatch(typeof(TickManager), "DoSingleTick")] -public static class TickManagerPatch -{ - static void Postfix() - { - // Consume AI results from queue (main thread safe) - while (AIRequestQueue.Results.TryDequeue(out var result)) - result.Apply(); - - // Enqueue new requests (triggers async AI call) - if (ShouldQueryAI()) - AIRequestQueue.Enqueue(new AIRequest(BuildContext())); - } -} - -// 2. Async AI call (runs on background thread) -public static async Task QueryAI(AIRequest request) -{ - var response = await httpClient.PostAsync(endpoint, content); - var result = ParseResponse(await response.Content.ReadAsStringAsync()); - AIRequestQueue.Results.Enqueue(result); -} -``` - ---- - -## Key Game Systems & How to Hook Them - -### Pawn Behavior (Jobs / ThinkTree) - -```csharp -// Force a pawn to do a specific job -pawn.jobs.StartJob(new Job(JobDefOf.GotoWander, targetCell), JobCondition.InterruptForced); - -// Hook into job giving (Harmony prefix on JobGiver_Work) -[HarmonyPatch(typeof(JobGiver_Work), "TryGiveJob")] -static void Postfix(Pawn pawn, ref Job __result) -{ - if (AIController.ShouldOverride(pawn)) - __result = AIController.GetAIJob(pawn); -} -``` - -### Incidents / Storyteller - -```csharp -// Custom StorytellerComp - AI selects which incident to fire -public class StorytellerComp_AIDirector : StorytellerComp -{ - public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) - { - var chosen = AIDirector.GetNextIncident(target); // reads from result queue - if (chosen != null) - yield return new FiringIncident(chosen, this); - } -} -``` - -XML registration: -```xml - - AIDirectorStoryteller - -
  • - - -``` - -### Thoughts / Mood - -```csharp -// Add a thought (affects mood) -pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SomeThought); - -// Remove a thought -pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(thoughtDef); -``` - -### Mental States - -```csharp -// Trigger mental break -pawn.mindState.mentalStateHandler.TryStartMentalState( - MentalStateDefOf.Berserk, forceWake: true); -``` - -### Faction Relations - -```csharp -Faction.OfPlayer.TryAffectGoodwillWith(otherFaction, delta: 15, - lookTarget: pawn, reason: HistoryEventDefOf.GiftsGiven); -``` - ---- - -## ThingComp Pattern (Per-Pawn State) - -```csharp -// 1. Properties class -public class CompProperties_AIController : CompProperties -{ - public CompProperties_AIController() => compClass = typeof(CompAIController); -} - -// 2. Comp class with save/load -public class CompAIController : ThingComp -{ - public bool AIEnabled = false; - public string LastAIDecision = ""; - - public override void ExposeData() - { - base.ExposeData(); - Scribe_Values.Look(ref AIEnabled, "aiEnabled", false); - Scribe_Values.Look(ref LastAIDecision, "lastAIDecision", ""); - } -} - -// 3. XML patch to add comp to all Pawns -// Patches/AddAIComp.xml -``` - -```xml - - - /Defs/ThingDef[thingClass="Pawn"]/comps - -
  • - - - -``` - ---- - -## Harmony Patch Patterns - -```csharp -// PostFix: runs after original method, can modify result -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static void Postfix(ref ReturnType __result, Pawn __instance, OtherParam param) - { - // __result = modified return value - // __instance = the object the method was called on - } -} - -// Prefix: runs before original, can skip original with return false -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static bool Prefix(ref ReturnType __result, Pawn __instance) - { - if (ShouldSkip(__instance)) - { - __result = myResult; - return false; // skip original - } - return true; // run original - } -} -``` - ---- - -## About.xml Template - -```xml - - - My Mod - YourName - YourName.MyMod - -
  • 1.5
  • -
  • 1.6
  • - - My awesome mod. - -
  • - brrainz.harmony - Harmony - steam://url/CommunityFilePage/2009463077 -
  • -
    - -
  • brrainz.harmony
  • -
    - -``` - ---- - -## Mod Entry Point Pattern - -```csharp -using HarmonyLib; -using Verse; - -namespace MyMod -{ - public class MyModMain : Mod - { - public static MyModSettings Settings; - - public MyModMain(ModContentPack content) : base(content) - { - Settings = GetSettings(); - new Harmony("YourName.MyMod").PatchAll(); - } - - public override string SettingsCategory() => "My Mod"; - public override void DoSettingsWindowContents(Rect rect) - => Settings.DoWindowContents(rect); - } - - public class MyModSettings : ModSettings - { - public string ApiKey = ""; - public string Model = "gpt-4o-mini"; - public int CooldownTicks = 2500; // ~1 game hour - - public override void ExposeData() - { - Scribe_Values.Look(ref ApiKey, "apiKey", ""); - Scribe_Values.Look(ref Model, "model", "gpt-4o-mini"); - Scribe_Values.Look(ref CooldownTicks, "cooldownTicks", 2500); - } - } -} -``` - ---- - -## AI Context Building (Game State → Prompt) - -Key game state to include in AI prompts: - -```csharp -public static string BuildGameContext(Map map) -{ - var sb = new StringBuilder(); - // Colony stats - sb.AppendLine($"Colonists: {map.mapPawns.FreeColonists.Count}"); - sb.AppendLine($"Food: {map.resourceCounter.GetCount(ThingDefOf.MealSimple)}"); - sb.AppendLine($"Threat: {StorytellerUtility.GetThreatBiggestGoodwill(Faction.OfPlayer)}"); - // Recent events (from WorldComponent history) - // Current threats - foreach (var raid in map.attackTargetsCache.TargetsHostileToColony) - sb.AppendLine($"Threat: {raid.Thing.Label}"); - return sb.ToString(); -} -``` - ---- - -## Common XML Def Types - -| Def | Purpose | -|-----|---------| -| `ThingDef` (thingClass=Pawn) | Pawn/creature definition | -| `IncidentDef` | Events (raids, traders, etc.) | -| `StorytellerDef` | Storyteller configuration | -| `ThoughtDef` | Mood thoughts | -| `MentalStateDef` | Mental breaks | -| `JobDef` | Work job types | -| `HediffDef` | Health conditions/implants | -| `TraitDef` | Pawn traits | -| `InteractionDef` | Social interactions | -| `ThinkTreeDef` | AI behavior tree | -| `DutyDef` | Temporary behavior duties | - -## Performance Guidelines - -- AI calls: minimum 2500 ticks (~1 game hour) cooldown between calls per pawn -- Use `ConcurrentQueue` for all cross-thread data transfer -- Cache game state reads (don't traverse all pawns every tick) -- Use `ModsConfig.IsActive("packageId")` for conditional compatibility patches -- Limit AI context to ~500 tokens for routine decisions - ---- - -## Debugging - -```csharp -// Log to RimWorld debug log -Log.Message("[MyMod] Debug info here"); -Log.Warning("[MyMod] Something unexpected"); -Log.Error("[MyMod] Something broke"); - -// Dev mode actions (shows in debug menu) -[DebugAction("MyMod", "Trigger AI Event")] -static void TriggerAIEvent() { /* ... */ } -``` - -Enable dev mode in game: Options → Development Mode - ---- - -## Pitfalls & Lessons Learned - -### 1. UnityWebRequest 只能在主线程调用 - -**症状**:`UnityWebRequest.SendWebRequest()` 在 `Task.Run` 内调用时返回 HTTP 0,无任何错误日志。 - -**原因**:Unity 的 `UnityWebRequest` 不是线程安全的,必须在主线程发起。 - -**修复**:后台线程 HTTP 调用改用 `System.Net.Http.HttpClient`(net48 支持,线程安全): - -```csharp -private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; - -// 可在 Task.Run 内安全调用 -using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = content }; -req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); -using var res = await _httpClient.SendAsync(req); -``` - ---- - -### 2. OpenAI 兼容 API 的 FormatEndpoint 三段式逻辑 - -用户填写的 endpoint 格式不一,需统一处理: - -```csharp -private static string FormatEndpoint(string baseUrl) -{ - if (string.IsNullOrEmpty(baseUrl)) return string.Empty; - string trimmed = baseUrl.Trim().TrimEnd('/'); - // 已是完整 endpoint → 不变 - if (trimmed.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase)) - return trimmed; - var uri = new Uri(trimmed); - string path = uri.AbsolutePath.Trim('/'); - // 有版本路径(如 /v1)→ 只追加 /chat/completions - if (!string.IsNullOrEmpty(path)) - return trimmed + "/chat/completions"; - // 裸域名 → 追加 /v1/chat/completions - return trimmed + "/v1/chat/completions"; -} -``` - -| 输入 | 输出 | -|------|------| -| `https://api.deepseek.com` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1/chat/completions` | 原样返回 | - ---- - -### 3. net48 中禁止使用 `dynamic` 类型 - -**症状**:编译报错,缺少 `Microsoft.CSharp` 引用。 - -**替代方案**:用 Newtonsoft.Json 的 `JObject`: - -```csharp -// 不要用 dynamic -// dynamic obj = JsonConvert.DeserializeObject(text); // 编译失败 - -// 改用 JObject -var jobj = JObject.Parse(text); -string reply = jobj["choices"]?[0]?["message"]?["content"]?.ToString() ?? ""; -int tokens = jobj["usage"]?["total_tokens"]?.Value() ?? 0; -``` - ---- - -### 4. RimWorld 纹理必须是 2 的幂次方(PoT) - -**症状**:`Texture X.png is being reloaded with reduced mipmap count (clamped to 2) due to non-power-of-two dimensions: (24x24)` - -**原因**:RimWorld(Unity)要求 UI 纹理尺寸为 2 的幂次方(16、32、64…)。 - -**规则**: -- 不要用游戏内置的非 PoT 纹理(如 `UI/Buttons/Info` 是 24×24) -- 自己提供纹理放在 `Textures/UI/MyMod/Icon.png`,使用 32×32 或 64×64 - -```csharp -// 错误:复用游戏内置 24×24 纹理 -ContentFinder.Get("UI/Buttons/Info", reportFailure: false) - -// 正确:使用自己的 32×32 纹理 -ContentFinder.Get("UI/MyMod/Icon", reportFailure: false) -``` - ---- - -### 5. `[DebugAction]` Dev 菜单搜索按动作名,不按分类名 - -Dev 菜单搜索框只匹配**动作名称**,不匹配 category 参数。 - -```csharp -// category="MyMod", name="Test API Connection" -[DebugAction("MyMod", "Test API Connection", actionType = DebugActionType.Action)] -``` - -- 搜索 `"MyMod"` → **找不到** -- 搜索 `"Test API"` → **可以找到** -- 或者在 Actions 列表滚动到 "MyMod" 分类下查看 - ---- - -### 6. Keyed XML 不会产生翻译错误 - -"Translation data has X errors" 这条日志**只来自 `DefInjected/` 翻译文件**(key 与 Def 不匹配时触发)。 - -`Languages/*/Keyed/*.xml` 无论多余还是缺失 key 都**不会**触发该错误: -- 多余的 key → 静默忽略 -- 缺失的 key → 代码中显示 key 原文字符串 - -如果看到翻译错误,首先检查其他 mod 的 DefInjected 目录,而非自己的 Keyed 文件。 - ---- - -### 7. WorkGiver 三模式扫描:用 `wg.def.scanCells` 区分,而非类型判断 - -**背景**:枚举某 WorkType 可执行目标时,WorkGiver 有三种工作模式。 - -**错误做法**:`if (scanner is WorkGiver_Grower)` — 只覆盖 Growing,漏掉 SmoothWall、BuildRoof、RemoveRoof、ClearSnow、PaintFloor 等 8 个格子类 WorkGiver。 - -**正确做法**:用 `wg.def.scanCells` 属性区分,与具体类型无关: - -```csharp -foreach (var wg in workType.workGiversByPriority) -{ - if (wg.Worker is not WorkGiver_Scanner scanner) continue; - - if (wg.scanCells) - { - // 格子类:Growing / SmoothWall / BuildRoof / RemoveRoof / - // ClearSnow / PaintFloor / ClearPollution 等 - var cells = scanner.PotentialWorkCellsGlobal(pawn); - foreach (var cell in cells) - { - if (scanner.HasJobOnCell(pawn, cell, false)) - // 处理 cell 目标 - } - } - else - { - // 物体类(默认):Mining / Hauling / Tend / Hunt 等 - // DoBill 工作台(Cooking / Crafting / Smithing)也在此分支, - // 额外通过 IBillGiver.BillStack.FirstShouldDoNow 获取账单名称 - var things = scanner.PotentialWorkThingsGlobal(pawn); - foreach (var thing in things) - { - if (scanner.HasJobOnThing(pawn, thing, false)) - // 处理 thing 目标 - } - } -} -``` - -`IBillGiver` 账单名称: -```csharp -if (thing is IBillGiver billGiver) -{ - var bill = billGiver.BillStack?.FirstShouldDoNow; - label = bill != null ? $"{thing.LabelShort} → {bill.LabelCap}" : thing.LabelShort; -} -``` - -所有 WorkGiver 调用包在 `try-catch` 内,部分 WorkGiver 在特定地图状态下会抛异常。 - ---- - -### 8. 插件 API 可扩展分类:C# 8 接口默认方法代替硬编码 HashSet - -**问题**:`ExecuteBatch` 需要知道哪些动作是 Job 类(需要 `requestQueueing`),原实现用硬编码 HashSet: -```csharp -// 脆弱:外部 mod 注册的 Job 类动作不在此集合中 -private static readonly HashSet _jobBasedIntents = new() { "force_rest", "assign_work", ... }; -``` - -**修复**:用 C# 8 接口默认方法声明扩展点: -```csharp -public interface IActionRule -{ - bool IsJobBased => false; // 默认非 Job 类;Job 类实现覆盖为 true - bool Execute(Pawn actor, Pawn? target, string? param, bool requestQueueing = false); -} - -// 内置 Job 类动作 -public class ForceRestAction : IActionRule -{ - public bool IsJobBased => true; - // ... -} - -// ExecuteBatch 直接读属性,无需查 HashSet -bool isJobAction = rule.IsJobBased; -``` - -**优点**:外部 mod 注册自定义 Job 类动作时,只需在自己的类中声明 `public bool IsJobBased => true;`,框架代码无需改动。 - ---- - -### 9. RimWorld AI 空闲判断:GotoWander ≠ 游戏空闲,但 = AI 可接管 - -**问题**:`pawn.jobs.curJob == null` 不足以判断"AI 是否可以重定向小人"。 - -- `GotoWander`:小人在漫步,`curJob != null`,游戏认为不空闲 -- `playerForced = true`:玩家手动命令的 Job,AI 不应打断 - -**正确的 AI 可接管判断**: - -```csharp -public static bool IsAdvisorIdle(Pawn pawn) -{ - var job = pawn.jobs?.curJob; - if (job == null) return true; - if (job.playerForced) return false; // 玩家命令优先 - - // 这些 Job 类型 AI 可安全打断 - var def = job.def; - return def == JobDefOf.Wait - || def == JobDefOf.Wait_Wander - || def == JobDefOf.GotoWander - || def == JobDefOf.Wait_MaintainPosture; -} -``` - -调试输出应明确区分:`"是否空闲(AI 可接管)"` 而非 `"游戏空闲"`,避免概念混淆。 - ---- - -### 10. ModSettings 孤儿条目:warn 但不删除,保留以备 mod 重启恢复 - -**场景**:玩家禁用了某外部 mod 的某动作(存入 `DisabledIntents`),然后卸载该外部 mod。 -下次加载时该 intentId 不再注册,但 `DisabledIntents` 仍保存着它。 - -**策略**:`[StaticConstructorOnStartup]`(所有 Mod 构造器完成后运行,此时所有动作已注册)中验证并 **warn 但不删除**: - -```csharp -[StaticConstructorOnStartup] -internal static class ActionsSettingsValidator -{ - static ActionsSettingsValidator() - { - if (MyModMain.Settings == null) return; - var registered = new HashSet(MyModAPI.GetSupportedIntents()); - foreach (var id in MyModMain.Settings.DisabledIntents) - { - if (!registered.Contains(id)) - Log.Warning($"[MyMod] 设置中有未注册的动作 '{id}'(对应 mod 未加载?),已保留以备恢复。"); - } - } -} -``` - -**为什么不删除**:若玩家重新启用该外部 mod,孤儿条目会自动重新生效,无需玩家重新配置。 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fb71105..d7378da 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,11 +1,13 @@ name: Unit Tests on: + workflow_dispatch: push: branches: [main, master] paths: - 'Source/**' - 'Tests/**' + - 'IntegrationTests/**' - 'ArchTests/**' - '.github/workflows/test.yml' pull_request: @@ -13,6 +15,7 @@ on: paths: - 'Source/**' - 'Tests/**' + - 'IntegrationTests/**' - 'ArchTests/**' - '.github/workflows/test.yml' diff --git a/AGENTS.md b/AGENTS.md index c1f61e0..7ada904 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,10 +16,10 @@ | 项 | 值 | |----|-----| -| 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 | RimMindMemory, RootNS: RimMind.Memory | -| 依赖 | RimMindCore.dll, Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json | +| 依赖 | 0_RimMindDomain.dll, 1_RimMindApplication.dll, 2_RimMindCore.dll (`Private=false`), Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json | ## 源码结构 @@ -42,17 +42,19 @@ Source/ ├── Injection/MemoryContextProvider.cs 注册ContextKey(memory_pawn/memory_narrator,主线程快照 + MemoryRetrievalScorer)与公开Brief Provider │ WorkingMemoryProvider.cs 只读旧工作记忆ContextKey(working_memory,主线程快照读取) ├── Aggregation/ +│ ├── JobMemoryPolicy.cs 数据驱动的工作记忆分类策略(Ignored/SignificantSingle/Aggregatable + RegisterRule) │ ├── WorkSessionAggregator.cs GameComponent工作聚合(不持久化, 每日清理非活跃Pawn会话) │ └── Patch_StartJob_Memory.cs JobTracker Postfix ├── Triggers/ 5个Patch(AddHediff/Kill/MentalBreak/SkillLevelUp/AddRelation) │ MemoryTriggerHelper.cs 触发器辅助(ShouldProcess+WriteMemory+TryUpgradeToNarrator) -├── Narrator/Patch_IncidentWorker.cs 叙事者事件Postfix -├── DarkMemory/DarkMemoryUpdater.cs 每日暗记忆生成(ScenarioIds.Memory, LlmRequestEnvelopeBuilder + RimMindAPI.Request.Send) -│ DarkMemoryResultParserPure.cs 纯逻辑解析器(生产+测试共用,JSON修复+解析) -├── Decay/ImportanceDecayManager.cs 衰减管理(默认关闭,单MemoryStoreBase重载) -├── Core/TimeFormatter.cs + ImportanceDecayCalculator.cs + MemoryRetrievalScorer.cs + PawnLookup.cs +├── Narrator/Patch_IncidentWorker.cs 叙事者事件Postfix(元数据分类+词元表评分) +├── DarkMemory/DarkMemoryUpdater.cs 每日暗记忆生成(250tick槽位交错+ScenarioIds.Memory+DarkMemoryOutput Schema) +│ DarkMemoryResultParserPure.cs 纯逻辑解析器+DarkMemoryOutput Schema(生产+测试共用,JSON修复+解析) +├── Decay/ImportanceDecayManager.cs 衰减管理(默认开启 enableDecay=true, 返回清理条数) +├── Core/TimeFormatter.cs + ImportanceDecayCalculator.cs + MemoryRetrievalScorer.cs + RimMindMemoryBridge.cs +├── Extensions/ Core扩展适配器(ActionSkipCheck/ModCooldown/SettingsTab/ToggleBehavior) ├── UI/BioTabMemoryPatch.cs + Dialog_MemoryLog.cs -└── Debug/MemoryDebugActions.cs +└── Debug/MemoryDebugActions.cs + MemoryBehaviorAutotestSuite.cs ``` ## 记忆触发来源 @@ -83,7 +85,7 @@ Source/ |-----|------|------| | ContextKeyRegistry.Register | 注入记忆上下文 | ✅ 使用中 | | LlmRequestEnvelopeBuilder + RimMindAPI.Request.Send | 暗记忆AI生成 | ✅ 使用中 | -| SchemaRegistry.DarkMemoryOutput | 暗记忆JSON Schema | ✅ 使用中 | +| RimMindAPI.Context.RegisterSchema / FindSchema | 暗记忆JSON Schema(`DarkMemoryOutput`) | ✅ 使用中 | | RimMindAPI.RegisterSettingsTab | 设置页标签 | ✅ 使用中 | | RimMindAPI.RegisterModCooldown | 冷却注册 | ✅ 使用中 | | RimMindAPI.IsConfigured | API可用性检查 | ✅ 使用中 | @@ -119,7 +121,7 @@ Source/ ### ✅ 必须做 - 新触发器在Settings添加开关 + UI暴露控件 -- 新工作类型在对应HashSet添加 + 翻译XML添加 `RimMind.Memory.Work.{defName}` +- 新工作类型通过 `JobMemoryPolicy.RegisterRule`(或在 `JobMemoryPolicy` 默认表)注册,并在翻译XML添加 `RimMind.Memory.Work.{defName}` - 记忆写入用try-catch ### ⚠️ 先询问 diff --git a/About/About.xml b/About/About.xml index 8291f79..0f0ceea 100644 --- a/About/About.xml +++ b/About/About.xml @@ -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][b]RimMind-Memory[/b][/td][td]3-Tier cognitive memory hierarchy, work aggregation & temporal decay[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Memory]Link[/url][/td][/tr] -[tr][td]RimMind-Personality[/td][td]Big-Five psychological profiles, dawn monologues & dynamic mood thoughts[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality]Link[/url][/td][/tr] +[tr][td]RimMind-Personality[/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] diff --git a/INTRODUCTION.txt b/INTRODUCTION.txt deleted file mode 100644 index 95292cf..0000000 --- a/INTRODUCTION.txt +++ /dev/null @@ -1,85 +0,0 @@ -RimMind - Memory -[h1]RimMind - Memory (三层记忆与时间沉淀)[/h1] - -你的殖民者终于有记忆了。 -[i]你的殖民者终于拥有了记忆——不仅活在当下,更沉淀着过去的荣光、创伤与羁绊。[/i] -[i]Your colonists finally remember — Not just living in the moment, but carrying past triumphs, traumas, and bonds.[/i] - -在原版 RimWorld 里,小人被海盗砍伤、经历精神崩溃、和爱人结婚——然后转头就忘。昨天差点死掉?不记得了。上个月连续挖了十天矿?毫无印象。RimMind-Memory 让殖民者真正记住发生在他们身上的一切。 -[hr] -[h2]📖 中文介绍 / Chinese Overview[/h2] - -三层记忆,越久越深 -[b]RimMind-Memory[/b] 为殖民者与整个殖民地构建了由浅入深的三层记忆体系。在原版游戏中,小人经历九死一生的围攻、目睹至亲离世,往往转眼就如同从未发生。而 RimMind-Memory 让每一段过往都在小人心中留下不可磨灭的印记。 - -活跃记忆是"最近发生了什么"——刚被袭击、刚升了技能、刚和谁吵了架。存档记忆是"过去的重要片段"——按重要度排列,琐事淡去,关键时刻长留。最有趣的是暗记忆:AI 每天把当日记忆凝练成不超过 50 字的长期印象。一个连续挖矿的小人会逐渐形成"资深矿工,经常长时间工作"的印象;被海盗袭击受伤后,会沉淀出"对袭击保持警惕"。这些印象永久保留,构成了殖民者性格的底色——而且会随着经历不断演进。 -[h3]🌟 核心特性[/h3] -[list] -[*] [b]三层递进式记忆架构[/b]: - [list] - [*] [b]活跃记忆 (Working Memory)[/b]:记录刚发生的小事、近期的争执与偶遇。 - [*] [b]情节归档记忆 (Episodic Memory)[/b]:筛选并归档真正重大的里程碑事件(战斗救护、重伤、结婚、奇迹生还)。 - [*] [b]暗记忆与潜意识 (Dark / Semantic Memory)[/b]:由 AI 每日自动凝练出深层印象(例如:“经历多次严寒袭击后,对食物短缺与危机高度警惕”),化为小人性格的恒久底色! - [/list] -[*] [b]记忆自然衰减与重点固定 (Pinning)[/b]:普通琐事会随着游戏天数自然淡忘,关键记忆可手动加星固定,永久保留。 -[*] [b]全地图与殖民地大事件史诗[/b]:独立记录整个殖民地的编年史,供叙事者与小人决策调用。 -[*] [b]100% 存档安全持久化[/b]:所有记忆随游戏存档无损保存与反序列化,读档不失忆。 -[/list] - -暗记忆是最值得体验的部分。它不是简单的摘要,而是 AI 对殖民者经历的"理解"。一个经历了多次袭击的小人,暗记忆会从"遭遇袭击受伤"逐渐演变为"对危险保持高度警觉";一个长期照顾病人的医生,会沉淀出"富有同情心,经常照料伤员"。你会在记忆面板里看到这些印象一条条生长,像是在读一本人物小传。 -[hr] -[h2]🌐 English Overview[/h2] - -工作也有记忆 -[b]RimMind-Memory[/b] constructs a rich three-tier cognitive memory architecture for individual colonists and the colony as a whole. Rather than instantly forgetting past perils or companions, pawns accumulate enduring experiences. - -搬运了 12 次货物、挖了 4 小时矿、救了受伤的队友——不再是转瞬即逝的 Job 日志。连续同类工作会被智能合并为一条记忆,不会刷屏。而救援、战斗等重要行为则单独记录,不会被日常琐事淹没。你甚至能看到小人的空闲时段——"休息/待机 约2.4游戏时",仿佛他们真的偷了个懒。 -[h3]🌟 Key Highlights[/h3] -[list] -[*] [b]Three-Tier Memory Architecture[/b]: - [list] - [*] [b]Working Memory[/b]: Tracks immediate real-time happenings, minor discussions, and work stints. - [*] [b]Episodic Memory[/b]: Archives high-salience milestones such as miraculous survival, loss of loved ones, or heroic rescues. - [*] [b]Dark / Semantic Memory[/b]: Subconscious impressions distilled by the LLM that permanently shape the colonist's core identity. - [/list] -[*] [b]Natural Decay & Memory Pinning[/b]: Trivial memories gradually fade over seasons unless pinned by the player as key life moments. -[*] [b]Colony Chronicle[/b]: Preserves colony-wide historical events for use in storytelling and collective reflection. -[*] [b]Savegame Serialization[/b]: Perfectly serialized into save files via WorldComponent. -[/list] - -叙事者:殖民地的编年史 - -除了个人记忆,还有一个叙事者在记录殖民地的历史。海盗袭击、商队来访、新殖民者加入——这些超越个人的大事件被独立记录。当 AI 做决策时,不仅知道"我经历了什么",还知道"我们经历了什么"。叙事者也有自己的暗记忆——AI 会把殖民地的重大事件凝练为长期叙事,比如"频繁遭受海盗袭击"或"近期人口快速增长"。 - -记忆会衰减,但你可以固定 - -开启衰减后,普通琐事的重要度逐日降低,最终归档淡出。但你可以"固定"不想遗忘的记忆——就像在日记本里画重点。暗记忆不受衰减影响,它们是永恒的性格底色。 - -配合其他 RimMind 模组,记忆变得有力量 - -Memory 是 RimMind 生态的基础。当 Personality 生成人格、Advisor 做工作决策、Dialogue 进行对话时,它们都能读取殖民者的记忆。一个记得"上次独自面对袭击差点死掉"的小人,在面对危险时会做出完全不同的反应。记忆让 AI 的行为从"此刻的判断"变成"经验的积累"——这才是真正的智能。 - -25 项精细设置 - -从触发来源到容量上限,从注入比例到衰减速率,每一项都可以调节。默认配置开箱即用,但如果你想微调——比如只记录重大事件来节省 Token,或者增大暗记忆条数让 AI 更了解每个殖民者——都可以在设置中实现。 - -手动添加记忆 - -在记忆日志窗口中,你可以手动为殖民者添加自定义记忆。想给某个小人加一段"曾经是贵族"的背景故事?直接输入即可。手动记忆和自动记忆享有同等地位,会被 AI 读取和参考。 - -记忆随存档保存 - -所有记忆通过 WorldComponent 序列化,载入存档后完整恢复。你的殖民者不会因为读档而失忆。 - -推荐搭配 - -- RimMind-Personality:让 AI 基于记忆生成更真实的人格 -- RimMind-Dialogue:对话中殖民者会引用自己的记忆 -- RimMind-Advisor:工作决策会考虑过去的经验 -- RimMind-Storyteller:叙事者结合记忆选择更合理的事件 -[hr] -[h2]⚙️ 依赖与推荐 / Requirements & Recommendations[/h2] -[list] -[*] [b]必需前置 (Required)[/b]: Harmony, [b]RimMind-Core[/b] -[*] [b]推荐搭配 (Recommended)[/b]: [b]RimMind-Personality[/b]、[b]RimMind-Advisor[/b] -[/list] diff --git a/Languages/English/Keyed/RimMind_Memory.xml b/Languages/English/Keyed/RimMind_Memory.xml index 8bc411c..ac4eeff 100644 --- a/Languages/English/Keyed/RimMind_Memory.xml +++ b/Languages/English/Keyed/RimMind_Memory.xml @@ -156,7 +156,7 @@ Contracted {0} ({1}) Unknown - {0}{1} died + {0} {1} died {0} died Colonist {0} died (killed by {0}) diff --git a/README.md b/README.md index b52e872..09ddd17 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@

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

    @@ -23,9 +23,9 @@ **RimMind-Memory** implements a biologically inspired, multi-tiered cognitive memory system for RimWorld. Rather than overwhelming LLM prompts with unfiltered event dumps, memories are structured, filtered, and consolidated across distinct cognitive layers. ### 3-Tier Architecture -1. **Sensory & Working Buffer (L1)**: Captures immediate environmental sensations and short-lived interactions. Automatically decays after several hours. -2. **Episodic Daily Chronicle (L2)**: Records daily milestones, battle triumphs, tragic losses, and relationship shifts in concise narrative entries. -3. **Reflective & Dark Memories (L3)**: Enduring convictions, traumas, and life philosophy shaped by major colony events (e.g., witnessing cannibalism, surviving a betrayal, or falling in love). +1. **Active Memory (Tier 1)**: Chronological record of recent work sessions, combat/medical milestones, social relations, injuries, and colony incidents (`maxActive`, default 30). +2. **Archive Memory (Tier 2)**: Importance-ranked episodic store retaining overflowed milestones while pruning lowest-importance noise (`maxArchive`, default 50). +3. **Deep / Dark Memory (Tier 3)**: Pinned long-term psychological impressions synthesized daily via staggered AI consolidation (`DarkMemoryUpdater`, under 50 characters each) and aligned with Core's KV-cache-friendly context layers. --- @@ -40,13 +40,14 @@ ```mermaid flowchart TD - RawEvent["In-Game Event (Raid / Wedding / Trauma)"] --> L1["Sensory Buffer (Immediate Context)"] - L1 --> Filter{"Importance Filter"} - Filter -- Low Significance --> Decay["Natural Forgetting & Pruning"] - Filter -- High Significance --> L2["Episodic Memory Consolidation"] - L2 --> Synthesis["Sleep / Meditation Synthesis"] - Synthesis --> L3["Deep Reflection & Permanent Personality Imprint"] - L3 --> Prompt["Injected into Core Zone 2 Context"] + RawEvent["In-Game Event (Work / Combat / Relations / Incidents)"] --> Policy["JobMemoryPolicy & Event Triggers"] + Policy --> Active["Active Tier (Chronological Recent Events)"] + Active --> Overflow{"Capacity Overflow or Daily Decay"} + Overflow -- Low Importance --> Decay["Natural Importance Decay & Pruning"] + Overflow -- High Importance --> Archive["Archive Tier (Importance-Ranked Episodes)"] + Active --> DailyConsolidation["Daily Staggered AI Consolidation (DarkMemoryUpdater)"] + DailyConsolidation --> Dark["Deep / Dark Tier (Pinned Long-Term Impressions)"] + Dark --> Prompt["Injected into Core Context (memory_pawn / memory_narrator)"] ``` --- diff --git a/README_zh.md b/README_zh.md index d11293f..7110591 100644 --- a/README_zh.md +++ b/README_zh.md @@ -8,7 +8,7 @@

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

    @@ -22,10 +22,10 @@ **RimMind-Memory** 为 RimWorld 引入了受生物认知心理学启发的三层记忆体系。它拒绝将未经清洗的事件全量丢给大模型,而是通过分层聚合、自然遗忘衰减与重点固定,让小人的记忆既丰富又高效。 -### 三层认知架构 -1. **感知与工作记忆 (L1)**:捕获当下的即时感知与琐碎交流,随时间推移数小时内平滑衰减。 -2. **情节记忆编年史 (L2)**:记录战役胜利、惨痛牺牲、重要婚礼等关键里程碑,以简明摘要方式沉淀。 -3. **反思与暗记忆 (L3)**:重大人生挫折(目睹同类相食、遭遇背叛、痛失挚友)形成的根深蒂固信念与人生哲学,永久性重塑其心理防御机制。 +### 三层记忆架构 +1. **活跃记忆(Active 层)**:按时间顺序记录近期工作会话、战斗/医疗节点、社交关系变化、伤病与殖民地重大事件(默认上限 `maxActive=30`)。 +2. **归档记忆(Archive 层)**:按重要度排序承接活跃层溢出的情节里程碑,自动淘汰最低重要度的日常噪音(默认上限 `maxArchive=50`)。 +3. **暗记忆(Dark 层)**:每日按交错槽位由 AI 提炼(`DarkMemoryUpdater`,每条 ≤50 字)的固定长期心理烙印,与 Core 的前缀缓存上下文层级对齐。 --- @@ -40,14 +40,14 @@ ```mermaid flowchart TD - RawEvent["游戏内突发事件 (袭击 / 婚礼 / 绝望)"] --> L1["瞬时感知层 (即时上下文)"] - L1 --> Filter{"重要度评估过滤"} - Filter -- 低重要度 --> Decay["自然遗忘与修剪"] - Filter -- 高重要度 --> L2["情节记忆凝聚与编年史"] - L2 --> Synthesis["睡眠与冥想状态整理反思"] - L3["深度反思层与永久心理烙印"] - Synthesis --> L3 - L3 --> Prompt["安全注入 Core 核心 Zone 2 上下文"] + RawEvent["游戏内事件 (工作会话 / 战斗 / 关系 / 袭击)"] --> Policy["JobMemoryPolicy 与事件触发器"] + Policy --> Active["活跃层 Active (按时间记录近期事件)"] + Active --> Overflow{"容量溢出与每日重要度衰减"} + Overflow -- 低重要度 --> Decay["自然遗忘与修剪"] + Overflow -- 高重要度 --> Archive["归档层 Archive (按重要度保留情节里程碑)"] + Active --> DailyConsolidation["每日交错槽位 AI 暗记忆提炼 (DarkMemoryUpdater)"] + DailyConsolidation --> Dark["暗记忆层 Dark (固定长期心理烙印)"] + Dark --> Prompt["安全注入 Core 上下文 (memory_pawn / memory_narrator)"] ``` --- diff --git a/Source/Aggregation/JobMemoryPolicy.cs b/Source/Aggregation/JobMemoryPolicy.cs new file mode 100644 index 0000000..3ef8965 --- /dev/null +++ b/Source/Aggregation/JobMemoryPolicy.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; + +namespace RimMind.Memory.Aggregation +{ + public enum JobMemoryKind + { + Unknown = 0, + Ignored = 1, + SignificantSingle = 2, + Aggregatable = 3 + } + + public readonly struct JobMemoryRule + { + public JobMemoryKind Kind { get; } + public float Importance { get; } + + public JobMemoryRule(JobMemoryKind kind, float importance = 0f) + { + Kind = kind; + Importance = importance; + } + } + + /// + /// Data-driven single source of truth for classifying RimWorld job defNames into + /// ignored, significant single-event, or aggregatable work-session memories. + /// External mods may register or override rules at runtime via . + /// + public static class JobMemoryPolicy + { + private static readonly ConcurrentDictionary Rules = BuildDefaultRules(); + + private static ConcurrentDictionary BuildDefaultRules() + { + var map = new Dictionary(StringComparer.Ordinal); + + // Ignored ambient / movement / non-work jobs + string[] ignoredJobs = + { + "Wait", "Wait_MaintainPosture", "Wait_Asleep", "Wait_Downed", + "Wait_SafeTemperature", "Wait_Wander", "Wait_Combat", + "Goto", "GotoWander", "GotoSafeTemperature", + "SocialFight", "MarryAdjacentPawn", "Lovin", "StandAndStare", + "IdleWhileDespawned" + }; + foreach (var job in ignoredJobs) + map[job] = new JobMemoryRule(JobMemoryKind.Ignored); + + // Significant single-occurrence jobs recorded immediately as events + (string Name, float Importance)[] significantJobs = + { + ("AttackMelee", 0.9f), + ("AttackStatic", 0.9f), + ("Rescue", 0.8f), + ("TendPatient", 0.8f), + ("FeedPatient", 0.7f), + ("DeliverFood", 0.6f), + ("Slaughter", 0.6f), + ("Tame", 0.7f), + ("Train", 0.6f), + ("Milk", 0.5f), + ("Shear", 0.5f), + ("PrisonerAttemptRecruit", 0.7f) + }; + foreach (var (name, importance) in significantJobs) + map[name] = new JobMemoryRule(JobMemoryKind.SignificantSingle, importance); + + // Repetitive work jobs aggregated into work sessions + string[] aggregatableJobs = + { + "Sow", "PlantSeed", "Replant", + "Harvest", "HarvestDesignated", + "CutPlant", "CutPlantDesignated", + "FinishFrame", "PlaceNoCostFrame", + "Deconstruct", "Uninstall", + "Repair", "FixBrokenDownBuilding", + "Mine", "Clean", + "HaulToCell", "HaulToContainer", + "HaulToTransporter", "HaulToPortal", + "HaulCorpseToPublicPlace", + "DoBill", "Research", "Hunt", + "BeatFire", "ExtinguishSelf", + "SmoothFloor", "RemoveFloor", "SmoothWall", + "BuildRoof", "RemoveRoof", + "PaintBuilding", "PaintFloor", + "RemovePaintBuilding", "RemovePaintFloor", + "OperateDeepDrill", "OperateScanner", + "ExtractTree", "Refuel", "RearmTurret", + "ClearSnow", "ManTurret" + }; + foreach (var job in aggregatableJobs) + map[job] = new JobMemoryRule(JobMemoryKind.Aggregatable); + + return new ConcurrentDictionary(map, StringComparer.Ordinal); + } + + public static void RegisterRule(string jobDefName, JobMemoryRule rule) + { + if (string.IsNullOrWhiteSpace(jobDefName)) return; + Rules[jobDefName] = rule; + } + + public static JobMemoryRule Resolve(string? jobDefName) + { + if (string.IsNullOrEmpty(jobDefName)) + return new JobMemoryRule(JobMemoryKind.Unknown); + + return Rules.TryGetValue(jobDefName!, out var rule) + ? rule + : new JobMemoryRule(JobMemoryKind.Unknown); + } + } +} diff --git a/Source/Aggregation/Patch_StartJob_Memory.cs b/Source/Aggregation/Patch_StartJob_Memory.cs index 9b5aeb9..511b79d 100644 --- a/Source/Aggregation/Patch_StartJob_Memory.cs +++ b/Source/Aggregation/Patch_StartJob_Memory.cs @@ -1,8 +1,6 @@ using System.Reflection; using HarmonyLib; -using RimMind.Memory.Aggregation; using RimMind.Presentation.Api; -using RimWorld; using Verse; using Verse.AI; diff --git a/Source/Aggregation/WorkSessionAggregator.cs b/Source/Aggregation/WorkSessionAggregator.cs index 9a7071a..c51e6a6 100644 --- a/Source/Aggregation/WorkSessionAggregator.cs +++ b/Source/Aggregation/WorkSessionAggregator.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using RimMind.Memory.Data; -using RimMind.Memory.Core; +using RimMind.Memory.Injection; +using RimMind.Memory.Triggers; using RimMind.Presentation.Api; -using RimWorld; using Verse; using Verse.AI; @@ -22,8 +22,19 @@ public class WorkSessionAggregator : GameComponent public WorkSessionAggregator(Game game) { _instance = this; } - public override void StartedNewGame() { _sessions.Clear(); _lastPruneTick = 0; } - public override void LoadedGame() { _sessions.Clear(); _lastPruneTick = 0; } + public override void StartedNewGame() + { + _sessions.Clear(); + _lastPruneTick = 0; + Patch_AddHediff.ClearCooldowns(); + } + + public override void LoadedGame() + { + _sessions.Clear(); + _lastPruneTick = 0; + Patch_AddHediff.ClearCooldowns(); + } public override void GameComponentTick() { @@ -82,17 +93,18 @@ public void OnJobStarted(Pawn pawn, Job job, int maxActive, int maxArchive, int int pawnId = pawn.thingIDNumber; string jobDefName = job.def.defName; - if (IsBlacklisted(jobDefName)) + JobMemoryRule rule = JobMemoryPolicy.Resolve(jobDefName); + if (rule.Kind == JobMemoryKind.Ignored) + return; + + if (rule.Kind == JobMemoryKind.SignificantSingle) { - if (IsSignificantSingleJob(jobDefName)) - { - RecordSignificantJob(pawn, jobDefName, now, maxActive, maxArchive); - UpdateLastMeaningfulJob(pawnId, now); - } + RecordSignificantJob(pawn, jobDefName, rule.Importance, now, maxActive, maxArchive); + UpdateLastMeaningfulJob(pawnId, now); return; } - if (!IsWhitelisted(jobDefName)) + if (rule.Kind != JobMemoryKind.Aggregatable) { CheckIdleGap(pawn, pawnId, now, idleGapThresholdTicks, maxActive, maxArchive); return; @@ -141,8 +153,12 @@ private void FlushSession(Pawn pawn, PawnSession session, int now, int maxActive float hours = session.totalTicks / 2500f; float importance = session.totalTicks > 15000 ? 0.5f : 0.4f; - string content = "RimMind.Memory.Work.Session".Translate( - JobLabel(session.currentJobDef), session.count.ToString(), $"{hours:F1}"); + string content = RimMindAPI.Text.TrOr( + "RimMind.Memory.Work.Session", + "{0} x{1} ~{2} game hours", + JobLabel(session.currentJobDef), + session.count.ToString(), + $"{hours:F1}"); var wc = RimMindMemoryWorldComponent.Instance; if (wc == null) { session.Reset(); return; } @@ -154,9 +170,8 @@ private void FlushSession(Pawn pawn, PawnSession session, int now, int maxActive session.Reset(); } - private void RecordSignificantJob(Pawn pawn, string jobDefName, int now, int maxActive, int maxArchive) + private void RecordSignificantJob(Pawn pawn, string jobDefName, float importance, int now, int maxActive, int maxArchive) { - float importance = GetSignificantJobImportance(jobDefName); string content = JobLabel(jobDefName); var wc = RimMindMemoryWorldComponent.Instance; @@ -176,21 +191,22 @@ private void CheckIdleGap(Pawn pawn, int pawnId, int now, int idleGapThresholdTi if (gap > idleGapThresholdTicks) { float hours = gap / 2500f; - string content = "RimMind.Memory.Work.Idle".Translate($"{hours:F1}"); + string content = RimMindAPI.Text.TrOr( + "RimMind.Memory.Work.Idle", + "Idle/Standby ~{0} game hours", + $"{hours:F1}"); var wc = RimMindMemoryWorldComponent.Instance; if (wc != null) { var store = wc.GetPawnStore(pawn); - string idlePrefix = RimMindAPI.Text.TrOr("RimMind.Memory.Work.Idle", "Idle", "{0}") - .Split(new[] { "{0}" }, StringSplitOptions.None)[0] - .Trim(); bool updatedExisting = false; - if (store != null) + if (store != null && !string.IsNullOrEmpty(session.lastIdleEntryId)) { lock (store.SyncRoot) { - if (store.active.Count > 0 && store.active[0].type == MemoryType.Work && - (!string.IsNullOrEmpty(idlePrefix) && store.active[0].content.Contains(idlePrefix))) + if (store.active.Count > 0 + && store.active[0].type == MemoryType.Work + && store.active[0].id == session.lastIdleEntryId) { store.active[0].content = content; store.active[0].tick = now; @@ -198,9 +214,16 @@ private void CheckIdleGap(Pawn pawn, int pawnId, int now, int idleGapThresholdTi } } } - if (!updatedExisting) + + if (updatedExisting) { - wc.AddPawnMemory(pawn, MemoryEntry.Create(content, MemoryType.Work, now, 0.1f), maxActive, maxArchive); + MemoryChangedEvent.Publish(pawnId); + } + else + { + var idleEntry = MemoryEntry.Create(content, MemoryType.Work, now, 0.1f); + session.lastIdleEntryId = idleEntry.id; + wc.AddPawnMemory(pawn, idleEntry, maxActive, maxArchive); } } session.lastMeaningfulJobTick = now; @@ -209,8 +232,13 @@ private void CheckIdleGap(Pawn pawn, int pawnId, int now, int idleGapThresholdTi private void UpdateLastMeaningfulJob(int pawnId, int now) { - if (!_sessions.TryGetValue(pawnId, out var session)) return; + if (!_sessions.TryGetValue(pawnId, out var session)) + { + session = new PawnSession(); + _sessions[pawnId] = session; + } session.lastMeaningfulJobTick = now; + session.lastIdleEntryId = null; } private void TryUpgradeToNarrator(Pawn pawn, string content, int now, float importance, RimMindMemoryWorldComponent wc) @@ -226,66 +254,6 @@ private void TryUpgradeToNarrator(Pawn pawn, string content, int now, float impo } } - private static readonly HashSet BlacklistedJobs = new HashSet - { - "Wait", "Wait_MaintainPosture", "Wait_Asleep", "Wait_Downed", - "Wait_SafeTemperature", "Wait_Wander", "Wait_Combat", - "Goto", "GotoWander", "GotoSafeTemperature", - "AttackMelee", "AttackStatic", "SocialFight", - "MarryAdjacentPawn", "Lovin", "StandAndStare", - "IdleWhileDespawned", - }; - - private static readonly HashSet SignificantJobs = new HashSet - { - "AttackMelee", "AttackStatic", - "Rescue", "TendPatient", "FeedPatient", "DeliverFood", - "Slaughter", "Tame", "Train", "Milk", "Shear", - "PrisonerAttemptRecruit", - }; - - private static readonly HashSet WhitelistedJobs = new HashSet - { - "Sow", "PlantSeed", "Replant", - "Harvest", "HarvestDesignated", - "CutPlant", "CutPlantDesignated", - "FinishFrame", "PlaceNoCostFrame", - "Deconstruct", "Uninstall", - "Repair", "FixBrokenDownBuilding", - "Mine", "Clean", - "HaulToCell", "HaulToContainer", - "HaulToTransporter", "HaulToPortal", - "HaulCorpseToPublicPlace", - "DoBill", "Research", "Hunt", - "BeatFire", "ExtinguishSelf", - "SmoothFloor", "RemoveFloor", "SmoothWall", - "BuildRoof", "RemoveRoof", - "PaintBuilding", "PaintFloor", - "RemovePaintBuilding", "RemovePaintFloor", - "OperateDeepDrill", "OperateScanner", - "ExtractTree", "Refuel", "RearmTurret", - "ClearSnow", "ManTurret", - }; - - private static readonly Dictionary SignificantJobImportanceMap = new Dictionary - { - { "AttackMelee", 0.9f }, { "AttackStatic", 0.9f }, - { "Rescue", 0.8f }, { "TendPatient", 0.8f }, - { "FeedPatient", 0.7f }, { "DeliverFood", 0.6f }, - { "Slaughter", 0.6f }, { "Tame", 0.7f }, - { "Train", 0.6f }, { "Milk", 0.5f }, { "Shear", 0.5f }, - { "PrisonerAttemptRecruit", 0.7f }, - }; - - private static bool IsBlacklisted(string defName) => BlacklistedJobs.Contains(defName); - - private static bool IsWhitelisted(string defName) => WhitelistedJobs.Contains(defName); - - private static bool IsSignificantSingleJob(string defName) => SignificantJobs.Contains(defName); - - private static float GetSignificantJobImportance(string defName) - => SignificantJobImportanceMap.TryGetValue(defName, out var v) ? v : 0.6f; - private static string JobLabel(string defName) { return RimMindAPI.Text.TrOr($"RimMind.Memory.Work.{defName}", defName); @@ -299,6 +267,7 @@ private class PawnSession public int count; public int totalTicks; public int lastMeaningfulJobTick; + public string? lastIdleEntryId; public void Reset() { diff --git a/Source/Core/PawnLookup.cs b/Source/Core/PawnLookup.cs deleted file mode 100644 index f019447..0000000 --- a/Source/Core/PawnLookup.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using RimMind.Presentation.Api; -using Verse; - -namespace RimMind.Memory.Core -{ - [Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup directly.")] - public static class PawnLookup - { - public static Pawn? FindPawnById(string pawnId) - => RimMindPawnLookup.FindPawnById(pawnId); - - public static Pawn? FindPawnByNumber(int thingIDNumber) - => RimMindPawnLookup.FindPawnByNumber(thingIDNumber); - } -} diff --git a/Source/Core/TimeFormatter.cs b/Source/Core/TimeFormatter.cs index f8c0608..fa7ca68 100644 --- a/Source/Core/TimeFormatter.cs +++ b/Source/Core/TimeFormatter.cs @@ -1,7 +1,5 @@ -using System; using RimMind.Domain.Common; using RimMind.Presentation.Api; -using Verse; namespace RimMind.Memory.Core { @@ -37,7 +35,7 @@ public static string FormatTimeAgo(int eventTick, int nowTick) if (days <= 3) return Tr("RimMind.Memory.Time.DaysAgo", days); - return FormatGameDate(nowTick); + return FormatGameDate(eventTick); } public static string FormatGameDate(int tick) diff --git a/Source/DarkMemory/DarkMemoryResultParserPure.cs b/Source/DarkMemory/DarkMemoryResultParserPure.cs index 2b0dfab..490b108 100644 --- a/Source/DarkMemory/DarkMemoryResultParserPure.cs +++ b/Source/DarkMemory/DarkMemoryResultParserPure.cs @@ -10,6 +10,10 @@ namespace RimMind.Memory.DarkMemory /// public static class DarkMemoryResultParserPure { + public const string SchemaKey = "DarkMemoryOutput"; + public const string DarkMemoryOutputSchema = + "{\"type\":\"object\",\"properties\":{\"dark\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"dark\"],\"additionalProperties\":false}"; + public class DarkMemoryResultDto { public string[] dark = Array.Empty(); diff --git a/Source/DarkMemory/DarkMemoryUpdater.cs b/Source/DarkMemory/DarkMemoryUpdater.cs index 5353b0d..4968bc6 100644 --- a/Source/DarkMemory/DarkMemoryUpdater.cs +++ b/Source/DarkMemory/DarkMemoryUpdater.cs @@ -1,16 +1,13 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Text; using RimMind.Application.Common.Helpers; -using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Features.Llm; -using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; -using RimMind.Application.Common.Interfaces.Context; using RimMind.Memory.Data; using RimMind.Memory.Decay; +using RimMind.Memory.Injection; using RimWorld; using Verse; @@ -21,7 +18,8 @@ public class DarkMemoryUpdater : GameComponent public const string RequestModId = "RimMind.Memory"; public const int DailyInterval = 60000; public const int DarkMemoryMaxQueueWaitTicks = DailyInterval; - private const int JitterRange = 3000; + private const int StaggerStepTicks = 250; + private const int DailyStaggerSlots = DailyInterval / StaggerStepTicks; private static DarkMemoryUpdater? _instance; public static DarkMemoryUpdater? Instance => Current.Game != null ? _instance : null; @@ -31,49 +29,42 @@ public class DarkMemoryUpdater : GameComponent public DarkMemoryUpdater(Game game) { _instance = this; - _narratorOffset = new System.Random().Next(0, DailyInterval); + _narratorOffset = new System.Random().Next(0, DailyStaggerSlots); } public static string BuildCoalesceKey(string npcId) => $"{RequestModId}:dark_memory:{npcId}"; - public static int GetPawnJitter(int thingID) - { - int span = JitterRange * 2 + 1; - return TickStagger.PhaseOffset(thingID, span) - JitterRange; - } - - public static void CleanupPawnJitter(int thingID) - { - // Jitter is computed deterministically from thingIDNumber via TickStagger; no per-pawn state to prune. - } - public override void GameComponentTick() { if (!RimMindMemoryMod.Settings.enableMemory) return; var wc = RimMindMemoryWorldComponent.Instance; if (wc == null) return; - var settings = RimMindMemoryMod.Settings; int now = Find.TickManager.TicksGame; - if (now <= 0) return; + if (now <= 0 || (now % StaggerStepTicks) != 0) return; - foreach (var map in Find.Maps) + int slot = now / StaggerStepTicks; + var settings = RimMindMemoryMod.Settings; + + if (Find.Maps != null) { - var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map); - if (colonists.Count == 0) continue; - for (int i = 0; i < colonists.Count; i++) + for (int m = 0; m < Find.Maps.Count; m++) { - var pawn = colonists[i]; - if (pawn == null || pawn.Dead || pawn.Destroyed || pawn.IsKidnapped()) continue; - if (!TickStagger.IsDue(now, pawn.thingIDNumber, DailyInterval)) continue; - TriggerPawnDarkMemoryUpdate(pawn, wc, settings); - - if (settings.enableDecay) + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(Find.Maps[m]); + for (int i = 0; i < colonists.Count; i++) { - var store = wc.GetPawnStore(pawn); - if (store != null) - ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold); + var pawn = colonists[i]; + if (pawn == null || pawn.Dead || pawn.Destroyed || pawn.IsKidnapped()) continue; + if (!TickStagger.IsDue(slot, pawn.thingIDNumber, DailyStaggerSlots)) continue; + TriggerPawnDarkMemoryUpdate(pawn, wc, settings); + + if (settings.enableDecay) + { + var store = wc.GetPawnStore(pawn); + if (store != null && ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold) > 0) + MemoryChangedEvent.Publish(pawn.thingIDNumber); + } } } } @@ -90,25 +81,28 @@ public override void GameComponentTick() { var pawn = caravanPawns[i]; if (pawn == null || !pawn.IsFreeNonSlaveColonist || pawn.Faction != Faction.OfPlayer || pawn.Dead || pawn.Destroyed || pawn.IsKidnapped()) continue; - if (!TickStagger.IsDue(now, pawn.thingIDNumber, DailyInterval)) continue; + if (!TickStagger.IsDue(slot, pawn.thingIDNumber, DailyStaggerSlots)) continue; TriggerPawnDarkMemoryUpdate(pawn, wc, settings); if (settings.enableDecay) { var store = wc.GetPawnStore(pawn); - if (store != null) - ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold); + if (store != null && ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold) > 0) + MemoryChangedEvent.Publish(pawn.thingIDNumber); } } } } - if (TickStagger.IsDue(now, _narratorOffset, DailyInterval)) + if (TickStagger.IsDue(slot, _narratorOffset, DailyStaggerSlots)) { TriggerNarratorDarkMemoryUpdate(wc, settings); - if (settings.enableDecay) - ImportanceDecayManager.ApplyDecay(wc.NarratorStore, settings.decayRate, settings.minImportanceThreshold); + if (settings.enableDecay + && ImportanceDecayManager.ApplyDecay(wc.NarratorStore, settings.decayRate, settings.minImportanceThreshold) > 0) + { + MemoryChangedEvent.Publish(0); + } } } @@ -135,21 +129,31 @@ public void TriggerPawnDarkMemoryUpdate(Pawn pawn, RimMindMemoryWorldComponent w if (todayEntries.Count == 0) return; var sb = new StringBuilder(); - sb.AppendLine("RimMind.Memory.Prompt.PawnTodayMemory".Translate(pawn.Name?.ToStringShort ?? pawn.LabelShort)); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.PawnTodayMemory", + "{0}'s memories today:", + pawn.Name?.ToStringShort ?? pawn.LabelShort)); foreach (var e in todayEntries) sb.AppendLine($"- {e.content}"); sb.AppendLine(); - sb.AppendLine("RimMind.Memory.Prompt.ExistingImpression".Translate()); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.ExistingImpression", + "Existing long-term impressions (each <=50 chars, evolvable):")); foreach (var d in darkList) sb.AppendLine($"- {d.content}"); sb.AppendLine(); - sb.AppendLine("RimMind.Memory.Prompt.MergeInstruction".Translate(settings.darkCount)); - sb.AppendLine("RimMind.Memory.Prompt.JsonTemplate".Translate()); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.MergeInstruction", + "Merge today's memories into existing impressions, output JSON (keep {0} entries, each <=50 chars):", + settings.darkCount)); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.JsonTemplate", + "{{\"dark\":[\"...\",\"...\"]}}")); var npcId = $"NPC-{pawn.thingIDNumber}"; var currentQuery = RimMindAPI.Prompt.Sanitize(sb.ToString()); - - var schema = RimMindAPI.Context.SchemaDarkMemoryOutput; + var schema = RimMindAPI.Context.FindSchema(DarkMemoryResultParserPure.SchemaKey) + ?? DarkMemoryResultParserPure.DarkMemoryOutputSchema; var envelope = LlmRequestEnvelopeBuilder .ForScenario(RimMindAPI.Context.ScenarioMemory) @@ -166,8 +170,13 @@ public void TriggerPawnDarkMemoryUpdate(Pawn pawn, RimMindMemoryWorldComponent w RimMindAPI.Request.Send(envelope, result => { if (result.IsErr) return; - if (pawn.Dead || pawn.Destroyed || pawn.IsKidnapped()) return; - ApplyPawnDarkMemory(result.Value.Content, store, settings.darkCount, now); + if (!ReferenceEquals(wc, RimMindMemoryWorldComponent.Instance)) return; + if (pawn.Dead || pawn.Destroyed || pawn.IsKidnapped() || pawn.Faction != Faction.OfPlayer) return; + if (!pawn.Spawned && !RimWorld.Planet.CaravanUtility.IsCaravanMember(pawn)) return; + if (ApplyDarkMemory(result.Value.Content, settings.darkCount, now, store)) + { + MemoryChangedEvent.Publish(pawn.thingIDNumber); + } }); } @@ -184,21 +193,30 @@ public void TriggerNarratorDarkMemoryUpdate(RimMindMemoryWorldComponent wc, RimM if (todayEntries.Count == 0) return; var sb = new StringBuilder(); - sb.AppendLine("RimMind.Memory.Prompt.ColonyTodayEvents".Translate()); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.ColonyTodayEvents", + "Colony events today:")); foreach (var e in todayEntries) sb.AppendLine($"- {e.content}"); sb.AppendLine(); - sb.AppendLine("RimMind.Memory.Prompt.ExistingNarrative".Translate()); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.ExistingNarrative", + "Existing long-term narratives (each <=50 chars, evolvable):")); foreach (var d in darkList) sb.AppendLine($"- {d.content}"); sb.AppendLine(); - sb.AppendLine("RimMind.Memory.Prompt.MergeNarrativeInstruction".Translate(settings.narratorDarkCount)); - sb.AppendLine("RimMind.Memory.Prompt.JsonTemplate".Translate()); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.MergeNarrativeInstruction", + "Merge today's events into existing narratives, output JSON (keep {0} entries, each <=50 chars):", + settings.narratorDarkCount)); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Memory.Prompt.JsonTemplate", + "{{\"dark\":[\"...\",\"...\"]}}")); var npcId = "NPC-storyteller"; var currentQuery = RimMindAPI.Prompt.Sanitize(sb.ToString()); - - var schema = RimMindAPI.Context.SchemaDarkMemoryOutput; + var schema = RimMindAPI.Context.FindSchema(DarkMemoryResultParserPure.SchemaKey) + ?? DarkMemoryResultParserPure.DarkMemoryOutputSchema; var envelope = LlmRequestEnvelopeBuilder .ForScenario(RimMindAPI.Context.ScenarioMemory) @@ -215,26 +233,20 @@ public void TriggerNarratorDarkMemoryUpdate(RimMindMemoryWorldComponent wc, RimM RimMindAPI.Request.Send(envelope, result => { if (result.IsErr) return; - ApplyNarratorDarkMemory(result.Value.Content, store, settings.narratorDarkCount, now); + if (!ReferenceEquals(wc, RimMindMemoryWorldComponent.Instance)) return; + if (ApplyDarkMemory(result.Value.Content, settings.narratorDarkCount, now, store)) + { + MemoryChangedEvent.Publish(0); + } }); } - private void ApplyPawnDarkMemory(string jsonContent, PawnMemoryStore store, int darkCount, int now) - { - ApplyDarkMemory(jsonContent, darkCount, now, store); - } - - private void ApplyNarratorDarkMemory(string jsonContent, NarratorMemoryStore store, int darkCount, int now) - { - ApplyDarkMemory(jsonContent, darkCount, now, store); - } - - private static void ApplyDarkMemory(string json, int darkCount, int now, MemoryStoreBase store) + private static bool ApplyDarkMemory(string json, int darkCount, int now, MemoryStoreBase store) { try { var entries = DarkMemoryResultParserPure.Parse(json, darkCount); - if (entries == null || entries.Count == 0) return; + if (entries == null || entries.Count == 0) return false; lock (store.SyncRoot) { @@ -244,10 +256,12 @@ private static void ApplyDarkMemory(string json, int darkCount, int now, MemoryS store.dark.Add(MemoryEntry.Create(text, MemoryType.Dark, now, 1.0f)); } } + return true; } catch (Exception ex) { RimMindErrors.Warn($"[RimMind-Memory] Failed to parse dark memory response: {ex.Message}"); + return false; } } } diff --git a/Source/Data/MemoryEntry.cs b/Source/Data/MemoryEntry.cs index a386292..d6fc333 100644 --- a/Source/Data/MemoryEntry.cs +++ b/Source/Data/MemoryEntry.cs @@ -22,6 +22,7 @@ public MemoryEntry() { } public static MemoryEntry Create(string content, MemoryType type, int tick, float importance, string? pawnId = null, string? targetPawnId = null) { + content ??= string.Empty; if (content.Length > 2000) { var originalLength = content.Length; diff --git a/Source/Data/MemorySnapshotService.cs b/Source/Data/MemorySnapshotService.cs index 0d263c2..d35261f 100644 --- a/Source/Data/MemorySnapshotService.cs +++ b/Source/Data/MemorySnapshotService.cs @@ -133,11 +133,9 @@ public static void Merge( limits.NarratorActive, narratorStore.archive, limits.NarratorArchive); - MemoryStoreBase.EnforceLimit( + MemoryStoreBase.TrimToLimit( narratorStore.archive, - limits.NarratorArchive, - narratorStore.dark, - int.MaxValue); + limits.NarratorArchive); } } @@ -178,11 +176,9 @@ private static void EnforcePawnLimits( limits.PawnActive, store.archive, limits.PawnArchive); - MemoryStoreBase.EnforceLimit( + MemoryStoreBase.TrimToLimit( store.archive, - limits.PawnArchive, - store.dark, - int.MaxValue); + limits.PawnArchive); } } diff --git a/Source/Data/MemoryStoreBase.cs b/Source/Data/MemoryStoreBase.cs index 09132f2..92e4721 100644 --- a/Source/Data/MemoryStoreBase.cs +++ b/Source/Data/MemoryStoreBase.cs @@ -27,7 +27,7 @@ public virtual void AddActive(MemoryEntry e, int maxActive, int maxArchive) if (active.Count >= maxActive && active.All(x => x.isPinned)) { archive.Insert(0, e); - EnforceLimit(archive, maxArchive, dark, int.MaxValue); + TrimToLimit(archive, maxArchive); return; } active.Insert(0, e); @@ -35,6 +35,23 @@ public virtual void AddActive(MemoryEntry e, int maxActive, int maxArchive) } } + public static void TrimToLimit(List list, int max) + { + while (list.Count > max) + { + var least = list.LastOrDefault(x => !x.isPinned); + if (least != null) + { + list.Remove(least); + } + else + { + RimMindErrors.Warn($"[RimMind-Memory] Cannot trim list: all {list.Count} entries are pinned (max={max})"); + break; + } + } + } + public static void EnforceLimit(List src, int srcMax, List dst, int dstMax) { diff --git a/Source/Data/NarratorMemoryStore.cs b/Source/Data/NarratorMemoryStore.cs index 7555860..677bb64 100644 --- a/Source/Data/NarratorMemoryStore.cs +++ b/Source/Data/NarratorMemoryStore.cs @@ -1,5 +1,3 @@ -using Verse; - namespace RimMind.Memory.Data { public class NarratorMemoryStore : MemoryStoreBase diff --git a/Source/Data/PawnMemoryStore.cs b/Source/Data/PawnMemoryStore.cs index 2a111f1..e7dad8b 100644 --- a/Source/Data/PawnMemoryStore.cs +++ b/Source/Data/PawnMemoryStore.cs @@ -1,5 +1,3 @@ -using Verse; - namespace RimMind.Memory.Data { public class PawnMemoryStore : MemoryStoreBase diff --git a/Source/Data/RimMindMemoryWorldComponent.cs b/Source/Data/RimMindMemoryWorldComponent.cs index b92d217..78b7950 100644 --- a/Source/Data/RimMindMemoryWorldComponent.cs +++ b/Source/Data/RimMindMemoryWorldComponent.cs @@ -89,11 +89,19 @@ private void SaveAllEntriesToStorage() var version = Find.TickManager.TicksGame; Task.Run(async () => { - var result = await RimMindAPI.RemoteSync.EnqueuePushAsync( - "rimmind:memory:full", - json, - version); - if (result.IsErr && result.Error.Code != RimMindErrorCode.Cancelled) RimMindErrors.Warn($"[RimMind-Memory] Remote push failed: {result.Error}"); + try + { + var result = await RimMindAPI.RemoteSync.EnqueuePushAsync( + "rimmind:memory:full", + json, + version); + if (result.IsErr && result.Error.Code != RimMindErrorCode.Cancelled) + RimMindErrors.Warn($"[RimMind-Memory] Remote push failed: {result.Error}"); + } + catch (Exception ex) + { + RimMindErrors.Warn($"[RimMind-Memory] Remote push exception: {ex.Message}"); + } }); } catch (Exception ex) { RimMindErrors.Warn($"[RimMind-Memory] SaveAllEntriesToStorage failed: {ex.Message}"); } @@ -105,16 +113,24 @@ private void LoadAllEntriesFromStorage() Task.Run(async () => { - await MemoryRemoteSyncCoordinator.PullAndMergeAsync( - () => RimMindAPI.RemoteSync.SyncOnLoadAsync("rimmind:memory:full", 0), - RimMindAPI.MainThread.Post, - MergeFromSnapshot, - message => RimMindErrors.Warn($"[RimMind-Memory] {message}")); + try + { + await MemoryRemoteSyncCoordinator.PullAndMergeAsync( + () => RimMindAPI.RemoteSync.SyncOnLoadAsync("rimmind:memory:full", 0), + RimMindAPI.MainThread.Post, + MergeFromSnapshot, + message => RimMindErrors.Warn($"[RimMind-Memory] {message}")); + } + catch (Exception ex) + { + RimMindErrors.Warn($"[RimMind-Memory] Remote load exception: {ex.Message}"); + } }); } private void MergeFromSnapshot(string? json) { + if (!ReferenceEquals(this, Instance)) return; var settings = RimMindMemoryMod.Settings; lock (_storesLock) { @@ -147,9 +163,17 @@ public void AddNarratorMemory(MemoryEntry e, int maxActive, int maxArchive) int tick = Find.TickManager.TicksGame; Task.Run(async () => { - var key = "rimmind:memory:narrator"; - var result = await RimMindAPI.RemoteSync.EnqueuePushAsync(key, e.content, tick); - if (result.IsErr && result.Error.Code != RimMindErrorCode.Cancelled) RimMindErrors.Warn($"[RimMind-Memory] Remote push narrator failed: {result.Error}"); + try + { + var key = "rimmind:memory:narrator"; + var result = await RimMindAPI.RemoteSync.EnqueuePushAsync(key, e.content, tick); + if (result.IsErr && result.Error.Code != RimMindErrorCode.Cancelled) + RimMindErrors.Warn($"[RimMind-Memory] Remote push narrator failed: {result.Error}"); + } + catch (Exception ex) + { + RimMindErrors.Warn($"[RimMind-Memory] Remote push narrator exception: {ex.Message}"); + } }); } } @@ -176,9 +200,14 @@ public IReadOnlyList GetNarratorMemories() public void ClearWorkingMemory(Pawn pawn) { + bool removed; lock (_storesLock) { - _workingMemories.Remove(pawn.thingIDNumber); + removed = _workingMemories.Remove(pawn.thingIDNumber); + } + if (removed) + { + RimMind.Memory.Injection.MemoryChangedEvent.Publish(pawn.thingIDNumber); } } diff --git a/Source/Debug/MemoryBehaviorAutotestSuite.cs b/Source/Debug/MemoryBehaviorAutotestSuite.cs index 695bd7b..e709717 100644 --- a/Source/Debug/MemoryBehaviorAutotestSuite.cs +++ b/Source/Debug/MemoryBehaviorAutotestSuite.cs @@ -4,7 +4,6 @@ using RimMind.Memory.Core; using RimMind.Memory.Data; using RimMind.Presentation.Api; -using RimWorld; using Verse; namespace RimMind.Memory.Debug @@ -36,20 +35,29 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) try { var store = comp.GetOrCreatePawnStore(pawn); - context.Assert(store != null, $"PawnMemoryStore retrieved for {pawn.Name.ToStringShort}"); + context.Assert(store != null, $"PawnMemoryStore retrieved for {pawn.Name?.ToStringShort ?? pawn.LabelShort}"); if (store != null) { var testEntry = MemoryEntry.Create("Completed a test in laboratory", MemoryType.Event, Find.TickManager.TicksGame, 0.75f, pawn.thingIDNumber.ToString()); testEntry.id = "autotest_mem_001"; - int beforeCount = store.active.Count; + int beforeCount; + lock (store.SyncRoot) + { + beforeCount = store.active.Count; + } store.AddActive(testEntry, 50, 100); - context.Assert(store.active.Any(m => m.id == "autotest_mem_001"), "Active memory entry added successfully to PawnMemoryStore"); - - // Self-cleanup - store.active.RemoveAll(m => m.id == "autotest_mem_001"); - context.Assert(store.active.Count == beforeCount, "Test memory entry cleaned up without state pollution"); + bool added; + int afterCleanupCount; + lock (store.SyncRoot) + { + added = store.active.Any(m => m.id == "autotest_mem_001"); + store.active.RemoveAll(m => m.id == "autotest_mem_001"); + afterCleanupCount = store.active.Count; + } + context.Assert(added, "Active memory entry added successfully to PawnMemoryStore"); + context.Assert(afterCleanupCount == beforeCount, "Test memory entry cleaned up without state pollution"); } } catch (Exception ex) diff --git a/Source/Debug/MemoryDebugActions.cs b/Source/Debug/MemoryDebugActions.cs index 8269f80..a54b01d 100644 --- a/Source/Debug/MemoryDebugActions.cs +++ b/Source/Debug/MemoryDebugActions.cs @@ -5,7 +5,7 @@ using RimMind.Memory.Data; using RimMind.Memory.DarkMemory; using RimMind.Memory.Decay; -using RimWorld; +using RimMind.Memory.Injection; using Verse; namespace RimMind.Memory.Debug @@ -13,6 +13,8 @@ namespace RimMind.Memory.Debug [StaticConstructorOnStartup] public static class MemoryDebugActions { + private static string PawnName(Pawn pawn) => pawn.Name?.ToStringShort ?? pawn.LabelShort; + [DebugAction("RimMind Memory", "Force Add Memory (selected)", actionType = DebugActionType.Action)] public static void ForceAddMemory() { @@ -28,7 +30,7 @@ public static void ForceAddMemory() MemoryEntry.Create("[Debug] Test memory entry", MemoryType.Manual, now, 0.6f), settings.maxActive, settings.maxArchive); - Log.Message($"[RimMind-Memory] Added test memory for {pawn.Name.ToStringShort}."); + Log.Message($"[RimMind-Memory] Added test memory for {PawnName(pawn)}."); } [DebugAction("RimMind Memory", "Show Memory State (selected)", actionType = DebugActionType.Action)] @@ -42,7 +44,7 @@ public static void ShowMemoryState() var store = wc.GetPawnStore(pawn); var sb = new StringBuilder(); - sb.AppendLine($"=== {pawn.Name.ToStringShort} Memory State ==="); + sb.AppendLine($"=== {PawnName(pawn)} Memory State ==="); sb.AppendLine($"[Diag] Memory system enabled: {RimMindMemoryMod.Settings.enableMemory}"); sb.AppendLine($"[Diag] API configured: {RimMindAPI.Settings.IsConfigured()}"); @@ -79,7 +81,7 @@ public static void ClearPawnMemory() if (wc == null) return; wc.ClearPawnStore(pawn); - Log.Message($"[RimMind-Memory] Cleared all memories for {pawn.Name.ToStringShort}."); + Log.Message($"[RimMind-Memory] Cleared all memories for {PawnName(pawn)}."); } [DebugAction("RimMind Memory", "Force Add Narrator Memory", actionType = DebugActionType.Action)] @@ -94,7 +96,8 @@ public static void ForceAddNarratorMemory() MemoryEntry.Create("[Debug] Test narrator entry", MemoryType.Event, now, 0.7f), settings.narratorMaxActive, settings.narratorMaxArchive); - Log.Message($"[RimMind-Memory] Added test narrator memory. Active count: {wc.NarratorStore.active.Count}"); + var (activeList, _, _) = wc.NarratorStore.GetSnapshots(); + Log.Message($"[RimMind-Memory] Added test narrator memory. Active count: {activeList.Count}"); } [DebugAction("RimMind Memory", "Show Narrator Memory", actionType = DebugActionType.Action)] @@ -103,19 +106,19 @@ public static void ShowNarratorMemory() var wc = RimMindMemoryWorldComponent.Instance; if (wc == null) { RimMindErrors.Warn("[RimMind-Memory] WorldComponent not initialized."); return; } - var store = wc.NarratorStore; + var (activeList, archiveList, darkList) = wc.NarratorStore.GetSnapshots(); var sb = new StringBuilder("=== Narrator Memory ===\n"); - sb.AppendLine($"[Active Narratives] {store.active.Count} entries"); - foreach (var e in store.active) + sb.AppendLine($"[Active Narratives] {activeList.Count} entries"); + foreach (var e in activeList) sb.AppendLine($" {e.content} (imp={e.importance:F2})"); - sb.AppendLine($"\n[Archived Narratives] {store.archive.Count} entries"); - foreach (var e in store.archive) + sb.AppendLine($"\n[Archived Narratives] {archiveList.Count} entries"); + foreach (var e in archiveList) sb.AppendLine($" {e.content} (imp={e.importance:F2})"); - sb.AppendLine($"\n[Dark Narratives] {store.dark.Count} entries"); - foreach (var d in store.dark) + sb.AppendLine($"\n[Dark Narratives] {darkList.Count} entries"); + foreach (var d in darkList) sb.AppendLine($" {d.content}"); Log.Message(sb.ToString()); @@ -138,7 +141,7 @@ public static void ForcePawnDarkMemory() var settings = RimMindMemoryMod.Settings; DarkMemoryUpdater.Instance?.TriggerPawnDarkMemoryUpdate(pawn, wc, settings); - Log.Message($"[RimMind-Memory] Triggered dark memory update for {pawn.Name.ToStringShort}."); + Log.Message($"[RimMind-Memory] Triggered dark memory update for {PawnName(pawn)}."); } [DebugAction("RimMind Memory", "Force Narrator Dark Memory", actionType = DebugActionType.Action)] @@ -170,15 +173,14 @@ public static void TriggerImportanceDecay() foreach (var store in wc.AllPawnStores) { - int before = store.archive.Count; - ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold); - removed += before - store.archive.Count; - decayed += store.active.Count + store.archive.Count; + removed += ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold); + var (activeList, archiveList, _) = store.GetSnapshots(); + decayed += activeList.Count + archiveList.Count; } - int narratorBefore = wc.NarratorStore.archive.Count; - ImportanceDecayManager.ApplyDecay(wc.NarratorStore, settings.decayRate, settings.minImportanceThreshold); - removed += narratorBefore - wc.NarratorStore.archive.Count; + removed += ImportanceDecayManager.ApplyDecay(wc.NarratorStore, settings.decayRate, settings.minImportanceThreshold); + if (removed > 0) + MemoryChangedEvent.Publish(0); Log.Message($"[RimMind-Memory] Decay complete: {decayed} memories decayed, {removed} below threshold removed."); } @@ -199,7 +201,7 @@ public static void ShowWorkingMemory() return; } var sb = new StringBuilder(); - sb.AppendLine($"=== {pawn.Name.ToStringShort} Working Memory ({wm.Entries.Count}/{wm.Capacity}) ==="); + sb.AppendLine($"=== {PawnName(pawn)} Working Memory ({wm.Entries.Count}/{wm.Capacity}) ==="); foreach (var e in wm.Entries) sb.AppendLine($" {e.Content} | src={e.Source} | rel={e.Relevance:F2}"); @@ -216,7 +218,7 @@ public static void ClearWorkingMemory() if (wc == null) { RimMindErrors.Warn("[RimMind-Memory] WorldComponent not initialized."); return; } wc.ClearWorkingMemory(pawn); - Log.Message($"[RimMind-Memory] Cleared working memory for {pawn.Name.ToStringShort}."); + Log.Message($"[RimMind-Memory] Cleared working memory for {PawnName(pawn)}."); } [DebugAction("RimMind Memory", "Show Memory Settings Summary", actionType = DebugActionType.Action)] @@ -249,11 +251,11 @@ public static void ShowAllPawnMemoryCounts() var store = wc.GetPawnStore(pawn); if (store == null) { - sb.AppendLine($" {pawn.Name.ToStringShort}: active=0 archive=0 dark=0"); + sb.AppendLine($" {PawnName(pawn)}: active=0 archive=0 dark=0"); continue; } var (activeList, archiveList, darkList) = store.GetSnapshots(); - sb.AppendLine($" {pawn.Name.ToStringShort}: active={activeList.Count} archive={archiveList.Count} dark={darkList.Count}"); + sb.AppendLine($" {PawnName(pawn)}: active={activeList.Count} archive={archiveList.Count} dark={darkList.Count}"); } Log.Message(sb.ToString()); } diff --git a/Source/Decay/ImportanceDecayManager.cs b/Source/Decay/ImportanceDecayManager.cs index 5a6caf0..6f00250 100644 --- a/Source/Decay/ImportanceDecayManager.cs +++ b/Source/Decay/ImportanceDecayManager.cs @@ -6,15 +6,16 @@ namespace RimMind.Memory.Decay { public static class ImportanceDecayManager { - public static void ApplyDecay(MemoryStoreBase store, float decayRate, float minThreshold) + public static int ApplyDecay(MemoryStoreBase store, float decayRate, float minThreshold) { - if (store == null) return; + if (store == null) return 0; lock (store.SyncRoot) { DecayList(store.active, decayRate); DecayList(store.archive, decayRate); - store.active.RemoveAll(e => !e.isPinned && ImportanceDecayCalculator.ShouldRemove(e.importance, minThreshold)); - store.archive.RemoveAll(e => !e.isPinned && ImportanceDecayCalculator.ShouldRemove(e.importance, minThreshold)); + int removed = store.active.RemoveAll(e => !e.isPinned && ImportanceDecayCalculator.ShouldRemove(e.importance, minThreshold)); + removed += store.archive.RemoveAll(e => !e.isPinned && ImportanceDecayCalculator.ShouldRemove(e.importance, minThreshold)); + return removed; } } diff --git a/Source/Extensions/MemoryActionSkipCheck.cs b/Source/Extensions/MemoryActionSkipCheck.cs index 9034681..5d94fb8 100644 --- a/Source/Extensions/MemoryActionSkipCheck.cs +++ b/Source/Extensions/MemoryActionSkipCheck.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; namespace RimMind.Memory @@ -5,8 +6,10 @@ namespace RimMind.Memory internal sealed class MemoryActionSkipCheck : ISkipCheck { public string Id => "memory.action"; - public string OwnerModId => "RimMindMemory"; + public string OwnerModId => RimMindOwnerConsts.MemoryModId; public SkipCheckKind Kind => SkipCheckKind.Action; - public bool ShouldSkip(in SkipCheckArgs args) => !RimMindMemoryMod.Settings.enableMemory; + // Memory never vetoes Advisor/Actions when memory recording is disabled; + // memory enablement only gates Memory's own recording, injection, and consolidation. + public bool ShouldSkip(in SkipCheckArgs args) => false; } } diff --git a/Source/Extensions/MemoryModCooldown.cs b/Source/Extensions/MemoryModCooldown.cs index 3ada88a..f6ba61b 100644 --- a/Source/Extensions/MemoryModCooldown.cs +++ b/Source/Extensions/MemoryModCooldown.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Memory.DarkMemory; using RimMind.Presentation.Api; @@ -13,8 +14,8 @@ internal sealed class MemoryModCooldown : IModCooldown public const int BaseModCooldownTicks = 3000; public const int MinModCooldownTicks = 600; - public string Id => "DarkMemory"; - public string OwnerModId => DarkMemoryUpdater.RequestModId; + public string Id => DarkMemoryUpdater.RequestModId; + public string OwnerModId => RimMindOwnerConsts.MemoryModId; public int CooldownTicks => RimMindAPI.Settings.ScaleCooldown(BaseModCooldownTicks, MinModCooldownTicks); } } diff --git a/Source/Extensions/MemorySettingsTab.cs b/Source/Extensions/MemorySettingsTab.cs index 41196e1..3947f50 100644 --- a/Source/Extensions/MemorySettingsTab.cs +++ b/Source/Extensions/MemorySettingsTab.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.Memory internal sealed class MemorySettingsTab : ISettingsTab { public string Id => "memory"; - public string OwnerModId => "RimMindMemory"; + public string OwnerModId => RimMindOwnerConsts.MemoryModId; public string Label => RimMindAPI.Text.TrOr("RimMind.Memory.Settings.TabLabel", "Memory"); public void Draw(Rect rect) => MemorySettingsDrawer.Draw(rect); } diff --git a/Source/Extensions/MemoryToggleBehavior.cs b/Source/Extensions/MemoryToggleBehavior.cs index 9c5cd9b..3eada0f 100644 --- a/Source/Extensions/MemoryToggleBehavior.cs +++ b/Source/Extensions/MemoryToggleBehavior.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; namespace RimMind.Memory @@ -5,8 +6,12 @@ namespace RimMind.Memory internal sealed class MemoryToggleBehavior : IToggleBehavior { public string Id => "memory.toggle"; - public string OwnerModId => "RimMindMemory"; + public string OwnerModId => RimMindOwnerConsts.MemoryModId; public bool IsActive => RimMindMemoryMod.Settings.enableMemory; - public void Toggle() => RimMindMemoryMod.Settings.enableMemory = !RimMindMemoryMod.Settings.enableMemory; + public void Toggle() + { + RimMindMemoryMod.Settings.enableMemory = !RimMindMemoryMod.Settings.enableMemory; + RimMindMemoryMod.Settings.Write(); + } } } diff --git a/Source/Injection/MemoryContextProvider.cs b/Source/Injection/MemoryContextProvider.cs index 7ec286b..e9445b6 100644 --- a/Source/Injection/MemoryContextProvider.cs +++ b/Source/Injection/MemoryContextProvider.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using System.Threading; using System.Threading.Tasks; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Context; @@ -18,7 +17,7 @@ namespace RimMind.Memory.Injection { public static class MemoryContextProvider { - private const string PublicProviderOwner = "RimMind.Memory"; + private const string PublicProviderOwner = RimMindOwnerConsts.MemoryModId; private const int PublicProviderPriority = 100; private static string Tr(string key, params object[] args) @@ -33,7 +32,7 @@ public static void Register() // to a real event (unknown names never fall back to the base bus event). MemoryChangedEvent.Register(); - ScenarioRegistry.Register(new ScenarioDescriptor + RimMindAPI.Context.RegisterScenario(new ScenarioDescriptor { Id = ScenarioIds.Memory, DefaultBaseRounds = 0, @@ -62,7 +61,7 @@ public static void Register() "memory_pawn", ContextLayer.L3_State, 0.25f, async (ctx, ct) => { - if (ctx.PawnId <= 0) return null; + if (ctx.PawnId <= 0 || !RimMindMemoryMod.Settings.enableMemory) return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { try @@ -143,6 +142,7 @@ public static void Register() "memory_narrator", ContextLayer.L4_History, 0.6f, async (ctx, ct) => { + if (!RimMindMemoryMod.Settings.enableMemory) return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { try @@ -232,6 +232,7 @@ private static string BuildPawnBrief(Pawn pawn) { try { + if (!RimMindMemoryMod.Settings.enableMemory) return string.Empty; if (pawn == null || Current.Game == null) return string.Empty; var store = RimMindMemoryWorldComponent.Instance?.GetPawnStore(pawn); if (store == null || store.IsEmpty) return string.Empty; @@ -239,7 +240,8 @@ private static string BuildPawnBrief(Pawn pawn) var (activeList, _, darkList) = store.GetSnapshots(); if (activeList.Count == 0 && darkList.Count == 0) return string.Empty; - var sb = new StringBuilder(TrOrFallback("RimMind.Memory.Context.BriefHeader", "[RimMind Memory]")); + var sb = new StringBuilder(); + sb.AppendLine(TrOrFallback("RimMind.Memory.Context.BriefHeader", "[RimMind Memory]")); foreach (var memory in activeList.Take(5)) sb.AppendLine($"- {memory.content}"); @@ -262,6 +264,7 @@ private static string BuildNarratorBrief() { try { + if (!RimMindMemoryMod.Settings.enableMemory) return string.Empty; if (Current.Game == null) return string.Empty; var store = RimMindMemoryWorldComponent.Instance?.NarratorStore; if (store == null || store.IsEmpty) return string.Empty; @@ -269,7 +272,8 @@ private static string BuildNarratorBrief() var (activeList, _, _) = store.GetSnapshots(); if (activeList.Count == 0) return string.Empty; - var sb = new StringBuilder(TrOrFallback("RimMind.Memory.Context.NarratorBriefHeader", "[RimMind Storyteller]")); + var sb = new StringBuilder(); + sb.AppendLine(TrOrFallback("RimMind.Memory.Context.NarratorBriefHeader", "[RimMind Storyteller]")); foreach (var memory in activeList.Take(5)) sb.AppendLine($"- {memory.content}"); return sb.ToString().TrimEnd(); diff --git a/Source/Injection/WorkingMemoryProvider.cs b/Source/Injection/WorkingMemoryProvider.cs index 981161c..2f9d1be 100644 --- a/Source/Injection/WorkingMemoryProvider.cs +++ b/Source/Injection/WorkingMemoryProvider.cs @@ -1,11 +1,8 @@ using System.Text; -using System.Threading; -using System.Threading.Tasks; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Context; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; -using RimMind.Memory.Core; using RimMind.Memory.Data; using Verse; @@ -23,7 +20,7 @@ public static void Register() "working_memory", ContextLayer.L3_State, 0.3f, async (ctx, ct) => { - if (ctx.PawnId <= 0) return null; + if (ctx.PawnId <= 0 || !RimMindMemoryMod.Settings.enableMemory) return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { var pawn = RimMindPawnLookup.FindPawnByNumber(ctx.PawnId); diff --git a/Source/Narrator/Patch_IncidentWorker.cs b/Source/Narrator/Patch_IncidentWorker.cs index 983b0f2..2b4fc14 100644 --- a/Source/Narrator/Patch_IncidentWorker.cs +++ b/Source/Narrator/Patch_IncidentWorker.cs @@ -1,7 +1,9 @@ using System; +using System.Collections.Generic; using HarmonyLib; using RimMind.Domain.ValueObjects; using RimMind.Memory.Data; +using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -10,6 +12,46 @@ namespace RimMind.Memory.Narrator [HarmonyPatch(typeof(IncidentWorker), nameof(IncidentWorker.TryExecute))] public static class Patch_IncidentWorker { + private static readonly Dictionary CategoryImportances = + new Dictionary(StringComparer.Ordinal) + { + ["ThreatBig"] = 0.9f, + ["DiseaseHuman"] = 0.75f, + ["ThreatSmall"] = 0.7f, + ["GiveQuest"] = 0.65f, + ["OrbitalVisitor"] = 0.6f, + ["FactionArrival"] = 0.6f, + }; + private static readonly (string Token, float Importance)[] NameTokenImportances = + { + ("Death", 1.0f), + ("Execution", 1.0f), + ("Funeral", 0.9f), + ("Burial", 0.9f), + ("Raid", 0.9f), + ("Siege", 0.9f), + ("MechCluster", 0.9f), + ("Infestation", 0.85f), + ("Hive", 0.85f), + ("Fire", 0.85f), + ("Explosion", 0.85f), + ("Tornado", 0.85f), + ("Meteor", 0.85f), + ("Wedding", 0.85f), + ("Joiner", 0.85f), + ("Wanderer", 0.85f), + ("Research", 0.8f), + ("Disease", 0.75f), + ("Plague", 0.75f), + ("Flu", 0.75f), + ("Birthday", 0.7f), + ("Anniversary", 0.7f), + ("Quest", 0.65f), + ("Trader", 0.6f), + ("Visitor", 0.6f), + ("Caravan", 0.6f), + }; + static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __result) { if (!__result) return; @@ -25,7 +67,8 @@ static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __resul if (wc == null) return; int now = Find.TickManager.TicksGame; - string content = $"[{"RimMind.Memory.Context.Map".Translate()}] {BuildNarratorText(__instance.def, parms)}"; + string mapTag = RimMindAPI.Text.TrOr("RimMind.Memory.Context.Map", "[Map]"); + string content = $"{mapTag} {BuildNarratorText(__instance.def, parms)}"; wc.AddNarratorMemory( MemoryEntry.Create(content, MemoryType.Event, now, importance), @@ -39,28 +82,38 @@ static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __resul private static float GetIncidentImportance(IncidentDef def) { - string name = def.defName; - if (name.Contains("Death") || name.Contains("Execution")) return 1.0f; - if (name.Contains("Funeral") || name.Contains("Burial")) return 0.9f; - if (name.Contains("Raid") || name.Contains("Siege") || name.Contains("MechCluster")) return 0.9f; - if (name.Contains("Infestation") || name.Contains("Hive") || name.Contains("Fire") || - name.Contains("Explosion") || name.Contains("Tornado") || name.Contains("Meteor")) return 0.85f; - if (name.Contains("Wedding") || name.Contains("Joiner") || name.Contains("Wanderer")) return 0.85f; - if (name.Contains("Disease") || name.Contains("Plague") || name.Contains("Flu")) return 0.75f; - if (name.Contains("Research")) return 0.8f; - if (name.Contains("Birthday") || name.Contains("Anniversary")) return 0.7f; - if (name.Contains("Trader") || name.Contains("Visitor") || name.Contains("Caravan")) return 0.6f; - if (name.Contains("Quest")) return 0.65f; - if (def.category == IncidentCategoryDefOf.ThreatBig) return 0.9f; - if (def.category == IncidentCategoryDefOf.ThreatSmall) return 0.7f; - return 0.3f; + if (def == null) return 0.3f; + + // Prefer structured RimWorld IncidentCategoryDef metadata first. + float categoryScore = 0.3f; + string? catName = def.category?.defName; + if (!string.IsNullOrEmpty(catName) && CategoryImportances.TryGetValue(catName!, out float mapped)) + { + categoryScore = mapped; + } + else if (def.category == IncidentCategoryDefOf.ThreatBig) + { + categoryScore = 0.9f; + } + else if (def.category == IncidentCategoryDefOf.ThreatSmall) + { + categoryScore = 0.7f; + } + + string name = def.defName ?? string.Empty; + for (int i = 0; i < NameTokenImportances.Length; i++) + { + if (name.Contains(NameTokenImportances[i].Token) && NameTokenImportances[i].Importance > categoryScore) + return NameTokenImportances[i].Importance; + } + return categoryScore; } private static string BuildNarratorText(IncidentDef def, IncidentParms parms) { string label = def.LabelCap.RawText.NullOrEmpty() ? def.defName : def.LabelCap.RawText; if (parms.faction != null) - return "RimMind.Memory.Context.FromFaction".Translate(label, parms.faction.Name); + return RimMindAPI.Text.TrOr("RimMind.Memory.Context.FromFaction", "({0} from {1})", label, parms.faction.Name); return label; } } diff --git a/Source/RimMindMemory.csproj b/Source/RimMindMemory.csproj index 95c9f02..355edfa 100644 --- a/Source/RimMindMemory.csproj +++ b/Source/RimMindMemory.csproj @@ -42,17 +42,4 @@ - - - $(RIMWORLD_DIR)\Mods\RimMind-Memory\ - - - - - - - - - diff --git a/Source/RimMindMemoryMod.cs b/Source/RimMindMemoryMod.cs index 822ec7f..812ac42 100644 --- a/Source/RimMindMemoryMod.cs +++ b/Source/RimMindMemoryMod.cs @@ -1,9 +1,9 @@ -using HarmonyLib; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Presentation; using RimMind.Presentation.Api; using RimMind.Presentation.Settings; using RimMind.Memory.Core; +using RimMind.Memory.DarkMemory; using RimMind.Memory.Injection; using RimMind.Memory.UI; using UnityEngine; @@ -20,6 +20,9 @@ public RimMindMemoryMod(ModContentPack content) : base(content) Settings = base.Settings; InitializeHarmony(); + RimMindAPI.Context.RegisterSchema( + DarkMemoryResultParserPure.SchemaKey, + DarkMemoryResultParserPure.DarkMemoryOutputSchema); MemoryContextProvider.Register(); WorkingMemoryProvider.Register(); RimMindAPI.Memory.RegisterBridge(new RimMindMemoryBridge()); diff --git a/Source/Settings/MemorySettingsDrawer.cs b/Source/Settings/MemorySettingsDrawer.cs index 9d5828c..35a6349 100644 --- a/Source/Settings/MemorySettingsDrawer.cs +++ b/Source/Settings/MemorySettingsDrawer.cs @@ -1,5 +1,6 @@ using RimMind.Memory.Core; using RimMind.Memory.Data; +using RimMind.Presentation.Api; using RimMind.Presentation.UI; using UnityEngine; using Verse; @@ -13,6 +14,9 @@ internal static class MemorySettingsDrawer private static RimMindMemorySettings Settings => RimMindMemoryMod.Settings; + 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( @@ -26,105 +30,120 @@ internal static void Draw(Rect inRect) private static void DrawContent(Listing_Standard listing) { - - listing.CheckboxLabeled("RimMind.Memory.Settings.EnableMemory".Translate(), ref Settings.enableMemory, - "RimMind.Memory.Settings.EnableMemory.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.TriggerSources".Translate()); - listing.CheckboxLabeled("RimMind.Memory.Settings.TriggerWorkSession".Translate(), ref Settings.triggerWorkSession, - "RimMind.Memory.Settings.TriggerWorkSession.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Memory.Settings.TriggerInjury".Translate(), ref Settings.triggerInjury, - "RimMind.Memory.Settings.TriggerInjury.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Memory.Settings.TriggerMentalBreak".Translate(), ref Settings.triggerMentalBreak, - "RimMind.Memory.Settings.TriggerMentalBreak.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Memory.Settings.TriggerDeath".Translate(), ref Settings.triggerDeath, - "RimMind.Memory.Settings.TriggerDeath.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Memory.Settings.TriggerSkillLevelUp".Translate(), ref Settings.triggerSkillLevelUp, - "RimMind.Memory.Settings.TriggerSkillLevelUp.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Memory.Settings.TriggerRelation".Translate(), ref Settings.triggerRelation, - "RimMind.Memory.Settings.TriggerRelation.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.PawnCapacity".Translate()); - string maxActiveTip = "RimMind.Memory.Settings.MaxActive.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.MaxActive".Translate(Settings.maxActive), maxActiveTip); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.EnableMemory", "Enable Memory System"), + ref Settings.enableMemory, + Tr("RimMind.Memory.Settings.EnableMemory.Desc", "When enabled, colonists automatically record game events as personal memories.")); + + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.TriggerSources", "Trigger Sources")); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.TriggerWorkSession", "Work Session End"), + ref Settings.triggerWorkSession, + Tr("RimMind.Memory.Settings.TriggerWorkSession.Desc", "Automatically record work content as memory when a work session ends.")); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.TriggerInjury", "Injury / Illness"), + ref Settings.triggerInjury, + Tr("RimMind.Memory.Settings.TriggerInjury.Desc", "Automatically record as memory when a colonist is injured or falls ill.")); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.TriggerMentalBreak", "Mental Break"), + ref Settings.triggerMentalBreak, + Tr("RimMind.Memory.Settings.TriggerMentalBreak.Desc", "Automatically record as memory when a colonist has a mental break.")); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.TriggerDeath", "Close One Died"), + ref Settings.triggerDeath, + Tr("RimMind.Memory.Settings.TriggerDeath.Desc", "Automatically record as memory when a colonist's friend or family member dies.")); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.TriggerSkillLevelUp", "Skill Level Up"), + ref Settings.triggerSkillLevelUp, + Tr("RimMind.Memory.Settings.TriggerSkillLevelUp.Desc", "Automatically record as memory when a colonist levels up a skill.")); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.TriggerRelation", "Relationship Change"), + ref Settings.triggerRelation, + Tr("RimMind.Memory.Settings.TriggerRelation.Desc", "Automatically record as memory when a colonist establishes or changes a relationship.")); + + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.PawnCapacity", "Pawn Memory Capacity")); + string maxActiveTip = Tr("RimMind.Memory.Settings.MaxActive.Desc", "Active memories are recent, high-importance memories injected into AI context."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.MaxActive", "Active Memory Limit: {0}", Settings.maxActive), maxActiveTip); Settings.maxActive = (int)listing.SliderWithTooltip(Settings.maxActive, 10, 100, maxActiveTip); - string maxArchiveTip = "RimMind.Memory.Settings.MaxArchive.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.MaxArchive".Translate(Settings.maxArchive), maxArchiveTip); + string maxArchiveTip = Tr("RimMind.Memory.Settings.MaxArchive.Desc", "Archive memories are older memories with reduced importance, injected proportionally."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.MaxArchive", "Archive Memory Limit: {0}", Settings.maxArchive), maxArchiveTip); Settings.maxArchive = (int)listing.SliderWithTooltip(Settings.maxArchive, 10, 100, maxArchiveTip); - string darkCountTip = "RimMind.Memory.Settings.DarkCount.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.DarkCount".Translate(Settings.darkCount), darkCountTip); + string darkCountTip = Tr("RimMind.Memory.Settings.DarkCount.Desc", "Dark memories are AI-compressed long-term impressions, each no more than 50 characters."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.DarkCount", "Dark Memory Count: {0}", Settings.darkCount), darkCountTip); Settings.darkCount = (int)listing.SliderWithTooltip(Settings.darkCount, 1, 10, darkCountTip); - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.NarratorCapacity".Translate()); - string nMaxActiveTip = "RimMind.Memory.Settings.NarratorMaxActive.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.NarratorMaxActive".Translate(Settings.narratorMaxActive), nMaxActiveTip); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.NarratorCapacity", "Narrator Memory Capacity")); + string nMaxActiveTip = Tr("RimMind.Memory.Settings.NarratorMaxActive.Desc", "Maximum active event records for the narrator."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.NarratorMaxActive", "Active Narrative Limit: {0}", Settings.narratorMaxActive), nMaxActiveTip); Settings.narratorMaxActive = (int)listing.SliderWithTooltip(Settings.narratorMaxActive, 10, 100, nMaxActiveTip); - string nMaxArchiveTip = "RimMind.Memory.Settings.NarratorMaxArchive.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.NarratorMaxArchive".Translate(Settings.narratorMaxArchive), nMaxArchiveTip); + string nMaxArchiveTip = Tr("RimMind.Memory.Settings.NarratorMaxArchive.Desc", "Maximum archived event records for the narrator."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.NarratorMaxArchive", "Archive Narrative Limit: {0}", Settings.narratorMaxArchive), nMaxArchiveTip); Settings.narratorMaxArchive = (int)listing.SliderWithTooltip(Settings.narratorMaxArchive, 5, 50, nMaxArchiveTip); - string nDarkCountTip = "RimMind.Memory.Settings.NarratorDarkCount.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.NarratorDarkCount".Translate(Settings.narratorDarkCount), nDarkCountTip); + string nDarkCountTip = Tr("RimMind.Memory.Settings.NarratorDarkCount.Desc", "Number of AI-compressed long-term narratives for the narrator."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.NarratorDarkCount", "Dark Narrative Count: {0}", Settings.narratorDarkCount), nDarkCountTip); Settings.narratorDarkCount = (int)listing.SliderWithTooltip(Settings.narratorDarkCount, 1, 20, nDarkCountTip); - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.InjectRatio".Translate()); - string activeInjectTip = "RimMind.Memory.Settings.ActiveInjectRatio.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.ActiveInjectRatio".Translate($"{Settings.activeInjectRatio:F2}"), activeInjectTip); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.InjectRatio", "Injection Ratios")); + string activeInjectTip = Tr("RimMind.Memory.Settings.ActiveInjectRatio.Desc", "Ratio of active memories injected into AI context."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.ActiveInjectRatio", "Active Injection Ratio: {0}", $"{Settings.activeInjectRatio:F2}"), activeInjectTip); Settings.activeInjectRatio = listing.SliderWithTooltip(Settings.activeInjectRatio, 0f, 1f, activeInjectTip); - string archiveInjectTip = "RimMind.Memory.Settings.ArchiveInjectRatio.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.ArchiveInjectRatio".Translate($"{Settings.archiveInjectRatio:F2}"), archiveInjectTip); + string archiveInjectTip = Tr("RimMind.Memory.Settings.ArchiveInjectRatio.Desc", "Ratio of archive memories injected into AI context."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.ArchiveInjectRatio", "Archive Injection Ratio: {0}", $"{Settings.archiveInjectRatio:F2}"), archiveInjectTip); Settings.archiveInjectRatio = listing.SliderWithTooltip(Settings.archiveInjectRatio, 0f, 1f, archiveInjectTip); - string nActiveInjectTip = "RimMind.Memory.Settings.NarratorActiveInjectRatio.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.NarratorActiveInjectRatio".Translate($"{Settings.narratorActiveInjectRatio:F2}"), nActiveInjectTip); + string nActiveInjectTip = Tr("RimMind.Memory.Settings.NarratorActiveInjectRatio.Desc", "Ratio of active narrator narratives injected into AI context."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.NarratorActiveInjectRatio", "Narrator Active Injection Ratio: {0}", $"{Settings.narratorActiveInjectRatio:F2}"), nActiveInjectTip); Settings.narratorActiveInjectRatio = listing.SliderWithTooltip(Settings.narratorActiveInjectRatio, 0f, 1f, nActiveInjectTip); - string nArchiveInjectTip = "RimMind.Memory.Settings.NarratorArchiveInjectRatio.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.NarratorArchiveInjectRatio".Translate($"{Settings.narratorArchiveInjectRatio:F2}"), nArchiveInjectTip); + string nArchiveInjectTip = Tr("RimMind.Memory.Settings.NarratorArchiveInjectRatio.Desc", "Ratio of archived narrator narratives injected into AI context."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.NarratorArchiveInjectRatio", "Narrator Archive Injection Ratio: {0}", $"{Settings.narratorArchiveInjectRatio:F2}"), nArchiveInjectTip); Settings.narratorArchiveInjectRatio = listing.SliderWithTooltip(Settings.narratorArchiveInjectRatio, 0f, 1f, nArchiveInjectTip); - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.Section.Aggregation".Translate()); - string minAggTip = "RimMind.Memory.Settings.MinAggregationCount.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.MinAggregationCount".Translate(Settings.minAggregationCount), minAggTip); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.Section.Aggregation", "Work Session Aggregation")); + string minAggTip = Tr("RimMind.Memory.Settings.MinAggregationCount.Desc", "Minimum number of same-type jobs before aggregating into a single memory."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.MinAggregationCount", "Min Aggregation Count: {0}", Settings.minAggregationCount), minAggTip); Settings.minAggregationCount = (int)listing.SliderWithTooltip(Settings.minAggregationCount, 1, 10, minAggTip); - string idleGapTip = "RimMind.Memory.Settings.IdleGapThreshold.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.IdleGapThreshold".Translate($"{Settings.idleGapThresholdTicks / 2500f:F1}"), idleGapTip); + string idleGapTip = Tr("RimMind.Memory.Settings.IdleGapThreshold.Desc", "Gaps between meaningful jobs exceeding this duration are recorded as idle time."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.IdleGapThreshold", "Idle Gap Threshold: {0} game hours", $"{Settings.idleGapThresholdTicks / 2500f:F1}"), idleGapTip); Settings.idleGapThresholdTicks = (int)listing.SliderWithTooltip(Settings.idleGapThresholdTicks, 1500f, 30000f, idleGapTip); Settings.idleGapThresholdTicks = (Settings.idleGapThresholdTicks / 500) * 500; - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.Section.Decay".Translate()); - listing.CheckboxLabeled("RimMind.Memory.Settings.EnableDecay".Translate(), ref Settings.enableDecay, - "RimMind.Memory.Settings.EnableDecay.Desc".Translate()); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.Section.Decay", "Memory Decay")); + listing.CheckboxLabeled( + Tr("RimMind.Memory.Settings.EnableDecay", "Enable Importance Decay"), + ref Settings.enableDecay, + Tr("RimMind.Memory.Settings.EnableDecay.Desc", "When enabled, memory importance decreases over time and memories below the threshold are removed.")); if (Settings.enableDecay) { - string decayRateTip = "RimMind.Memory.Settings.DecayRate.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.DecayRate".Translate($"{Settings.decayRate * 100f:F1}"), decayRateTip); + string decayRateTip = Tr("RimMind.Memory.Settings.DecayRate.Desc", "Percentage of importance reduction per game day."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.DecayRate", "Decay Rate: {0}%/day", $"{Settings.decayRate * 100f:F1}"), decayRateTip); Settings.decayRate = listing.SliderWithTooltip(Settings.decayRate, 0f, 0.2f, decayRateTip); - string minThreshTip = "RimMind.Memory.Settings.MinThreshold.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.MinThreshold".Translate($"{Settings.minImportanceThreshold:F3}"), minThreshTip); + string minThreshTip = Tr("RimMind.Memory.Settings.MinThreshold.Desc", "Memories with importance below this threshold are automatically removed."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.MinThreshold", "Minimum Threshold: {0}", $"{Settings.minImportanceThreshold:F3}"), minThreshTip); Settings.minImportanceThreshold = listing.SliderWithTooltip(Settings.minImportanceThreshold, 0f, 0.2f, minThreshTip); } - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.CollectionControl".Translate()); - string nEventThreshTip = "RimMind.Memory.Settings.NarratorEventThreshold.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.NarratorEventThreshold".Translate($"{Settings.narratorEventThreshold:F2}"), nEventThreshTip); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.CollectionControl", "Collection Control")); + string nEventThreshTip = Tr("RimMind.Memory.Settings.NarratorEventThreshold.Desc", "Events must reach this importance threshold to be recorded by the narrator."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.NarratorEventThreshold", "Narrator Event Threshold: {0}", $"{Settings.narratorEventThreshold:F2}"), nEventThreshTip); Settings.narratorEventThreshold = listing.SliderWithTooltip(Settings.narratorEventThreshold, 0f, 1f, nEventThreshTip); - string p2nThreshTip = "RimMind.Memory.Settings.PawnToNarratorThreshold.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Memory.Settings.PawnToNarratorThreshold".Translate($"{Settings.pawnToNarratorThreshold:F2}"), p2nThreshTip); + string p2nThreshTip = Tr("RimMind.Memory.Settings.PawnToNarratorThreshold.Desc", "Pawn memories must reach this importance threshold to be synced to the narrator."); + listing.LabelWithTooltip(Tr("RimMind.Memory.Settings.PawnToNarratorThreshold", "Pawn->Narrator Threshold: {0}", $"{Settings.pawnToNarratorThreshold:F2}"), p2nThreshTip); Settings.pawnToNarratorThreshold = listing.SliderWithTooltip(Settings.pawnToNarratorThreshold, 0f, 1f, p2nThreshTip); - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Memory.Settings.NarratorMemoryReadonly".Translate()); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Memory.Settings.NarratorMemoryReadonly", "Narrator Memory (Read-only):")); var wc = RimMindMemoryWorldComponent.Instance; if (wc == null || Current.Game == null || Find.TickManager == null) { - listing.Label("RimMind.Memory.Settings.NeedLoadGame".Translate()); + listing.Label(Tr("RimMind.Memory.Settings.NeedLoadGame", " Load a game to view")); } else { @@ -132,19 +151,19 @@ private static void DrawContent(Listing_Standard listing) int now = Find.TickManager.TicksGame; if (darkList.Count > 0) { - listing.Label("RimMind.Memory.Settings.LongTermNarrative".Translate()); + listing.Label(Tr("RimMind.Memory.Settings.LongTermNarrative", " Long-term Narratives (AI-generated):")); foreach (var d in darkList) listing.Label($" {d.content}"); } - listing.Label("RimMind.Memory.Settings.ActiveNarrative".Translate(activeList.Count, Settings.narratorMaxActive)); + listing.Label(Tr("RimMind.Memory.Settings.ActiveNarrative", " Active Narratives ({0}/{1}):", activeList.Count, Settings.narratorMaxActive)); for (int i = 0; i < activeList.Count && i < 10; i++) { var e = activeList[i]; string timeStr = TimeFormatter.FormatTimeAgo(e.tick, now); - listing.Label($" {"RimMind.Memory.Time.TimeContent".Translate(timeStr, e.content)}"); + listing.Label($" {Tr("RimMind.Memory.Time.TimeContent", "{0}: {1}", timeStr, e.content)}"); } if (archiveList.Count > 0) - listing.Label("RimMind.Memory.Settings.ArchiveNarrativeCount".Translate(archiveList.Count)); + listing.Label(Tr("RimMind.Memory.Settings.ArchiveNarrativeCount", " Archive Narratives: {0} entries", archiveList.Count)); } } diff --git a/Source/Triggers/MemoryTriggerHelper.cs b/Source/Triggers/MemoryTriggerHelper.cs index 1311840..6a69107 100644 --- a/Source/Triggers/MemoryTriggerHelper.cs +++ b/Source/Triggers/MemoryTriggerHelper.cs @@ -11,25 +11,35 @@ internal static bool ShouldProcess(bool triggerEnabled) } internal static void WriteMemory(Pawn pawn, string content, MemoryType type, float importance) - => WriteMemory(pawn, content, type, importance, upgradeNarrator: true); + => WriteMemory(pawn, content, type, importance, upgradeNarrator: true, pawnId: null, targetPawnId: null); - internal static void WriteMemory(Pawn pawn, string content, MemoryType type, float importance, bool upgradeNarrator) + internal static void WriteMemory( + Pawn pawn, + string content, + MemoryType type, + float importance, + bool upgradeNarrator, + string? pawnId = null, + string? targetPawnId = null) { var wc = RimMindMemoryWorldComponent.Instance; if (wc == null) return; var settings = RimMindMemoryMod.Settings; int now = Find.TickManager.TicksGame; + string resolvedPawnId = !string.IsNullOrEmpty(pawnId) + ? pawnId! + : (!string.IsNullOrEmpty(pawn.ThingID) ? pawn.ThingID : pawn.thingIDNumber.ToString()); wc.AddPawnMemory(pawn, - MemoryEntry.Create(content, type, now, importance), + MemoryEntry.Create(content, type, now, importance, pawnId, targetPawnId), settings.maxActive, settings.maxArchive); if (upgradeNarrator && importance >= settings.pawnToNarratorThreshold) { string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; wc.AddNarratorMemory( - MemoryEntry.Create($"[{pawnName}] {content}", type, now, importance, pawn.ThingID), + MemoryEntry.Create($"[{pawnName}] {content}", type, now, importance, resolvedPawnId, targetPawnId), settings.narratorMaxActive, settings.narratorMaxArchive); } } diff --git a/Source/Triggers/Patch_AddHediff.cs b/Source/Triggers/Patch_AddHediff.cs index 08bd6e3..1510400 100644 --- a/Source/Triggers/Patch_AddHediff.cs +++ b/Source/Triggers/Patch_AddHediff.cs @@ -20,6 +20,8 @@ public static class Patch_AddHediff private static readonly FieldInfo? PawnField = AccessTools.Field(typeof(Pawn_HealthTracker), "pawn"); private static readonly KeyedCooldownGate LastInjuryTickByPawn = new KeyedCooldownGate(256); + internal static void ClearCooldowns() => LastInjuryTickByPawn.Clear(); + public static bool ShouldRecordHediff( bool isBad, bool isTendable, @@ -91,31 +93,22 @@ static void Postfix(Pawn_HealthTracker __instance, Hediff hediff, DamageInfo? di hediff.Part?.Label)); float importance = EstimateImportance(hediff); - string content = BuildContent(pawn, hediff, dinfo); - if (content.NullOrEmpty()) return; + string? content = BuildContent(hediff, dinfo); + if (string.IsNullOrEmpty(content)) return; - var wc = RimMindMemoryWorldComponent.Instance; - if (wc == null) return; - var settings = RimMindMemoryMod.Settings; - string? pawnId = !string.IsNullOrEmpty(pawn.ThingID) ? pawn.ThingID : pawn.thingIDNumber.ToString(); + string pawnId = !string.IsNullOrEmpty(pawn.ThingID) ? pawn.ThingID : pawn.thingIDNumber.ToString(); string? targetPawnId = dinfo != null && dinfo.HasValue && dinfo.Value.Instigator is Pawn attackerPawn ? (!string.IsNullOrEmpty(attackerPawn.ThingID) ? attackerPawn.ThingID : attackerPawn.thingIDNumber.ToString()) : null; - wc.AddPawnMemory( + MemoryTriggerHelper.WriteMemory( pawn, - MemoryEntry.Create(content, MemoryType.Event, now, importance, pawnId, targetPawnId), - settings.maxActive, - settings.maxArchive); - - if (importance >= settings.pawnToNarratorThreshold) - { - string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; - wc.AddNarratorMemory( - MemoryEntry.Create($"[{pawnName}] {content}", MemoryType.Event, now, importance, pawnId, targetPawnId), - settings.narratorMaxActive, - settings.narratorMaxArchive); - } + content!, + MemoryType.Event, + importance, + upgradeNarrator: true, + pawnId: pawnId, + targetPawnId: targetPawnId); } catch (System.Exception ex) { @@ -132,26 +125,38 @@ private static float EstimateImportance(Hediff hediff) return 0.5f; } - private static string BuildContent(Pawn pawn, Hediff hediff, DamageInfo? dinfo) + private static string? BuildContent(Hediff hediff, DamageInfo? dinfo) { try { string label = hediff.def.LabelCap.RawText.NullOrEmpty() ? hediff.def.defName : hediff.def.LabelCap.RawText; - string part = hediff.Part?.Label ?? "RimMind.Memory.Trigger.FullBody".Translate(); + string part = hediff.Part?.Label ?? RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.FullBody", "Whole Body"); if (dinfo != null && dinfo.HasValue && dinfo.Value.Instigator != null && !dinfo.Value.Instigator.Destroyed) { var instigator = dinfo.Value.Instigator; string attacker = instigator is Pawn p && p.Name != null ? p.Name.ToStringShort - : (!instigator.Label.NullOrEmpty() ? instigator.Label : "RimMind.Memory.Trigger.UnknownSource".Translate()); - return "RimMind.Memory.Trigger.AttackedBy".Translate(attacker, label, part); + : (!instigator.Label.NullOrEmpty() + ? instigator.Label + : RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.UnknownSource", "Unknown Source")); + return RimMindAPI.Text.TrOr( + "RimMind.Memory.Trigger.AttackedBy", + "Attacked by {0}, causing {1} ({2})", + attacker, + label, + part); } - return "RimMind.Memory.Trigger.Contracted".Translate(label, part); + return RimMindAPI.Text.TrOr( + "RimMind.Memory.Trigger.Contracted", + "Contracted {0} ({1})", + label, + part); } - catch + catch (System.Exception ex) { - return null!; + RimMindErrors.Warn($"[RimMind-Memory] Patch_AddHediff.BuildContent error: {ex.Message}"); + return null; } } } diff --git a/Source/Triggers/Patch_AddRelation.cs b/Source/Triggers/Patch_AddRelation.cs index 986b946..083ab6f 100644 --- a/Source/Triggers/Patch_AddRelation.cs +++ b/Source/Triggers/Patch_AddRelation.cs @@ -2,6 +2,7 @@ using HarmonyLib; using RimMind.Domain.ValueObjects; using RimMind.Memory.Data; +using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -19,23 +20,34 @@ static void Postfix(Pawn_RelationsTracker __instance, PawnRelationDef def, Pawn try { var pawn = PawnField?.GetValue(__instance) as Pawn; - if (pawn == null || !RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(pawn) || pawn.Name == null) return; + if (pawn == null || !RimMindPawnLookup.IsActiveSpawnedColonist(pawn) || pawn.Name == null) return; if (otherPawn == null || otherPawn.Name == null) return; if (def == null) return; float importance = EstimateImportance(def); string relLabel = def.LabelCap.RawText.NullOrEmpty() ? def.defName : def.LabelCap.RawText; - string content = "RimMind.Memory.Trigger.EstablishRelation".Translate(otherPawn.Name.ToStringShort, relLabel); + string content = RimMindAPI.Text.TrOr( + "RimMind.Memory.Trigger.EstablishRelation", + "Established {1} relationship with {0}", + otherPawn.Name.ToStringShort, + relLabel); WriteRelationMemory(pawn, otherPawn, content, importance, upgradeNarrator: true); - if (RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(otherPawn) && otherPawn.Name != null) + if (RimMindPawnLookup.IsActiveSpawnedColonist(otherPawn) && otherPawn.Name != null) { try { - string reverseContent = "RimMind.Memory.Trigger.EstablishRelation".Translate(pawn.Name.ToStringShort, relLabel); + string reverseContent = RimMindAPI.Text.TrOr( + "RimMind.Memory.Trigger.EstablishRelation", + "Established {1} relationship with {0}", + pawn.Name.ToStringShort, + relLabel); WriteRelationMemory(otherPawn, pawn, reverseContent, importance, upgradeNarrator: false); } - catch { } + catch (System.Exception ex) + { + RimMindErrors.Warn($"[RimMind-Memory] Patch_AddRelation reverse memory error: {ex.Message}"); + } } } catch (System.Exception ex) @@ -46,28 +58,16 @@ static void Postfix(Pawn_RelationsTracker __instance, PawnRelationDef def, Pawn private static void WriteRelationMemory(Pawn pawn, Pawn targetPawn, string content, float importance, bool upgradeNarrator) { - var wc = RimMindMemoryWorldComponent.Instance; - if (wc == null) return; - - var settings = RimMindMemoryMod.Settings; - int now = Find.TickManager.TicksGame; string pawnId = !string.IsNullOrEmpty(pawn.ThingID) ? pawn.ThingID : pawn.thingIDNumber.ToString(); string targetPawnId = !string.IsNullOrEmpty(targetPawn.ThingID) ? targetPawn.ThingID : targetPawn.thingIDNumber.ToString(); - - wc.AddPawnMemory( + MemoryTriggerHelper.WriteMemory( pawn, - MemoryEntry.Create(content, MemoryType.Event, now, importance, pawnId, targetPawnId), - settings.maxActive, - settings.maxArchive); - - if (upgradeNarrator && importance >= settings.pawnToNarratorThreshold) - { - string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; - wc.AddNarratorMemory( - MemoryEntry.Create($"[{pawnName}] {content}", MemoryType.Event, now, importance, pawnId, targetPawnId), - settings.narratorMaxActive, - settings.narratorMaxArchive); - } + content, + MemoryType.Event, + importance, + upgradeNarrator, + pawnId, + targetPawnId); } private static float EstimateImportance(PawnRelationDef def) diff --git a/Source/Triggers/Patch_MentalBreak.cs b/Source/Triggers/Patch_MentalBreak.cs index bc93edd..edc6738 100644 --- a/Source/Triggers/Patch_MentalBreak.cs +++ b/Source/Triggers/Patch_MentalBreak.cs @@ -27,7 +27,11 @@ static void Postfix(MentalStateHandler __instance, MentalStateDef stateDef, bool float importance = EstimateImportance(stateDef); string label = stateDef.LabelCap.RawText.NullOrEmpty() ? stateDef.defName : stateDef.LabelCap.RawText; - string content = "RimMind.Memory.Trigger.MentalBreak".Translate(pawn.Name.ToStringShort, label); + string content = RimMindAPI.Text.TrOr( + "RimMind.Memory.Trigger.MentalBreak", + "{0} had a mental break: {1}", + pawn.Name.ToStringShort, + label); MemoryTriggerHelper.WriteMemory(pawn, content, MemoryType.Event, importance); } catch (System.Exception ex) diff --git a/Source/Triggers/Patch_PawnKill.cs b/Source/Triggers/Patch_PawnKill.cs index 76655ce..81e29c0 100644 --- a/Source/Triggers/Patch_PawnKill.cs +++ b/Source/Triggers/Patch_PawnKill.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using HarmonyLib; -using RimMind.Memory.DarkMemory; using RimMind.Memory.Data; +using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -23,11 +23,12 @@ static void Postfix(Pawn __instance, DamageInfo? dinfo) if (wc == null) return; if (__instance == null) return; - DarkMemoryUpdater.CleanupPawnJitter(__instance.thingIDNumber); var settings = RimMindMemoryMod.Settings; int now = Find.TickManager.TicksGame; - string deadName = __instance.Name?.ToStringShort ?? __instance.def?.label ?? "RimMind.Memory.Trigger.Unknown".Translate(); + string deadName = __instance.Name?.ToStringShort + ?? __instance.def?.label + ?? RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.Unknown", "Unknown"); string deadTargetId = !string.IsNullOrEmpty(__instance.ThingID) ? __instance.ThingID : __instance.thingIDNumber.ToString(); @@ -40,8 +41,8 @@ static void Postfix(Pawn __instance, DamageInfo? dinfo) { string relation = GetRelationLabel(colonist, __instance); string content = relation != null - ? "RimMind.Memory.Trigger.RelationDeath".Translate(relation, deadName) - : "RimMind.Memory.Trigger.Death".Translate(deadName); + ? RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.RelationDeath", "{0} {1} died", relation, deadName) + : RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.Death", "{0} died", deadName); float importance = relation != null ? 1.0f : 0.85f; string colonistPawnId = !string.IsNullOrEmpty(colonist.ThingID) @@ -54,15 +55,18 @@ static void Postfix(Pawn __instance, DamageInfo? dinfo) settings.maxActive, settings.maxArchive); } - catch { } + catch (System.Exception ex) + { + RimMindErrors.Warn($"[RimMind-Memory] Patch_PawnKill related colonist memory error: {ex.Message}"); + } } if (!ShouldRecordNarratorDeath(__instance, hadRelatedColonist)) return; string narratorContent = __instance.IsFreeNonSlaveColonist - ? "RimMind.Memory.Trigger.ColonistDeath".Translate(deadName) - : "RimMind.Memory.Trigger.Death".Translate(deadName); + ? RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.ColonistDeath", "Colonist {0} died", deadName) + : RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.Death", "{0} died", deadName); string attackerStr = ""; string? killerPawnId = null; @@ -76,8 +80,10 @@ static void Postfix(Pawn __instance, DamageInfo? dinfo) : killerPawn.thingIDNumber.ToString(); } attackerStr = inst is Pawn p && p.Name != null - ? "RimMind.Memory.Trigger.KilledBy".Translate(p.Name.ToStringShort) - : (!inst.Label.NullOrEmpty() ? "RimMind.Memory.Trigger.KilledBy".Translate(inst.Label) : ""); + ? RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.KilledBy", "(killed by {0})", p.Name.ToStringShort) + : (!inst.Label.NullOrEmpty() + ? RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.KilledBy", "(killed by {0})", inst.Label) + : ""); } wc.AddNarratorMemory( diff --git a/Source/Triggers/Patch_SkillLevelUp.cs b/Source/Triggers/Patch_SkillLevelUp.cs index 97de37e..958b7d4 100644 --- a/Source/Triggers/Patch_SkillLevelUp.cs +++ b/Source/Triggers/Patch_SkillLevelUp.cs @@ -33,10 +33,15 @@ static void Postfix(SkillRecord __instance, int __state) float importance = __instance.Level >= 15 ? 0.7f : 0.5f; string skillLabel = (__instance.def?.LabelCap.RawText.NullOrEmpty() ?? true) - ? (__instance.def?.defName ?? "RimMind.Memory.Trigger.Skill".Translate()) - : __instance.def.LabelCap.RawText; - string content = "RimMind.Memory.Trigger.SkillUp".Translate( - skillLabel, __instance.Level.ToString(), prevLevel.ToString(), __instance.Level.ToString()); + ? (__instance.def?.defName ?? RimMindAPI.Text.TrOr("RimMind.Memory.Trigger.Skill", "Skill")) + : __instance.def!.LabelCap.RawText; + string content = RimMindAPI.Text.TrOr( + "RimMind.Memory.Trigger.SkillUp", + "{0} skill increased to level {1} ({2}→{3})", + skillLabel, + __instance.Level.ToString(), + prevLevel.ToString(), + __instance.Level.ToString()); MemoryTriggerHelper.WriteMemory(pawn, content, MemoryType.Event, importance); } catch (System.Exception ex) diff --git a/Source/UI/BioTabMemoryPatch.cs b/Source/UI/BioTabMemoryPatch.cs index b7142e7..f5e75ca 100644 --- a/Source/UI/BioTabMemoryPatch.cs +++ b/Source/UI/BioTabMemoryPatch.cs @@ -22,6 +22,7 @@ public sealed class MemoryBioTabBadgeProvider : IBioTabBadgeProvider public BioTabBadgeDescriptor? TryGetBadge(Pawn pawn) { if (pawn == null) return null; + if (!pawn.IsColonist && RimMindMemoryWorldComponent.Instance?.GetPawnStore(pawn) == null) return null; string label = RimMindAPI.Text.TrOr("RimMind.Memory.UI.MemoryTab", "Memory"); return new BioTabBadgeDescriptor( diff --git a/Source/UI/Dialog_MemoryLog.cs b/Source/UI/Dialog_MemoryLog.cs index 2bff655..40277b4 100644 --- a/Source/UI/Dialog_MemoryLog.cs +++ b/Source/UI/Dialog_MemoryLog.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; using RimMind.Memory.Core; using RimMind.Memory.Data; +using RimMind.Memory.Injection; +using RimMind.Presentation.Api; using RimWorld; using UnityEngine; using Verse; @@ -11,7 +13,6 @@ public class Dialog_MemoryLog : Window { private readonly Pawn _pawn; private Vector2 _scrollPosition; - private float _lastContentHeight; public Dialog_MemoryLog(Pawn pawn) { @@ -30,19 +31,19 @@ public override void DoWindowContents(Rect inRect) { var wc = RimMindMemoryWorldComponent.Instance; if (wc == null) return; - var store = wc.GetOrCreatePawnStore(_pawn); + var store = wc.GetPawnStore(_pawn); var settings = RimMindMemoryMod.Settings; Text.Font = GameFont.Medium; Widgets.Label(new Rect(inRect.x, inRect.y, inRect.width - 100f, 30f), - "RimMind.Memory.UI.MemoryLogTitle".Translate(_pawn.LabelShort)); + RimMindAPI.Text.TrOr("RimMind.Memory.UI.MemoryLogTitle", "{0}'s Memories", _pawn.LabelShort)); Text.Font = GameFont.Small; float btnY = inRect.y + 2f; if (Widgets.ButtonText(new Rect(inRect.xMax - 96f, btnY, 96f, 28f), - "RimMind.Memory.UI.AddMemoryManually".Translate())) + RimMindAPI.Text.TrOr("RimMind.Memory.UI.AddMemoryManually", "Add Memory Manually"))) { - var dialog = new Dialog_InputMemory(_pawn, store, settings); + var dialog = new Dialog_InputMemory(_pawn, settings); Find.WindowStack.Add(dialog); } @@ -50,10 +51,13 @@ public override void DoWindowContents(Rect inRect) Rect scrollOuter = new Rect(inRect.x, inRect.y + headerH, inRect.width, inRect.height - headerH); int now = Find.TickManager.TicksGame; - var (activeList, archiveList, darkList) = store.GetSnapshots(); - float contentH = CalculateContentHeight(activeList, archiveList, darkList); + var (activeList, archiveList, darkList) = store != null + ? store.GetSnapshots() + : (new List(), new List(), new List()); + float viewWidth = scrollOuter.width - 16f; + float contentH = CalculateContentHeight(activeList, archiveList, darkList, viewWidth); - Rect viewRect = new Rect(0f, 0f, scrollOuter.width - 16f, contentH); + Rect viewRect = new Rect(0f, 0f, viewWidth, contentH); Widgets.BeginScrollView(scrollOuter, ref _scrollPosition, viewRect); float y = 0f; @@ -63,8 +67,9 @@ public override void DoWindowContents(Rect inRect) { Text.Font = GameFont.Small; Widgets.Label(new Rect(0f, y, w, 20f), - "RimMind.Memory.UI.DarkMemoryReadonly".Translate()); + RimMindAPI.Text.TrOr("RimMind.Memory.UI.DarkMemoryReadonly", "Long-term Impressions (Read-only, AI-generated)")); y += 22f; + bool prevWrap = Text.WordWrap; Text.WordWrap = true; try { @@ -77,13 +82,13 @@ public override void DoWindowContents(Rect inRect) } finally { - Text.WordWrap = false; + Text.WordWrap = prevWrap; } y += 6f; } Widgets.Label(new Rect(0f, y, w, 20f), - "RimMind.Memory.UI.ActiveMemory".Translate(activeList.Count, settings.maxActive)); + RimMindAPI.Text.TrOr("RimMind.Memory.UI.ActiveMemory", "Active Memories ({0}/{1})", activeList.Count, settings.maxActive)); y += 22f; for (int i = 0; i < activeList.Count; i++) @@ -91,22 +96,24 @@ public override void DoWindowContents(Rect inRect) var e = activeList[i]; string timeStr = TimeFormatter.FormatTimeAgo(e.tick, now); string pinMark = e.isPinned ? " [P]" : ""; - Widgets.Label(new Rect(0f, y, w - 60f, 22f), - $"{"RimMind.Memory.Time.TimeContent".Translate(timeStr, e.content)}{pinMark}"); + string lineText = RimMindAPI.Text.TrOr("RimMind.Memory.Time.TimeContent", "{0}: {1}", timeStr, e.content); + Widgets.Label(new Rect(0f, y, w - 60f, 22f), $"{lineText}{pinMark}"); - if (Widgets.ButtonText(new Rect(w - 56f, y + 1f, 24f, 20f), "P")) + if (store != null && Widgets.ButtonText(new Rect(w - 56f, y + 1f, 24f, 20f), "P")) { lock (store.SyncRoot) { e.isPinned = !e.isPinned; } + MemoryChangedEvent.Publish(_pawn.thingIDNumber); } - if (Widgets.ButtonText(new Rect(w - 28f, y + 1f, 24f, 20f), "X")) + if (store != null && Widgets.ButtonText(new Rect(w - 28f, y + 1f, 24f, 20f), "X")) { lock (store.SyncRoot) { store.active.Remove(e); } + MemoryChangedEvent.Publish(_pawn.thingIDNumber); break; } y += 24f; @@ -116,44 +123,45 @@ public override void DoWindowContents(Rect inRect) if (archiveList.Count > 0) { Widgets.Label(new Rect(0f, y, w, 20f), - "RimMind.Memory.UI.ArchiveMemoryUI".Translate(archiveList.Count, settings.maxArchive)); + RimMindAPI.Text.TrOr("RimMind.Memory.UI.ArchiveMemoryUI", "Archived Memories ({0}/{1})", archiveList.Count, settings.maxArchive)); y += 22f; foreach (var e in archiveList) { string timeStr = TimeFormatter.FormatTimeAgo(e.tick, now); - Widgets.Label(new Rect(8f, y, w - 16f, 20f), - $"{"RimMind.Memory.Time.TimeContent".Translate(timeStr, $"{e.content} (imp={e.importance:F2})")}"); + string lineText = RimMindAPI.Text.TrOr("RimMind.Memory.Time.TimeContent", "{0}: {1}", timeStr, $"{e.content} (imp={e.importance:F2})"); + Widgets.Label(new Rect(8f, y, w - 16f, 20f), lineText); y += 20f; } } - _lastContentHeight = y; Widgets.EndScrollView(); } private float CalculateContentHeight( List activeList, List archiveList, - List darkList) + List darkList, + float viewWidth) { float h = 0f; + float darkWrapWidth = Mathf.Max(60f, viewWidth - 16f); if (darkList.Count > 0) { h += 22f; - foreach (var d in darkList) + bool prevWrap = Text.WordWrap; + try { - bool prevWrap = Text.WordWrap; - try + Text.WordWrap = true; + foreach (var d in darkList) { - Text.WordWrap = true; - float textH = Text.CalcHeight(d.content, 520f); + float textH = Text.CalcHeight(d.content, darkWrapWidth); h += textH + 2f; } - finally - { - Text.WordWrap = prevWrap; - } + } + finally + { + Text.WordWrap = prevWrap; } h += 6f; } @@ -169,14 +177,12 @@ private float CalculateContentHeight( public class Dialog_InputMemory : Window { private readonly Pawn _pawn; - private readonly PawnMemoryStore _store; private readonly RimMindMemorySettings _settings; private string _inputText = ""; - public Dialog_InputMemory(Pawn pawn, PawnMemoryStore store, RimMindMemorySettings settings) + public Dialog_InputMemory(Pawn pawn, RimMindMemorySettings settings) { _pawn = pawn; - _store = store; _settings = settings; doCloseX = true; closeOnAccept = false; @@ -188,11 +194,11 @@ public Dialog_InputMemory(Pawn pawn, PawnMemoryStore store, RimMindMemorySetting public override void DoWindowContents(Rect inRect) { Widgets.Label(new Rect(inRect.x, inRect.y, inRect.width, 20f), - "RimMind.Memory.UI.InputMemoryContent".Translate()); + RimMindAPI.Text.TrOr("RimMind.Memory.UI.InputMemoryContent", "Enter memory content:")); _inputText = Widgets.TextField(new Rect(inRect.x, inRect.y + 24f, inRect.width, 30f), _inputText); if (Widgets.ButtonText(new Rect(inRect.x, inRect.yMax - 36f, 100f, 30f), - "RimMind.Memory.UI.Add".Translate()) && + RimMindAPI.Text.TrOr("RimMind.Memory.UI.Add", "Add")) && !_inputText.Trim().NullOrEmpty()) { int now = Find.TickManager.TicksGame; @@ -204,13 +210,13 @@ public override void DoWindowContents(Rect inRect) _settings.maxActive, _settings.maxArchive); } Messages.Message( - "RimMind.Memory.UI.MemoryAdded".Translate(_pawn.LabelShort), + RimMindAPI.Text.TrOr("RimMind.Memory.UI.MemoryAdded", "[RimMind] Memory added for {0}", _pawn.LabelShort), MessageTypeDefOf.SilentInput, historical: false); Close(); } if (Widgets.ButtonText(new Rect(inRect.x + 108f, inRect.yMax - 36f, 80f, 30f), - "RimMind.Memory.UI.Cancel".Translate())) + RimMindAPI.Text.TrOr("RimMind.Memory.UI.Cancel", "Cancel"))) Close(); } } diff --git a/Tests/Contracts/MemoryParsingContextContracts.cs b/Tests/Contracts/MemoryParsingContextContracts.cs index ee3d172..a1c9f7c 100644 --- a/Tests/Contracts/MemoryParsingContextContracts.cs +++ b/Tests/Contracts/MemoryParsingContextContracts.cs @@ -1,6 +1,8 @@ using System; using System.IO; using System.Linq; +using Newtonsoft.Json.Linq; +using RimMind.Memory.Aggregation; using RimMind.Memory.Core; using RimMind.Memory.DarkMemory; using RimMind.Memory.Data; @@ -62,6 +64,12 @@ public void Dark_memory_request_input_and_parsing_preserve_contracts() 3); Assert.Equal(new[] { "first memory", "second memory" }, result); + }), + ("dark memory schema metadata is valid JSON targeting the dark string array", () => + { + Assert.Equal("DarkMemoryOutput", DarkMemoryResultParserPure.SchemaKey); + var schema = JObject.Parse(DarkMemoryResultParserPure.DarkMemoryOutputSchema); + Assert.Equal("array", schema["properties"]?["dark"]?["type"]?.Value()); })); } @@ -79,16 +87,19 @@ public void Importance_decay_preserves_threshold_and_pinned_boundaries() Assert.False(ImportanceDecayCalculator.ShouldRemove(0.05f, 0.05f)); Assert.True(ImportanceDecayCalculator.ShouldRemove(0.049f, 0.05f)); }), - ("manager decays active and archive entries", () => + ("manager decays active and archive entries and reports removed count", () => { var store = new PawnMemoryStore(); store.active.Add(Entry("active", 0.8f)); + store.active.Add(Entry("active-drop", 0.06f)); store.archive.Add(Entry("archive", 0.6f)); + store.archive.Add(Entry("archive-drop", 0.05f)); - ImportanceDecayManager.ApplyDecay(store, 0.25f, 0.05f); + int removed = ImportanceDecayManager.ApplyDecay(store, 0.25f, 0.05f); - Assert.Equal(0.6f, store.active[0].importance, 3); - Assert.Equal(0.45f, store.archive[0].importance, 3); + Assert.Equal(2, removed); + Assert.Equal(0.6f, Assert.Single(store.active).importance, 3); + Assert.Equal(0.45f, Assert.Single(store.archive).importance, 3); }), ("pinned and dark state survives decay", () => { @@ -96,13 +107,61 @@ public void Importance_decay_preserves_threshold_and_pinned_boundaries() store.active.Add(Entry("pinned", 0.01f, pinned: true)); store.dark.Add(Entry("dark", 0.01f, pinned: true)); - ImportanceDecayManager.ApplyDecay(store, 0.5f, 0.05f); + int removed = ImportanceDecayManager.ApplyDecay(store, 0.5f, 0.05f); + Assert.Equal(0, removed); Assert.Equal(0.01f, Assert.Single(store.active).importance); Assert.Equal(0.01f, Assert.Single(store.dark).importance); })); } + [Fact] + public void Job_memory_policy_classifies_significant_aggregatable_ignored_and_custom_jobs() + { + ContractCaseRunner.Run( + ("significant combat, medical, animal, and social jobs resolve as SignificantSingle", () => + { + var attack = JobMemoryPolicy.Resolve("AttackMelee"); + Assert.Equal(JobMemoryKind.SignificantSingle, attack.Kind); + Assert.Equal(0.9f, attack.Importance, 3); + + var rescue = JobMemoryPolicy.Resolve("Rescue"); + Assert.Equal(JobMemoryKind.SignificantSingle, rescue.Kind); + Assert.Equal(0.8f, rescue.Importance, 3); + + var tend = JobMemoryPolicy.Resolve("TendPatient"); + Assert.Equal(JobMemoryKind.SignificantSingle, tend.Kind); + Assert.Equal(0.8f, tend.Importance, 3); + + var recruit = JobMemoryPolicy.Resolve("PrisonerAttemptRecruit"); + Assert.Equal(JobMemoryKind.SignificantSingle, recruit.Kind); + Assert.Equal(0.7f, recruit.Importance, 3); + }), + ("repetitive work jobs resolve as Aggregatable and idle movement jobs as Ignored", () => + { + Assert.Equal(JobMemoryKind.Aggregatable, JobMemoryPolicy.Resolve("Sow").Kind); + Assert.Equal(JobMemoryKind.Aggregatable, JobMemoryPolicy.Resolve("Mine").Kind); + Assert.Equal(JobMemoryKind.Aggregatable, JobMemoryPolicy.Resolve("DoBill").Kind); + Assert.Equal(JobMemoryKind.Aggregatable, JobMemoryPolicy.Resolve("HaulToCell").Kind); + + Assert.Equal(JobMemoryKind.Ignored, JobMemoryPolicy.Resolve("Wait").Kind); + Assert.Equal(JobMemoryKind.Ignored, JobMemoryPolicy.Resolve("Goto").Kind); + Assert.Equal(JobMemoryKind.Ignored, JobMemoryPolicy.Resolve("Wait_Asleep").Kind); + + Assert.Equal(JobMemoryKind.Unknown, JobMemoryPolicy.Resolve("UnregisteredJobXYZ").Kind); + Assert.Equal(JobMemoryKind.Unknown, JobMemoryPolicy.Resolve(null).Kind); + }), + ("custom job rules can be registered dynamically", () => + { + string customJob = "CustomRitual_" + Guid.NewGuid().ToString("N"); + JobMemoryPolicy.RegisterRule(customJob, new JobMemoryRule(JobMemoryKind.SignificantSingle, 0.75f)); + + var resolved = JobMemoryPolicy.Resolve(customJob); + Assert.Equal(JobMemoryKind.SignificantSingle, resolved.Kind); + Assert.Equal(0.75f, resolved.Importance, 3); + })); + } + [Fact] public void Trigger_filtering_dark_memory_gate_and_store_pruning_contracts_hold() { @@ -127,12 +186,14 @@ public void Trigger_filtering_dark_memory_gate_and_store_pruning_contracts_hold( Assert.Contains("public const int InjuryCoalesceWindowTicks = 2500;", hediffSource, StringComparison.Ordinal); Assert.Contains("ShouldRecordHediff(", hediffSource, StringComparison.Ordinal); }), - ("relation trigger populates targetPawnId on both forward and reverse memories", () => + ("relation trigger writes forward and reverse memories with targetPawnId", () => { string relSource = ReadMemorySource("Triggers/Patch_AddRelation.cs"); + string helperSource = ReadMemorySource("Triggers/MemoryTriggerHelper.cs"); Assert.Contains("WriteRelationMemory(pawn, otherPawn, content, importance, upgradeNarrator: true);", relSource, StringComparison.Ordinal); Assert.Contains("WriteRelationMemory(otherPawn, pawn, reverseContent, importance, upgradeNarrator: false);", relSource, StringComparison.Ordinal); - Assert.Contains("MemoryEntry.Create(content, MemoryType.Event, now, importance, pawnId, targetPawnId)", relSource, StringComparison.Ordinal); + Assert.Contains("MemoryTriggerHelper.WriteMemory(", relSource, StringComparison.Ordinal); + Assert.Contains("MemoryEntry.Create(content, type, now, importance, pawnId, targetPawnId)", helperSource, StringComparison.Ordinal); }), ("world component and work session aggregator prune inactive pawns daily", () => { @@ -146,10 +207,11 @@ public void Trigger_filtering_dark_memory_gate_and_store_pruning_contracts_hold( Assert.Contains("RimMindPawnLookup.GetSpawnedColonistsSafe(map)", workSource, StringComparison.Ordinal); Assert.DoesNotContain("FreeColonistsSpawned", workSource, StringComparison.Ordinal); }), - ("dark memory requests attach coalesce key, 1-day TTL, TickStagger, and non-starving mod cooldown", () => + ("dark memory requests attach coalesce key, 1-day TTL, TickStagger, and clean Core extension metadata", () => { string darkSource = ReadMemorySource("DarkMemory/DarkMemoryUpdater.cs"); string cooldownSource = ReadMemorySource("Extensions/MemoryModCooldown.cs"); + string skipSource = ReadMemorySource("Extensions/MemoryActionSkipCheck.cs"); string parserSource = ReadMemorySource("DarkMemory/DarkMemoryResultParserPure.cs"); string bioTabSource = ReadMemorySource("UI/BioTabMemoryPatch.cs"); string drawerSource = ReadMemorySource("Settings/MemorySettingsDrawer.cs"); @@ -161,7 +223,9 @@ public void Trigger_filtering_dark_memory_gate_and_store_pruning_contracts_hold( Assert.DoesNotContain("0x7feb352du", darkSource, StringComparison.Ordinal); Assert.Contains("BaseModCooldownTicks = 3000", cooldownSource, StringComparison.Ordinal); - Assert.Contains("OwnerModId => DarkMemoryUpdater.RequestModId", cooldownSource, StringComparison.Ordinal); + Assert.Contains("Id => DarkMemoryUpdater.RequestModId", cooldownSource, StringComparison.Ordinal); + Assert.Contains("OwnerModId => RimMindOwnerConsts.MemoryModId", cooldownSource, StringComparison.Ordinal); + Assert.Contains("ShouldSkip(in SkipCheckArgs args) => false;", skipSource, StringComparison.Ordinal); Assert.DoesNotContain("using RimMind.Application.Features.Json", parserSource, StringComparison.Ordinal); Assert.Contains("RimMindAPI.Json.TryDeserializeWithRepair", parserSource, StringComparison.Ordinal); @@ -242,7 +306,7 @@ private static void PublicProvidersRetainBridgeBriefContract() "public static class MemoryContextProvider", "public static void Register()"); Assert.Contains( - "private const string PublicProviderOwner = \"RimMind.Memory\";", + "private const string PublicProviderOwner = RimMindOwnerConsts.MemoryModId;", providerFields, StringComparison.Ordinal); Assert.Contains( @@ -276,15 +340,15 @@ private static void PublicProvidersRetainBridgeBriefContract() "GetOrCreatePawnStore", pawnBrief, StringComparison.Ordinal); + Assert.Contains( + "if(!RimMindMemoryMod.Settings.enableMemory)returnstring.Empty;", + compactPawnBrief, + StringComparison.Ordinal); Assert.Contains( "if(store==null||store.IsEmpty)returnstring.Empty;", compactPawnBrief, StringComparison.Ordinal); - AssertSeparatedOnlyByWhitespace( - pawnBrief, - "var sb = new StringBuilder(TrOrFallback(\"RimMind.Memory.Context.BriefHeader\", \"[RimMind Memory]\"));", - "foreach (var memory in activeList.Take(5))"); - Assert.DoesNotContain("sb.AppendLine();", pawnBrief, StringComparison.Ordinal); + Assert.Contains("sb.AppendLine(TrOrFallback(\"RimMind.Memory.Context.BriefHeader\"", pawnBrief, StringComparison.Ordinal); Assert.Equal(2, CountOccurrences(pawnBrief, "Take(5)")); Assert.Equal( 2, @@ -302,15 +366,15 @@ private static void PublicProvidersRetainBridgeBriefContract() providerSource, "private static string BuildNarratorBrief()"); string compactNarratorBrief = RemoveWhitespace(narratorBrief); + Assert.Contains( + "if(!RimMindMemoryMod.Settings.enableMemory)returnstring.Empty;", + compactNarratorBrief, + StringComparison.Ordinal); Assert.Contains( "if(store==null||store.IsEmpty)returnstring.Empty;", compactNarratorBrief, StringComparison.Ordinal); - AssertSeparatedOnlyByWhitespace( - narratorBrief, - "var sb = new StringBuilder(TrOrFallback(\"RimMind.Memory.Context.NarratorBriefHeader\", \"[RimMind Storyteller]\"));", - "foreach (var memory in activeList.Take(5))"); - Assert.DoesNotContain("sb.AppendLine();", narratorBrief, StringComparison.Ordinal); + Assert.Contains("sb.AppendLine(TrOrFallback(\"RimMind.Memory.Context.NarratorBriefHeader\"", narratorBrief, StringComparison.Ordinal); Assert.Equal(1, CountOccurrences(narratorBrief, "Take(5)")); Assert.Equal( 1, @@ -352,24 +416,6 @@ private static int FindMatchingBrace(string source, int openBrace) throw new InvalidOperationException("Unbalanced source method braces."); } - private static void AssertSeparatedOnlyByWhitespace( - string source, - string first, - string second) - { - int firstStart = source.IndexOf(first, StringComparison.Ordinal); - Assert.True(firstStart >= 0, $"Source fragment was not found: {first}"); - - int gapStart = firstStart + first.Length; - int secondStart = source.IndexOf(second, gapStart, StringComparison.Ordinal); - Assert.True(secondStart >= gapStart, $"Source fragment was not found after {first}: {second}"); - - string gap = source.Substring(gapStart, secondStart - gapStart); - Assert.True( - gap.All(char.IsWhiteSpace), - $"Only formatting whitespace may separate {first} from {second}."); - } - private static string SliceSource(string source, string startMarker, string endMarker) { int start = source.IndexOf(startMarker, StringComparison.Ordinal); @@ -477,8 +523,11 @@ public void Time_context_preserves_elapsed_and_game_date_boundaries() Assert.Equal("Today", TimeFormatter.FormatTimeAgo(0, 59999))), ("three days remains relative", () => Assert.Equal("3 days ago", TimeFormatter.FormatTimeAgo(0, 180000))), - ("older history uses a stable game date", () => - Assert.Equal("Day 5 00:00", TimeFormatter.FormatTimeAgo(0, 240000))), + ("older history uses the event's own game date rather than nowTick", () => + { + Assert.Equal("Day 1 00:00", TimeFormatter.FormatTimeAgo(0, 240000)); + Assert.Equal("Day 2 06:00", TimeFormatter.FormatTimeAgo(75000, 360000)); + }), ("game date preserves day and hour", () => Assert.Equal("Day 2 06:00", TimeFormatter.FormatGameDate(75000)))); } diff --git a/Tests/Contracts/MemoryStoreContracts.cs b/Tests/Contracts/MemoryStoreContracts.cs index 7e3077d..d515b1c 100644 --- a/Tests/Contracts/MemoryStoreContracts.cs +++ b/Tests/Contracts/MemoryStoreContracts.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using RimMind.Memory.Core; using RimMind.Memory.Data; @@ -53,6 +54,15 @@ public void Memory_entries_preserve_identity_and_layer_routing() Assert.Equal("active", Assert.Single(store.active).id); Assert.Equal("archive", Assert.Single(store.archive).id); + }), + ("null content degrades to empty string and oversized content truncates safely", () => + { + var empty = MemoryEntry.Create(null!, MemoryType.Event, 50, 0.5f); + Assert.Equal(string.Empty, empty.content); + + var oversized = MemoryEntry.Create(new string('x', 2500), MemoryType.Event, 51, 0.5f); + Assert.Equal(2003, oversized.content.Length); + Assert.EndsWith("...", oversized.content, StringComparison.Ordinal); })); } @@ -88,16 +98,21 @@ public void Memory_store_preserves_capacity_and_importance_order() entry => Assert.Equal("high", entry.id), entry => Assert.Equal("medium", entry.id)); }), - ("pinned active entries send overflow directly to archive", () => + ("pinned active entries send overflow directly to archive without spilling into dark", () => { var store = new PawnMemoryStore(); var pinned = Entry("pinned", 1, 1.0f, pinned: true); store.AddActive(pinned, maxActive: 1, maxArchive: 2); - store.AddActive(Entry("overflow", 2, 0.4f), maxActive: 1, maxArchive: 2); + store.AddActive(Entry("overflow-1", 2, 0.4f), maxActive: 1, maxArchive: 2); + store.AddActive(Entry("overflow-2", 3, 0.7f), maxActive: 1, maxArchive: 2); + store.AddActive(Entry("overflow-3", 4, 0.9f), maxActive: 1, maxArchive: 2); Assert.Same(pinned, Assert.Single(store.active)); - Assert.Equal("overflow", Assert.Single(store.archive).id); + Assert.Equal(2, store.archive.Count); + Assert.Empty(store.dark); + Assert.Contains(store.archive, e => e.id == "overflow-3"); + Assert.Contains(store.archive, e => e.id == "overflow-2"); })); } @@ -221,12 +236,15 @@ public void Remote_snapshot_round_trip_preserves_layers_deduplication_and_limits Assert.Empty(existing.active); Assert.Equal("same", Assert.Single(existing.archive).id); }), - ("merge enforces active and archive limits", () => + ("merge enforces active and archive limits without spilling archive into dark", () => { var source = new Dictionary(); var incoming = new PawnMemoryStore(); incoming.active.Add(Entry("new", 3, 0.9f)); incoming.active.Add(Entry("old", 1, 0.2f)); + incoming.archive.Add(Entry("arch-a", 1, 0.8f)); + incoming.archive.Add(Entry("arch-b", 2, 0.3f)); + incoming.archive.Add(Entry("arch-c", 3, 0.6f)); source[9] = incoming; var target = new Dictionary(); @@ -234,10 +252,11 @@ public void Remote_snapshot_round_trip_preserves_layers_deduplication_and_limits MemorySnapshotService.Serialize(source, new NarratorMemoryStore()), target, new NarratorMemoryStore(), - new MemorySnapshotLimits(1, 1, 1, 1)); + new MemorySnapshotLimits(1, 2, 1, 1)); Assert.Single(target[9].active); - Assert.Single(target[9].archive); + Assert.Equal(2, target[9].archive.Count); + Assert.Empty(target[9].dark); })); } diff --git a/Tests/README.md b/Tests/README.md index 37024f8..3309adf 100644 --- a/Tests/README.md +++ b/Tests/README.md @@ -2,8 +2,8 @@ Active contract sources are `Contracts/*.cs`. The compact suite contains: -- `MemoryStoreContracts` — entry identity, layer routing, limits, importance ordering and legacy working-memory save compatibility. -- `MemoryParsingContextContracts` — dark-memory parsing, decay boundaries and time context. +- `MemoryStoreContracts` — entry identity, layer routing, limits (without archive->dark spill), importance ordering, retrieval scoring and legacy working-memory save compatibility. +- `MemoryParsingContextContracts` — dark-memory schema & parsing, decay boundaries and removed counts, `JobMemoryPolicy` classification/extensibility, Core extension contracts, and time context. - `RemoteSyncBoundaryContracts` — remote failure isolation, main-thread scheduling and successful merge boundaries. Count actual discovered cases with the root test-budget script; all projects per mod must total fewer than 1000. Add behavior and failure-boundary tests, not private-shape assertions or unrelated aggregate scenarios. @@ -19,8 +19,8 @@ Count actual discovered cases with the root test-budget script; all projects per ``` - Required retained stub include: `VerseStubs.cs` -- Required production includes: `TimeFormatter.cs`, `ImportanceDecayCalculator.cs`, - `MemoryEntry.cs`, `MemoryStoreBase.cs`, `PawnMemoryStore.cs`, +- Required production includes: `JobMemoryPolicy.cs`, `TimeFormatter.cs`, `ImportanceDecayCalculator.cs`, + `MemoryRetrievalScorer.cs`, `MemoryEntry.cs`, `MemoryStoreBase.cs`, `PawnMemoryStore.cs`, `NarratorMemoryStore.cs`, `MemorySnapshotService.cs`, `ImportanceDecayManager.cs`, `WorkingMemory.cs`, `WorkingMemoryEntry.cs`, and `DarkMemoryResultParserPure.cs` diff --git a/Tests/RimMindMemory.Tests.csproj b/Tests/RimMindMemory.Tests.csproj index bb05f1a..90056f8 100644 --- a/Tests/RimMindMemory.Tests.csproj +++ b/Tests/RimMindMemory.Tests.csproj @@ -21,6 +21,7 @@ + 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