AX Agent loop 정책을 분리하고 transcript 가상화·성능 계측 구조를 강화한다
Some checks failed
Release Gate / gate (push) Has been cancelled
Some checks failed
Release Gate / gate (push) Has been cancelled
- AgentLoop 검증/문서/compact 정책 메서드를 partial 파일로 분리해 loop 본문의 책임을 줄임 - transcript 렌더에 cache pruning과 deferred scrolling을 적용해 긴 세션의 UI 부담을 낮춤 - AgentPerformanceLogService를 추가해 transcript 렌더와 agent loop 실행 요약을 perf 로그로 남김 - README와 DEVELOPMENT 문서에 2026-04-09 10:08 (KST) 기준 구조 개선 및 계측 이력을 반영함 - dotnet build src/AxCopilot/AxCopilot.csproj -c Release -v minimal -p:OutputPath=bin\\verify\\ -p:IntermediateOutputPath=obj\\verify\\ 검증 결과 경고 0개 오류 0개
This commit is contained in:
116
src/AxCopilot/Services/Agent/AgentLoopCompactionPolicy.cs
Normal file
116
src/AxCopilot/Services/Agent/AgentLoopCompactionPolicy.cs
Normal file
@@ -0,0 +1,116 @@
|
||||
namespace AxCopilot.Services.Agent;
|
||||
|
||||
public partial class AgentLoopService
|
||||
{
|
||||
private void MarkRunPostCompaction(ContextCompactionResult result, RunState runState)
|
||||
{
|
||||
runState.PendingPostCompactionTurn = true;
|
||||
runState.PostCompactionTurnCounter = 0;
|
||||
runState.LastCompactionStageSummary = result.StageSummary;
|
||||
runState.LastCompactionSavedTokens = result.SavedTokens;
|
||||
SyncRunPostCompactionState(runState);
|
||||
}
|
||||
|
||||
private void NotifyPostCompactionTurnIfNeeded(RunState runState)
|
||||
{
|
||||
if (!runState.PendingPostCompactionTurn)
|
||||
return;
|
||||
|
||||
runState.PendingPostCompactionTurn = false;
|
||||
runState.PostCompactionTurnCounter++;
|
||||
SyncRunPostCompactionState(runState);
|
||||
|
||||
var stage = string.IsNullOrWhiteSpace(runState.LastCompactionStageSummary)
|
||||
? "기본"
|
||||
: runState.LastCompactionStageSummary;
|
||||
var saved = runState.LastCompactionSavedTokens > 0
|
||||
? $" · {Services.TokenEstimator.Format(runState.LastCompactionSavedTokens)} tokens 절감"
|
||||
: "";
|
||||
EmitEvent(
|
||||
AgentEventType.Thinking,
|
||||
"",
|
||||
$"compact 이후 {runState.PostCompactionTurnCounter}번째 턴 · {stage}{saved}");
|
||||
}
|
||||
|
||||
private void SyncRunPostCompactionState(RunState runState)
|
||||
{
|
||||
_runPendingPostCompactionTurn = runState.PendingPostCompactionTurn;
|
||||
_runPostCompactionTurnCounter = runState.PostCompactionTurnCounter;
|
||||
_runLastCompactionStageSummary = runState.LastCompactionStageSummary ?? "";
|
||||
_runLastCompactionSavedTokens = runState.LastCompactionSavedTokens;
|
||||
_runPostCompactionToolResultCompactions = runState.PostCompactionToolResultCompactions;
|
||||
}
|
||||
|
||||
private bool ShouldSuppressPostCompactionThinking(string summary)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(summary))
|
||||
return false;
|
||||
|
||||
var postCompactActive = _runPendingPostCompactionTurn || _runPostCompactionTurnCounter > 0;
|
||||
if (!postCompactActive)
|
||||
return false;
|
||||
|
||||
if (_runPostCompactionTurnCounter > 1)
|
||||
return false;
|
||||
|
||||
return summary.StartsWith("LLM에 요청 중", StringComparison.Ordinal)
|
||||
|| summary.StartsWith("사용자 프롬프트 제출", StringComparison.Ordinal)
|
||||
|| summary.StartsWith("무료 티어 모드", StringComparison.Ordinal)
|
||||
|| summary.StartsWith("컨텍스트 압축 완료", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private string BuildLoopToolResultMessage(LlmService.ContentBlock call, ToolResult result, RunState runState)
|
||||
{
|
||||
var output = result.Output ?? "";
|
||||
if (!ShouldCompactToolResultForPostCompactionTurn(runState, call.ToolName, output))
|
||||
return TruncateOutput(output, 4000);
|
||||
|
||||
runState.PostCompactionToolResultCompactions++;
|
||||
SyncRunPostCompactionState(runState);
|
||||
|
||||
var compacted = CompactToolResultForPostCompaction(call.ToolName, output);
|
||||
var stage = string.IsNullOrWhiteSpace(runState.LastCompactionStageSummary)
|
||||
? "compact"
|
||||
: runState.LastCompactionStageSummary;
|
||||
return $"[POST_COMPACTION_TOOL_RESULT:{call.ToolName}] {stage}\n{compacted}";
|
||||
}
|
||||
|
||||
private static bool ShouldCompactToolResultForPostCompactionTurn(RunState runState, string toolName, string output)
|
||||
{
|
||||
if (runState.PostCompactionTurnCounter != 1)
|
||||
return false;
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
return false;
|
||||
if (output.Length < 900)
|
||||
return false;
|
||||
|
||||
return toolName is "process" or "build_run" or "test_loop" or "snippet_runner" or "git_tool" or "http_tool"
|
||||
|| output.Length > 1800;
|
||||
}
|
||||
|
||||
private static string CompactToolResultForPostCompaction(string toolName, string output)
|
||||
{
|
||||
var normalized = output.Replace("\r\n", "\n");
|
||||
var lines = normalized.Split('\n', StringSplitOptions.None)
|
||||
.Select(line => line.TrimEnd())
|
||||
.Where(line => !string.IsNullOrWhiteSpace(line))
|
||||
.ToList();
|
||||
|
||||
if (lines.Count == 0)
|
||||
return TruncateOutput(output, 1200);
|
||||
|
||||
var headCount = toolName is "build_run" or "test_loop" or "process" ? 6 : 4;
|
||||
var tailCount = toolName is "build_run" or "test_loop" or "process" ? 4 : 3;
|
||||
var kept = new List<string>();
|
||||
kept.AddRange(lines.Take(headCount));
|
||||
|
||||
if (lines.Count > headCount + tailCount)
|
||||
kept.Add($"...[post-compact snip: {lines.Count - headCount - tailCount:N0}줄 생략]...");
|
||||
|
||||
if (lines.Count > headCount)
|
||||
kept.AddRange(lines.Skip(Math.Max(headCount, lines.Count - tailCount)));
|
||||
|
||||
var compacted = string.Join("\n", kept.Distinct(StringComparer.Ordinal));
|
||||
return TruncateOutput(compacted, 1400);
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,7 @@ public partial class AgentLoopService
|
||||
{
|
||||
if (IsRunning) throw new InvalidOperationException("에이전트가 이미 실행 중입니다.");
|
||||
|
||||
var runStopwatch = Stopwatch.StartNew();
|
||||
IsRunning = true;
|
||||
_currentRunId = Guid.NewGuid().ToString("N");
|
||||
_docFallbackAttempted = false;
|
||||
@@ -1741,6 +1742,30 @@ public partial class AgentLoopService
|
||||
EmitEvent(AgentEventType.StepDone, "total_stats", summary);
|
||||
}
|
||||
}
|
||||
|
||||
runStopwatch.Stop();
|
||||
AgentPerformanceLogService.LogMetric(
|
||||
"agent_loop",
|
||||
"run_summary",
|
||||
_conversationId,
|
||||
ActiveTab ?? "",
|
||||
runStopwatch.ElapsedMilliseconds,
|
||||
new
|
||||
{
|
||||
runId = _currentRunId,
|
||||
iterations = iteration,
|
||||
toolCalls = totalToolCalls,
|
||||
toolSuccess = statsSuccessCount,
|
||||
toolFail = statsFailCount,
|
||||
inputTokens = statsInputTokens,
|
||||
outputTokens = statsOutputTokens,
|
||||
repeatedFailureBlocks = statsRepeatedFailureBlocks,
|
||||
recoveredAfterFailure = statsRecoveredAfterFailure,
|
||||
postCompactionNoiseSuppressed = _runPostCompactionSuppressedThinkingCount,
|
||||
postCompactionToolResultCompactions = _runPostCompactionToolResultCompactions,
|
||||
taskType = taskPolicy.TaskType,
|
||||
model = _settings.Settings.Llm.Model ?? "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4619,118 +4644,6 @@ public partial class AgentLoopService
|
||||
}
|
||||
}
|
||||
|
||||
private void MarkRunPostCompaction(ContextCompactionResult result, RunState runState)
|
||||
{
|
||||
runState.PendingPostCompactionTurn = true;
|
||||
runState.PostCompactionTurnCounter = 0;
|
||||
runState.LastCompactionStageSummary = result.StageSummary;
|
||||
runState.LastCompactionSavedTokens = result.SavedTokens;
|
||||
SyncRunPostCompactionState(runState);
|
||||
}
|
||||
|
||||
private void NotifyPostCompactionTurnIfNeeded(RunState runState)
|
||||
{
|
||||
if (!runState.PendingPostCompactionTurn)
|
||||
return;
|
||||
|
||||
runState.PendingPostCompactionTurn = false;
|
||||
runState.PostCompactionTurnCounter++;
|
||||
SyncRunPostCompactionState(runState);
|
||||
|
||||
var stage = string.IsNullOrWhiteSpace(runState.LastCompactionStageSummary)
|
||||
? "기본"
|
||||
: runState.LastCompactionStageSummary;
|
||||
var saved = runState.LastCompactionSavedTokens > 0
|
||||
? $" · {Services.TokenEstimator.Format(runState.LastCompactionSavedTokens)} tokens 절감"
|
||||
: "";
|
||||
EmitEvent(
|
||||
AgentEventType.Thinking,
|
||||
"",
|
||||
$"compact 이후 {runState.PostCompactionTurnCounter}번째 턴 · {stage}{saved}");
|
||||
}
|
||||
|
||||
private void SyncRunPostCompactionState(RunState runState)
|
||||
{
|
||||
_runPendingPostCompactionTurn = runState.PendingPostCompactionTurn;
|
||||
_runPostCompactionTurnCounter = runState.PostCompactionTurnCounter;
|
||||
_runLastCompactionStageSummary = runState.LastCompactionStageSummary ?? "";
|
||||
_runLastCompactionSavedTokens = runState.LastCompactionSavedTokens;
|
||||
_runPostCompactionToolResultCompactions = runState.PostCompactionToolResultCompactions;
|
||||
}
|
||||
|
||||
private bool ShouldSuppressPostCompactionThinking(string summary)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(summary))
|
||||
return false;
|
||||
|
||||
var postCompactActive = _runPendingPostCompactionTurn || _runPostCompactionTurnCounter > 0;
|
||||
if (!postCompactActive)
|
||||
return false;
|
||||
|
||||
if (_runPostCompactionTurnCounter > 1)
|
||||
return false;
|
||||
|
||||
return summary.StartsWith("LLM에 요청 중", StringComparison.Ordinal)
|
||||
|| summary.StartsWith("사용자 프롬프트 제출", StringComparison.Ordinal)
|
||||
|| summary.StartsWith("무료 티어 모드", StringComparison.Ordinal)
|
||||
|| summary.StartsWith("컨텍스트 압축 완료", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private string BuildLoopToolResultMessage(LlmService.ContentBlock call, ToolResult result, RunState runState)
|
||||
{
|
||||
var output = result.Output ?? "";
|
||||
if (!ShouldCompactToolResultForPostCompactionTurn(runState, call.ToolName, output))
|
||||
return TruncateOutput(output, 4000);
|
||||
|
||||
runState.PostCompactionToolResultCompactions++;
|
||||
SyncRunPostCompactionState(runState);
|
||||
|
||||
var compacted = CompactToolResultForPostCompaction(call.ToolName, output);
|
||||
var stage = string.IsNullOrWhiteSpace(runState.LastCompactionStageSummary)
|
||||
? "compact"
|
||||
: runState.LastCompactionStageSummary;
|
||||
return $"[POST_COMPACTION_TOOL_RESULT:{call.ToolName}] {stage}\n{compacted}";
|
||||
}
|
||||
|
||||
private static bool ShouldCompactToolResultForPostCompactionTurn(RunState runState, string toolName, string output)
|
||||
{
|
||||
if (runState.PostCompactionTurnCounter != 1)
|
||||
return false;
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
return false;
|
||||
if (output.Length < 900)
|
||||
return false;
|
||||
|
||||
return toolName is "process" or "build_run" or "test_loop" or "snippet_runner" or "git_tool" or "http_tool"
|
||||
|| output.Length > 1800;
|
||||
}
|
||||
|
||||
private static string CompactToolResultForPostCompaction(string toolName, string output)
|
||||
{
|
||||
var normalized = output.Replace("\r\n", "\n");
|
||||
var lines = normalized.Split('\n', StringSplitOptions.None)
|
||||
.Select(line => line.TrimEnd())
|
||||
.Where(line => !string.IsNullOrWhiteSpace(line))
|
||||
.ToList();
|
||||
|
||||
if (lines.Count == 0)
|
||||
return TruncateOutput(output, 1200);
|
||||
|
||||
var headCount = toolName is "build_run" or "test_loop" or "process" ? 6 : 4;
|
||||
var tailCount = toolName is "build_run" or "test_loop" or "process" ? 4 : 3;
|
||||
var kept = new List<string>();
|
||||
kept.AddRange(lines.Take(headCount));
|
||||
|
||||
if (lines.Count > headCount + tailCount)
|
||||
kept.Add($"...[post-compact snip: {lines.Count - headCount - tailCount:N0}줄 생략]...");
|
||||
|
||||
if (lines.Count > headCount)
|
||||
kept.AddRange(lines.Skip(Math.Max(headCount, lines.Count - tailCount)));
|
||||
|
||||
var compacted = string.Join("\n", kept.Distinct(StringComparer.Ordinal));
|
||||
return TruncateOutput(compacted, 1400);
|
||||
}
|
||||
|
||||
/// <summary>영향 범위 기반 의사결정 체크. 확인이 필요하면 메시지를 반환, 불필요하면 null.</summary>
|
||||
private string? CheckDecisionRequired(LlmService.ContentBlock call, AgentContext context)
|
||||
{
|
||||
|
||||
156
src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs
Normal file
156
src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs
Normal file
@@ -0,0 +1,156 @@
|
||||
using AxCopilot.Models;
|
||||
|
||||
namespace AxCopilot.Services.Agent;
|
||||
|
||||
public partial class AgentLoopService
|
||||
{
|
||||
private void ApplyDocumentPlanSuccessTransitions(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<ChatMessage> messages,
|
||||
ref bool documentPlanCalled,
|
||||
ref string? documentPlanPath,
|
||||
ref string? documentPlanTitle,
|
||||
ref string? documentPlanScaffold)
|
||||
{
|
||||
if (!string.Equals(call.ToolName, "document_plan", StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
|
||||
documentPlanCalled = true;
|
||||
var po = result.Output ?? string.Empty;
|
||||
var pm = System.Text.RegularExpressions.Regex.Match(po, @"path:\s*""([^""]+)""");
|
||||
if (pm.Success) documentPlanPath = pm.Groups[1].Value;
|
||||
var tm = System.Text.RegularExpressions.Regex.Match(po, @"title:\s*""([^""]+)""");
|
||||
if (tm.Success) documentPlanTitle = tm.Groups[1].Value;
|
||||
documentPlanScaffold = ExtractDocumentPlanScaffold(po);
|
||||
|
||||
if (!ContainsDocumentPlanFollowUpInstruction(po))
|
||||
return;
|
||||
|
||||
var toolHint = ResolveDocumentPlanFollowUpTool(po);
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content =
|
||||
"document_plan이 완료되었습니다. " +
|
||||
"방금 생성된 골격의 [내용...] 자리와 각 섹션 내용을 실제 상세 본문으로 모두 채운 뒤 " +
|
||||
$"{toolHint} 도구를 지금 즉시 호출하세요. " +
|
||||
"설명만 하지 말고 실제 문서 생성 도구 호출로 바로 이어가세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", $"문서 개요 완료 · {toolHint} 실행 유도");
|
||||
}
|
||||
|
||||
private static string? ExtractDocumentPlanScaffold(string output)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
return null;
|
||||
|
||||
var markers = new (string Start, string End)[]
|
||||
{
|
||||
("--- body 시작 ---", "--- body 끝 ---"),
|
||||
("--- body start ---", "--- body end ---"),
|
||||
("<!-- body start marker -->", "<!-- body end marker -->"),
|
||||
};
|
||||
|
||||
foreach (var (startMarker, endMarker) in markers)
|
||||
{
|
||||
var start = output.IndexOf(startMarker, StringComparison.OrdinalIgnoreCase);
|
||||
if (start < 0)
|
||||
continue;
|
||||
|
||||
var contentStart = start + startMarker.Length;
|
||||
var end = output.IndexOf(endMarker, contentStart, StringComparison.OrdinalIgnoreCase);
|
||||
if (end <= contentStart)
|
||||
continue;
|
||||
|
||||
var scaffold = output[contentStart..end].Trim();
|
||||
if (!string.IsNullOrWhiteSpace(scaffold))
|
||||
return scaffold;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool ContainsDocumentPlanFollowUpInstruction(string output)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
return false;
|
||||
|
||||
return output.Contains("즉시 실행", StringComparison.OrdinalIgnoreCase)
|
||||
|| output.Contains("immediate next step", StringComparison.OrdinalIgnoreCase)
|
||||
|| output.Contains("call html_create", StringComparison.OrdinalIgnoreCase)
|
||||
|| output.Contains("call document_assemble", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string ResolveDocumentPlanFollowUpTool(string output)
|
||||
{
|
||||
if (output.Contains("document_assemble", StringComparison.OrdinalIgnoreCase))
|
||||
return "document_assemble";
|
||||
if (output.Contains("docx_create", StringComparison.OrdinalIgnoreCase))
|
||||
return "docx_create";
|
||||
if (output.Contains("markdown_create", StringComparison.OrdinalIgnoreCase))
|
||||
return "markdown_create";
|
||||
if (output.Contains("file_write", StringComparison.OrdinalIgnoreCase))
|
||||
return "file_write";
|
||||
return "html_create";
|
||||
}
|
||||
|
||||
private async Task<(bool Completed, bool ConsumedExtraIteration)> TryHandleTerminalDocumentCompletionTransitionAsync(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<LlmService.ContentBlock> toolCalls,
|
||||
List<ChatMessage> messages,
|
||||
Models.LlmSettings llm,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy,
|
||||
AgentContext context,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (!result.Success || !IsTerminalDocumentTool(call.ToolName) || toolCalls.Count != 1)
|
||||
return (false, false);
|
||||
|
||||
var verificationEnabled = executionPolicy.EnablePostToolVerification
|
||||
&& AgentTabSettingsResolver.IsPostToolVerificationEnabled(ActiveTab, llm);
|
||||
var shouldVerify = ShouldRunPostToolVerification(
|
||||
ActiveTab,
|
||||
call.ToolName,
|
||||
result.Success,
|
||||
verificationEnabled,
|
||||
verificationEnabled);
|
||||
var consumedExtraIteration = false;
|
||||
if (shouldVerify)
|
||||
{
|
||||
await RunPostToolVerificationAsync(messages, call.ToolName, result, context, ct);
|
||||
consumedExtraIteration = true;
|
||||
}
|
||||
|
||||
EmitEvent(AgentEventType.Complete, "", "에이전트 작업 완료");
|
||||
return (true, consumedExtraIteration);
|
||||
}
|
||||
|
||||
private async Task<bool> TryApplyPostToolVerificationTransitionAsync(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<ChatMessage> messages,
|
||||
Models.LlmSettings llm,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy,
|
||||
AgentContext context,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (!result.Success)
|
||||
return false;
|
||||
|
||||
var verificationEnabled = executionPolicy.EnablePostToolVerification
|
||||
&& AgentTabSettingsResolver.IsPostToolVerificationEnabled(ActiveTab, llm);
|
||||
var shouldVerify = ShouldRunPostToolVerification(
|
||||
ActiveTab,
|
||||
call.ToolName,
|
||||
result.Success,
|
||||
verificationEnabled,
|
||||
verificationEnabled);
|
||||
if (!shouldVerify)
|
||||
return false;
|
||||
|
||||
await RunPostToolVerificationAsync(messages, call.ToolName, result, context, ct);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -58,205 +58,6 @@ public partial class AgentLoopService
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryApplyCodeCompletionGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
bool requireHighImpactCodeVerification,
|
||||
int totalToolCalls,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase) || totalToolCalls <= 0)
|
||||
return false;
|
||||
|
||||
var hasCodeVerificationEvidence = HasCodeVerificationEvidenceAfterLastModification(
|
||||
messages,
|
||||
requireHighImpactCodeVerification);
|
||||
if (executionPolicy.CodeVerificationGateMaxRetries > 0
|
||||
&& !hasCodeVerificationEvidence
|
||||
&& runState.CodeVerificationGateRetry < executionPolicy.CodeVerificationGateMaxRetries)
|
||||
{
|
||||
runState.CodeVerificationGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = requireHighImpactCodeVerification
|
||||
? "[System:CodeQualityGate] 공용/핵심 코드 변경 이후 검증 근거가 부족합니다. 종료하지 말고 file_read, grep/glob, git diff, build/test까지 확인한 뒤에만 마무리하세요."
|
||||
: "[System:CodeQualityGate] 마지막 코드 수정 이후 build/test/file_read/diff 근거가 부족합니다. 종료하지 말고 검증 근거를 보강한 뒤에만 마무리하세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", requireHighImpactCodeVerification
|
||||
? "핵심 코드 변경의 검증 근거가 부족해 추가 검증을 진행합니다..."
|
||||
: "코드 결과 검증 근거가 부족해 추가 검증을 진행합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (requireHighImpactCodeVerification
|
||||
&& executionPolicy.HighImpactBuildTestGateMaxRetries > 0
|
||||
&& !HasSuccessfulBuildAndTestAfterLastModification(messages)
|
||||
&& runState.HighImpactBuildTestGateRetry < executionPolicy.HighImpactBuildTestGateMaxRetries)
|
||||
{
|
||||
runState.HighImpactBuildTestGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = "[System:HighImpactBuildTestGate] 핵심 코드 변경입니다. 종료하지 말고 build_run과 test_loop를 모두 실행해 성공 근거를 확보한 뒤에만 마무리하세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "핵심 변경이라 build+test 성공 근거를 모두 확보할 때까지 진행합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (executionPolicy.FinalReportGateMaxRetries > 0
|
||||
&& !HasSufficientFinalReportEvidence(textResponse, taskPolicy, requireHighImpactCodeVerification, messages)
|
||||
&& runState.FinalReportGateRetry < executionPolicy.FinalReportGateMaxRetries)
|
||||
{
|
||||
runState.FinalReportGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildFinalReportQualityPrompt(taskPolicy, requireHighImpactCodeVerification)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "최종 보고에 변경·검증·리스크 요약이 부족해 한 번 더 정리합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryApplyCodeDiffEvidenceGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
if (executionPolicy.CodeDiffGateMaxRetries <= 0 || runState.CodeDiffGateRetry >= executionPolicy.CodeDiffGateMaxRetries)
|
||||
return false;
|
||||
|
||||
if (HasDiffEvidenceAfterLastModification(messages))
|
||||
return false;
|
||||
|
||||
runState.CodeDiffGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = "[System:CodeDiffGate] 코드 변경 이후 diff 근거가 부족합니다. " +
|
||||
"git_tool 도구로 변경 파일과 핵심 diff를 먼저 확인하고 요약하세요. " +
|
||||
"지금 즉시 git_tool 도구를 호출하세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "코드 diff 근거가 부족해 git diff 검증을 추가합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryApplyRecentExecutionEvidenceGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
if (executionPolicy.RecentExecutionGateMaxRetries <= 0 || runState.RecentExecutionGateRetry >= executionPolicy.RecentExecutionGateMaxRetries)
|
||||
return false;
|
||||
|
||||
if (!HasAnyBuildOrTestEvidence(messages))
|
||||
return false;
|
||||
|
||||
if (HasBuildOrTestEvidenceAfterLastModification(messages))
|
||||
return false;
|
||||
|
||||
runState.RecentExecutionGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildRecentExecutionEvidencePrompt(taskPolicy)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "최근 수정 이후 실행 근거가 부족해 build/test 재검증을 수행합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryApplyExecutionSuccessGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
if (executionPolicy.ExecutionSuccessGateMaxRetries <= 0 || runState.ExecutionSuccessGateRetry >= executionPolicy.ExecutionSuccessGateMaxRetries)
|
||||
return false;
|
||||
|
||||
if (!HasAnyBuildOrTestAttempt(messages))
|
||||
return false;
|
||||
|
||||
if (HasAnyBuildOrTestEvidence(messages))
|
||||
return false;
|
||||
|
||||
runState.ExecutionSuccessGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildExecutionSuccessGatePrompt(taskPolicy)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "실패한 실행 근거만 있어 build/test 성공 결과를 다시 검증합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryApplyTerminalEvidenceGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
string userQuery,
|
||||
int totalToolCalls,
|
||||
string? lastArtifactFilePath,
|
||||
RunState runState,
|
||||
int retryMax)
|
||||
{
|
||||
if (totalToolCalls <= 0)
|
||||
return false;
|
||||
|
||||
if (ShouldSkipTerminalEvidenceGateForAnalysisQuery(userQuery, taskPolicy))
|
||||
return false;
|
||||
|
||||
if (runState.TerminalEvidenceGateRetry >= retryMax)
|
||||
return false;
|
||||
|
||||
if (HasTerminalProgressEvidence(taskPolicy, messages, lastArtifactFilePath))
|
||||
return false;
|
||||
|
||||
runState.TerminalEvidenceGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildTerminalEvidenceGatePrompt(taskPolicy, lastArtifactFilePath)
|
||||
});
|
||||
EmitEvent(
|
||||
AgentEventType.Thinking,
|
||||
"",
|
||||
$"종료 전 실행 증거가 부족해 보강 단계를 진행합니다 ({runState.TerminalEvidenceGateRetry}/{retryMax})");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool ShouldSkipTerminalEvidenceGateForAnalysisQuery(string userQuery, TaskTypePolicy taskPolicy)
|
||||
{
|
||||
if (string.Equals(taskPolicy.TaskType, "docs", StringComparison.OrdinalIgnoreCase))
|
||||
@@ -1318,189 +1119,6 @@ public partial class AgentLoopService
|
||||
|| lower.Contains("json parse");
|
||||
}
|
||||
|
||||
private void ApplyDocumentPlanSuccessTransitions(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<ChatMessage> messages,
|
||||
ref bool documentPlanCalled,
|
||||
ref string? documentPlanPath,
|
||||
ref string? documentPlanTitle,
|
||||
ref string? documentPlanScaffold)
|
||||
{
|
||||
if (!string.Equals(call.ToolName, "document_plan", StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
|
||||
documentPlanCalled = true;
|
||||
var po = result.Output ?? string.Empty;
|
||||
var pm = System.Text.RegularExpressions.Regex.Match(po, @"path:\s*""([^""]+)""");
|
||||
if (pm.Success) documentPlanPath = pm.Groups[1].Value;
|
||||
var tm = System.Text.RegularExpressions.Regex.Match(po, @"title:\s*""([^""]+)""");
|
||||
if (tm.Success) documentPlanTitle = tm.Groups[1].Value;
|
||||
documentPlanScaffold = ExtractDocumentPlanScaffold(po);
|
||||
|
||||
if (!ContainsDocumentPlanFollowUpInstruction(po))
|
||||
return;
|
||||
|
||||
var toolHint = ResolveDocumentPlanFollowUpTool(po);
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content =
|
||||
"document_plan이 완료되었습니다. " +
|
||||
"방금 생성된 골격의 [내용...] 자리와 각 섹션 내용을 실제 상세 본문으로 모두 채운 뒤 " +
|
||||
$"{toolHint} 도구를 지금 즉시 호출하세요. " +
|
||||
"설명만 하지 말고 실제 문서 생성 도구 호출로 바로 이어가세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", $"문서 개요 완료 · {toolHint} 실행 유도");
|
||||
}
|
||||
|
||||
private static string? ExtractDocumentPlanScaffold(string output)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
return null;
|
||||
|
||||
var markers = new (string Start, string End)[]
|
||||
{
|
||||
("--- body 시작 ---", "--- body 끝 ---"),
|
||||
("--- body start ---", "--- body end ---"),
|
||||
("<!-- body start marker -->", "<!-- body end marker -->"),
|
||||
};
|
||||
|
||||
foreach (var (startMarker, endMarker) in markers)
|
||||
{
|
||||
var start = output.IndexOf(startMarker, StringComparison.OrdinalIgnoreCase);
|
||||
if (start < 0)
|
||||
continue;
|
||||
|
||||
var contentStart = start + startMarker.Length;
|
||||
var end = output.IndexOf(endMarker, contentStart, StringComparison.OrdinalIgnoreCase);
|
||||
if (end <= contentStart)
|
||||
continue;
|
||||
|
||||
var scaffold = output[contentStart..end].Trim();
|
||||
if (!string.IsNullOrWhiteSpace(scaffold))
|
||||
return scaffold;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool ContainsDocumentPlanFollowUpInstruction(string output)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
return false;
|
||||
|
||||
return output.Contains("즉시 실행", StringComparison.OrdinalIgnoreCase)
|
||||
|| output.Contains("immediate next step", StringComparison.OrdinalIgnoreCase)
|
||||
|| output.Contains("call html_create", StringComparison.OrdinalIgnoreCase)
|
||||
|| output.Contains("call document_assemble", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string ResolveDocumentPlanFollowUpTool(string output)
|
||||
{
|
||||
if (output.Contains("document_assemble", StringComparison.OrdinalIgnoreCase))
|
||||
return "document_assemble";
|
||||
if (output.Contains("docx_create", StringComparison.OrdinalIgnoreCase))
|
||||
return "docx_create";
|
||||
if (output.Contains("markdown_create", StringComparison.OrdinalIgnoreCase))
|
||||
return "markdown_create";
|
||||
if (output.Contains("file_write", StringComparison.OrdinalIgnoreCase))
|
||||
return "file_write";
|
||||
return "html_create";
|
||||
}
|
||||
|
||||
private void ApplyCodeQualityFollowUpTransition(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<ChatMessage> messages,
|
||||
TaskTypePolicy taskPolicy,
|
||||
ref bool requireHighImpactCodeVerification,
|
||||
ref string? lastModifiedCodeFilePath)
|
||||
{
|
||||
var highImpactCodeChange = IsHighImpactCodeModification(ActiveTab ?? "", call.ToolName, result);
|
||||
if (ShouldInjectCodeQualityFollowUp(ActiveTab ?? "", call.ToolName, result))
|
||||
{
|
||||
requireHighImpactCodeVerification = highImpactCodeChange;
|
||||
lastModifiedCodeFilePath = result.FilePath;
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildCodeQualityFollowUpPrompt(
|
||||
call.ToolName,
|
||||
result,
|
||||
highImpactCodeChange,
|
||||
HasAnyBuildOrTestEvidence(messages),
|
||||
taskPolicy)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", highImpactCodeChange
|
||||
? "怨좎쁺??肄붾뱶 蹂寃쎌쑝濡?李몄“ 寃利앷낵 build/test 寃利앹쓣 ???꾧꺽?섍쾶 ?댁뼱媛묐땲??."
|
||||
: "肄붾뱶 蹂寃???build/test/diff 寃利앹쓣 ?댁뼱媛묐땲??.");
|
||||
}
|
||||
else if (HasCodeVerificationEvidenceAfterLastModification(messages, requireHighImpactCodeVerification))
|
||||
{
|
||||
requireHighImpactCodeVerification = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(bool Completed, bool ConsumedExtraIteration)> TryHandleTerminalDocumentCompletionTransitionAsync(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<LlmService.ContentBlock> toolCalls,
|
||||
List<ChatMessage> messages,
|
||||
Models.LlmSettings llm,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy,
|
||||
AgentContext context,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (!result.Success || !IsTerminalDocumentTool(call.ToolName) || toolCalls.Count != 1)
|
||||
return (false, false);
|
||||
|
||||
var verificationEnabled = executionPolicy.EnablePostToolVerification
|
||||
&& AgentTabSettingsResolver.IsPostToolVerificationEnabled(ActiveTab, llm);
|
||||
var shouldVerify = ShouldRunPostToolVerification(
|
||||
ActiveTab,
|
||||
call.ToolName,
|
||||
result.Success,
|
||||
verificationEnabled,
|
||||
verificationEnabled);
|
||||
var consumedExtraIteration = false;
|
||||
if (shouldVerify)
|
||||
{
|
||||
await RunPostToolVerificationAsync(messages, call.ToolName, result, context, ct);
|
||||
consumedExtraIteration = true;
|
||||
}
|
||||
|
||||
EmitEvent(AgentEventType.Complete, "", "에이전트 작업 완료");
|
||||
return (true, consumedExtraIteration);
|
||||
}
|
||||
|
||||
private async Task<bool> TryApplyPostToolVerificationTransitionAsync(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<ChatMessage> messages,
|
||||
Models.LlmSettings llm,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy,
|
||||
AgentContext context,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (!result.Success)
|
||||
return false;
|
||||
|
||||
var verificationEnabled = executionPolicy.EnablePostToolVerification
|
||||
&& AgentTabSettingsResolver.IsPostToolVerificationEnabled(ActiveTab, llm);
|
||||
var shouldVerify = ShouldRunPostToolVerification(
|
||||
ActiveTab,
|
||||
call.ToolName,
|
||||
result.Success,
|
||||
verificationEnabled,
|
||||
verificationEnabled);
|
||||
if (!shouldVerify)
|
||||
return false;
|
||||
|
||||
await RunPostToolVerificationAsync(messages, call.ToolName, result, context, ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<(bool ShouldContinue, string? TerminalResponse)> TryHandleUserDecisionTransitionsAsync(
|
||||
LlmService.ContentBlock call,
|
||||
AgentContext context,
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
using AxCopilot.Models;
|
||||
|
||||
namespace AxCopilot.Services.Agent;
|
||||
|
||||
public partial class AgentLoopService
|
||||
{
|
||||
private void ApplyCodeQualityFollowUpTransition(
|
||||
LlmService.ContentBlock call,
|
||||
ToolResult result,
|
||||
List<ChatMessage> messages,
|
||||
TaskTypePolicy taskPolicy,
|
||||
ref bool requireHighImpactCodeVerification,
|
||||
ref string? lastModifiedCodeFilePath)
|
||||
{
|
||||
var highImpactCodeChange = IsHighImpactCodeModification(ActiveTab ?? "", call.ToolName, result);
|
||||
if (ShouldInjectCodeQualityFollowUp(ActiveTab ?? "", call.ToolName, result))
|
||||
{
|
||||
requireHighImpactCodeVerification = highImpactCodeChange;
|
||||
lastModifiedCodeFilePath = result.FilePath;
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildCodeQualityFollowUpPrompt(
|
||||
call.ToolName,
|
||||
result,
|
||||
highImpactCodeChange,
|
||||
HasAnyBuildOrTestEvidence(messages),
|
||||
taskPolicy)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", highImpactCodeChange
|
||||
? "고영향 코드 변경으로 분류돼 참조 검증과 build/test 검증을 더 엄격하게 이어갑니다."
|
||||
: "코드 변경 후 build/test/diff 검증을 이어갑니다.");
|
||||
}
|
||||
else if (HasCodeVerificationEvidenceAfterLastModification(messages, requireHighImpactCodeVerification))
|
||||
{
|
||||
requireHighImpactCodeVerification = false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryApplyCodeCompletionGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
bool requireHighImpactCodeVerification,
|
||||
int totalToolCalls,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase) || totalToolCalls <= 0)
|
||||
return false;
|
||||
|
||||
var hasCodeVerificationEvidence = HasCodeVerificationEvidenceAfterLastModification(
|
||||
messages,
|
||||
requireHighImpactCodeVerification);
|
||||
if (executionPolicy.CodeVerificationGateMaxRetries > 0
|
||||
&& !hasCodeVerificationEvidence
|
||||
&& runState.CodeVerificationGateRetry < executionPolicy.CodeVerificationGateMaxRetries)
|
||||
{
|
||||
runState.CodeVerificationGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = requireHighImpactCodeVerification
|
||||
? "[System:CodeQualityGate] 공용/핵심 코드 변경 이후 검증 근거가 부족합니다. 종료하지 말고 file_read, grep/glob, git diff, build/test까지 확인한 뒤에만 마무리하세요."
|
||||
: "[System:CodeQualityGate] 마지막 코드 수정 이후 build/test/file_read/diff 근거가 부족합니다. 종료하지 말고 검증 근거를 보강한 뒤에만 마무리하세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", requireHighImpactCodeVerification
|
||||
? "핵심 코드 변경의 검증 근거가 부족해 추가 검증을 진행합니다..."
|
||||
: "코드 결과 검증 근거가 부족해 추가 검증을 진행합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (requireHighImpactCodeVerification
|
||||
&& executionPolicy.HighImpactBuildTestGateMaxRetries > 0
|
||||
&& !HasSuccessfulBuildAndTestAfterLastModification(messages)
|
||||
&& runState.HighImpactBuildTestGateRetry < executionPolicy.HighImpactBuildTestGateMaxRetries)
|
||||
{
|
||||
runState.HighImpactBuildTestGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = "[System:HighImpactBuildTestGate] 핵심 코드 변경입니다. 종료하지 말고 build_run과 test_loop를 모두 실행해 성공 근거를 확보한 뒤에만 마무리하세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "핵심 변경이라 build+test 성공 근거를 모두 확보할 때까지 진행합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (executionPolicy.FinalReportGateMaxRetries > 0
|
||||
&& !HasSufficientFinalReportEvidence(textResponse, taskPolicy, requireHighImpactCodeVerification, messages)
|
||||
&& runState.FinalReportGateRetry < executionPolicy.FinalReportGateMaxRetries)
|
||||
{
|
||||
runState.FinalReportGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildFinalReportQualityPrompt(taskPolicy, requireHighImpactCodeVerification)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "최종 보고에 변경·검증·리스크 요약이 부족해 한 번 더 정리합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryApplyCodeDiffEvidenceGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
if (executionPolicy.CodeDiffGateMaxRetries <= 0 || runState.CodeDiffGateRetry >= executionPolicy.CodeDiffGateMaxRetries)
|
||||
return false;
|
||||
|
||||
if (HasDiffEvidenceAfterLastModification(messages))
|
||||
return false;
|
||||
|
||||
runState.CodeDiffGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = "[System:CodeDiffGate] 코드 변경 이후 diff 근거가 부족합니다. git_tool 도구로 변경 파일과 핵심 diff를 먼저 확인하고 요약하세요. 지금 즉시 git_tool 도구를 호출하세요."
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "코드 diff 근거가 부족해 git diff 검증을 추가합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryApplyRecentExecutionEvidenceGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
if (executionPolicy.RecentExecutionGateMaxRetries <= 0 || runState.RecentExecutionGateRetry >= executionPolicy.RecentExecutionGateMaxRetries)
|
||||
return false;
|
||||
|
||||
if (!HasAnyBuildOrTestEvidence(messages))
|
||||
return false;
|
||||
|
||||
if (HasBuildOrTestEvidenceAfterLastModification(messages))
|
||||
return false;
|
||||
|
||||
runState.RecentExecutionGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildRecentExecutionEvidencePrompt(taskPolicy)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "최근 수정 이후 실행 근거가 부족해 build/test 재검증을 수행합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryApplyExecutionSuccessGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
RunState runState,
|
||||
ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy)
|
||||
{
|
||||
if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
if (executionPolicy.ExecutionSuccessGateMaxRetries <= 0 || runState.ExecutionSuccessGateRetry >= executionPolicy.ExecutionSuccessGateMaxRetries)
|
||||
return false;
|
||||
|
||||
if (!HasAnyBuildOrTestAttempt(messages))
|
||||
return false;
|
||||
|
||||
if (HasAnyBuildOrTestEvidence(messages))
|
||||
return false;
|
||||
|
||||
runState.ExecutionSuccessGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildExecutionSuccessGatePrompt(taskPolicy)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", "실패한 실행 근거만 있어 build/test 성공 결과를 다시 검증합니다...");
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryApplyTerminalEvidenceGateTransition(
|
||||
List<ChatMessage> messages,
|
||||
string? textResponse,
|
||||
TaskTypePolicy taskPolicy,
|
||||
string userQuery,
|
||||
int totalToolCalls,
|
||||
string? lastArtifactFilePath,
|
||||
RunState runState,
|
||||
int retryMax)
|
||||
{
|
||||
if (totalToolCalls <= 0)
|
||||
return false;
|
||||
|
||||
if (ShouldSkipTerminalEvidenceGateForAnalysisQuery(userQuery, taskPolicy))
|
||||
return false;
|
||||
|
||||
if (runState.TerminalEvidenceGateRetry >= retryMax)
|
||||
return false;
|
||||
|
||||
if (HasTerminalProgressEvidence(taskPolicy, messages, lastArtifactFilePath))
|
||||
return false;
|
||||
|
||||
runState.TerminalEvidenceGateRetry++;
|
||||
if (!string.IsNullOrEmpty(textResponse))
|
||||
messages.Add(new ChatMessage { Role = "assistant", Content = textResponse });
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "user",
|
||||
Content = BuildTerminalEvidenceGatePrompt(taskPolicy, lastArtifactFilePath)
|
||||
});
|
||||
EmitEvent(AgentEventType.Thinking, "", $"종료 전 실행 증거가 부족해 보강 단계를 진행합니다 ({runState.TerminalEvidenceGateRetry}/{retryMax})");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user