Skip to content

Commit 2f83fd1

Browse files
committed
style(comments): strip obvious comments and label WHY/TODO/HACK across the rest of runtime
Second wave over 42 comment-dense runtime files (AgentMemory, World, Lua-CSharp mods, benchmarking, composition, hub): remove restate-the-code comments and banners, tag genuine rationale with a WHY:/TODO:/HACK: prefix (first line of each block); strip stray UTF-8 BOMs. Comment-only, code verified unchanged, compiles clean. Bulk pass by gpt-5.3-spark agents, de-duplicated + reviewed.
1 parent d849e99 commit 2f83fd1

42 files changed

Lines changed: 242 additions & 265 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Assets/CoreAI/Runtime/Core/Features/AgentMemory/AgentBuilder.cs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using CoreAI.AgentMemory;
44
using CoreAI.Logging;
@@ -44,7 +44,7 @@ public sealed class AgentBuilder
4444

4545
private AgentMode _mode = AgentMode.ToolsAndChat;
4646

47-
// Default chat history keeps agent continuity; callers can opt out to save prompt tokens.
47+
// WHY: Default chat history keeps agent continuity; callers can opt out to save prompt tokens.
4848
private bool _withChatHistory = true;
4949
private int? _contextWindowTokens;
5050
private bool _persistChatHistory;
@@ -62,7 +62,7 @@ public sealed class AgentBuilder
6262
/// <summary>Null = default true (LLM-assisted compaction when global setting allows).</summary>
6363
private bool? _useLlmContextCompaction;
6464

65-
// Skill authoring (manage_skills): when set, the agent can create/update/persist/reuse its own skills.
65+
// WHY: Skill authoring (manage_skills): when set, the agent can create/update/persist/reuse its own skills.
6666
private ISkillStore _skillStore;
6767
private ILuaScriptVersionStore _skillVersionStore;
6868
private bool _skillAuthoring;
@@ -179,7 +179,7 @@ public AgentBuilder WithSkill(SkillSet skill)
179179
throw new ArgumentNullException(nameof(skill));
180180
}
181181

182-
// Skill tools are routed through call_skill_tool to keep the prompt surface small.
182+
// WHY: Skill tools are routed through call_skill_tool to keep the prompt surface small.
183183
_skills.Add(skill);
184184

185185
return this;
@@ -483,7 +483,7 @@ public AgentConfig BuildDetached()
483483
int ctxTokens = _contextWindowTokens ??
484484
_settings?.ContextWindowTokens ?? CoreAISettings.ContextWindowTokens;
485485

486-
// final composition time (three-layer architecture):
486+
// WHY: final composition time (three-layer architecture):
487487
// Layer 1: universalSystemPromptPrefix (project-wide rules)
488488
// Layer 2: role base prompt from Manifest / Resources (.txt files)
489489
// Layer 3: extra prompt from this builder (the one above)
@@ -600,7 +600,7 @@ private void CollectIssues(List<AgentBuilderIssue> issues)
600600

601601
if (_mode == AgentMode.ToolsOnly && _tools.Count == 0)
602602
{
603-
// Already reported by the rule above; no extra issue here.
603+
// WHY: Already reported by the rule above; no extra issue here.
604604
}
605605

606606
if (_useLlmContextCompaction == true)
@@ -734,7 +734,7 @@ public void ApplyToPolicy(AgentMemoryPolicy policy)
734734

735735
policy.SetStreamingEnabled(RoleId, streamingOverride);
736736

737-
// Self-service skills: register catalog context provider + meta-tools.
737+
// WHY: Self-service skills: register catalog context provider + meta-tools.
738738
// The catalog (name + description per skill) goes into the system prompt.
739739
// The model calls read_skill(name) to load instructions + tool schemas,
740740
// then call_skill_tool(tool_name, args_json) to execute them.
@@ -743,7 +743,7 @@ public void ApplyToPolicy(AgentMemoryPolicy policy)
743743
bool hasSkills = Skills != null && Skills.Count > 0;
744744
if (hasSkills || SkillAuthoringEnabled)
745745
{
746-
// When the agent can author skills, the read_skill / call_skill_tool proxies read from a
746+
// WHY: When the agent can author skills, the read_skill / call_skill_tool proxies read from a
747747
// LIVE catalog so a skill created via manage_skills is immediately visible to the same
748748
// agent. Without authoring, the static snapshot is used (cacheable, unchanged behavior).
749749
IReadOnlyList<SkillSet> catalogSkills = Skills ?? (IReadOnlyList<SkillSet>)Array.Empty<SkillSet>();
@@ -755,7 +755,7 @@ public void ApplyToPolicy(AgentMemoryPolicy policy)
755755
catalogSkills = liveCatalog;
756756
}
757757

