Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 145 additions & 0 deletions ArchTests/Contracts/CoreGenericSeparationContracts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using RimMind.Testing;
using Xunit;

namespace RimMind.Core.ArchTests.Contracts
{
/// <summary>
/// Architecture guardrails locking in generic-vs-specific separation inside RimMind-Core:
/// no vendor hardcoding outside concrete client adapters, no submodule prompt/tool literals
/// in generic Core infrastructure, and declarative mechanism/provider extension seams.
/// </summary>
public sealed class CoreGenericSeparationContracts
{
[Fact]
public void Core_source_maintains_generic_vs_specific_separation_invariants()
{
string sourceRoot = ArchTestExtensions.FindSourceDirectory();
Assert.True(Directory.Exists(sourceRoot), "RimMind-Core/Source must be discoverable.");

ContractCaseRunner.Run(
("no vendor literals outside concrete client adapters and dev harnesses", () =>
{
string[] forbiddenVendors =
{
"\"opencode\"",
"\"oc_sk_\"",
"opencode.ai",
"deepseek.com",
"deepseek-flash",
"deepseek-v4",
"siliconflow.cn",
"moonshot.cn",
"grok-"
};

var violations = new List<string>();
foreach (string file in EnumerateCoreSourceFiles(sourceRoot))
{
string rel = Path.GetRelativePath(sourceRoot, file).Replace('\\', '/');
if (IsAllowedVendorAdapterPath(rel))
continue;

string code = StripComments(File.ReadAllText(file));
foreach (string literal in forbiddenVendors)
{
if (code.IndexOf(literal, StringComparison.OrdinalIgnoreCase) >= 0)
{
violations.Add($"{rel} contains forbidden vendor literal '{literal}'");
}
}
}

Assert.True(
violations.Count == 0,
$"Generic Core code must not hardcode vendor literals:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}");
}),
("HttpTransport has zero vendor sniffing and delegates to IHttpRequestDecorator", () =>
{
string transportPath = Path.Combine(sourceRoot, "Infrastructure", "Services", "Clients", "HttpTransport.cs");
string code = StripComments(File.ReadAllText(transportPath));
Assert.DoesNotContain("opencode", code, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("oc_sk_", code, StringComparison.OrdinalIgnoreCase);
Assert.Contains("IHttpRequestDecorator", code, StringComparison.Ordinal);
}),
("CoreContextProviders contains zero Storyteller prompt literals", () =>
{
string providersPath = Path.Combine(sourceRoot, "Presentation", "Context", "CoreContextProviders.cs");
string code = StripComments(File.ReadAllText(providersPath));
Assert.DoesNotContain("You are the RimWorld storyteller AI", code, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Storyteller rules:", code, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("IncidentOutput schema", code, StringComparison.OrdinalIgnoreCase);
}),
("MechanismToolHandler uses declarative IMechanismAutonomyMetadata instead of hardcoding pawn.work", () =>
{
string handlerPath = Path.Combine(sourceRoot, "Infrastructure", "Mechanisms", "MechanismToolHandler.cs");
string code = StripComments(File.ReadAllText(handlerPath));
Assert.DoesNotContain("\"pawn.work\"", code, StringComparison.OrdinalIgnoreCase);
Assert.Contains("IMechanismAutonomyMetadata", code, StringComparison.Ordinal);
}),
("Core lookup and map context builders contain zero hardcoded Actions tool prefixes", () =>
{
string[] filesToCheck =
{
Path.Combine(sourceRoot, "Presentation", "Common", "RimMindPawnLookup.cs"),
Path.Combine(sourceRoot, "Presentation", "Agent", "MapContextBuilder.cs"),
Path.Combine(sourceRoot, "Presentation", "Context", "CoreContextProviders.cs")
};

var violations = new List<string>();
foreach (string path in filesToCheck)
{
string code = StripComments(File.ReadAllText(path));
if (code.IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0)
{
violations.Add(Path.GetRelativePath(sourceRoot, path));
}
}

Assert.True(
violations.Count == 0,
$"Core must not hardcode RimMind-Actions tool IDs or prefixes:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}");
}),
("RimMindRuntimeGameComponent.NotifyGameStopped uses pure IGameScopedService dispatch without Player2 hardcoding", () =>
{
string compPath = Path.Combine(sourceRoot, "Presentation", "Runtime", "RimMindRuntimeGameComponent.cs");
string code = StripComments(File.ReadAllText(compPath));
int start = code.IndexOf("internal static void NotifyGameStopped", StringComparison.Ordinal);
Assert.True(start >= 0, "NotifyGameStopped method must exist");
int nextMethod = code.IndexOf("private static IExtensionRegistry<IGameScopedService>", start, StringComparison.Ordinal);
Assert.True(nextMethod > start, "NotifyGameStopped method boundary must be discoverable");
string methodBody = code.Substring(start, nextMethod - start);
Assert.DoesNotContain("Player2GameLifecycleService", methodBody, StringComparison.Ordinal);
}));
}

private static bool IsAllowedVendorAdapterPath(string relativeSlashPath)
{
return relativeSlashPath.StartsWith("Infrastructure/Services/Clients/OpenAI/", StringComparison.OrdinalIgnoreCase)
|| relativeSlashPath.StartsWith("Infrastructure/Services/Clients/Player2/", StringComparison.OrdinalIgnoreCase)
|| relativeSlashPath.StartsWith("Infrastructure/UI/DebugActions/", StringComparison.OrdinalIgnoreCase);
}

private static IEnumerable<string> EnumerateCoreSourceFiles(string sourceRoot)
{
return Directory.EnumerateFiles(sourceRoot, "*.cs", SearchOption.AllDirectories)
.Where(path => !path.Split(Path.DirectorySeparatorChar).Any(part =>
part.Equals("bin", StringComparison.OrdinalIgnoreCase) ||
part.Equals("obj", StringComparison.OrdinalIgnoreCase) ||
part.Equals("backup", StringComparison.OrdinalIgnoreCase)));
}

private static string StripComments(string source)
{
return Regex.Replace(
source,
@"//[^\r\n]*|/\*.*?\*/",
" ",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
}
}
}
83 changes: 83 additions & 0 deletions ArchTests/Contracts/CrossModBoundaryContracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,89 @@ public void Core_production_code_does_not_hardcode_submod_package_ids()
.ToArray());
}

[Fact]
public void Downstream_submodules_maintain_generic_vs_specific_separation_boundaries()
{
string root = RepositoryRoot();
string[] allDependentMods =
{
"RimMind-Actions",
"RimMind-Advisor",
"RimMind-Dialogue",
"RimMind-Memory",
"RimMind-Personality",
"RimMind-Storyteller",
"RimMind-Bridge-RimTalk",
"RimMind-Bridge-RimChat",
"RimMind-Extension-ModelService"
};

ContractCaseRunner.Run(
("no dependent submodule imports RimMind.Infrastructure", () =>
{
var pattern = new Regex(
@"^\s*using\s+RimMind\.Infrastructure(?:\.|;)",
RegexOptions.Multiline | RegexOptions.CultureInvariant);

var violations = allDependentMods
.Select(mod => Path.Combine(root, mod, "Source"))
.Where(Directory.Exists)
.SelectMany(SourceFiles)
.Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file))))
.Select(file => Path.GetRelativePath(root, file))
.OrderBy(path => path, StringComparer.Ordinal)
.ToArray();

Assert.True(
violations.Length == 0,
$"Dependent submodules must not import RimMind.Infrastructure:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}");
}),
("RimMind-Advisor Perception layer contains zero hardcoded actions_ tool literals", () =>
{
string perceptionDir = Path.Combine(root, "RimMind-Advisor", "Source", "Perception");
if (!Directory.Exists(perceptionDir))
return;

var violations = SourceFiles(perceptionDir)
.Where(file => StripCommentsOnly(File.ReadAllText(file)).IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0)
.Select(file => Path.GetRelativePath(root, file))
.OrderBy(path => path, StringComparer.Ordinal)
.ToArray();

Assert.True(
violations.Length == 0,
$"RimMind-Advisor/Source/Perception must not hardcode concrete actions_ tool names:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}");
}),
("no dependent submodule bypasses RimMindAPI.Json by importing RimMind.Application.Features.Json", () =>
{
var pattern = new Regex(
@"^\s*using\s+RimMind\.Application\.Features\.Json(?:\.|;)",
RegexOptions.Multiline | RegexOptions.CultureInvariant);

var violations = allDependentMods
.Select(mod => Path.Combine(root, mod, "Source"))
.Where(Directory.Exists)
.SelectMany(SourceFiles)
.Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file))))
.Select(file => Path.GetRelativePath(root, file))
.OrderBy(path => path, StringComparer.Ordinal)
.ToArray();

