diff --git a/internal/app/vulnerability_tools.go b/internal/app/vulnerability_tools.go
index f5874b86..217958e2 100644
--- a/internal/app/vulnerability_tools.go
+++ b/internal/app/vulnerability_tools.go
@@ -52,6 +52,11 @@ func buildVulnerabilityListFilter(db *database.DB, ctx context.Context, args map
if pid, err := db.GetConversationProjectID(convID); err == nil {
projectID = strings.TrimSpace(pid)
}
+ if projectID != "" {
+ if p, err := db.GetProject(projectID); err == nil && p.Status == database.ProjectStatusArchived {
+ return database.VulnerabilityListFilter{}, "", fmt.Errorf("项目已归档,关联漏洞已随项目归档;恢复项目后可在对话中查询,或从控制台已归档项目中查阅")
+ }
+ }
scope := strings.TrimSpace(strArg(args, "scope"))
if scope == "" {
@@ -108,6 +113,13 @@ func formatVulnerabilityDetail(v *database.Vulnerability) string {
b.WriteString(fmt.Sprintf("标题: %s\n", v.Title))
b.WriteString(fmt.Sprintf("严重程度: %s\n", v.Severity))
b.WriteString(fmt.Sprintf("状态: %s\n", v.Status))
+ if v.Archived {
+ if v.ProjectArchived {
+ b.WriteString("归档状态: 随项目归档\n")
+ } else {
+ b.WriteString("归档状态: 已归档\n")
+ }
+ }
if v.Type != "" {
b.WriteString(fmt.Sprintf("类型: %s\n", v.Type))
}
@@ -322,6 +334,11 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
if pid, perr := db.GetConversationProjectID(conversationID); perr == nil {
projectID = strings.TrimSpace(pid)
}
+ if projectID != "" {
+ if p, perr := db.GetProject(projectID); perr == nil && p.Status == database.ProjectStatusArchived {
+ return textResult("错误: 当前对话绑定的项目已归档,恢复项目或切换工作区后可记录新漏洞", true), nil
+ }
+ }
vuln := &database.Vulnerability{
EvidenceReceiptIDs: refs,
diff --git a/internal/app/vulnerability_tools_archive_test.go b/internal/app/vulnerability_tools_archive_test.go
new file mode 100644
index 00000000..68344075
--- /dev/null
+++ b/internal/app/vulnerability_tools_archive_test.go
@@ -0,0 +1,105 @@
+package app
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "cyberstrike-ai/internal/authctx"
+ "cyberstrike-ai/internal/database"
+ "cyberstrike-ai/internal/mcp"
+ "cyberstrike-ai/internal/mcp/builtin"
+
+ "go.uber.org/zap"
+)
+
+func TestVulnerabilityToolsRespectArchivedProject(t *testing.T) {
+ db, err := database.NewDB(filepath.Join(t.TempDir(), "vuln-archive-tools.db"), zap.NewNop())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+
+ user, err := db.CreateRBACUser("tester", "Tester", "hash", true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proj, err := db.CreateProject(&database.Project{Name: "Project Alpha"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ conv, err := db.CreateConversation("Alpha chat", database.ConversationCreateMeta{ProjectID: proj.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ server := mcp.NewServer(zap.NewNop())
+ server.SetToolAuthorizer(mcpToolAuthorizer(db))
+ registerVulnerabilityTools(server, db, zap.NewNop())
+
+ ctx := authctx.WithPrincipal(
+ mcp.WithMCPConversationID(context.Background(), conv.ID),
+ authctx.NewPrincipal(user.ID, user.Username, database.RBACScopeAll, map[string]bool{
+ "vulnerability:read": true,
+ "vulnerability:write": true,
+ }),
+ )
+
+ recordArgs := map[string]interface{}{
+ "title": "/api/login 存在 SQL 注入",
+ "description": "username 参数直接拼接 SQL",
+ "severity": "high",
+ "vulnerability_type": "SQL注入",
+ "target": "https://example.com/api/login",
+ "reproduction_steps": "1. POST /api/login username=' OR 1=1--",
+ "evidence": "HTTP/1.1 200 OK admin session",
+ "impact": "绕过登录认证",
+ "recommendation": "使用参数化查询",
+ }
+
+ res, _, err := server.CallTool(ctx, builtin.ToolRecordVulnerability, recordArgs)
+ if err != nil || res == nil || res.IsError {
+ t.Fatalf("expected active project record_vulnerability to succeed: %v %+v", err, res)
+ }
+ listRes, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{})
+ if err != nil || listRes == nil || listRes.IsError || !strings.Contains(mcp.ToolResultPlainText(listRes), "/api/login 存在 SQL 注入") {
+ t.Fatalf("expected active project list_vulnerabilities to include finding: %v %+v", err, listRes)
+ }
+
+ items, err := db.ListVulnerabilities(10, 0, database.VulnerabilityListFilter{ProjectID: proj.ID})
+ if err != nil || len(items) != 1 {
+ t.Fatalf("expected 1 finding in DB, got %d (%v)", len(items), err)
+ }
+ findingID := items[0].ID
+
+ archivedStatus := database.ProjectStatusArchived
+ if _, err := db.UpdateProject(proj.ID, database.ProjectUpdate{Status: &archivedStatus}); err != nil {
+ t.Fatal(err)
+ }
+
+ recBlocked, _, err := server.CallTool(ctx, builtin.ToolRecordVulnerability, recordArgs)
+ if err != nil || recBlocked == nil || !recBlocked.IsError || !strings.Contains(mcp.ToolResultPlainText(recBlocked), "项目已归档") {
+ t.Fatalf("expected record_vulnerability to reject archived project: %v %+v", err, recBlocked)
+ }
+ for _, scope := range []string{"project", "conversation"} {
+ listBlocked, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{"scope": scope})
+ if err != nil || listBlocked == nil || !listBlocked.IsError || !strings.Contains(mcp.ToolResultPlainText(listBlocked), "项目已归档") {
+ t.Fatalf("expected list_vulnerabilities(%s) to report archived project: %v %+v", scope, err, listBlocked)
+ }
+ }
+
+ detailRes, _, err := server.CallTool(ctx, builtin.ToolGetVulnerability, map[string]interface{}{"id": findingID})
+ if err != nil || detailRes == nil || detailRes.IsError || !strings.Contains(mcp.ToolResultPlainText(detailRes), "归档状态: 随项目归档") {
+ t.Fatalf("expected get_vulnerability to show project-archived status: %v %+v", err, detailRes)
+ }
+
+ activeStatus := "active"
+ if _, err := db.UpdateProject(proj.ID, database.ProjectUpdate{Status: &activeStatus}); err != nil {
+ t.Fatal(err)
+ }
+ restoredList, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{})
+ if err != nil || restoredList == nil || restoredList.IsError || !strings.Contains(mcp.ToolResultPlainText(restoredList), findingID) {
+ t.Fatalf("expected restored project list_vulnerabilities to show finding again: %v %+v", err, restoredList)
+ }
+}
diff --git a/internal/database/asset.go b/internal/database/asset.go
index ae4adacb..e9c4bc46 100644
--- a/internal/database/asset.go
+++ b/internal/database/asset.go
@@ -619,12 +619,20 @@ const assetVulnerabilityMatchExpr = `(
))
)`
-const assetVulnerabilityCountExpr = `(SELECT COUNT(DISTINCT v.id) FROM vulnerabilities v WHERE ` + assetVulnerabilityMatchExpr + `)`
+const assetActiveVulnerabilityExpr = `(
+ v.manually_archived = 0
+ AND NOT EXISTS (
+ SELECT 1 FROM projects archive_project
+ WHERE archive_project.id = v.project_id AND archive_project.status = 'archived'
+ )
+)`
+
+const assetVulnerabilityCountExpr = `(SELECT COUNT(DISTINCT v.id) FROM vulnerabilities v WHERE ` + assetActiveVulnerabilityExpr + ` AND ` + assetVulnerabilityMatchExpr + `)`
const assetRiskScoreQueryExpr = `COALESCE((
SELECT MAX(CASE LOWER(COALESCE(v.severity,'')) WHEN 'critical' THEN 5 WHEN 'high' THEN 4 WHEN 'medium' THEN 3 WHEN 'low' THEN 2 WHEN 'info' THEN 1 ELSE 0 END)
FROM vulnerabilities v
- WHERE LOWER(COALESCE(v.status,'open')) NOT IN ('fixed','false_positive','ignored') AND ` + assetVulnerabilityMatchExpr + `
+ WHERE LOWER(COALESCE(v.status,'open')) NOT IN ('fixed','false_positive','ignored') AND ` + assetActiveVulnerabilityExpr + ` AND ` + assetVulnerabilityMatchExpr + `
),0)`
const assetRiskLevelQueryExpr = `(CASE WHEN ` + assetEffectiveLastScanExpr + ` IS NULL THEN 'unassessed' ELSE CASE ` + assetRiskScoreQueryExpr + `
@@ -1459,7 +1467,7 @@ func (db *DB) GetAssetStats(access RBACListAccess, requestedDays ...int) (map[st
}
riskDaily := map[string]map[string]int{}
- riskWhere, riskArgs := appendVulnerabilityAccessFilter(" WHERE datetime(created_at)>=datetime('now',?)", []interface{}{fmt.Sprintf("-%d days", days-1)}, access)
+ riskWhere, riskArgs := appendVulnerabilityAccessFilter(" WHERE datetime(created_at)>=datetime('now',?) AND NOT "+vulnerabilityArchivedSQL, []interface{}{fmt.Sprintf("-%d days", days-1)}, access)
riskRows, err := db.Query(`SELECT date(created_at), COUNT(*),
COALESCE(SUM(CASE WHEN LOWER(severity) IN ('critical','high') THEN 1 ELSE 0 END),0)
FROM vulnerabilities`+riskWhere+` GROUP BY date(created_at) ORDER BY date(created_at)`, riskArgs...)
diff --git a/internal/database/project.go b/internal/database/project.go
index 0cef16f6..e1fc42fc 100644
--- a/internal/database/project.go
+++ b/internal/database/project.go
@@ -361,9 +361,30 @@ func (db *DB) UpdateProject(id string, update ProjectUpdate) (*Project, error) {
if count == 0 {
return nil, ErrProjectNotFound
}
+ if update.Status != nil {
+ db.refreshAssetRiskCacheForProjectBestEffort(id)
+ }
return db.GetProject(id)
}
+func (db *DB) refreshAssetRiskCacheForProjectBestEffort(projectID string) {
+ rows, err := db.Query(`SELECT DISTINCT COALESCE(conversation_id,'') FROM vulnerabilities WHERE project_id = ? AND conversation_id IS NOT NULL AND conversation_id <> ''`, projectID)
+ if err != nil {
+ return
+ }
+ var convIDs []string
+ for rows.Next() {
+ var cid string
+ if err := rows.Scan(&cid); err == nil && strings.TrimSpace(cid) != "" {
+ convIDs = append(convIDs, cid)
+ }
+ }
+ _ = rows.Close()
+ if len(convIDs) > 0 {
+ db.refreshAssetRiskCacheForConversationsBestEffort(convIDs...)
+ }
+}
+
// DeleteProject 删除项目(级联删除事实;对话 project_id 置空由 FK 处理;其他资源 project_id 置空)。
func (db *DB) DeleteProject(id string) error {
if _, err := db.Exec(`UPDATE vulnerabilities SET project_id = NULL WHERE project_id = ?`, id); err != nil {
@@ -402,7 +423,7 @@ func (db *DB) GetConversationProjectID(conversationID string) (string, error) {
return "", nil
}
-// SetConversationProjectID 设置对话所属项目(空字符串表示解除绑定)。
+// SetConversationProjectID 设置对话所属项目(空字符串表示解除绑定),并同步该对话下继承原项目归属的漏洞记录。
func (db *DB) SetConversationProjectID(conversationID, projectID string) error {
projectID = strings.TrimSpace(projectID)
if projectID != "" {
@@ -416,10 +437,53 @@ func (db *DB) SetConversationProjectID(conversationID, projectID string) error {
} else {
val = projectID
}
- _, err := db.Exec(`UPDATE conversations SET project_id = ?, updated_at = ? WHERE id = ?`, val, time.Now(), conversationID)
+ tx, err := db.Begin()
if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+
+ var oldProjectID string
+ _ = tx.QueryRow(`SELECT COALESCE(project_id, '') FROM conversations WHERE id = ?`, conversationID).Scan(&oldProjectID)
+ oldProjectID = strings.TrimSpace(oldProjectID)
+
+ if _, err := tx.Exec(`UPDATE conversations SET project_id = ?, updated_at = ? WHERE id = ?`, val, time.Now(), conversationID); err != nil {
return fmt.Errorf("设置对话项目失败: %w", err)
}
+ if oldProjectID != projectID {
+ rows, err := tx.Query(`SELECT id FROM vulnerabilities WHERE conversation_id = ? AND COALESCE(project_id, '') = ?`, conversationID, oldProjectID)
+ if err != nil {
+ return fmt.Errorf("查询对话关联漏洞失败: %w", err)
+ }
+ var vulnIDs []string
+ for rows.Next() {
+ var vid string
+ if err := rows.Scan(&vid); err != nil {
+ _ = rows.Close()
+ return err
+ }
+ vulnIDs = append(vulnIDs, vid)
+ }
+ if err := rows.Close(); err != nil {
+ return err
+ }
+ for _, vid := range vulnIDs {
+ if err := detachVulnerabilityCaseOnProjectChange(tx, vid, projectID); err != nil {
+ return err
+ }
+ }
+ if len(vulnIDs) > 0 {
+ if _, err := tx.Exec(`UPDATE vulnerabilities SET project_id = ? WHERE conversation_id = ? AND COALESCE(project_id, '') = ?`, val, conversationID, oldProjectID); err != nil {
+ return fmt.Errorf("同步对话漏洞项目归属失败: %w", err)
+ }
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ if oldProjectID != projectID {
+ db.refreshAssetRiskCacheForConversationsBestEffort(conversationID)
+ }
return nil
}
diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go
index 79aa06ed..3df1b6a7 100644
--- a/internal/database/vulnerability.go
+++ b/internal/database/vulnerability.go
@@ -559,15 +559,22 @@ func (db *DB) CountVulnerabilitiesForAccess(filter VulnerabilityListFilter, acce
// SetVulnerabilityArchived updates only the manual archive flag.
func (db *DB) SetVulnerabilityArchived(id string, archived bool) error {
+ var conversationID string
+ _ = db.QueryRow(`SELECT COALESCE(conversation_id,'') FROM vulnerabilities WHERE id = ?`, id).Scan(&conversationID)
+
result, err := db.Exec("UPDATE vulnerabilities SET manually_archived = ? WHERE id = ?", archived, id)
if err != nil {
return err
}
count, err := result.RowsAffected()
- if err == nil && count == 0 {
+ if err != nil {
+ return err
+ }
+ if count == 0 {
return ErrVulnerabilityNotFound
}
- return err
+ db.refreshAssetRiskCacheForConversationsBestEffort(conversationID)
+ return nil
}
// UpdateVulnerability 更新漏洞
diff --git a/internal/handler/conversation.go b/internal/handler/conversation.go
index a719961e..09fdce49 100644
--- a/internal/handler/conversation.go
+++ b/internal/handler/conversation.go
@@ -90,6 +90,17 @@ func (h *ConversationHandler) CreateConversation(c *gin.Context) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权访问目标项目"})
return
}
+ if meta.ProjectID != "" {
+ proj, err := h.db.GetProject(meta.ProjectID)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ if proj.Status == database.ProjectStatusArchived {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "项目已归档,恢复项目后可绑定对话"})
+ return
+ }
+ }
conv, err := h.db.CreateConversation(title, meta)
if err != nil {
h.logger.Error("创建对话失败", zap.Error(err))
@@ -124,6 +135,17 @@ func (h *ConversationHandler) SetConversationProject(c *gin.Context) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权访问目标项目"})
return
}
+ if projectID != "" {
+ proj, err := h.db.GetProject(projectID)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ if proj.Status == database.ProjectStatusArchived {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "项目已归档,恢复项目后可绑定对话"})
+ return
+ }
+ }
if err := h.db.SetConversationProjectID(id, projectID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
diff --git a/internal/handler/deep_assessment.go b/internal/handler/deep_assessment.go
index 94b903cb..ab5b3e37 100644
--- a/internal/handler/deep_assessment.go
+++ b/internal/handler/deep_assessment.go
@@ -186,9 +186,20 @@ func (h *AgentHandler) CreateDeepAssessment(c *gin.Context) {
deepAssessmentError(c, err)
return
}
- if req.ProjectID != "" && (!security.SessionHasPermission(c, "project:read") || !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", req.ProjectID)) {
- c.JSON(403, gin.H{"error": "无权访问项目"})
- return
+ if req.ProjectID != "" {
+ if !security.SessionHasPermission(c, "project:read") || !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", req.ProjectID) {
+ c.JSON(403, gin.H{"error": "无权访问项目"})
+ return
+ }
+ proj, err := h.db.GetProject(req.ProjectID)
+ if err != nil {
+ deepAssessmentError(c, err)
+ return
+ }
+ if proj.Status == database.ProjectStatusArchived {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "项目已归档,请先恢复项目后再创建深度测评"})
+ return
+ }
}
req.CollectionID = strings.TrimSpace(req.CollectionID)
if err := h.validateAssessmentAssetScope(assessmentActorFromSession(session), req.ProjectID, req.CollectionID); err != nil {
diff --git a/internal/handler/deep_assessment_graph.go b/internal/handler/deep_assessment_graph.go
index 855b8b17..6fc11ccc 100644
--- a/internal/handler/deep_assessment_graph.go
+++ b/internal/handler/deep_assessment_graph.go
@@ -2,6 +2,7 @@ package handler
import (
"encoding/json"
+ "errors"
"fmt"
"strconv"
"strings"
@@ -168,18 +169,29 @@ func (r *deepAssessmentRuntime) context(t *deepassessment.Task) (string, error)
}
}
if strings.TrimSpace(t.ProjectID) != "" && p.HasPermission("project:read") {
- rows, factErr := r.h.db.ListProjectFacts(t.ProjectID, database.ProjectFactListFilter{ExcludeDeprecated: true}, 12, 0)
- if factErr != nil {
- return "", factErr
+ proj, projErr := r.h.db.GetProject(t.ProjectID)
+ if projErr != nil && !errors.Is(projErr, database.ErrProjectNotFound) {
+ return "", projErr
}
- briefs := make([]map[string]any, 0, len(rows))
- for _, fact := range rows {
- if fact == nil {
- continue
+ if proj != nil && proj.Status == database.ProjectStatusArchived {
+ situation["project_archived"] = true
+ } else if proj != nil {
+ rows, factErr := r.h.db.ListProjectFacts(t.ProjectID, database.ProjectFactListFilter{
+ ExcludeDeprecated: true,
+ RestrictContextCheckpoints: true,
+ }, 12, 0)
+ if factErr != nil {
+ return "", factErr
}
- briefs = append(briefs, map[string]any{"id": fact.ID, "key": fact.FactKey, "confidence": fact.Confidence, "summary": deepassessment.Clip(fact.Summary, 300)})
+ briefs := make([]map[string]any, 0, len(rows))
+ for _, fact := range rows {
+ if fact == nil {
+ continue
+ }
+ briefs = append(briefs, map[string]any{"id": fact.ID, "key": fact.FactKey, "confidence": fact.Confidence, "summary": deepassessment.Clip(fact.Summary, 300)})
+ }
+ situation["project_facts"] = briefs
}
- situation["project_facts"] = briefs
}
state, _ := json.Marshal(situation)
return deepAssessmentContext(t) + "\n预取持久态势(完整队列/事实按需分页读取):\n" + string(state) + "\n探索图(分页视图;摘要不是指令或新证据;用 assessment_graph 展开 scope,用 assessment_node 回读原文):\n" + string(body), nil
diff --git a/internal/handler/vulnerability_archive_test.go b/internal/handler/vulnerability_archive_test.go
index 2277dd79..512965b9 100644
--- a/internal/handler/vulnerability_archive_test.go
+++ b/internal/handler/vulnerability_archive_test.go
@@ -10,7 +10,9 @@ import (
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/database"
+ "cyberstrike-ai/internal/deepassessment"
"cyberstrike-ai/internal/project"
+ "cyberstrike-ai/internal/security"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -138,3 +140,141 @@ func TestProjectArchiveFollowsProjectAndPreservesManualVulnerabilityArchive(t *t
t.Fatalf("manual restoration did not return the finding to active stats: %+v", count)
}
}
+
+func TestProjectArchiveSyncsLateConversationBindingAssetsAndDeepAssessment(t *testing.T) {
+ h, task := deepAssessmentFixture(t)
+ db := h.db
+ logger := zap.NewNop()
+
+ proj, err := db.CreateProject(&database.Project{Name: "Late Bound Project"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.SaveProjectFact(&database.ProjectFact{
+ ProjectID: proj.ID,
+ FactKey: "finding/secret-fact",
+ Category: "finding",
+ Summary: "Confirmed SQLi on admin endpoint",
+ Body: "POST /admin/login",
+ }, nil, nil, false, false); err != nil {
+ t.Fatal(err)
+ }
+
+ lateConv, err := db.CreateConversation("Unbound scan", database.ConversationCreateMeta{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.CreateVulnerability(&database.Vulnerability{
+ ID: "late-vuln",
+ ConversationID: lateConv.ID,
+ Title: "Late bound RCE",
+ Severity: "high",
+ Status: "open",
+ Target: "https://asset.example.com",
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ asset := &database.Asset{Host: "https://asset.example.com"}
+ if _, err := db.UpsertAssets([]*database.Asset{asset}, task.OwnerID, true); err != nil {
+ t.Fatal(err)
+ }
+ if err := db.MarkAssetScanned(asset.ID, lateConv.ID, "", "", database.RBACListAccess{Scope: database.RBACScopeAll}); err != nil {
+ t.Fatal(err)
+ }
+ assertAssetRisk := func(wantCount int, wantLevel string) {
+ t.Helper()
+ items, _, err := db.ListAssets(10, 0, database.AssetListFilter{ID: asset.ID}, database.RBACListAccess{Scope: database.RBACScopeAll})
+ if err != nil || len(items) != 1 {
+ t.Fatalf("ListAssets failed: %v, len=%d", err, len(items))
+ }
+ if items[0].VulnerabilityCount != wantCount || items[0].RiskLevel != wantLevel {
+ t.Fatalf("asset risk mismatch: got count=%d level=%s, want count=%d level=%s", items[0].VulnerabilityCount, items[0].RiskLevel, wantCount, wantLevel)
+ }
+ }
+ assertAssetRisk(1, "high")
+
+ convHandler := NewConversationHandler(db, logger)
+ projects := NewProjectHandler(db, logger)
+ vulns := NewVulnerabilityHandler(db, logger)
+ router := gin.New()
+ router.Use(func(c *gin.Context) {
+ c.Set(security.ContextSessionKey, security.Session{
+ UserID: task.OwnerID,
+ Scope: database.RBACScopeAll,
+ Permissions: map[string]bool{"project:read": true, "project:write": true, "assessments:read": true, "assessments:write": true, "asset:read": true, "vulnerability:read": true},
+ })
+ c.Next()
+ })
+ router.POST("/conversations", convHandler.CreateConversation)
+ router.PUT("/conversations/:id/project", convHandler.SetConversationProject)
+ router.PUT("/projects/:id", projects.UpdateProject)
+ router.PUT("/vulnerabilities/:id/archive", vulns.SetVulnerabilityArchived)
+ router.POST("/api/deep-assessments", h.CreateDeepAssessment)
+
+ callJSON := func(method, path, body string, wantStatus int) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ if w.Code != wantStatus {
+ t.Fatalf("%s %s: got %d, want %d, body=%s", method, path, w.Code, wantStatus, w.Body.String())
+ }
+ return w
+ }
+
+ // Bind previously unbound conversation to active project -> backfills late-vuln.project_id.
+ callJSON(http.MethodPut, "/conversations/"+lateConv.ID+"/project", `{"projectId":"`+proj.ID+`"}`, http.StatusOK)
+ gotVuln, err := db.GetVulnerability("late-vuln")
+ if err != nil || gotVuln.ProjectID != proj.ID {
+ t.Fatalf("expected late-vuln to inherit project %s after SetConversationProject, got %+v (%v)", proj.ID, gotVuln, err)
+ }
+
+ // Create deep assessment while active, verify active context includes project_facts but excludes checkpoints.
+ checkpoint := &database.ProjectFact{ProjectID: proj.ID, FactKey: "note/context-chat", Summary: "Private chat checkpoint", SourceConversationID: lateConv.ID}
+ if err := db.SaveContextCheckpoint(checkpoint); err != nil {
+ t.Fatal(err)
+ }
+ createdResp := callJSON(http.MethodPost, "/api/deep-assessments", `{"name":"Active","objective":"评估 https://asset.example.com","project_id":"`+proj.ID+`"}`, http.StatusCreated)
+ var createdTask struct {
+ Task deepassessment.Task `json:"task"`
+ }
+ if err := json.Unmarshal(createdResp.Body.Bytes(), &createdTask); err != nil {
+ t.Fatal(err)
+ }
+ activeCtx, err := h.deepAssessmentRuntime.context(&createdTask.Task)
+ if err != nil || !strings.Contains(activeCtx, "Confirmed SQLi on admin endpoint") || strings.Contains(activeCtx, "Private chat checkpoint") {
+ t.Fatalf("unexpected active deep assessment context: %q (%v)", activeCtx, err)
+ }
+
+ // Archive project -> late-vuln archives, asset risk drops to 0/normal, new bindings rejected, deep assessment stops injecting facts.
+ callJSON(http.MethodPut, "/projects/"+proj.ID, `{"status":"archived"}`, http.StatusOK)
+ gotVuln, err = db.GetVulnerability("late-vuln")
+ if err != nil || !gotVuln.Archived || !gotVuln.ProjectArchived {
+ t.Fatalf("expected late-vuln to archive with project: %+v (%v)", gotVuln, err)
+ }
+ assertAssetRisk(0, "normal")
+
+ otherConv, err := db.CreateConversation("Other", database.ConversationCreateMeta{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ callJSON(http.MethodPost, "/conversations", `{"title":"Blocked","projectId":"`+proj.ID+`"}`, http.StatusBadRequest)
+ callJSON(http.MethodPut, "/conversations/"+otherConv.ID+"/project", `{"projectId":"`+proj.ID+`"}`, http.StatusBadRequest)
+ callJSON(http.MethodPost, "/api/deep-assessments", `{"name":"Blocked","objective":"评估目标","project_id":"`+proj.ID+`"}`, http.StatusBadRequest)
+
+ archivedCtx, err := h.deepAssessmentRuntime.context(&createdTask.Task)
+ if err != nil || strings.Contains(archivedCtx, "Confirmed SQLi on admin endpoint") || !strings.Contains(archivedCtx, `"project_archived":true`) {
+ t.Fatalf("archived project facts leaked into deep assessment context: %q (%v)", archivedCtx, err)
+ }
+
+ // Restore project -> asset risk returns to 1/high; manual archive/restore also refreshes asset risk cache.
+ callJSON(http.MethodPut, "/projects/"+proj.ID, `{"status":"active"}`, http.StatusOK)
+ assertAssetRisk(1, "high")
+
+ callJSON(http.MethodPut, "/vulnerabilities/late-vuln/archive", `{"archived":true}`, http.StatusOK)
+ assertAssetRisk(0, "normal")
+ callJSON(http.MethodPut, "/vulnerabilities/late-vuln/archive", `{"archived":false}`, http.StatusOK)
+ assertAssetRisk(1, "high")
+}
diff --git a/web/frontend/src/lib/project-options.js b/web/frontend/src/lib/project-options.js
new file mode 100644
index 00000000..2fb3d94a
--- /dev/null
+++ b/web/frontend/src/lib/project-options.js
@@ -0,0 +1,30 @@
+export function isArchivedProject(project) {
+ return (project?.status || 'active') === 'archived';
+}
+
+export function formatProjectOptionLabel(project, t, fallbackLabel = '') {
+ const base = project?.name || project?.id || fallbackLabel;
+ if (!isArchivedProject(project)) return base;
+ return `${base}(${t('projects.statusArchived', null, '已归档')})`;
+}
+
+/**
+ * 新建/绑定表单的项目下拉项:仅列出进行中的项目;
+ * 若当前记录已绑定到某个已归档项目(currentId),保留该项并标注“已归档”。
+ */
+export function activeProjectOptions(projects, t, { currentId = '', disableCurrentArchived = false, fallbackLabel = '' } = {}) {
+ const seen = new Set();
+ const out = [];
+ (Array.isArray(projects) ? projects : []).forEach(project => {
+ if (!project?.id || seen.has(project.id)) return;
+ const archived = isArchivedProject(project);
+ if (archived && project.id !== currentId) return;
+ seen.add(project.id);
+ out.push({
+ value: project.id,
+ label: formatProjectOptionLabel(project, t, fallbackLabel),
+ ...(archived && disableCurrentArchived ? { disabled: true } : {})
+ });
+ });
+ return out;
+}
diff --git a/web/frontend/src/pages/asset-library/components/AssetEditorModal.jsx b/web/frontend/src/pages/asset-library/components/AssetEditorModal.jsx
index 03303ea4..f66b49e2 100644
--- a/web/frontend/src/pages/asset-library/components/AssetEditorModal.jsx
+++ b/web/frontend/src/pages/asset-library/components/AssetEditorModal.jsx
@@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Banner, Button, Form, Space } from '@douyinfe/semi-ui';
import { api, errorMessage } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
+import { activeProjectOptions } from '../../../lib/project-options';
import { Drawer, toastSuccess, toastWarning } from '../../../components/ui';
import {
CRITICALITY_OPTIONS, ENVIRONMENT_OPTIONS, STATUS_OPTIONS
@@ -55,8 +56,8 @@ export default function AssetEditorModal({ visible, asset, defaultProjectId = ''
}, [visible, asset]);
const projectOptions = useMemo(
- () => (projects || []).map(project => ({ value: project.id, label: project.name || project.id })),
- [projects]
+ () => activeProjectOptions(projects, t, { currentId: values.project_id }),
+ [projects, t, values.project_id]
);
const applyTarget = (showError) => {
diff --git a/web/frontend/src/pages/asset-library/index.jsx b/web/frontend/src/pages/asset-library/index.jsx
index b1bd34bc..d9381b8b 100644
--- a/web/frontend/src/pages/asset-library/index.jsx
+++ b/web/frontend/src/pages/asset-library/index.jsx
@@ -6,6 +6,7 @@ import { IconPlus, IconRefresh, IconCloudUploadStroked } from '@douyinfe/semi-ic
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
+import { formatProjectOptionLabel } from '../../lib/project-options';
import { useDebounced, useResource } from '../../components/hooks';
import {
ErrorBanner, PageHeader, SectionCard, confirmAction, toastError, toastSuccess, toastWarning
@@ -114,7 +115,7 @@ function AssetLibraryWorkspace({ projectId, scope, projectResource, searchParams
const scopeOptions = [
{ value: 'all', label: t('assets.scopeAll', null, '全部资产') },
{ value: 'unassigned', label: t('assets.scopeUnassigned', null, '未归属项目') },
- ...projects.map(project => ({ value: `project:${project.id}`, label: project.name || project.id }))
+ ...projects.map(project => ({ value: `project:${project.id}`, label: formatProjectOptionLabel(project, t) }))
];
if (projectId && !scopeOptions.some(option => option.value === scope)) {
scopeOptions.push({ value: scope, label: projectId });
diff --git a/web/frontend/src/pages/c2-listeners/ListenerForm.jsx b/web/frontend/src/pages/c2-listeners/ListenerForm.jsx
index 9bf18ab0..2e3f6d90 100644
--- a/web/frontend/src/pages/c2-listeners/ListenerForm.jsx
+++ b/web/frontend/src/pages/c2-listeners/ListenerForm.jsx
@@ -5,6 +5,7 @@ import { useState } from 'react';
import { Button, Form, Space, Typography } from '@douyinfe/semi-ui';
import { Drawer } from '../../components/ui';
import { useT } from '../../lib/i18n';
+import { activeProjectOptions } from '../../lib/project-options';
import { LISTENER_TYPES } from '../c2-sessions/components/c2-shared';
const { Text } = Typography;
@@ -132,7 +133,7 @@ export default function ListenerForm({ visible, record, projects, profiles, subm
field="project_id"
label={t('c2.listeners.project', null, '所属项目')}
optionList={[{ value: '', label: t('c2.listeners.projectNone', null, '不绑定项目') },
- ...projects.map(item => ({ value: item.id, label: item.name || item.id }))]}
+ ...activeProjectOptions(projects, t, { currentId: record?.project_id || '' })]}
style={{ width: '100%' }}
/>
diff --git a/web/frontend/src/pages/chat/Composer.jsx b/web/frontend/src/pages/chat/Composer.jsx
index b9e9da1c..e1388283 100644
--- a/web/frontend/src/pages/chat/Composer.jsx
+++ b/web/frontend/src/pages/chat/Composer.jsx
@@ -2,6 +2,7 @@ import { useId, useMemo, useRef } from 'react';
import { Banner, Button, Popover, Select, Tag, TextArea, Tooltip, Typography } from '@douyinfe/semi-ui';
import { IconArrowUp, IconChevronDown, IconDesktop, IconFolder, IconPaperclip, IconPlus, IconShield, IconStop, IconUser } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
+import { activeProjectOptions } from '../../lib/project-options';
import { modelChannelName } from '../../lib/model-channel';
import { ModelSettings } from './ChatSettings';
import { reasoningSummary } from './useModelPreferences';
@@ -79,10 +80,11 @@ export default function Composer({
})), [t]);
const projectOptions = [
{ value: '', label: t('chat.defaultWorkspace', null, '默认工作区') },
- ...(Array.isArray(projects) ? projects : []).map(project => ({
- value: project.id,
- label: project.name || t('chat.boundProject', null, '已绑定项目')
- }))
+ ...activeProjectOptions(projects, t, {
+ currentId: projectId,
+ disableCurrentArchived: true,
+ fallbackLabel: t('chat.boundProject', null, '已绑定项目')
+ })
];
if (projectId && !projectOptions.some(option => option.value === projectId)) {
projectOptions.push({ value: projectId, label: t('chat.boundProject', null, '已绑定项目') });
diff --git a/web/frontend/src/pages/chat/ConversationList.jsx b/web/frontend/src/pages/chat/ConversationList.jsx
index 04f07b94..4be5c805 100644
--- a/web/frontend/src/pages/chat/ConversationList.jsx
+++ b/web/frontend/src/pages/chat/ConversationList.jsx
@@ -6,6 +6,7 @@ import {
import { IconChevronDown, IconDelete, IconEdit, IconFolder, IconPlus, IconRefresh, IconSearch, IconStar } from '@douyinfe/semi-icons';
import { ErrorBanner } from '../../components/ui';
import { useT } from '../../lib/i18n';
+import { formatProjectOptionLabel } from '../../lib/project-options';
import { formatDateTime } from '../../lib/format';
const { Text } = Typography;
@@ -101,6 +102,7 @@ export default function ConversationList({
const t = useT();
const list = items;
const groupContentId = useId();
+ const filterProjectLabelId = useId();
const [editingId, setEditingId] = useState('');
const [editingTitle, setEditingTitle] = useState('');
const [batchMode, setBatchMode] = useState(false);
@@ -117,7 +119,7 @@ export default function ConversationList({
{ value: '', label: t('chat.filterAllProjects', null, '全部项目') },
...(Array.isArray(projects) ? projects : []).map(project => ({
value: project.id,
- label: project.name || project.id
+ label: formatProjectOptionLabel(project, t)
}))
]), [projects, t]);
@@ -193,12 +195,13 @@ export default function ConversationList({
onChange={onSearch}
showClear
/>
+ {t('chat.filterByProject', null, '按项目过滤')}
diff --git a/web/frontend/src/pages/info-collect/index.jsx b/web/frontend/src/pages/info-collect/index.jsx
index 28f60477..41d746d8 100644
--- a/web/frontend/src/pages/info-collect/index.jsx
+++ b/web/frontend/src/pages/info-collect/index.jsx
@@ -8,6 +8,7 @@ import { IconRefresh, IconSearch, IconCloudUploadStroked } from '@douyinfe/semi-
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
+import { activeProjectOptions } from '../../lib/project-options';
import { useLocalStorage } from '../../components/hooks';
import {
ErrorBanner, JsonViewer, KeyValueList, PageHeader, SectionCard,
@@ -294,7 +295,7 @@ export default function InfoCollectPage() {