758-
// Inject the lightweight catalog into the stable system prefix. Skill catalog data is static
758+
// WHY: Inject the lightweight catalog into the stable system prefix. Skill catalog data is static
759759
// per agent build (host skills), unlike live world-state context, so it stays cacheable.
760760
string catalog = SkillSet.BuildCatalog(Skills);
761761
if (!string.IsNullOrWhiteSpace(catalog))
@@ -765,10 +765,10 @@ public void ApplyToPolicy(AgentMemoryPolicy policy)
765765
: additionalPrompt.TrimEnd() + "\n\n" + catalog.Trim();
766766
}
767767

768-
// Register read_skill meta-tool (loads instructions + tool schemas)
768+
// WHY: Register read_skill meta-tool (loads instructions + tool schemas)
769769
policy.AddToolForRole(RoleId, ReadSkillLlmTool.Create(catalogSkills));
770770

771-
// Register call_skill_tool proxy (routes to real skill tools)
771+
// WHY: Register call_skill_tool proxy (routes to real skill tools)
772772
policy.AddToolForRole(RoleId, CallSkillToolLlmTool.Create(catalogSkills));
773773
}
774774

@@ -787,7 +787,7 @@ public void ApplyToPolicy(AgentMemoryPolicy policy)
787787
/// </summary>
788788
private void RehydrateAndRegisterAuthoring(AgentMemoryPolicy policy, MutableSkillCatalog liveCatalog)
789789
{
790-
// Index every tool the role already has, by name, so an authored skill can reference it.
790+
// WHY: Index every tool the role already has, by name, so an authored skill can reference it.
791791
Dictionary<string, ILlmTool> toolsByName = new(StringComparer.OrdinalIgnoreCase);
792792
foreach (ILlmTool tool in Tools)
793793
{
@@ -826,10 +826,10 @@ private void RehydrateAndRegisterAuthoring(AgentMemoryPolicy policy, MutableSkil
826826
resolver,
827827
RequireKnownSkillTools);
828828

829-
// Rehydrate persisted skills so prior-session skills reappear in this agent's read_skill catalog.
829+
// WHY: Rehydrate persisted skills so prior-session skills reappear in this agent's read_skill catalog.
830830
coordinator.RehydrateFromStore();
831831

832-
// One extra visible tool (progressive disclosure: skill bodies still load on demand).
832+
// WHY: One extra visible tool (progressive disclosure: skill bodies still load on demand).
833833
policy.AddToolForRole(RoleId, new ManageSkillsLlmTool(coordinator));
834834
}
835835

Assets/CoreAI/Runtime/Core/Features/AgentMemory/AgentConfigExtensions.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Threading;
33
using System.Threading.Tasks;
44
using CoreAI.Logging;
@@ -40,7 +40,7 @@ public static Task<string> AskAsync(
4040
int priority = 0,
4141
CancellationToken cancellationToken = default)
4242
{
43-
// Make sure the role is known to the global policy before we run. For the common newcomer
43+
// WHY: Make sure the role is known to the global policy before we run. For the common newcomer
4444
// flow this AUTO-REGISTERS the built config, so `Build()` + `Ask*()` just works without an
4545
// explicit `ApplyToPolicy(CoreAIAgent.Policy)` call. Done before the orchestrator null-check
4646
// so a missing lifetime scope still surfaces its own clear message.
@@ -77,7 +77,7 @@ private static void EnsureRoleRegistered(AgentConfig config)
7777
"(add CoreAILifetimeScope to the scene / run CoreAI setup) before asking an agent.");
7878
}
7979

