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

This file was deleted.

4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ RimMind 的运行时与公共 API 前置。Core 负责 LLM 请求、上下文、
- AI 请求:`Source/Application/Features/Requests/README.md`
- 上下文:`Source/Presentation/Context/README.md`
- Agent:`Source/Presentation/Agent/PawnAgent.cs`
- 自治分级治理:`Source/Application/Features/Agent/AgentAutonomyPolicyService.cs`(`AutonomyDomain` / `AutonomyLevel`)
- 自治分级治理:`Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs`(`AutonomyDomain` / `AutonomyLevel`)
- ToolCall 与渐进式帮助:`Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs`、`Source/Application/Features/Tools/QueryToolHelpTool.cs`
- 主备端点容灾:`Source/Domain/Settings/BackupEndpointNode.cs`、`Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs`
- 主备端点容灾:`Source/Application/Common/Models/Client/BackupEndpointNode.cs`、`Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs`
- 组合与生命周期:`Source/Presentation/Runtime/RimMindCompositionRoot.cs`
- 游戏内调试:`Source/Infrastructure/UI/DebugActions/README.md`
- Agent 流程实验室:`Source/Infrastructure/UI/AgentFlow/README.md`
Expand Down
128 changes: 58 additions & 70 deletions ArchTests/ArchTestExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,14 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using NetArchTest.Rules;
using Xunit;