Assert.True(
violations.Length == 0,
$"Dependent submodules must use RimMindAPI.Json instead of importing RimMind.Application.Features.Json directly:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}");
}));
}

private static string StripCommentsOnly(string source)
{
return Regex.Replace(
source,
@"//[^\r\n]*|/\*.*?\*/",
" ",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
}

private static void AssertDependentSourceAbsent(string forbiddenPattern)
{
var pattern = new Regex(forbiddenPattern, RegexOptions.CultureInvariant);
Expand Down
2 changes: 2 additions & 0 deletions IntegrationTests/RimMindCore.Integration.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
<ItemGroup>
<Compile Include="Contracts\**\*.cs" />
<Compile Include="..\TestSupport\ContractCaseRunner.cs" Link="Support\ContractCaseRunner.cs" />
<Compile Include="..\Source\Infrastructure\Services\Clients\IHttpRequestDecorator.cs" Link="Adapters\IHttpRequestDecorator.cs" />
<Compile Include="..\Source\Infrastructure\Services\Clients\OpenAI\OpenCodeHeaderDecorator.cs" Link="Adapters\OpenCodeHeaderDecorator.cs" />
<Compile Include="..\Source\Infrastructure\Services\Clients\HttpTransport.cs" Link="Adapters\HttpTransport.cs" />
<Compile Include="..\Source\Infrastructure\Services\Clients\Shared\LogSanitizer.cs" Link="Adapters\LogSanitizer.cs" />
<Compile Include="..\Source\Infrastructure\Mechanisms\GameMechanismRegistry.cs" Link="Adapters\GameMechanismRegistry.cs" />
Expand Down
2 changes: 1 addition & 1 deletion Languages/ChineseSimplified/Keyed/RimMind_Core.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<RimMind.Settings.BackupEndpoints.Desc>按顺序排列的备用 API 节点列表。当主 API 节点请求失败(如 HTTP 503/502/429、超时或空响应)时,RimMind 会在单次请求内自动平滑切换至列表中的下一个可用备用节点,并对故障节点执行 60 秒临时隔离。</RimMind.Settings.BackupEndpoints.Desc>
<RimMind.Settings.BackupEndpoints.AddOpenCode>+ OpenCode Go 备用</RimMind.Settings.BackupEndpoints.AddOpenCode>
<RimMind.Settings.BackupEndpoints.AddCustom>+ 自定义备用</RimMind.Settings.BackupEndpoints.AddCustom>
<RimMind.Settings.BackupEndpoints.Empty>暂未配置备用节点。点击「+ OpenCode Go 备用」或「+ 自定义备用」添加自动容灾保护。</RimMind.Settings.BackupEndpoints.Empty>
<RimMind.Settings.BackupEndpoints.Empty>暂未配置备用节点。点击「+ 自定义备用」添加自动容灾保护。</RimMind.Settings.BackupEndpoints.Empty>
<RimMind.Settings.ForceJsonMode>强制 JSON 模式(response_format)</RimMind.Settings.ForceJsonMode>
<RimMind.Settings.ForceJsonModeDesc>向 API 追加 response_format=json_object,强制模型返回 JSON。不支持该参数的本地模型请关闭。</RimMind.Settings.ForceJsonModeDesc>
<RimMind.Settings.MaxTokens>最大 Token 数</RimMind.Settings.MaxTokens>
Expand Down
2 changes: 1 addition & 1 deletion Languages/English/Keyed/RimMind_Core.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<RimMind.Settings.BackupEndpoints.Desc>Ordered failover list of backup API endpoints. When the primary endpoint fails (HTTP 503/502/429, timeout, or empty response), RimMind automatically switches to the next healthy backup node and isolates the failing node for 60s.</RimMind.Settings.BackupEndpoints.Desc>
<RimMind.Settings.BackupEndpoints.AddOpenCode>+ OpenCode Go Backup</RimMind.Settings.BackupEndpoints.AddOpenCode>
<RimMind.Settings.BackupEndpoints.AddCustom>+ Custom Backup</RimMind.Settings.BackupEndpoints.AddCustom>
<RimMind.Settings.BackupEndpoints.Empty>No backup nodes configured. Click "+ OpenCode Go Backup" or "+ Custom Backup" to add automatic failover protection.</RimMind.Settings.BackupEndpoints.Empty>
<RimMind.Settings.BackupEndpoints.Empty>No backup nodes configured. Click "+ Custom Backup" to add automatic failover protection.</RimMind.Settings.BackupEndpoints.Empty>
<RimMind.Settings.ForceJsonMode>Force JSON Mode (response_format)</RimMind.Settings.ForceJsonMode>
<RimMind.Settings.ForceJsonModeDesc>Append response_format=json_object to the API request, forcing the model to return JSON. Disable this for local models that don't support this parameter.</RimMind.Settings.ForceJsonModeDesc>
<RimMind.Settings.MaxTokens>Max Tokens</RimMind.Settings.MaxTokens>
Expand Down
Loading