80-
// Convenience: register the built config with the global policy on first use, so newcomers
80+
// WHY: Convenience: register the built config with the global policy on first use, so newcomers
8181
// do not have to call ApplyToPolicy(CoreAIAgent.Policy) by hand. Re-applying is idempotent;
8282
// advanced users targeting a CUSTOM AgentMemoryPolicy still call ApplyToPolicy on that policy
8383
// themselves (and, once registered here, this no-ops).
@@ -108,7 +108,7 @@ public static void AskWithCallback(
108108
Action<string> onDone = null,
109109
int priority = 0)
110110
{
111-
// Capture the caller's synchronization context (Unity main thread when called from it)
111+
// WHY: Capture the caller's synchronization context (Unity main thread when called from it)
112112
// so onDone is safe to use with Unity APIs; without it the continuation after
113113
// ConfigureAwait(false) may land on a thread-pool thread.
114114
_ = RunAskFireAndForgetAsync(config, message, onDone, priority, SynchronizationContext.Current);

Assets/CoreAI/Runtime/Core/Features/AgentMemory/AgentMemoryPolicy.cs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using CoreAI.AgentMemory;
44

@@ -10,8 +10,6 @@ namespace CoreAI.Ai
1010
/// </summary>
1111
public sealed class AgentMemoryPolicy
1212
{
13-
// ARCH-4 fix: lock protects all dictionary/set read-write operations
14-
// against concurrent access from different coroutines/async continuations.
1513
private readonly object _lock = new();
1614
private readonly Dictionary<string, RoleMemoryConfig> _roleConfigs;
1715
private readonly Dictionary<string, List<ILlmTool>> _customTools = new();
@@ -279,7 +277,7 @@ public AgentMemoryPolicy()
279277
bool isProgrammer = roleId == BuiltInAgentRoleIds.Programmer;
280278
bool needsExactToolOutput = isProgrammer || roleId == BuiltInAgentRoleIds.CoreMechanic;
281279
bool smartCompaction = !isProgrammer;
282-
// Programmer keeps history off by default; chat-source runs enable it per-run
280+
// WHY: Programmer keeps history off by default; chat-source runs enable it per-run
283281
// without mutating global policy (see AiOrchestratorHistoryEditModeTests).
284282
// Code/mechanics agents need exact tool output across turns for iterative correctness.
285283
RoleMemoryConfig builtIn = new(
@@ -291,7 +289,7 @@ public AgentMemoryPolicy()
291289
: ToolResultMemoryPolicy.CompactSummary,
292290
useLlmContextCompaction: smartCompaction);
293291

294-
// The Programmer writes/iterates Lua and routinely needs many tool roundtrips in one turn
292+
// WHY: The Programmer writes/iterates Lua and routinely needs many tool roundtrips in one turn
295293
// (generate → run → read error → fix → re-run …), and the Creator orchestrates a whole
296294
// build across many tool calls. Cap both at 0 = unlimited so they are never cut off
297295
// mid-task. Other built-in roles inherit the global default (null = 20).
@@ -303,7 +301,7 @@ public AgentMemoryPolicy()
303301
_roleConfigs[roleId] = builtIn;
304302
}
305303

306-
// Built-in chat roles:
304+
// WHY: Built-in chat roles:
307305
// - PlainChat: no MemoryTool by default, persistent chat history only.
308306
// - SmartChat: MemoryTool + persistent chat history by default.
309307
_roleConfigs[BuiltInAgentRoleIds.PlainChat] = new RoleMemoryConfig(
@@ -652,10 +650,8 @@ private static bool ListContainsMemoryTool(List<ILlmTool> list)
652650

653651
private readonly Dictionary<string, string> _additionalSystemPrompts = new();
654652

655-
// ===== Override Universal Prefix (per-role) =====
656653
private readonly HashSet<string> _overrideUniversalPrefix = new();
657654

658-
// ===== Streaming override (per-role) =====
659655
private readonly Dictionary<string, bool> _streamingOverrides = new();
660656

661657
/// <summary>
@@ -741,8 +737,6 @@ public bool IsUniversalPrefixOverridden(string roleId)
741737
}
742738
}
743739

744-
// ===== Streaming (per-role override) =====
745-
746740
/// <summary>
747741
/// Applies a per-role streaming override; <c>null</c> clears the override and uses
748742
/// <see cref="ICoreAISettings.EnableStreaming"/>.

Assets/CoreAI/Runtime/Core/Features/AgentMemory/Context/BpeEncoder.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ namespace CoreAI.Ai
1919
/// </remarks>
2020
public sealed class BpeEncoder
2121
{
22-
// tiktoken pre-tokenization regexes. cl100k_base and o200k_base use different patterns.
22+
// WHY: tiktoken pre-tokenization regexes. cl100k_base and o200k_base use different patterns.
2323
// These are the canonical patterns; .NET regex supports the needed constructs.
2424
private const string Cl100kPattern =
2525
@"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+";
@@ -68,7 +68,7 @@ public static BpeEncoder TryLoad(
6868
}
6969
catch
7070
{
71-
// Corrupt/partial data: signal fallback rather than producing wrong counts.
71+
// WHY: Corrupt/partial data: signal fallback rather than producing wrong counts.
7272
return null;
7373
}
7474

@@ -84,7 +84,7 @@ public static BpeEncoder TryLoad(
8484
}
8585
catch
8686
{
87-
// RegexOptions.Compiled is unsupported on some AOT/WebGL targets: retry interpreted.
87+
// WHY: RegexOptions.Compiled is unsupported on some AOT/WebGL targets: retry interpreted.
8888
try
8989
{
9090
pattern = new Regex(patternText, RegexOptions.CultureInvariant);
@@ -128,7 +128,7 @@ public int CountTokens(string text)
128128
int total = 0;
129129
int cursor = 0;
130130

131-
// Walk the string, peeling off special tokens as single tokens and BPE-encoding the gaps.
131+
// WHY: Walk the string, peeling off special tokens as single tokens and BPE-encoding the gaps.
132132
while (cursor < text.Length)
133133
{
134134
int nextSpecial = -1;
@@ -192,13 +192,13 @@ private int CountPiece(byte[] piece)
192192
return 0;
193193
}
194194

195-
// A single byte is always a known token in byte-level BPE.
195+
// WHY: A single byte is always a known token in byte-level BPE.
196196
if (n == 1)
197197
{
198198
return 1;
199199
}
200200

201-
// Segment boundaries: parts[i] is the start index of segment i; there are (count) segments
201+
// WHY: Segment boundaries: parts[i] is the start index of segment i; there are (count) segments
202202
// covering [parts[i], parts[i+1]). Initialize to one byte per segment.
203203
List<int> starts = new(n + 1);
204204
for (int i = 0; i <= n; i++)
@@ -226,11 +226,11 @@ private int CountPiece(byte[] piece)
226226
break; // no further merges possible
227227
}
228228

229-
// Merge segments bestIdx and bestIdx+1 by removing the boundary between them.
229+
// WHY: Merge segments bestIdx and bestIdx+1 by removing the boundary between them.
230230
starts.RemoveAt(bestIdx + 1);
231231
}
232232

233-
// Number of segments = starts.Count - 1.
233+
// WHY: Number of segments = starts.Count - 1.
234234
return starts.Count - 1;
235235
}
236236