namespace RimMind.Core.ArchTests
{
public static class ArchTestExtensions
{
public static string FormatFailingTypes(this TestResult result)
{
if (result.IsSuccessful)
return string.Empty;

var names = result.FailingTypes?
.Select(t => t.FullName ?? t.Name)
.OrderBy(n => n)
?? Enumerable.Empty<string>();

return string.Join("\n ", names);
}

public static string FormatFailingTypes(this IEnumerable<Type> types)
{
var names = types
.Select(t => t.FullName ?? t.Name)
.OrderBy(n => n);

return string.Join("\n ", names);
}

public static string FindSourceDirectory()
{
var dir = Path.GetDirectoryName(typeof(ArchTestExtensions).Assembly.Location);
Expand All @@ -50,63 +26,74 @@ public static string FindSourceDirectory()
return "";
}

public static string LocateAssembly(string fileName)
public static string RequireSourceDirectory()
{
var sourceDir = FindSourceDirectory();
var gameVersion = "1.6";

var candidates = new List<string>();

if (!string.IsNullOrEmpty(sourceDir))
{
candidates.Add(Path.Combine(sourceDir, "..", gameVersion, "Assemblies", fileName));
candidates.Add(Path.Combine(sourceDir, "..", "Assemblies", fileName));
}

candidates.Add(Path.Combine(AppContext.BaseDirectory, fileName));

foreach (var candidate in candidates)
{
var full = Path.GetFullPath(candidate);
if (File.Exists(full))
return full;
}
string source = FindSourceDirectory();
Assert.True(Directory.Exists(source), "RimMind-Core/Source must be discoverable.");
return source;
}

throw new FileNotFoundException(
$"R-D: 找不到 {fileName}。搜索路径:\n {string.Join("\n ", candidates.Select(Path.GetFullPath))}\n" +
"请先构建三个源码项目: dotnet build RimMind-Core/Source/Domain/RimMindCore.Domain.csproj 等");
public static string RepositoryRoot()
{
string source = RequireSourceDirectory();
DirectoryInfo? core = Directory.GetParent(source);
Assert.NotNull(core);
DirectoryInfo? root = core!.Parent;
Assert.NotNull(root);
return root!.FullName;
}

public static bool TryLocateAssembly(string fileName, out string? path)
public static IEnumerable<string> SourceFiles(string directory)
{
path = null;
try
{
path = LocateAssembly(fileName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
Assert.True(Directory.Exists(directory), $"Source directory must exist: {directory}");
return Directory.EnumerateFiles(directory, "*.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)));
}

public static HashSet<string> GetAssemblyReferences(string assemblyPath)
public static string StripComments(string source)
{
var refs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return Regex.Replace(
source,
@"//[^\r\n]*|/\*.*?\*/",
" ",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
}

using var stream = File.OpenRead(assemblyPath);
using var peReader = new PEReader(stream);
var metadataReader = peReader.GetMetadataReader();
public static string StripCommentsAndStrings(string source)
{
return Regex.Replace(
source,
@"@""(?:""""|[^""])*""|""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])'|//[^\r\n]*|/\*.*?\*/",
" ",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
}

foreach (var handle in metadataReader.AssemblyReferences)
public static string ExtractBraceBalancedBlock(string code, int startIndex)
{
int openBrace = code.IndexOf('{', startIndex);
Assert.True(openBrace >= startIndex, "Method opening brace must be discoverable.");
int depth = 0;
for (int i = openBrace; i < code.Length; i++)
{
var asmRef = metadataReader.GetAssemblyReference(handle);
var name = metadataReader.GetString(asmRef.Name);
refs.Add(name);
if (code[i] == '{')
{
depth++;
}
else if (code[i] == '}')
{
depth--;
if (depth == 0)
{
return code.Substring(startIndex, i - startIndex + 1);
}
}
}

return refs;
Assert.Fail("Unbalanced braces when extracting method block.");
return string.Empty;
}

public static CsprojAnalysis AnalyzeCsproj(string csprojPath)
Expand Down Expand Up @@ -134,6 +121,7 @@ public static CsprojAnalysis AnalyzeCsproj(string csprojPath)
.FirstOrDefault() ?? Path.GetFileNameWithoutExtension(csprojPath);

var targetFramework = doc.Descendants(ns + "TargetFramework")
.Concat(doc.Descendants(ns + "TargetFrameworks"))
.Select(el => el.Value)
.FirstOrDefault() ?? "";

Expand Down
118 changes: 77 additions & 41 deletions ArchTests/Contracts/CoreGenericSeparationContracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using RimMind.Testing;
using Xunit;

Expand All @@ -18,8 +17,7 @@ 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.");
string sourceRoot = ArchTestExtensions.RequireSourceDirectory();

ContractCaseRunner.Run(
("no vendor literals outside concrete client adapters and dev harnesses", () =>
Expand All @@ -38,13 +36,13 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants()
};

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

string code = StripComments(File.ReadAllText(file));
string code = ArchTestExtensions.StripComments(File.ReadAllText(file));
foreach (string literal in forbiddenVendors)
{
if (code.IndexOf(literal, StringComparison.OrdinalIgnoreCase) >= 0)
Expand All @@ -61,42 +59,39 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants()
("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));
string code = ArchTestExtensions.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));
string code = ArchTestExtensions.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));
string code = ArchTestExtensions.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", () =>
("Core production code contains zero hardcoded Actions tool prefixes outside dev debug harnesses", () =>
{
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)
foreach (string path in ArchTestExtensions.SourceFiles(sourceRoot))
{
string code = StripComments(File.ReadAllText(path));
string rel = Path.GetRelativePath(sourceRoot, path).Replace('\\', '/');
if (rel.StartsWith("Infrastructure/UI/DebugActions/", StringComparison.OrdinalIgnoreCase))
continue;

string code = ArchTestExtensions.StripComments(File.ReadAllText(path));
if (code.IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0)
{
violations.Add(Path.GetRelativePath(sourceRoot, path));
violations.Add(rel);
}
}

Expand All @@ -107,13 +102,72 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants()
("RimMindRuntimeGameComponent.NotifyGameStopped uses pure IGameScopedService dispatch without Player2 hardcoding", () =>
{
string compPath = Path.Combine(sourceRoot, "Presentation", "Runtime", "RimMindRuntimeGameComponent.cs");
string code = StripComments(File.ReadAllText(compPath));
string code = ArchTestExtensions.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);
string methodBody = ArchTestExtensions.ExtractBraceBalancedBlock(code, start);
Assert.DoesNotContain("Player2GameLifecycleService", methodBody, StringComparison.Ordinal);
}),
("Application layer contains zero Infrastructure/Verse adapter string leaks", () =>
{
string appDir = Path.Combine(sourceRoot, "Application");
var violations = new List<string>();
foreach (string file in ArchTestExtensions.SourceFiles(appDir))
{
string code = ArchTestExtensions.StripComments(File.ReadAllText(file));
if (code.IndexOf("VerseLogSink", StringComparison.Ordinal) >= 0
|| code.IndexOf("LongEventHandler", StringComparison.Ordinal) >= 0)
{
violations.Add(Path.GetRelativePath(sourceRoot, file));
}
}

Assert.True(
violations.Count == 0,
$"Application must not reference Infrastructure/Verse adapter names:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}");
}),
("Application generic seams stay free of hardcoded submodule/vendor/test leaks", () =>
{
string schemaCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Features", "Context", "SchemaRegistry.cs")));
Assert.DoesNotContain("PersonalityOutput", schemaCode, StringComparison.Ordinal);
Assert.DoesNotContain("IncidentOutput", schemaCode, StringComparison.Ordinal);
Assert.DoesNotContain("DarkMemoryOutput", schemaCode, StringComparison.Ordinal);

string credCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Common", "Interfaces", "Internal", "IApiCredentialSettings.cs")));
Assert.DoesNotContain("Player2RemoteUrl", credCode, StringComparison.Ordinal);
Assert.DoesNotContain("IsOpenAIConfigured", credCode, StringComparison.Ordinal);

string clientMgrCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Common", "Interfaces", "Internal", "IClientManager.cs")));
Assert.DoesNotContain("GetPlayer2Client", clientMgrCode, StringComparison.Ordinal);

string codecCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Features", "Llm", "OpenAIWireCodec.cs")));
Assert.DoesNotContain("\"RimMind.Test\"", codecCode, StringComparison.Ordinal);

string registryCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Features", "Tools", "ToolRegistry.cs")));
Assert.DoesNotContain("IToolRegistry? Current", registryCode, StringComparison.Ordinal);

string orchestratorCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Features", "Agent", "ProactiveBehaviorOrchestrator.cs")));
Assert.DoesNotContain("TaskScheduler.Current", orchestratorCode, StringComparison.Ordinal);

string redactorCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Features", "Llm", "LogSecretRedactor.cs")));
Assert.Contains("AIza[A-Za-z0-9", redactorCode, StringComparison.Ordinal);

string reactiveCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Features", "Agent", "Modes", "ReactiveAgentMode.cs")));
Assert.DoesNotContain("ExcludedToolPrefixes", reactiveCode, StringComparison.Ordinal);
Assert.Contains("RequiresProactiveMode", reactiveCode, StringComparison.Ordinal);

string taskBuilderCode = ArchTestExtensions.StripComments(File.ReadAllText(
Path.Combine(sourceRoot, "Application", "Features", "Prompt", "TaskInstructionBuilder.cs")));
Assert.DoesNotContain("StripDiacritics", taskBuilderCode, StringComparison.Ordinal);
Assert.Contains("CanTranslate", taskBuilderCode, StringComparison.Ordinal);
}));
}

Expand All @@ -123,23 +177,5 @@ private static bool IsAllowedVendorAdapterPath(string relativeSlashPath)
|| 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);
}
}
}
Loading