Skip to content
Open
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
2 changes: 1 addition & 1 deletion internal/domain/evolution.go
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ type EvoSOPGrayRound struct {
ProposalID string `json:"proposalId"`
BaseVersion string `json:"baseVersion"`
Target string `json:"target"`
Status string `json:"status"` // running, passed, failed, published
Status string `json:"status"` // running, passed, failed, published, rolled_back
Published bool `json:"published,omitempty"`
Percent int `json:"percent,omitempty"`
MinRuns int `json:"minRuns,omitempty"`
Expand Down
28 changes: 28 additions & 0 deletions internal/httpapi/evolution.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,13 @@ func (h *evolutionHandlers) dismissFinding(c *gin.Context) {
if !h.requireProjectWriter(c, finding.ProjectID) {
return
}
// PutEvoFinding keeps the status of a finding that an open or released
// proposal or a queued improvement depends on. Dismissing it anyway would
// answer 200 while the stored finding stayed proposed, so refuse instead.
if reason := h.dismissBlockedReason(finding); reason != "" {
c.JSON(http.StatusConflict, gin.H{"error": reason})
return
}
finding.Status = domain.EvoFindingDismissed
finding.CloseNote = domain.TrimEvoText(req.Reason, 500)
if err := h.repo.PutEvoFinding(finding); err != nil {
Expand All @@ -255,6 +262,27 @@ func (h *evolutionHandlers) dismissFinding(c *gin.Context) {
c.JSON(http.StatusOK, finding)
}

// dismissBlockedReason reports why a finding cannot be dismissed yet, or ""
// when it can. A finding linked to a proposal or to a queued improvement is
// kept by PutEvoFinding so the work in flight still points at it.
func (h *evolutionHandlers) dismissBlockedReason(finding domain.EvoFinding) string {
if finding.Status == domain.EvoFindingDismissed {
return ""
}
if p, ok := h.repo.EvoProposal(finding.ProposalID); ok && p.FindingID == finding.ID {
switch {
case p.Open():
return "该问题已进入改进流程,请先驳回或关闭对应的改进提案"
case p.Status == domain.EvoProposalReleased:
return "该问题的改进已发布,已按已解决归档,无法忽略"
}
}
if evoFindingQueued(h.repo.EvoQueue(finding.ProjectID), finding.ID) {
return "该问题已排入后续改进,请先在改进任务里取消排队"
}
return ""
}

// snoozeFinding keeps an open finding out of the active queue for a few
// days; days 0 wakes it up. New signals still update its statistics.
func (h *evolutionHandlers) snoozeFinding(c *gin.Context) {
Expand Down
4 changes: 4 additions & 0 deletions internal/httpapi/evolution_sop.go
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,10 @@ func (h *evolutionHandlers) buildSOPGrayRounds(
published := p.Status == domain.EvoProposalReleased
if published {
status = "published"
} else if p.Status == domain.EvoProposalRolledBack {
// The canary itself stays promoted after a rollback; the round is
// rolled back, which is what the table must show.
status = domain.EvoProposalRolledBack
}

rounds = append(rounds, domain.EvoSOPGrayRound{
Expand Down
63 changes: 63 additions & 0 deletions internal/httpapi/evolution_sop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -736,3 +736,66 @@ func TestEvolutionSOPRollbackHashFallbackPreservesPreRollbackRuns(t *testing.T)
t.Fatalf("P2-9: pre-rollback runs must stay on v1 and not bleed into v3 rollback row: v0=%+v v1=%+v", detail.Versions[0], detail.Versions[1])
}
}

// A rolled-back proposal keeps Canary.Status="promoted" (the gray run finished
// and went wide before the rollback), so the gray-round table used to print a
// raw English "promoted" for a round that had in fact been rolled back.
func TestEvolutionSOPGrayRoundShowsRolledBack(t *testing.T) {
env := newEvoTestEnv(t)
now := time.Now().UTC()

wf := env.wf
wf.Version = 2
if err := env.store.PutWorkflow(wf); err != nil {
t.Fatal(err)
}
v1Prompt := env.agent.Prompt
v2Prompt := env.agent.Prompt + "\n修改稿 v2"
for _, r := range []domain.Run{
{ID: "rb-ctrl", WorkflowID: wf.ID, WorkflowSnapshot: wf, Status: "succeeded",
ExecutionContext: domain.TelemetryContext{ProjectID: "evo-p"},
CreatedAt: now.Add(-3 * time.Hour), UpdatedAt: now.Add(-3 * time.Hour),
Usage: domain.TokenUsage{TotalTokens: 50000}, ToolCalls: 9,
Nodes: map[string]*domain.NodeRun{"code": {NodeID: "code", Status: "succeeded", Attempt: 1}}},
{ID: "rb-cand", WorkflowID: wf.ID, WorkflowSnapshot: wf, Status: "succeeded",
ExecutionContext: domain.TelemetryContext{ProjectID: "evo-p"},
CreatedAt: now.Add(-2 * time.Hour), UpdatedAt: now.Add(-2 * time.Hour),
Usage: domain.TokenUsage{TotalTokens: 44000}, ToolCalls: 7,
Nodes: map[string]*domain.NodeRun{"code": {NodeID: "code", Status: "succeeded", Attempt: 1}}},
} {
if err := env.store.PutRun(r); err != nil {
t.Fatal(err)
}
}
if err := env.store.PutRunAssetPins([]domain.RunAssetPin{
{RunID: "rb-ctrl", AssetKind: domain.EvoAssetAgent, AssetID: env.agent.ID, Version: 2, Hash: domain.ContentHash(v1Prompt), CreatedAt: now.Add(-3 * time.Hour)},
{RunID: "rb-cand", AssetKind: domain.EvoAssetAgent, AssetID: env.agent.ID, Version: 3, Hash: domain.ContentHash(v2Prompt), CreatedAt: now.Add(-2 * time.Hour)},
}); err != nil {
t.Fatal(err)
}
if err := env.store.PutEvoProposal(domain.EvoProposal{
ID: "evp-rb", ProjectID: "evo-p", AssetKind: domain.EvoAssetAgent, AssetID: env.agent.ID,
AssetName: env.agent.Name, Title: "回滚的灰度", BaseContent: v1Prompt, BaseHash: domain.ContentHash(v1Prompt), BaseVersion: 2,
CandidateContent: v2Prompt, Status: domain.EvoProposalRolledBack,
Canary: &domain.EvoCanary{
Percent: 50, MinRuns: 5, Status: domain.EvoCanaryPromoted,
StartedAt: now.Add(-4 * time.Hour), EndedAt: now.Add(-1 * time.Hour),
},
}); err != nil {
t.Fatal(err)
}

detail, ok := env.h.buildSOPDetail("evo-p", wf.ID, 14)
if !ok {
t.Fatal("expected SOP detail")
}
if len(detail.GrayRounds) != 1 {
t.Fatalf("expected 1 gray round, got %+v", detail.GrayRounds)
}
if got := detail.GrayRounds[0].Status; got != domain.EvoProposalRolledBack {
t.Fatalf("a rolled-back round must report %q, got %q (raw canary status leaked)", domain.EvoProposalRolledBack, got)
}
if detail.GrayRounds[0].Published {
t.Fatal("a rolled-back round must not be published")
}
}
104 changes: 104 additions & 0 deletions internal/httpapi/evolution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -642,3 +642,107 @@ func TestEvolutionReplayAutoApprovesGatesTheSourcePassed(t *testing.T) {
t.Fatalf("an approval the source passed should be auto-approved: node=%s replay=%+v", run.Nodes["accept"].Status, p.Replays[0])
}
}

// A finding an open or released proposal depends on cannot be dismissed: the
// store keeps its status, so answering 200 would report a change that never
// happened and the finding reappears on the next read.
func TestEvolutionDismissFindingRefusesWhileImprovementIsInFlight(t *testing.T) {
env := newEvoTestEnv(t)
env.seedRun(t, "evo-dismiss-src", "failed", "failed", "单元测试失败")
diag := requestJSON[struct {
Findings []domain.EvoFinding `json:"findings"`
}](t, env.router, http.MethodPost, "/api/evolution/diagnose", map[string]any{"projectId": "evo-p"}, http.StatusOK)
if len(diag.Findings) != 1 {
t.Fatalf("diagnose = %+v", diag)
}
finding := diag.Findings[0]

// No proposal yet: dismissing works and stores the reason.
dismissed := requestJSON[domain.EvoFinding](t, env.router, http.MethodPost, "/api/evolution/findings/"+finding.ID+"/dismiss",
map[string]any{"reason": "误报"}, http.StatusOK)
if dismissed.Status != domain.EvoFindingDismissed {
t.Fatalf("dismiss = %+v", dismissed)
}

// Open proposal: the request is refused and the stored finding is untouched.
if err := env.store.PutEvoProposal(domain.EvoProposal{
ID: "evp-dismiss", ProjectID: "evo-p", FindingID: finding.ID, AssetKind: domain.EvoAssetAgent, AssetID: env.agent.ID,
AssetName: env.agent.Name, Status: domain.EvoProposalValidating, CandidateContent: env.agent.Prompt + "\n补充检查",
BaseHash: domain.ContentHash(env.agent.Prompt),
}); err != nil {
t.Fatal(err)
}
requestJSONAuthed[map[string]any](t, env.router, env.user, http.MethodPost, "/api/evolution/findings/"+finding.ID+"/dismiss",
map[string]any{"reason": "误报"}, http.StatusConflict)
if stored, _ := env.store.EvoFinding(finding.ID); stored.Status != domain.EvoFindingProposed || stored.ProposalID != "evp-dismiss" {
t.Fatalf("a refused dismiss must not change the finding: %+v", stored)
}

// Rejected proposal reopens the finding, so dismissing works again.
requestJSONAuthed[domain.EvoProposal](t, env.router, env.user, http.MethodPost, "/api/evolution/proposals/evp-dismiss/reject", nil, http.StatusOK)
if stored, _ := env.store.EvoFinding(finding.ID); stored.Status != domain.EvoFindingOpen {
t.Fatalf("reject should reopen the finding: %+v", stored)
}
requestJSON[domain.EvoFinding](t, env.router, http.MethodPost, "/api/evolution/findings/"+finding.ID+"/dismiss",
map[string]any{"reason": "确认误报"}, http.StatusOK)
if stored, _ := env.store.EvoFinding(finding.ID); stored.Status != domain.EvoFindingDismissed || stored.CloseNote != "确认误报" {
t.Fatalf("dismiss after reject = %+v", stored)
}
}

// The dismiss guard also covers a released proposal: the finding is archived
// as resolved, so dismissing it would report a status the store never writes.
func TestEvolutionDismissBlockedReasonForReleased(t *testing.T) {
env := newEvoTestEnv(t)
finding := domain.EvoFinding{ID: "evf-guard", ProjectID: "evo-p", AssetKind: domain.EvoAssetAgent, AssetID: env.agent.ID, Status: domain.EvoFindingOpen}
if reason := env.h.dismissBlockedReason(finding); reason != "" {
t.Fatalf("a plain open finding must be dismissable, got %q", reason)
}
if err := env.store.PutEvoProposal(domain.EvoProposal{ID: "evp-released", ProjectID: "evo-p", FindingID: finding.ID, AssetKind: domain.EvoAssetAgent,
AssetID: env.agent.ID, Status: domain.EvoProposalReleased}); err != nil {
t.Fatal(err)
}
if reason := env.h.dismissBlockedReason(domain.EvoFinding{ID: finding.ID, ProjectID: "evo-p", AssetKind: finding.AssetKind, AssetID: finding.AssetID,
Status: domain.EvoFindingResolved, ProposalID: "evp-released"}); reason == "" {
t.Fatal("a finding whose improvement was released must not be dismissable")
}
// No queued item for this asset: the guard must not block.
if reason := env.h.dismissBlockedReason(domain.EvoFinding{ID: "evf-free", ProjectID: "evo-p", AssetKind: domain.EvoAssetAgent,
AssetID: env.agent.ID, Status: domain.EvoFindingOpen}); reason != "" {
t.Fatalf("a finding with nothing in flight must be dismissable, got %q", reason)
}
}

// A finding queued behind another proposal on the same asset keeps its status
// and close note in the store, so dismissing it must be refused until the
// queued improvement is removed.
func TestEvolutionDismissFindingRefusesWhileQueued(t *testing.T) {
env := newEvoTestEnv(t)
env.seedRun(t, "dismiss-queue-source", "failed", "failed", "缺少单测")
env.seedPendingProposal(t, "dismiss-queue-current")
f := domain.EvoFinding{ID: "dismiss-queue-finding", ProjectID: "evo-p", AssetKind: domain.EvoAssetAgent, AssetID: env.agent.ID,
AssetName: env.agent.Name, Title: "排队的问题", Status: domain.EvoFindingOpen, SampleRunIDs: []string{"dismiss-queue-source"}}
if err := env.store.PutEvoFinding(f); err != nil {
t.Fatal(err)
}
queued := requestJSONAuthed[struct {
Status string `json:"status"`
QueueID string `json:"queueId"`
}](t, env.router, env.user, http.MethodPost, "/api/evolution/proposals", map[string]any{"findingId": f.ID}, http.StatusAccepted)
if queued.Status != "queued" || queued.QueueID == "" {
t.Fatalf("second finding on a busy asset must be queued: %+v", queued)
}

requestJSONAuthed[map[string]any](t, env.router, env.user, http.MethodPost, "/api/evolution/findings/"+f.ID+"/dismiss",
map[string]any{"reason": "误报"}, http.StatusConflict)
if stored, _ := env.store.EvoFinding(f.ID); stored.Status != domain.EvoFindingOpen || stored.CloseNote != "" {
t.Fatalf("a refused dismiss must not change the queued finding: %+v", stored)
}

requestJSONAuthed[domain.EvoQueueItem](t, env.router, env.user, http.MethodPost, "/api/evolution/queue/"+queued.QueueID+"/reject", nil, http.StatusOK)
requestJSONAuthed[domain.EvoFinding](t, env.router, env.user, http.MethodPost, "/api/evolution/findings/"+f.ID+"/dismiss",
map[string]any{"reason": "确认误报"}, http.StatusOK)
if stored, _ := env.store.EvoFinding(f.ID); stored.Status != domain.EvoFindingDismissed || stored.CloseNote != "确认误报" {
t.Fatalf("dismiss after removing the queued improvement = %+v", stored)
}
}
2 changes: 1 addition & 1 deletion web/app/evolution-review.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function evoReviewChangeHTML(m,p){
function evoReviewProblemsHTML(m,p){
const r=m.row,issues=evoStoryCurrentIssues(m,p);
const list=issues.map(issue=>`<button type="button" class="evo-review-problem" data-tooltip="${escapeHTML(issue.title)}" data-evo-related-finding="${escapeHTML(issue.f.id)}" data-cluster="${escapeHTML(issue.key)}" aria-pressed="${issue.f.id===r?.f.id&&issue.key===r?.key}">${evoReviewIcon('alert')}<span><b>${escapeHTML(issue.title)}</b><small>${issue.c.runs||0} 次运行</small></span>${evoReviewIcon('arrow-right')}</button>`).join('');
const records=r?`<details class="evo-detail-more" id="evoRunDetails"><summary>运行记录</summary><div id="evoRunPreview" class="evo-run-preview"></div><select class="kb-input" aria-label="运行结果" data-evo-record-status><option value="">全部结果</option><option value="failed">失败</option><option value="succeeded">成功</option><option value="reworked">返工后成功</option><option value="unavailable">记录不可用</option></select><div id="evoFindingRecords" aria-live="polite"></div></details><details class="evo-detail-more" id="evoDiagnosisDetails"><summary>诊断与处理</summary>${evoFindingStats(r)}<div class="evo-finding-actions">${evoIssueState(r.f)==='done'?`<span>${escapeHTML(r.f.closeNote||'已归档')}</span>`:`<button type="button" class="kb-btn small" data-evo-snooze="${escapeHTML(r.f.id)}" data-days="${evoSnoozed(r.f)?0:EVO_SNOOZE_DAYS}"${r.f.status!=='open'?' disabled':''}>${evoSnoozed(r.f)?'取消暂缓':'暂缓 7 天'}</button><button type="button" class="kb-btn quiet small" data-evo-dismiss="${escapeHTML(r.f.id)}">忽略</button>`}</div></details>`:'';
const records=r?`<details class="evo-detail-more" id="evoRunDetails"><summary>运行记录</summary><div id="evoRunPreview" class="evo-run-preview"></div><select class="kb-input" aria-label="运行结果" data-evo-record-status><option value="">全部结果</option><option value="failed">失败</option><option value="succeeded">成功</option><option value="reworked">返工后成功</option><option value="unavailable">记录不可用</option></select><div id="evoFindingRecords" aria-live="polite"></div></details><details class="evo-detail-more" id="evoDiagnosisDetails"><summary>诊断与处理</summary>${evoFindingStats(r)}<div class="evo-finding-actions">${evoIssueState(r.f)==='done'?`<span>${escapeHTML(r.f.closeNote||'已归档')}</span>`:`<button type="button" class="kb-btn small" data-evo-snooze="${escapeHTML(r.f.id)}" data-days="${evoSnoozed(r.f)?0:EVO_SNOOZE_DAYS}"${r.f.status!=='open'?' disabled':''}>${evoSnoozed(r.f)?'取消暂缓':'暂缓 7 天'}</button><button type="button" class="kb-btn quiet small" data-evo-dismiss="${escapeHTML(r.f.id)}"${r.f.status!=='open'?' disabled title="已进入改进流程或已关闭的问题不能忽略"':''}>忽略</button>`}</div></details>`:'';
return `<header class="evo-review-filebar"><span>${evoReviewIcon('alert')}问题</span><span class="evo-muted">${issues.length}</span></header>${list||'<div class="evo-review-empty">未关联问题</div>'}<div class="evo-review-records">${records}</div>`;
}
// 保留验证时的整次运行评分;待完成 / 阻塞不能被默认 score=0 画成失败。
Expand Down
2 changes: 1 addition & 1 deletion web/app/evolution-sop.js
Original file line number Diff line number Diff line change
Expand Up @@ -846,7 +846,7 @@ function evoSOPGrayTableHTML(rounds, expandedId) {
if (!rounds.length) {
return '<div class="kb-empty">暂无灰度轮次数据。优化完成后点击「开始灰度」,系统将在此持续记录旧版与候选版的对比数据。</div>';
}
const statusLabel = { running: ['灰度中', 'warn'], passed: ['通过待发布', 'ok'], published: ['已发布', 'ok'], failed: ['未通过', 'err'], aborted: ['已终止', ''] };
const statusLabel = { running: ['灰度中', 'warn'], passed: ['通过待发布', 'ok'], published: ['已发布', 'ok'], failed: ['未通过', 'err'], aborted: ['已终止', ''], rolled_back: ['已回滚', ''] };
const pair = (a, b, fmt) => `${escapeHTML(fmt(a))} → <b>${escapeHTML(fmt(b))}</b>`;
const rows = [...rounds].reverse().map(r => {
const [stLabel, stTone] = statusLabel[r.status] || [r.status || '灰度', ''];
Expand Down
Loading
Loading