@@ -352,7 +352,7 @@ public byte At(int i)
352352

353353
public int ComputeHash()
354354
{
355-
// FNV-1a over the slice contents.
355+
// WHY: FNV-1a over the slice contents.
356356
unchecked
357357
{
358358
const int prime = 16777619;

Assets/CoreAI/Runtime/Core/Features/AgentMemory/Context/CalibratingTokenEstimator.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,15 +77,15 @@ public void RecordObservation(int estimatedPromptTokens, int realPromptTokens)
7777
double updatedScale;
7878
lock (_lock)
7979
{
80-
// The observed estimate was produced as baseEstimate * _scale. Convert the
80+
// WHY: The observed estimate was produced as baseEstimate * _scale. Convert the
8181
// real/estimated ratio back into scale units so repeated observations converge
8282
// toward real/baseEstimate, not sqrt(real/baseEstimate).
8383
double targetScale = _scale * realPromptTokens / estimatedPromptTokens;
8484
_scale = Clamp(_scale * (1d - Alpha) + targetScale * Alpha, MinScale, MaxScale);
8585
updatedScale = _scale;
8686
}
8787

88-
// Persist outside the lock so a blocking disk write in the store does not stall concurrent
88+
// WHY: Persist outside the lock so a blocking disk write in the store does not stall concurrent
8989
// EstimateText/CurrentScale calls (which also take _lock). The in-memory scale is already
9090
// updated; the store write does not need the estimator lock.
9191
_store.SaveScale(_modelKey, updatedScale);

Assets/CoreAI/Runtime/Core/Features/AgentMemory/ConversationHistoryPruner.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ private static string StripThinkBlocks(string content)
167167
int open = content.IndexOf(ThinkOpenTag, i, StringComparison.OrdinalIgnoreCase);
168168
int close = content.IndexOf(ThinkCloseTag, i, StringComparison.OrdinalIgnoreCase);
169169

170-
// Orphan close before any open: treat the leading text as hidden reasoning and drop it.
170+
// WHY: Orphan close before any open: treat the leading text as hidden reasoning and drop it.
171171
if (close >= 0 && (open < 0 || close < open))
172172
{
173173
i = close + ThinkCloseTag.Length;
@@ -189,7 +189,7 @@ private static string StripThinkBlocks(string content)
189189
int matchingClose = content.IndexOf(ThinkCloseTag, afterOpen, StringComparison.OrdinalIgnoreCase);
190190
if (matchingClose < 0)
191191
{
192-
// Unterminated reasoning block: drop everything to the end.
192+
// WHY: Unterminated reasoning block: drop everything to the end.
193193
break;
194194
}
195195

@@ -295,7 +295,7 @@ private static List<string> ExtractToolNames(string content)
295295
{
296296
string line = lines[i];
297297

298-
// Entry bullets are at column 0. Any leading whitespace means this is nested Detail content
298+
// WHY: Entry bullets are at column 0. Any leading whitespace means this is nested Detail content
299299
// (Full policy indents it by two spaces), never a tool-name entry — skip it.
300300
if (line.Length < 2 || line[0] != '-' || line[1] != ' ')
301301
{
@@ -309,7 +309,7 @@ private static List<string> ExtractToolNames(string content)
309309
continue;
310310
}
311311

312-
// The value after "name:" must begin with a status token; otherwise this "- x: y" line is
312+
// WHY: The value after "name:" must begin with a status token; otherwise this "- x: y" line is
313313
// arbitrary content that merely resembles an entry, not a real tool result.
314314
if (!ValueStartsWithStatus(line, colon + 1))
315315
{

0 commit comments

Comments
 (0)