diff --git a/Source/Aggregation/WorkSessionAggregator.cs b/Source/Aggregation/WorkSessionAggregator.cs
index 0dc110e..9a7071a 100644
--- a/Source/Aggregation/WorkSessionAggregator.cs
+++ b/Source/Aggregation/WorkSessionAggregator.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using RimMind.Memory.Data;
using RimMind.Memory.Core;
+using RimMind.Presentation.Api;
using RimWorld;
using Verse;
using Verse.AI;
@@ -43,12 +44,11 @@ public override void GameComponentTick()
{
foreach (var map in Find.Maps)
{
- var colonists = map?.mapPawns?.FreeColonistsSpawned;
- if (colonists == null) continue;
+ var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map);
for (int i = 0; i < colonists.Count; i++)
{
var p = colonists[i];
- if (p != null && RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(p))
+ if (p != null && RimMindPawnLookup.IsActiveSpawnedColonist(p))
activeIds.Add(p.thingIDNumber);
}
}
@@ -181,9 +181,9 @@ private void CheckIdleGap(Pawn pawn, int pawnId, int now, int idleGapThresholdTi
if (wc != null)
{
var store = wc.GetPawnStore(pawn);
- string idlePrefix = "RimMind.Memory.Work.Idle".CanTranslate()
- ? "RimMind.Memory.Work.Idle".Translate("0").RawText.Replace("0", "").Trim()
- : "Idle";
+ string idlePrefix = RimMindAPI.Text.TrOr("RimMind.Memory.Work.Idle", "Idle", "{0}")
+ .Split(new[] { "{0}" }, StringSplitOptions.None)[0]
+ .Trim();
bool updatedExisting = false;
if (store != null)
{
@@ -288,8 +288,7 @@ private static float GetSignificantJobImportance(string defName)
private static string JobLabel(string defName)
{
- string key = $"RimMind.Memory.Work.{defName}";
- return key.CanTranslate() ? key.Translate() : defName;
+ return RimMindAPI.Text.TrOr($"RimMind.Memory.Work.{defName}", defName);
}
private class PawnSession
diff --git a/Source/Core/PawnLookup.cs b/Source/Core/PawnLookup.cs
index dd4611b..f019447 100644
--- a/Source/Core/PawnLookup.cs
+++ b/Source/Core/PawnLookup.cs
@@ -1,14 +1,16 @@
-using System.Linq;
+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)
- => RimMind.Presentation.Api.RimMindPawnLookup.FindPawnById(pawnId);
+ => RimMindPawnLookup.FindPawnById(pawnId);
public static Pawn? FindPawnByNumber(int thingIDNumber)
- => RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber(thingIDNumber);
+ => RimMindPawnLookup.FindPawnByNumber(thingIDNumber);
}
}
diff --git a/Source/Core/RimMindMemoryBridge.cs b/Source/Core/RimMindMemoryBridge.cs
index a839065..89f4507 100644
--- a/Source/Core/RimMindMemoryBridge.cs
+++ b/Source/Core/RimMindMemoryBridge.cs
@@ -3,6 +3,7 @@
using RimMind.Application.Common.Interfaces.Memory;
using RimMind.Application.Common.Models.Memory;
using RimMind.Memory.Data;
+using RimMind.Presentation.Api;
namespace RimMind.Memory.Core
{
@@ -13,7 +14,7 @@ public bool AddPawnMemory(string content, MemoryKind kind, int tick, float impor
{
if (!RimMindMemoryMod.Settings.enableMemory) return false;
- var pawn = PawnLookup.FindPawnById(pawnId ?? string.Empty);
+ var pawn = RimMindPawnLookup.FindPawnById(pawnId ?? string.Empty);
var world = RimMindMemoryWorldComponent.Instance;
if (pawn == null || world == null) return false;
diff --git a/Source/DarkMemory/DarkMemoryResultParserPure.cs b/Source/DarkMemory/DarkMemoryResultParserPure.cs
index ba32f0d..2b0dfab 100644
--- a/Source/DarkMemory/DarkMemoryResultParserPure.cs
+++ b/Source/DarkMemory/DarkMemoryResultParserPure.cs
@@ -1,15 +1,12 @@
using System;
using System.Collections.Generic;
-using System.Text;
-using System.Text.RegularExpressions;
-using Newtonsoft.Json.Linq;
-using RimMind.Application.Features.Json;
+using RimMind.Presentation.Api;
namespace RimMind.Memory.DarkMemory
{
///
- /// 纯逻辑版本的暗记忆结果解析器,不依赖 RimMindAPI 或 RimWorld 运行时。
- /// 供测试项目直接编译使用。
+ /// 纯逻辑版本的暗记忆结果解析器,委托 Core 进行清洗、提取与修复。
+ /// 供生产与测试项目共用。
///
public static class DarkMemoryResultParserPure
{
@@ -18,23 +15,22 @@ public class DarkMemoryResultDto
public string[] dark = Array.Empty();
}
- private static readonly Regex TrailingCommaRegex = new Regex(
- @",\s*([}\]])",
- RegexOptions.Compiled);
-
public static List? Parse(string json, int maxCount)
{
+ if (string.IsNullOrWhiteSpace(json))
+ return null;
+
try
{
- var result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
- if (result?.dark == null)
+ string? payload = RimMindAPI.Json.ExtractJsonPayload(json);
+ if (string.IsNullOrWhiteSpace(payload) || HasUnclosedString(payload!))
+ return null;
+
+ if (!RimMindAPI.Json.TryDeserializeWithRepair(payload, out var result)
+ || result?.dark == null)
{
- // 尝试修复截断的JSON后重新反序列化
- string? repaired = TryRepairTruncatedJson(json);
- if (repaired != null)
- result = Newtonsoft.Json.JsonConvert.DeserializeObject(repaired);
+ return null;
}
- if (result?.dark == null) return null;
var entries = new List();
foreach (var text in result.dark)
@@ -51,17 +47,6 @@ public class DarkMemoryResultDto
}
}
- ///
- /// 尝试修复截断的JSON。若输入已是合法JSON则返回null(无需修复),
- /// 若输入为空白或不可修复则返回null。
- ///
- private static string? TryRepairTruncatedJson(string input)
- {
- if (string.IsNullOrWhiteSpace(input)) return null;
- if (HasUnclosedString(input)) return null;
- return JsonRepairer.TryRepairTruncatedJson(input) ?? TryRepairFallback(input);
- }
-
private static bool HasUnclosedString(string input)
{
bool inString = false;
@@ -81,45 +66,5 @@ private static bool HasUnclosedString(string input)
}
return inString;
}
-
- private static string? TryRepairFallback(string input)
- {
- try
- {
- JToken.Parse(input);
- return null; // 已是合法JSON,无需修复
- }
- catch
- {
- return Repair(input);
- }
- }
-
- private static string Repair(string input)
- {
- if (string.IsNullOrWhiteSpace(input)) return "{}";
-
- var result = new StringBuilder(input);
- result = new StringBuilder(TrailingCommaRegex.Replace(result.ToString(), "$1"));
- var balanced = BalanceBrackets(result.ToString());
- return balanced;
- }
-
- private static string BalanceBrackets(string input)
- {
- int openCurly = 0, openSquare = 0;
- foreach (char c in input)
- {
- if (c == '{') openCurly++;
- else if (c == '}') openCurly--;
- else if (c == '[') openSquare++;
- else if (c == ']') openSquare--;
- }
-
- var sb = new StringBuilder(input);
- while (openSquare > 0) { sb.Append(']'); openSquare--; }
- while (openCurly > 0) { sb.Append('}'); openCurly--; }
- return sb.ToString();
- }
}
}
diff --git a/Source/DarkMemory/DarkMemoryUpdater.cs b/Source/DarkMemory/DarkMemoryUpdater.cs
index 6aa2516..5353b0d 100644
--- a/Source/DarkMemory/DarkMemoryUpdater.cs
+++ b/Source/DarkMemory/DarkMemoryUpdater.cs
@@ -2,6 +2,7 @@
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;
@@ -17,12 +18,15 @@ namespace RimMind.Memory.DarkMemory
{
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 static DarkMemoryUpdater? _instance;
public static DarkMemoryUpdater? Instance => Current.Game != null ? _instance : null;
private int _narratorOffset;
- private const int DailyInterval = 60000;
- private const int JitterRange = 3000;
public DarkMemoryUpdater(Game game)
{
@@ -30,21 +34,18 @@ public DarkMemoryUpdater(Game game)
_narratorOffset = new System.Random().Next(0, DailyInterval);
}
+ public static string BuildCoalesceKey(string npcId)
+ => $"{RequestModId}:dark_memory:{npcId}";
+
public static int GetPawnJitter(int thingID)
{
- uint hash = unchecked((uint)(thingID ^ 0x5A5A5A5A));
- hash ^= hash >> 16;
- hash *= 0x7feb352du;
- hash ^= hash >> 15;
- hash *= 0x846ca68bu;
- hash ^= hash >> 16;
int span = JitterRange * 2 + 1;
- return (int)(hash % (uint)span) - JitterRange;
+ return TickStagger.PhaseOffset(thingID, span) - JitterRange;
}
public static void CleanupPawnJitter(int thingID)
{
- // Jitter is computed deterministically from thingIDNumber; no per-pawn state to prune.
+ // Jitter is computed deterministically from thingIDNumber via TickStagger; no per-pawn state to prune.
}
public override void GameComponentTick()
@@ -54,23 +55,25 @@ public override void GameComponentTick()
if (wc == null) return;
var settings = RimMindMemoryMod.Settings;
+ int now = Find.TickManager.TicksGame;
+ if (now <= 0) return;
foreach (var map in Find.Maps)
{
- var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map);
+ var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map);
if (colonists.Count == 0) continue;
for (int i = 0; i < colonists.Count; i++)
{
var pawn = colonists[i];
if (pawn == null || pawn.Dead || pawn.Destroyed || pawn.IsKidnapped()) continue;
- int jitteredInterval = DailyInterval + GetPawnJitter(pawn.thingIDNumber);
- if (!pawn.IsHashIntervalTick(jitteredInterval)) continue;
+ if (!TickStagger.IsDue(now, pawn.thingIDNumber, DailyInterval)) continue;
TriggerPawnDarkMemoryUpdate(pawn, wc, settings);
if (settings.enableDecay)
{
- var store = wc.GetOrCreatePawnStore(pawn);
- ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold);
+ var store = wc.GetPawnStore(pawn);
+ if (store != null)
+ ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold);
}
}
}
@@ -87,20 +90,20 @@ public override void GameComponentTick()
{
var pawn = caravanPawns[i];
if (pawn == null || !pawn.IsFreeNonSlaveColonist || pawn.Faction != Faction.OfPlayer || pawn.Dead || pawn.Destroyed || pawn.IsKidnapped()) continue;
- int jitteredInterval = DailyInterval + GetPawnJitter(pawn.thingIDNumber);
- if (!pawn.IsHashIntervalTick(jitteredInterval)) continue;
+ if (!TickStagger.IsDue(now, pawn.thingIDNumber, DailyInterval)) continue;
TriggerPawnDarkMemoryUpdate(pawn, wc, settings);
if (settings.enableDecay)
{
- var store = wc.GetOrCreatePawnStore(pawn);
- ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold);
+ var store = wc.GetPawnStore(pawn);
+ if (store != null)
+ ImportanceDecayManager.ApplyDecay(store, settings.decayRate, settings.minImportanceThreshold);
}
}
}
}
- if ((Find.TickManager.TicksGame + _narratorOffset) % DailyInterval == 0)
+ if (TickStagger.IsDue(now, _narratorOffset, DailyInterval))
{
TriggerNarratorDarkMemoryUpdate(wc, settings);
@@ -118,14 +121,16 @@ public override void ExposeData()
public void TriggerPawnDarkMemoryUpdate(Pawn pawn, RimMindMemoryWorldComponent wc, RimMindMemorySettings settings)
{
if (pawn == null || pawn.Dead || pawn.Destroyed || pawn.IsKidnapped() || pawn.Faction != Faction.OfPlayer) return;
- if (!pawn.Spawned && !RimWorld.Planet.CaravanUtility.IsCaravanMember(pawn)) return;
- if (!RimMind.Presentation.Api.RimMindAPI.IsConfigured()) return;
+ bool isCaravanMember = !pawn.Spawned && RimWorld.Planet.CaravanUtility.IsCaravanMember(pawn);
+ if (!pawn.Spawned && !isCaravanMember) return;
+ if (!RimMindAPI.Settings.IsConfigured()) return;
- var store = wc.GetOrCreatePawnStore(pawn);
+ var store = wc.GetPawnStore(pawn);
+ if (store == null) return;
int now = Find.TickManager.TicksGame;
- int todayStart = now - (now % DailyInterval);
+ int windowStart = Math.Max(0, now - DailyInterval);
var (activeList, _, darkList) = store.GetSnapshots();
- var todayEntries = activeList.Where(e => e.tick >= todayStart && e.type != MemoryType.Dark).ToList();
+ var todayEntries = activeList.Where(e => e.tick >= windowStart && e.type != MemoryType.Dark).ToList();
if (todayEntries.Count == 0) return;
@@ -148,29 +153,33 @@ public void TriggerPawnDarkMemoryUpdate(Pawn pawn, RimMindMemoryWorldComponent w
var envelope = LlmRequestEnvelopeBuilder
.ForScenario(RimMindAPI.Context.ScenarioMemory)
- .WithModId("RimMind.Memory")
+ .WithModId(RequestModId)
.WithSchema(schema)
.WithMaxTokens(400)
.WithTemperature(0.5f)
.WithNpcId(npcId)
.WithGameStateInfo(currentQuery)
+ .WithCoalesceKey(BuildCoalesceKey(npcId))
+ .WithMaxQueueWaitTicks(DarkMemoryMaxQueueWaitTicks)
+ .WithRequireAliveColonist(!isCaravanMember)
.Build();
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);
});
}
public void TriggerNarratorDarkMemoryUpdate(RimMindMemoryWorldComponent wc, RimMindMemorySettings settings)
{
- if (!RimMind.Presentation.Api.RimMindAPI.IsConfigured()) return;
+ if (!RimMindAPI.Settings.IsConfigured()) return;
var store = wc.NarratorStore;
int now = Find.TickManager.TicksGame;
- int todayStart = now - (now % DailyInterval);
+ int windowStart = Math.Max(0, now - DailyInterval);
var (activeList, _, darkList) = store.GetSnapshots();
- var todayEntries = activeList.Where(e => e.tick >= todayStart && e.type != MemoryType.Dark).ToList();
+ var todayEntries = activeList.Where(e => e.tick >= windowStart && e.type != MemoryType.Dark).ToList();
if (todayEntries.Count == 0) return;
@@ -193,12 +202,15 @@ public void TriggerNarratorDarkMemoryUpdate(RimMindMemoryWorldComponent wc, RimM
var envelope = LlmRequestEnvelopeBuilder
.ForScenario(RimMindAPI.Context.ScenarioMemory)
- .WithModId("RimMind.Memory")
+ .WithModId(RequestModId)
.WithSchema(schema)
.WithMaxTokens(400)
.WithTemperature(0.5f)
.WithNpcId(npcId)
.WithGameStateInfo(currentQuery)
+ .WithCoalesceKey(BuildCoalesceKey(npcId))
+ .WithMaxQueueWaitTicks(DarkMemoryMaxQueueWaitTicks)
+ .WithRequireAliveColonist(false)
.Build();
RimMindAPI.Request.Send(envelope, result =>
{
diff --git a/Source/Data/RimMindMemoryWorldComponent.cs b/Source/Data/RimMindMemoryWorldComponent.cs
index b8a7ea8..b92d217 100644
--- a/Source/Data/RimMindMemoryWorldComponent.cs
+++ b/Source/Data/RimMindMemoryWorldComponent.cs
@@ -16,13 +16,13 @@ public class RimMindMemoryWorldComponent : WorldComponent
private Dictionary _workingMemories = new Dictionary();
private readonly object _storesLock = new object();
- private static RimMindMemoryWorldComponent? _instance;
- public static RimMindMemoryWorldComponent? Instance =>
- Current.Game?.World != null && _instance?.world == Current.Game.World ? _instance : null;
+ private static readonly WorldScopedComponentCache InstanceCache =
+ new WorldScopedComponentCache();
+ public static RimMindMemoryWorldComponent? Instance => InstanceCache.Get();
public RimMindMemoryWorldComponent(World world) : base(world)
{
- _instance = this;
+ InstanceCache.Reset();
}
public PawnMemoryStore GetOrCreatePawnStore(Pawn pawn)
@@ -226,7 +226,7 @@ public override void WorldComponentTick()
public void PruneInactivePawnState()
{
- var retainedIds = CollectRetainedPawnIds();
+ var retainedIds = RimMindPawnLookup.CollectRetainedColonyPawnIds();
lock (_storesLock)
{
PrunePawnStores(_pawnStores, retainedIds, MaxRetainedInactivePawnStores);
@@ -304,71 +304,5 @@ private static int GetLatestStoreTick(PawnMemoryStore store)
}
return latest;
}
-
- private static HashSet CollectRetainedPawnIds()
- {
- var retained = new HashSet();
-
- var allAliveColonists = RimWorld.PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_Colonists;
- if (allAliveColonists != null)
- {
- foreach (var pawn in allAliveColonists)
- {
- if (pawn != null && pawn.thingIDNumber > 0)
- retained.Add(pawn.thingIDNumber);
- }
- }
-
- if (Find.Maps != null)
- {
- foreach (var map in Find.Maps)
- {
- var allMapPawns = map?.mapPawns?.AllPawns;
- if (allMapPawns != null)
- {
- foreach (var p in allMapPawns)
- {
- if (p != null && p.thingIDNumber > 0 && !p.Destroyed
- && (RimMindPawnLookup.IsEligibleColonist(p) || p.IsColonist || p.IsPrisonerOfColony || p.IsSlaveOfColony))
- {
- retained.Add(p.thingIDNumber);
- }
- }
- }
-
- var corpses = map?.listerThings?.ThingsInGroup(ThingRequestGroup.Corpse);
- if (corpses != null)
- {
- foreach (var thing in corpses)
- {
- if (thing is Corpse corpse && corpse.InnerPawn is Pawn inner
- && inner.thingIDNumber > 0 && !inner.Destroyed
- && (inner.IsColonist || inner.IsPrisonerOfColony || inner.IsSlaveOfColony))
- {
- retained.Add(inner.thingIDNumber);
- }
- }
- }
- }
- }
-
- var factions = Find.FactionManager?.AllFactionsListForReading;
- if (factions != null)
- {
- for (int i = 0; i < factions.Count; i++)
- {
- var kidnapped = factions[i]?.kidnapped?.KidnappedPawnsListForReading;
- if (kidnapped == null) continue;
- for (int j = 0; j < kidnapped.Count; j++)
- {
- var p = kidnapped[j];
- if (p != null && p.thingIDNumber > 0 && !p.Dead && !p.Destroyed)
- retained.Add(p.thingIDNumber);
- }
- }
- }
-
- return retained;
- }
}
}
diff --git a/Source/Debug/MemoryDebugActions.cs b/Source/Debug/MemoryDebugActions.cs
index 00fa535..8269f80 100644
--- a/Source/Debug/MemoryDebugActions.cs
+++ b/Source/Debug/MemoryDebugActions.cs
@@ -40,22 +40,30 @@ public static void ShowMemoryState()
var wc = RimMindMemoryWorldComponent.Instance;
if (wc == null) { RimMindErrors.Warn("[RimMind-Memory] WorldComponent not initialized."); return; }
- var store = wc.GetOrCreatePawnStore(pawn);
+ var store = wc.GetPawnStore(pawn);
var sb = new StringBuilder();
sb.AppendLine($"=== {pawn.Name.ToStringShort} Memory State ===");
sb.AppendLine($"[Diag] Memory system enabled: {RimMindMemoryMod.Settings.enableMemory}");
- sb.AppendLine($"[Diag] API configured: {RimMindAPI.IsConfigured()}");
+ sb.AppendLine($"[Diag] API configured: {RimMindAPI.Settings.IsConfigured()}");
- sb.AppendLine($"\n[Active Memories] {store.active.Count} entries");
- foreach (var e in store.active)
+ if (store == null)
+ {
+ sb.AppendLine("\n(No memory store initialized yet for this pawn)");
+ Log.Message(sb.ToString());
+ return;
+ }
+
+ var (activeList, archiveList, darkList) = store.GetSnapshots();
+ sb.AppendLine($"\n[Active Memories] {activeList.Count} entries");
+ foreach (var e in activeList)
sb.AppendLine($" {e.content} (imp={e.importance:F2}, pin={e.isPinned})");
- sb.AppendLine($"\n[Archived Memories] {store.archive.Count} entries");
- foreach (var e in store.archive)
+ sb.AppendLine($"\n[Archived Memories] {archiveList.Count} entries");
+ foreach (var e in archiveList)
sb.AppendLine($" {e.content} (imp={e.importance:F2})");
- sb.AppendLine($"\n[Dark Memories] {store.dark.Count} entries");
- foreach (var d in store.dark)
+ sb.AppendLine($"\n[Dark Memories] {darkList.Count} entries");
+ foreach (var d in darkList)
sb.AppendLine($" {d.content}");
Log.Message(sb.ToString());
@@ -119,7 +127,7 @@ public static void ForcePawnDarkMemory()
var pawn = Find.Selector.SingleSelectedThing as Pawn;
if (pawn == null) { RimMindErrors.Warn("[RimMind-Memory] Select a pawn first."); return; }
- if (!RimMindAPI.IsConfigured())
+ if (!RimMindAPI.Settings.IsConfigured())
{
RimMindErrors.Warn("[RimMind-Memory] API not configured, cannot trigger dark memory.");
return;
@@ -136,7 +144,7 @@ public static void ForcePawnDarkMemory()
[DebugAction("RimMind Memory", "Force Narrator Dark Memory", actionType = DebugActionType.Action)]
public static void ForceNarratorDarkMemory()
{
- if (!RimMindAPI.IsConfigured())
+ if (!RimMindAPI.Settings.IsConfigured())
{
RimMindErrors.Warn("[RimMind-Memory] API not configured, cannot trigger dark narrative.");
return;
@@ -236,10 +244,16 @@ public static void ShowAllPawnMemoryCounts()
if (wc == null) { RimMindErrors.Warn("[RimMind-Memory] WorldComponent not initialized."); return; }
var sb = new StringBuilder("=== All Pawn Memory Counts ===");
- foreach (var pawn in map.mapPawns.FreeColonists)
+ foreach (var pawn in RimMindPawnLookup.GetFreeColonistsSafe(map))
{
- var store = wc.GetOrCreatePawnStore(pawn);
- sb.AppendLine($" {pawn.Name.ToStringShort}: active={store.active.Count} archive={store.archive.Count} dark={store.dark.Count}");
+ var store = wc.GetPawnStore(pawn);
+ if (store == null)
+ {
+ sb.AppendLine($" {pawn.Name.ToStringShort}: 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}");
}
Log.Message(sb.ToString());
}
diff --git a/Source/Extensions/MemoryModCooldown.cs b/Source/Extensions/MemoryModCooldown.cs
index 90fe2ac..3ada88a 100644
--- a/Source/Extensions/MemoryModCooldown.cs
+++ b/Source/Extensions/MemoryModCooldown.cs
@@ -1,11 +1,20 @@
using RimMind.Application.Common.Interfaces.Extension;
+using RimMind.Memory.DarkMemory;
+using RimMind.Presentation.Api;
namespace RimMind.Memory
{
internal sealed class MemoryModCooldown : IModCooldown
{
+ // Mod-level pacing between consecutive dark-memory consolidation calls across colonists.
+ // Per-pawn daily cadence (60,000 ticks) is enforced by DarkMemoryUpdater via TickStagger;
+ // keeping the mod-global pacing short (3,000 ticks = 1.2 in-game hours) prevents multi-colonist
+ // queue starvation while avoiding simultaneous LLM bursts.
+ public const int BaseModCooldownTicks = 3000;
+ public const int MinModCooldownTicks = 600;
+
public string Id => "DarkMemory";
- public string OwnerModId => "RimMind.Memory";
- public int CooldownTicks => 60000;
+ public string OwnerModId => DarkMemoryUpdater.RequestModId;
+ public int CooldownTicks => RimMindAPI.Settings.ScaleCooldown(BaseModCooldownTicks, MinModCooldownTicks);
}
}
diff --git a/Source/Extensions/MemorySettingsTab.cs b/Source/Extensions/MemorySettingsTab.cs
index 4441223..41196e1 100644
--- a/Source/Extensions/MemorySettingsTab.cs
+++ b/Source/Extensions/MemorySettingsTab.cs
@@ -1,6 +1,6 @@
-using UnityEngine;
+using RimMind.Presentation.Api;
using RimMind.Presentation.Settings;
-using Verse;
+using UnityEngine;
namespace RimMind.Memory
{
@@ -8,7 +8,7 @@ internal sealed class MemorySettingsTab : ISettingsTab
{
public string Id => "memory";
public string OwnerModId => "RimMindMemory";
- public string Label => "RimMind.Memory.Settings.TabLabel".CanTranslate() ? (string)"RimMind.Memory.Settings.TabLabel".Translate() : "Memory";
+ public string Label => RimMindAPI.Text.TrOr("RimMind.Memory.Settings.TabLabel", "Memory");
public void Draw(Rect rect) => MemorySettingsDrawer.Draw(rect);
}
}
diff --git a/Source/Injection/MemoryContextProvider.cs b/Source/Injection/MemoryContextProvider.cs
index db2004f..7ec286b 100644
--- a/Source/Injection/MemoryContextProvider.cs
+++ b/Source/Injection/MemoryContextProvider.cs
@@ -68,7 +68,7 @@ public static void Register()
try
{
if (Current.Game == null) return null;
- var pawn = PawnLookup.FindPawnByNumber(ctx.PawnId);
+ var pawn = RimMindPawnLookup.FindPawnByNumber(ctx.PawnId);
if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn) || pawn == null) return null;
var wc = RimMindMemoryWorldComponent.Instance;
if (wc == null) return null;
@@ -84,7 +84,7 @@ public static void Register()
sb.AppendLine();
int? recipientId = RimMindAPI.Chat.GetActiveDialogueRecipient(pawn.thingIDNumber);
- Pawn? recipient = recipientId.HasValue && recipientId.Value > 0 ? PawnLookup.FindPawnByNumber(recipientId.Value) : null;
+ Pawn? recipient = recipientId.HasValue && recipientId.Value > 0 ? RimMindPawnLookup.FindPawnByNumber(recipientId.Value) : null;
string? targetPawnId = recipient != null
? (!string.IsNullOrEmpty(recipient.ThingID) ? recipient.ThingID : recipient.thingIDNumber.ToString())
: (recipientId.HasValue && recipientId.Value > 0 ? recipientId.Value.ToString() : null);
diff --git a/Source/Injection/WorkingMemoryProvider.cs b/Source/Injection/WorkingMemoryProvider.cs
index 9429799..981161c 100644
--- a/Source/Injection/WorkingMemoryProvider.cs
+++ b/Source/Injection/WorkingMemoryProvider.cs
@@ -26,7 +26,7 @@ public static void Register()
if (ctx.PawnId <= 0) return null;
return await RimMindAPI.MainThreadSnapshot.GetAsync(() =>
{
- var pawn = PawnLookup.FindPawnByNumber(ctx.PawnId);
+ var pawn = RimMindPawnLookup.FindPawnByNumber(ctx.PawnId);
if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn) || pawn == null) return null;
var wc = RimMindMemoryWorldComponent.Instance;
if (wc == null) return null;
diff --git a/Source/RimMindMemoryMod.cs b/Source/RimMindMemoryMod.cs
index da1169e..822ec7f 100644
--- a/Source/RimMindMemoryMod.cs
+++ b/Source/RimMindMemoryMod.cs
@@ -5,6 +5,7 @@
using RimMind.Presentation.Settings;
using RimMind.Memory.Core;
using RimMind.Memory.Injection;
+using RimMind.Memory.UI;
using UnityEngine;
using Verse;
@@ -22,6 +23,7 @@ public RimMindMemoryMod(ModContentPack content) : base(content)
MemoryContextProvider.Register();
WorkingMemoryProvider.Register();
RimMindAPI.Memory.RegisterBridge(new RimMindMemoryBridge());
+ RimMindAPI.UI.RegisterBioTabBadge(new MemoryBioTabBadgeProvider());
RimMindAPI.Extensions().Register(new MemorySettingsTab());
RimMindAPI.Extensions().Register(new MemoryToggleBehavior());
RimMindAPI.Extensions().Register(new MemoryModCooldown());
diff --git a/Source/Settings/MemorySettingsDrawer.cs b/Source/Settings/MemorySettingsDrawer.cs
index 1858f1a..9d5828c 100644
--- a/Source/Settings/MemorySettingsDrawer.cs
+++ b/Source/Settings/MemorySettingsDrawer.cs
@@ -9,21 +9,23 @@ namespace RimMind.Memory
internal static class MemorySettingsDrawer
{
private static Vector2 _settingsScrollPos = Vector2.zero;
+ private static float _measuredHeight = 900f;
private static RimMindMemorySettings Settings => RimMindMemoryMod.Settings;
internal static void Draw(Rect inRect)
{
- Rect contentArea = SettingsUIDrawer.SplitContentArea(inRect);
- Rect bottomBar = SettingsUIDrawer.SplitBottomBar(inRect);
-
- float viewWidth = contentArea.width - 16f;
- float contentH = EstimateSettingsHeight(viewWidth);
- Rect viewRect = new Rect(0f, 0f, viewWidth, contentH);
- Widgets.BeginScrollView(contentArea, ref _settingsScrollPos, viewRect);
+ SettingsUIDrawer.DrawScrollableSettingsPage(
+ inRect,
+ ref _settingsScrollPos,
+ ref _measuredHeight,
+ DrawContent,
+ ResetDefaults,
+ () => Settings.Write());
+ }
- var listing = new Listing_Standard();
- listing.Begin(viewRect);
+ private static void DrawContent(Listing_Standard listing)
+ {
listing.CheckboxLabeled("RimMind.Memory.Settings.EnableMemory".Translate(), ref Settings.enableMemory,
"RimMind.Memory.Settings.EnableMemory.Desc".Translate());
@@ -144,84 +146,34 @@ internal static void Draw(Rect inRect)
if (archiveList.Count > 0)
listing.Label("RimMind.Memory.Settings.ArchiveNarrativeCount".Translate(archiveList.Count));
}
-
- listing.End();
- Widgets.EndScrollView();
-
- SettingsUIDrawer.DrawBottomBar(bottomBar, () =>
- {
- Settings.enableMemory = true;
- Settings.triggerWorkSession = true;
- Settings.triggerInjury = true;
- Settings.triggerMentalBreak = true;
- Settings.triggerDeath = true;
- Settings.triggerSkillLevelUp = true;
- Settings.triggerRelation = true;
- Settings.maxActive = 30;
- Settings.maxArchive = 50;
- Settings.darkCount = 3;
- Settings.narratorMaxActive = 30;
- Settings.narratorMaxArchive = 10;
- Settings.narratorDarkCount = 10;
- Settings.activeInjectRatio = 0.5f;
- Settings.archiveInjectRatio = 0.5f;
- Settings.narratorActiveInjectRatio = 0.5f;
- Settings.narratorArchiveInjectRatio = 0.5f;
- Settings.enableDecay = true;
- Settings.decayRate = 0.02f;
- Settings.minImportanceThreshold = 0.05f;
- Settings.minAggregationCount = 2;
- Settings.idleGapThresholdTicks = 6000;
- Settings.narratorEventThreshold = 0.2f;
- Settings.pawnToNarratorThreshold = 0.8f;
- });
-
- Settings.Write();
}
- private static float EstimateSettingsHeight(float width)
+ private static void ResetDefaults()
{
- float h = 30f;
- h += 24f;
- h += 24f + 24f * 6;
- h += 24f + 56f * 3;
- h += 24f + 56f * 3;
- h += 24f + 56f * 4;
- h += 24f + 56f * 2;
- h += 24f + 24f;
- if (Settings.enableDecay)
- h += 56f * 2;
- h += 24f + 56f * 2;
-
- var wc = RimMindMemoryWorldComponent.Instance;
- if (wc != null && Current.Game != null && Find.TickManager != null)
- {
- var (activeList, archiveList, darkList) = wc.NarratorStore.GetSnapshots();
- int now = Find.TickManager.TicksGame;
- float textWidth = Mathf.Max(200f, width);
- if (darkList.Count > 0)
- {
- h += 24f;
- foreach (var d in darkList)
- h += Mathf.Max(24f, Text.CalcHeight($" {d.content}", textWidth) + 4f);
- }
- h += 24f;
- for (int i = 0; i < activeList.Count && i < 10; i++)
- {
- var e = activeList[i];
- string timeStr = TimeFormatter.FormatTimeAgo(e.tick, now);
- string line = $" {"RimMind.Memory.Time.TimeContent".Translate(timeStr, e.content)}";
- h += Mathf.Max(24f, Text.CalcHeight(line, textWidth) + 4f);
- }
- if (archiveList.Count > 0)
- h += 24f;
- }
- else
- {
- h += 24f;
- }
-
- return h + 40f;
+ Settings.enableMemory = true;
+ Settings.triggerWorkSession = true;
+ Settings.triggerInjury = true;
+ Settings.triggerMentalBreak = true;
+ Settings.triggerDeath = true;
+ Settings.triggerSkillLevelUp = true;
+ Settings.triggerRelation = true;
+ Settings.maxActive = 30;
+ Settings.maxArchive = 50;
+ Settings.darkCount = 3;
+ Settings.narratorMaxActive = 30;
+ Settings.narratorMaxArchive = 10;
+ Settings.narratorDarkCount = 10;
+ Settings.activeInjectRatio = 0.5f;
+ Settings.archiveInjectRatio = 0.5f;
+ Settings.narratorActiveInjectRatio = 0.5f;
+ Settings.narratorArchiveInjectRatio = 0.5f;
+ Settings.enableDecay = true;
+ Settings.decayRate = 0.02f;
+ Settings.minImportanceThreshold = 0.05f;
+ Settings.minAggregationCount = 2;
+ Settings.idleGapThresholdTicks = 6000;
+ Settings.narratorEventThreshold = 0.2f;
+ Settings.pawnToNarratorThreshold = 0.8f;
}
}
}
diff --git a/Source/UI/BioTabMemoryPatch.cs b/Source/UI/BioTabMemoryPatch.cs
index 3c1fba7..b7142e7 100644
--- a/Source/UI/BioTabMemoryPatch.cs
+++ b/Source/UI/BioTabMemoryPatch.cs
@@ -1,72 +1,50 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Reflection.Emit;
-using HarmonyLib;
+using RimMind.Application.Common.Constants;
using RimMind.Memory.Data;
-using RimWorld;
-using UnityEngine;
+using RimMind.Presentation.Api;
+using RimMind.Presentation.UI;
using Verse;
namespace RimMind.Memory.UI
{
- [HarmonyPatch(typeof(CharacterCardUtility), "DoTopStack")]
- public static class BioTabMemoryPatch
+ ///
+ /// Bio-tab badge provider for RimMind-Memory registered via Core's unified
+ /// CharacterCardUtility.DoTopStack host ().
+ /// Uses strictly read-only during hover/draw.
+ ///
+ public sealed class MemoryBioTabBadgeProvider : IBioTabBadgeProvider
{
- private static void AddMemoryButton(Pawn pawn)
- {
- var tmpStackElements = (List?)
- AccessTools.Field(typeof(CharacterCardUtility), "tmpStackElements")?.GetValue(null);
- if (tmpStackElements == null) return;
-
- string label = "RimMind.Memory.UI.MemoryTab".Translate();
- float textW = Text.CalcSize(label).x;
- float totalW = textW + 16f;
-
- tmpStackElements.Add(new GenUI.AnonymousStackElement
- {
- width = totalW,
- drawer = rect =>
- {
- Widgets.DrawOptionBackground(rect, false);
- Widgets.DrawHighlightIfMouseover(rect);
+ public const string BadgeId = "rimmind.memory.bio_tab";
- var wc = RimMindMemoryWorldComponent.Instance;
- var store = wc?.GetOrCreatePawnStore(pawn);
- int count = store?.active.Count + store?.archive.Count + store?.dark.Count ?? 0;
- string tip = count > 0
- ? "RimMind.Memory.UI.MemorySummary".Translate(
- store!.active.Count, store.archive.Count, store.dark.Count)
- : "RimMind.Memory.UI.NoMemory".Translate();
- TooltipHandler.TipRegion(rect, tip);
+ public string Id => BadgeId;
+ public string OwnerModId => RimMindOwnerConsts.MemoryModId;
+ public int Order => 20;
- Text.Anchor = TextAnchor.MiddleCenter;
- Widgets.Label(rect, label);
- Text.Anchor = TextAnchor.UpperLeft;
-
- if (Widgets.ButtonInvisible(rect))
- Find.WindowStack.Add(new Dialog_MemoryLog(pawn));
- }
- });
+ public BioTabBadgeDescriptor? TryGetBadge(Pawn pawn)
+ {
+ if (pawn == null) return null;
+
+ string label = RimMindAPI.Text.TrOr("RimMind.Memory.UI.MemoryTab", "Memory");
+ return new BioTabBadgeDescriptor(
+ Label: label,
+ TooltipProvider: () => BuildTooltip(pawn),
+ OnClick: () => Find.WindowStack.Add(new Dialog_MemoryLog(pawn)),
+ ExtraWidth: 16f);
}
- public static IEnumerable Transpiler(IEnumerable instructions)
+ private static string BuildTooltip(Pawn pawn)
{
- MethodInfo anchor = AccessTools.Method(
- typeof(QuestUtility),
- nameof(QuestUtility.AppendInspectStringsFromQuestParts),
- new Type[] { typeof(Action), typeof(ISelectable), typeof(int).MakeByRefType() });
-
- foreach (var instr in instructions)
- {
- yield return instr;
- if (anchor != null && instr.Calls(anchor))
- {
- yield return new CodeInstruction(OpCodes.Ldarg_0);
- yield return new CodeInstruction(OpCodes.Call,
- AccessTools.Method(typeof(BioTabMemoryPatch), nameof(AddMemoryButton)));
- }
- }
+ var store = RimMindMemoryWorldComponent.Instance?.GetPawnStore(pawn);
+ if (store == null)
+ return RimMindAPI.Text.TrOr("RimMind.Memory.UI.NoMemory", "No memory records");
+
+ var (activeList, archiveList, darkList) = store.GetSnapshots();
+ int count = activeList.Count + archiveList.Count + darkList.Count;
+ return count > 0
+ ? RimMindAPI.Text.TrOr(
+ "RimMind.Memory.UI.MemorySummary",
+ "Active {0} / Archived {1} / Dark {2}",
+ activeList.Count, archiveList.Count, darkList.Count)
+ : RimMindAPI.Text.TrOr("RimMind.Memory.UI.NoMemory", "No memory records");
}
}
}
diff --git a/Tests/Contracts/MemoryParsingContextContracts.cs b/Tests/Contracts/MemoryParsingContextContracts.cs
index 929709a..ee3d172 100644
--- a/Tests/Contracts/MemoryParsingContextContracts.cs
+++ b/Tests/Contracts/MemoryParsingContextContracts.cs
@@ -46,7 +46,23 @@ public void Dark_memory_request_input_and_parsing_preserve_contracts()
("unrepairable truncation returns no replacement value", () =>
Assert.Null(DarkMemoryResultParserPure.Parse(
"{\"dark\":[\"unfinished",
- 3))));
+ 3))),
+ ("markdown code fences and thinking tags are stripped before parsing", () =>
+ {
+ var result = DarkMemoryResultParserPure.Parse(
+ "summarizing day\n```json\n{\"dark\":[\"survived the raid\",\"built shelter\"]}\n```",
+ 3);
+
+ Assert.Equal(new[] { "survived the raid", "built shelter" }, result);
+ }),
+ ("truncated container after complete string repairs via Core Json", () =>
+ {
+ var result = DarkMemoryResultParserPure.Parse(
+ "{\"dark\":[\"first memory\",\"second memory\",",
+ 3);
+
+ Assert.Equal(new[] { "first memory", "second memory" }, result);
+ }));
}
[Fact]
@@ -123,8 +139,41 @@ public void Trigger_filtering_dark_memory_gate_and_store_pruning_contracts_hold(
string worldSource = ReadMemorySource("Data/RimMindMemoryWorldComponent.cs");
string workSource = ReadMemorySource("Aggregation/WorkSessionAggregator.cs");
Assert.Contains("PrunePawnStores(_pawnStores, retainedIds, MaxRetainedInactivePawnStores);", worldSource, StringComparison.Ordinal);
+ Assert.Contains("RimMindPawnLookup.CollectRetainedColonyPawnIds()", worldSource, StringComparison.Ordinal);
+ Assert.Contains("WorldScopedComponentCache", worldSource, StringComparison.Ordinal);
Assert.DoesNotContain("AllPawnsAlive", worldSource, StringComparison.Ordinal);
Assert.Contains("PruneInactiveSessions(", workSource, StringComparison.Ordinal);
+ 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", () =>
+ {
+ string darkSource = ReadMemorySource("DarkMemory/DarkMemoryUpdater.cs");
+ string cooldownSource = ReadMemorySource("Extensions/MemoryModCooldown.cs");
+ string parserSource = ReadMemorySource("DarkMemory/DarkMemoryResultParserPure.cs");
+ string bioTabSource = ReadMemorySource("UI/BioTabMemoryPatch.cs");
+ string drawerSource = ReadMemorySource("Settings/MemorySettingsDrawer.cs");
+
+ Assert.Equal(2, CountOccurrences(darkSource, ".WithCoalesceKey(BuildCoalesceKey(npcId))"));
+ Assert.Equal(2, CountOccurrences(darkSource, ".WithMaxQueueWaitTicks(DarkMemoryMaxQueueWaitTicks)"));
+ Assert.Contains(".WithRequireAliveColonist(false)", darkSource, StringComparison.Ordinal);
+ Assert.Contains("TickStagger.IsDue(", darkSource, StringComparison.Ordinal);
+ Assert.DoesNotContain("0x7feb352du", darkSource, StringComparison.Ordinal);
+
+ Assert.Contains("BaseModCooldownTicks = 3000", cooldownSource, StringComparison.Ordinal);
+ Assert.Contains("OwnerModId => DarkMemoryUpdater.RequestModId", cooldownSource, StringComparison.Ordinal);
+
+ Assert.DoesNotContain("using RimMind.Application.Features.Json", parserSource, StringComparison.Ordinal);
+ Assert.Contains("RimMindAPI.Json.TryDeserializeWithRepair", parserSource, StringComparison.Ordinal);
+
+ Assert.Contains("IBioTabBadgeProvider", bioTabSource, StringComparison.Ordinal);
+ Assert.Contains("GetPawnStore(pawn)", bioTabSource, StringComparison.Ordinal);
+ Assert.DoesNotContain("GetOrCreatePawnStore", bioTabSource, StringComparison.Ordinal);
+ Assert.DoesNotContain("[HarmonyPatch", bioTabSource, StringComparison.Ordinal);
+ Assert.DoesNotContain("AccessTools.Field", bioTabSource, StringComparison.Ordinal);
+
+ Assert.Contains("SettingsUIDrawer.DrawScrollableSettingsPage", drawerSource, StringComparison.Ordinal);
+ Assert.DoesNotContain("EstimateSettingsHeight", drawerSource, StringComparison.Ordinal);
}));
}
diff --git a/Tests/RimMindCoreStubs.cs b/Tests/RimMindCoreStubs.cs
new file mode 100644
index 0000000..cefbd00
--- /dev/null
+++ b/Tests/RimMindCoreStubs.cs
@@ -0,0 +1,26 @@
+using RimMind.Application.Features.Json;
+
+namespace RimMind.Presentation.Api
+{
+ ///
+ /// Thin test-only facade forwarding directly to Core Application's
+ /// real and implementations.
+ ///
+ public static class RimMindAPI
+ {
+ public static class Json
+ {
+ public static string StripThinkingAndCodeFences(string? raw)
+ => LlmPayloadParser.StripThinkingAndCodeFences(raw);
+
+ public static string? ExtractJsonPayload(string? raw)
+ => LlmPayloadParser.ExtractJsonPayload(raw);
+
+ public static bool TryDeserializeWithRepair(string? raw, out T? value) where T : class
+ => LlmPayloadParser.TryDeserializeWithRepair(raw, out value);
+
+ public static string? TryRepairTruncatedJson(string input)
+ => JsonRepairer.TryRepairTruncatedJson(input);
+ }
+ }
+}
diff --git a/Tests/RimMindMemory.Tests.csproj b/Tests/RimMindMemory.Tests.csproj
index 8112d29..bb05f1a 100644
--- a/Tests/RimMindMemory.Tests.csproj
+++ b/Tests/RimMindMemory.Tests.csproj
@@ -19,6 +19,7 @@
+