diff --git a/internal/app/app.go b/internal/app/app.go
index 4e9bea3c..13faaad9 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -1102,6 +1102,9 @@ func setupRoutes(
protected.GET("/assets", assetHandler.List)
protected.GET("/assets/selection", assetHandler.Selection)
protected.GET("/assets/stats", assetHandler.Stats)
+ protected.GET("/assets/collections", assetHandler.ListCollections)
+ protected.GET("/assets/collections/:id", assetHandler.GetCollection)
+ protected.GET("/assets/:id/facts", assetHandler.Facts)
protected.POST("/assets/import", assetHandler.Import)
protected.POST("/assets/scan-links", assetHandler.RecordScans)
protected.PUT("/assets/bulk", assetHandler.BulkUpdate)
diff --git a/internal/app/project_fact_tools.go b/internal/app/project_fact_tools.go
index 1a301e72..d1e4b678 100644
--- a/internal/app/project_fact_tools.go
+++ b/internal/app/project_fact_tools.go
@@ -78,9 +78,13 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
},
"confidence": map[string]interface{}{
"type": "string",
- "description": "confirmed | tentative | deprecated",
+ "description": "confirmed | tentative | deprecated。升级为 confirmed 必须同时提供 confirmation_note。",
"enum": []string{"confirmed", "tentative", "deprecated"},
},
+ "confirmation_note": map[string]interface{}{
+ "type": "string",
+ "description": "把事实标为 confirmed 时的审核说明。省略则不能从其他可信度升级为已确认。",
+ },
"pinned": map[string]interface{}{
"type": "boolean",
"description": "是否优先出现在黑板索引",
@@ -89,6 +93,16 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
"type": "string",
"description": "可选:关联的漏洞记录 ID",
},
+ "asset_ids": map[string]interface{}{
+ "type": "array",
+ "description": "可选:这条事实对应的资产 ID。传入后替换原关联;不传则保留。已确认且同时有成功工具回执时,计入资产观察覆盖。",
+ "items": map[string]interface{}{"type": "string"},
+ },
+ "execution_ids": map[string]interface{}{
+ "type": "array",
+ "description": "可选:支持这条事实的成功工具执行 ID(tool_executions.id)。传入后替换原关联;不传则保留。",
+ "items": map[string]interface{}{"type": "string"},
+ },
"links": map[string]interface{}{
"type": "array",
"description": "可选:关系边(from → 当前 fact)。finding 至少 1 条 {from:target/*, type:discovered_on};finding 上记录 exploit 用 {from:exploit/*, type:exploits}。省略保留已有边;传 [] 清空全部关系边。",
@@ -141,11 +155,14 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
Confidence: strArg(args, "confidence"),
Pinned: boolArg(args, "pinned"),
RelatedVulnerabilityID: strArg(args, "related_vulnerability_id"),
+ ConfirmationNote: strArg(args, "confirmation_note"),
}
if convID := mcpAuthorizationConversationID(ctx); convID != "" {
f.SourceConversationID = convID
}
- created, err := db.UpsertProjectFact(f)
+ _, hasAssets := args["asset_ids"]
+ _, hasExecutions := args["execution_ids"]
+ created, err := db.SaveProjectFact(f, stringListArg(args["asset_ids"]), stringListArg(args["execution_ids"]), hasAssets, hasExecutions)
if err != nil {
return textResult("错误: "+err.Error(), true), nil
}
@@ -397,6 +414,20 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
}
}
+func stringListArg(raw interface{}) []string {
+ items, ok := raw.([]interface{})
+ if !ok {
+ return nil
+ }
+ out := make([]string, 0, len(items))
+ for _, item := range items {
+ if text, ok := item.(string); ok {
+ out = append(out, text)
+ }
+ }
+ return out
+}
+
func strArg(args map[string]interface{}, key string) string {
if v, ok := args[key].(string); ok {
return v
diff --git a/internal/database/asset.go b/internal/database/asset.go
index a379b720..c2c8bbbc 100644
--- a/internal/database/asset.go
+++ b/internal/database/asset.go
@@ -93,9 +93,11 @@ type AssetListFilter struct {
}
type AssetImportResult struct {
- Created int `json:"created"`
- Updated int `json:"updated"`
- Skipped int `json:"skipped"`
+ Created int `json:"created"`
+ Updated int `json:"updated"`
+ Skipped int `json:"skipped"`
+ AppliedIDs []string `json:"-"`
+ Collection *AssetCollection `json:"collection,omitempty"`
}
func normalizeAsset(a *Asset) {
@@ -365,6 +367,7 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
}
}
result.Created++
+ result.AppliedIDs = append(result.AppliedIDs, asset.ID)
continue
}
if err != nil {
@@ -408,6 +411,7 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
}
}
result.Updated++
+ result.AppliedIDs = append(result.AppliedIDs, existingID)
}
if err := tx.Commit(); err != nil {
return result, err
@@ -1326,6 +1330,20 @@ func (db *DB) GetAssetStats(access RBACListAccess, requestedDays ...int) (map[st
coverage["rate"], coverage["recent_rate"] = 0, 0
}
stats["coverage"] = coverage
+ observedTotal, observed, err := db.ObservationCoverage(access, "")
+ if err != nil {
+ return nil, err
+ }
+ observation := map[string]interface{}{
+ "total": observedTotal, "observed": observed,
+ "meaning": "已有观察证据的资产。成功原始回执支持的测评观察,或带成功工具回执的已确认项目事实,同一资产只计一次。这不是扫描覆盖。",
+ }
+ if observedTotal > 0 {
+ observation["rate"] = int(float64(observed) / float64(observedTotal) * 100)
+ } else {
+ observation["rate"] = 0
+ }
+ stats["observation"] = observation
assetDaily := map[string]map[string]int{}
trendWhere, trendArgs := appendAssetAccess(" WHERE datetime(first_seen_at)>=datetime('now',?)", []interface{}{fmt.Sprintf("-%d days", days-1)}, access, "assets")
diff --git a/internal/database/asset_collection.go b/internal/database/asset_collection.go
new file mode 100644
index 00000000..7808d424
--- /dev/null
+++ b/internal/database/asset_collection.go
@@ -0,0 +1,214 @@
+package database
+
+import (
+ "database/sql"
+ "fmt"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/google/uuid"
+)
+
+// AssetCollection is a project-owned set of existing assets.
+type AssetCollection struct {
+ ID string `json:"id"`
+ ProjectID string `json:"project_id"`
+ Name string `json:"name"`
+ Source string `json:"source,omitempty"`
+ SourceQuery string `json:"source_query,omitempty"`
+ MemberCount int `json:"member_count"`
+ Observed int `json:"observed"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+const observationEvidenceMeaning = "已有观察证据:成功原始回执支持的测评观察,或带成功工具回执的已确认项目事实。同一资产只计一次。这不是扫描覆盖,也不表示没有漏洞。"
+
+// An asset counts once when either evidence path is present.
+func observationAssetPredicate(assetIDExpr, projectClause string) string {
+ return `(
+ EXISTS (
+ SELECT 1 FROM deep_assessment_facts f
+ WHERE f.confidence='observed'
+ AND EXISTS (SELECT 1 FROM json_each(f.assets_json) j WHERE j.value=` + assetIDExpr + `)
+ AND EXISTS (
+ SELECT 1 FROM json_each(f.evidence_json) e
+ JOIN deep_assessment_calls c ON c.id=e.value
+ WHERE c.task_id=f.task_id AND c.step_id=f.step_id AND c.status='completed'
+ AND c.tool NOT GLOB 'assessment_*'
+ AND c.tool NOT IN ('record_vulnerability','list_vulnerabilities','get_vulnerability')
+ )
+ )
+ OR EXISTS (
+ SELECT 1 FROM project_fact_assets pa
+ JOIN project_facts pf ON pf.id=pa.fact_id AND pf.confidence='confirmed'
+ JOIN project_fact_receipts pr ON pr.fact_id=pf.id
+ JOIN tool_executions te ON te.id=pr.execution_id AND te.status='completed'
+ WHERE pa.asset_id=` + assetIDExpr + projectClause + `
+ )
+ )`
+}
+
+// ObservationCoverage counts accessible assets, or the members of one collection.
+// total is the population; observed is how many of them have observation evidence.
+func (db *DB) ObservationCoverage(access RBACListAccess, collectionID string) (int, int, error) {
+ collectionID = strings.TrimSpace(collectionID)
+ var query string
+ var args []interface{}
+ if collectionID == "" {
+ query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", "") + ` THEN 1 ELSE 0 END),0) FROM assets WHERE 1=1`
+ query, args = appendAssetAccess(query, nil, access, "assets")
+ } else {
+ query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", "") + ` THEN 1 ELSE 0 END),0)
+ FROM asset_collection_members m JOIN assets ON assets.id=m.asset_id WHERE m.collection_id=?`
+ args = []interface{}{collectionID}
+ query, args = appendAssetAccess(query, args, access, "assets")
+ }
+ var total, observed int
+ err := db.QueryRow(query, args...).Scan(&total, &observed)
+ return total, observed, err
+}
+
+// ObservationCoverageVisible applies the caller's project read boundary to shared facts.
+func (db *DB) ObservationCoverageVisible(access RBACListAccess, vis FactVisibility, collectionID string) (int, int, error) {
+ clause, clauseArgs := vis.projectSQL("pf")
+ collectionID = strings.TrimSpace(collectionID)
+ var query string
+ args := append([]any{}, clauseArgs...)
+ if collectionID == "" {
+ query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", clause) + ` THEN 1 ELSE 0 END),0) FROM assets WHERE 1=1`
+ query, args = appendAssetAccess(query, args, access, "assets")
+ } else {
+ query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", clause) + ` THEN 1 ELSE 0 END),0)
+ FROM asset_collection_members m JOIN assets ON assets.id=m.asset_id WHERE m.collection_id=?`
+ args = append(args, collectionID)
+ query, args = appendAssetAccess(query, args, access, "assets")
+ }
+ var total, observed int
+ err := db.QueryRow(query, args...).Scan(&total, &observed)
+ return total, observed, err
+}
+
+func (db *DB) CreateAssetCollection(projectID, name, source, sourceQuery, owner string, assetIDs []string) (*AssetCollection, error) {
+ projectID = strings.TrimSpace(projectID)
+ name = strings.TrimSpace(name)
+ if projectID == "" {
+ return nil, fmt.Errorf("资产集合必须属于项目")
+ }
+ if name == "" {
+ return nil, fmt.Errorf("资产集合名称不能为空")
+ }
+ if utf8.RuneCountInString(name) > 120 {
+ name = string([]rune(name)[:120])
+ }
+ var projectExists int
+ if err := db.QueryRow(`SELECT COUNT(*) FROM projects WHERE id=?`, projectID).Scan(&projectExists); err != nil {
+ return nil, err
+ }
+ if projectExists != 1 {
+ return nil, fmt.Errorf("项目不存在")
+ }
+ now := time.Now().UTC()
+ id := uuid.NewString()
+ tx, err := db.Begin()
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+ if _, err = tx.Exec(`INSERT INTO asset_collections(id,project_id,name,source,source_query,created_by,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)`,
+ id, projectID, name, strings.TrimSpace(source), strings.TrimSpace(sourceQuery), strings.TrimSpace(owner), now, now); err != nil {
+ return nil, err
+ }
+ members, err := insertCollectionMembers(tx, id, projectID, assetIDs, now)
+ if err != nil {
+ return nil, err
+ }
+ if err = tx.Commit(); err != nil {
+ return nil, err
+ }
+ return &AssetCollection{ID: id, ProjectID: projectID, Name: name, Source: strings.TrimSpace(source), SourceQuery: strings.TrimSpace(sourceQuery), MemberCount: members, CreatedAt: now, UpdatedAt: now}, nil
+}
+
+func insertCollectionMembers(tx *sql.Tx, collectionID, projectID string, assetIDs []string, now time.Time) (int, error) {
+ seen := map[string]bool{}
+ n := 0
+ for _, id := range assetIDs {
+ id = strings.TrimSpace(id)
+ if id == "" || seen[id] {
+ continue
+ }
+ seen[id] = true
+ var assetProject string
+ err := tx.QueryRow(`SELECT COALESCE(project_id,'') FROM assets WHERE id=?`, id).Scan(&assetProject)
+ if err == sql.ErrNoRows {
+ continue
+ }
+ if err != nil {
+ return 0, err
+ }
+ if assetProject != "" && assetProject != projectID {
+ continue
+ }
+ if _, err = tx.Exec(`INSERT OR IGNORE INTO asset_collection_members(collection_id,asset_id,created_at) VALUES(?,?,?)`, collectionID, id, now); err != nil {
+ return 0, err
+ }
+ n++
+ }
+ return n, nil
+}
+
+func (db *DB) ListAssetCollections(projectID string) ([]AssetCollection, error) {
+ rows, err := db.Query(`SELECT id,project_id,name,source,source_query,created_at,updated_at,
+ (SELECT COUNT(*) FROM asset_collection_members m WHERE m.collection_id=asset_collections.id)
+ FROM asset_collections WHERE project_id=? ORDER BY updated_at DESC, id`, strings.TrimSpace(projectID))
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []AssetCollection{}
+ for rows.Next() {
+ var item AssetCollection
+ if err = rows.Scan(&item.ID, &item.ProjectID, &item.Name, &item.Source, &item.SourceQuery, &item.CreatedAt, &item.UpdatedAt, &item.MemberCount); err != nil {
+ return nil, err
+ }
+ out = append(out, item)
+ }
+ return out, rows.Err()
+}
+
+func (db *DB) GetAssetCollection(id string) (*AssetCollection, error) {
+ var item AssetCollection
+ err := db.QueryRow(`SELECT id,project_id,name,source,source_query,created_at,updated_at,
+ (SELECT COUNT(*) FROM asset_collection_members m WHERE m.collection_id=asset_collections.id)
+ FROM asset_collections WHERE id=?`, strings.TrimSpace(id)).Scan(&item.ID, &item.ProjectID, &item.Name, &item.Source, &item.SourceQuery, &item.CreatedAt, &item.UpdatedAt, &item.MemberCount)
+ if err != nil {
+ return nil, err
+ }
+ _, observed, err := db.ObservationCoverage(RBACListAccess{Scope: RBACScopeAll}, item.ID)
+ if err != nil {
+ return nil, err
+ }
+ item.Observed = observed
+ return &item, nil
+}
+
+func (db *DB) CollectionMemberIDs(id string, limit int) ([]string, error) {
+ if limit <= 0 || limit > 5000 {
+ limit = 5000
+ }
+ rows, err := db.Query(`SELECT asset_id FROM asset_collection_members WHERE collection_id=? ORDER BY created_at, asset_id LIMIT ?`, strings.TrimSpace(id), limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []string{}
+ for rows.Next() {
+ var assetID string
+ if err = rows.Scan(&assetID); err != nil {
+ return nil, err
+ }
+ out = append(out, assetID)
+ }
+ return out, rows.Err()
+}
diff --git a/internal/database/batch_task.go b/internal/database/batch_task.go
index fee35ad7..7c2917f8 100644
--- a/internal/database/batch_task.go
+++ b/internal/database/batch_task.go
@@ -24,6 +24,7 @@ type BatchTaskQueueRow struct {
LastScheduleError sql.NullString
LastRunError sql.NullString
ProjectID sql.NullString
+ CollectionID sql.NullString
Concurrency sql.NullInt64
Status string
CreatedAt time.Time
@@ -110,7 +111,7 @@ func (db *DB) CreateBatchQueue(
return tx.Commit()
}
-const batchQueueSelectColumns = `id, title, role, agent_mode, hitl_policy, schedule_mode, cron_expr, next_run_at, schedule_enabled, last_schedule_trigger_at, last_schedule_error, last_run_error, project_id, concurrency, status, created_at, started_at, completed_at, current_index`
+const batchQueueSelectColumns = `id, title, role, agent_mode, hitl_policy, schedule_mode, cron_expr, next_run_at, schedule_enabled, last_schedule_trigger_at, last_schedule_error, last_run_error, project_id, concurrency, status, created_at, started_at, completed_at, current_index, collection_id`
// GetBatchQueue 获取批量任务队列
func (db *DB) GetBatchQueue(queueID string) (*BatchTaskQueueRow, error) {
@@ -119,7 +120,7 @@ func (db *DB) GetBatchQueue(queueID string) (*BatchTaskQueueRow, error) {
err := db.QueryRow(
"SELECT "+batchQueueSelectColumns+" FROM batch_task_queues WHERE id = ?",
queueID,
- ).Scan(&row.ID, &row.Title, &row.Role, &row.AgentMode, &row.HITLPolicy, &row.ScheduleMode, &row.CronExpr, &row.NextRunAt, &row.ScheduleEnabled, &row.LastScheduleTriggerAt, &row.LastScheduleError, &row.LastRunError, &row.ProjectID, &row.Concurrency, &row.Status, &createdAt, &row.StartedAt, &row.CompletedAt, &row.CurrentIndex)
+ ).Scan(&row.ID, &row.Title, &row.Role, &row.AgentMode, &row.HITLPolicy, &row.ScheduleMode, &row.CronExpr, &row.NextRunAt, &row.ScheduleEnabled, &row.LastScheduleTriggerAt, &row.LastScheduleError, &row.LastRunError, &row.ProjectID, &row.Concurrency, &row.Status, &createdAt, &row.StartedAt, &row.CompletedAt, &row.CurrentIndex, &row.CollectionID)
if err == sql.ErrNoRows {
return nil, nil
}
@@ -154,7 +155,7 @@ func (db *DB) GetAllBatchQueues() ([]*BatchTaskQueueRow, error) {
for rows.Next() {
var row BatchTaskQueueRow
var createdAt string
- if err := rows.Scan(&row.ID, &row.Title, &row.Role, &row.AgentMode, &row.HITLPolicy, &row.ScheduleMode, &row.CronExpr, &row.NextRunAt, &row.ScheduleEnabled, &row.LastScheduleTriggerAt, &row.LastScheduleError, &row.LastRunError, &row.ProjectID, &row.Concurrency, &row.Status, &createdAt, &row.StartedAt, &row.CompletedAt, &row.CurrentIndex); err != nil {
+ if err := rows.Scan(&row.ID, &row.Title, &row.Role, &row.AgentMode, &row.HITLPolicy, &row.ScheduleMode, &row.CronExpr, &row.NextRunAt, &row.ScheduleEnabled, &row.LastScheduleTriggerAt, &row.LastScheduleError, &row.LastRunError, &row.ProjectID, &row.Concurrency, &row.Status, &createdAt, &row.StartedAt, &row.CompletedAt, &row.CurrentIndex, &row.CollectionID); err != nil {
return nil, fmt.Errorf("扫描批量任务队列失败: %w", err)
}
parsedTime, parseErr := time.Parse("2006-01-02 15:04:05", createdAt)
@@ -226,7 +227,7 @@ func (db *DB) ListBatchQueuesForAccess(limit, offset int, status, keyword, userI
for rows.Next() {
var row BatchTaskQueueRow
var createdAt string
- if err := rows.Scan(&row.ID, &row.Title, &row.Role, &row.AgentMode, &row.HITLPolicy, &row.ScheduleMode, &row.CronExpr, &row.NextRunAt, &row.ScheduleEnabled, &row.LastScheduleTriggerAt, &row.LastScheduleError, &row.LastRunError, &row.ProjectID, &row.Concurrency, &row.Status, &createdAt, &row.StartedAt, &row.CompletedAt, &row.CurrentIndex); err != nil {
+ if err := rows.Scan(&row.ID, &row.Title, &row.Role, &row.AgentMode, &row.HITLPolicy, &row.ScheduleMode, &row.CronExpr, &row.NextRunAt, &row.ScheduleEnabled, &row.LastScheduleTriggerAt, &row.LastScheduleError, &row.LastRunError, &row.ProjectID, &row.Concurrency, &row.Status, &createdAt, &row.StartedAt, &row.CompletedAt, &row.CurrentIndex, &row.CollectionID); err != nil {
return nil, fmt.Errorf("扫描批量任务队列失败: %w", err)
}
parsedTime, parseErr := time.Parse("2006-01-02 15:04:05", createdAt)
@@ -380,7 +381,7 @@ func (db *DB) UpdateBatchTaskStatus(queueID, taskID, status string, conversation
args = append(args, now)
}
- if status == "completed" || status == "failed" || status == "cancelled" {
+ if status == "completed" || status == "failed" || status == "cancelled" || status == "blocked" {
updates = append(updates, "completed_at = COALESCE(completed_at, ?)")
args = append(args, now)
}
diff --git a/internal/database/project.go b/internal/database/project.go
index 44080c9b..93a3eed6 100644
--- a/internal/database/project.go
+++ b/internal/database/project.go
@@ -54,6 +54,9 @@ type ProjectFact struct {
SourceMessageID string `json:"source_message_id,omitempty"`
Pinned bool `json:"pinned"`
RelatedVulnerabilityID string `json:"related_vulnerability_id,omitempty"`
+ ConfirmationNote string `json:"confirmation_note,omitempty"`
+ AssetIDs []string `json:"asset_ids,omitempty"`
+ ExecutionIDs []string `json:"execution_ids,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
@@ -400,7 +403,7 @@ func (db *DB) SetConversationProjectID(conversationID, projectID string) error {
func (db *DB) ListProjectFactsForIndex(projectID string, includeDeprecated bool, conversationIDs ...string) ([]*ProjectFact, error) {
query := `SELECT id, project_id, fact_key, category, summary, '', confidence,
COALESCE(source_conversation_id,''), COALESCE(source_message_id,''), pinned,
- COALESCE(related_vulnerability_id,''), created_at, updated_at
+ COALESCE(related_vulnerability_id,''), COALESCE(confirmation_note,''), created_at, updated_at
FROM project_facts WHERE project_id = ?`
args := []interface{}{projectID}
if len(conversationIDs) > 0 {
@@ -427,7 +430,7 @@ func (db *DB) ListProjectFacts(projectID string, filter ProjectFactListFilter, l
}
query := `SELECT id, project_id, fact_key, category, summary, COALESCE(body,''), confidence,
COALESCE(source_conversation_id,''), COALESCE(source_message_id,''), pinned,
- COALESCE(related_vulnerability_id,''), created_at, updated_at
+ COALESCE(related_vulnerability_id,''), COALESCE(confirmation_note,''), created_at, updated_at
FROM project_facts WHERE project_id = ?`
args := []interface{}{projectID}
if filter.RestrictContextCheckpoints {
@@ -475,7 +478,7 @@ func (db *DB) GetProjectFactByKey(projectID, factKey string) (*ProjectFact, erro
row := db.QueryRow(
`SELECT id, project_id, fact_key, category, summary, COALESCE(body,''), confidence,
COALESCE(source_conversation_id,''), COALESCE(source_message_id,''), pinned,
- COALESCE(related_vulnerability_id,''), created_at, updated_at
+ COALESCE(related_vulnerability_id,''), COALESCE(confirmation_note,''), created_at, updated_at
FROM project_facts WHERE project_id = ? AND fact_key = ?`,
projectID, factKey,
)
@@ -487,7 +490,7 @@ func (db *DB) GetProjectFact(id string) (*ProjectFact, error) {
row := db.QueryRow(
`SELECT id, project_id, fact_key, category, summary, COALESCE(body,''), confidence,
COALESCE(source_conversation_id,''), COALESCE(source_message_id,''), pinned,
- COALESCE(related_vulnerability_id,''), created_at, updated_at
+ COALESCE(related_vulnerability_id,''), COALESCE(confirmation_note,''), created_at, updated_at
FROM project_facts WHERE id = ?`, id,
)
return scanProjectFactRow(row)
@@ -571,6 +574,70 @@ func (db *DB) UpsertProjectFact(f *ProjectFact) (*ProjectFact, error) {
return f, nil
}
+// SaveProjectFact writes the fact body, confidence and evidence links in one transaction.
+// Evidence validation failure leaves the previous row unchanged.
+func (db *DB) SaveProjectFact(f *ProjectFact, assetIDs, executionIDs []string, replaceAssets, replaceExecutions bool) (*ProjectFact, error) {
+ keyErr := ValidateFactKey(f.FactKey)
+ if keyErr != nil {
+ var n int
+ _ = db.QueryRow(`SELECT COUNT(*) FROM project_facts WHERE project_id=? AND fact_key=?`, f.ProjectID, f.FactKey).Scan(&n)
+ if n == 0 {
+ return nil, keyErr
+ }
+ }
+ if strings.TrimSpace(f.Category) == "" {
+ f.Category = "note"
+ }
+ if strings.TrimSpace(f.Confidence) == "" {
+ f.Confidence = "tentative"
+ }
+ tx, err := db.Begin()
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+ var existingID, existingBody, existingConfidence, existingCreatedRaw string
+ err = tx.QueryRow(`SELECT id, body, confidence, created_at FROM project_facts WHERE project_id=? AND fact_key=?`, f.ProjectID, f.FactKey).Scan(&existingID, &existingBody, &existingConfidence, &existingCreatedRaw)
+ if err != nil && err != sql.ErrNoRows {
+ return nil, err
+ }
+ if f.Confidence == "confirmed" && existingConfidence != "confirmed" && strings.TrimSpace(f.ConfirmationNote) == "" {
+ return nil, fmt.Errorf("升级为已确认需要审核说明")
+ }
+ now := time.Now().UTC()
+ if err == nil {
+ f.ID = existingID
+ f.CreatedAt = parseDBTime(existingCreatedRaw)
+ f.Body = mergeFactBodyOnUpdate(f.Body, existingBody)
+ if _, err = tx.Exec(`UPDATE project_facts SET category=?, summary=?, body=?, confidence=?,
+ source_conversation_id=COALESCE(?, source_conversation_id), source_message_id=COALESCE(?, source_message_id),
+ pinned=?, related_vulnerability_id=?, confirmation_note=CASE WHEN ?<>'' THEN ? ELSE confirmation_note END, updated_at=?
+ WHERE id=?`, f.Category, f.Summary, f.Body, f.Confidence, nullIfEmpty(f.SourceConversationID), nullIfEmpty(f.SourceMessageID), boolToInt(f.Pinned), nullIfEmpty(f.RelatedVulnerabilityID), strings.TrimSpace(f.ConfirmationNote), strings.TrimSpace(f.ConfirmationNote), now, f.ID); err != nil {
+ return nil, err
+ }
+ } else {
+ if f.ID == "" {
+ f.ID = uuid.New().String()
+ }
+ f.CreatedAt = now
+ if _, err = tx.Exec(`INSERT INTO project_facts(id,project_id,fact_key,category,summary,body,confidence,source_conversation_id,source_message_id,pinned,related_vulnerability_id,confirmation_note,created_at,updated_at)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, f.ID, f.ProjectID, f.FactKey, f.Category, f.Summary, f.Body, f.Confidence, nullIfEmpty(f.SourceConversationID), nullIfEmpty(f.SourceMessageID), boolToInt(f.Pinned), nullIfEmpty(f.RelatedVulnerabilityID), strings.TrimSpace(f.ConfirmationNote), now, now); err != nil {
+ return nil, err
+ }
+ }
+ f.UpdatedAt = now
+ f.ConfirmationNote = strings.TrimSpace(f.ConfirmationNote)
+ if replaceAssets || replaceExecutions {
+ if err = replaceProjectFactEvidence(tx, f.ID, f.ProjectID, assetIDs, executionIDs, replaceAssets, replaceExecutions); err != nil {
+ return nil, err
+ }
+ }
+ if err = tx.Commit(); err != nil {
+ return nil, err
+ }
+ return f, nil
+}
+
// DeprecateProjectFact 将事实标记为 deprecated(关联边同步 deprecated)。
func (db *DB) DeprecateProjectFact(projectID, factKey string) error {
res, err := db.Exec(
@@ -644,7 +711,7 @@ func scanProjectFactRow(row *sql.Row) (*ProjectFact, error) {
err := row.Scan(
&f.ID, &f.ProjectID, &f.FactKey, &f.Category, &f.Summary, &f.Body, &f.Confidence,
&f.SourceConversationID, &f.SourceMessageID, &pinned,
- &f.RelatedVulnerabilityID, &createdAt, &updatedAt,
+ &f.RelatedVulnerabilityID, &f.ConfirmationNote, &createdAt, &updatedAt,
)
if err != nil {
if err == sql.ErrNoRows {
@@ -665,7 +732,7 @@ func scanProjectFactFromRows(rows *sql.Rows) (*ProjectFact, error) {
err := rows.Scan(
&f.ID, &f.ProjectID, &f.FactKey, &f.Category, &f.Summary, &f.Body, &f.Confidence,
&f.SourceConversationID, &f.SourceMessageID, &pinned,
- &f.RelatedVulnerabilityID, &createdAt, &updatedAt,
+ &f.RelatedVulnerabilityID, &f.ConfirmationNote, &createdAt, &updatedAt,
)
if err != nil {
return nil, err
diff --git a/internal/database/project_evidence.go b/internal/database/project_evidence.go
new file mode 100644
index 00000000..c1598bea
--- /dev/null
+++ b/internal/database/project_evidence.go
@@ -0,0 +1,533 @@
+package database
+
+import (
+ "crypto/sha256"
+ "database/sql"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// LoadProjectFactEvidence fills asset and tool-execution links for the given facts.
+func (db *DB) LoadProjectFactEvidence(facts []*ProjectFact) error {
+ if len(facts) == 0 {
+ return nil
+ }
+ ids := make([]string, 0, len(facts))
+ byID := map[string]*ProjectFact{}
+ for _, fact := range facts {
+ if fact == nil || fact.ID == "" {
+ continue
+ }
+ ids = append(ids, fact.ID)
+ fact.AssetIDs = []string{}
+ fact.ExecutionIDs = []string{}
+ byID[fact.ID] = fact
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ placeholders := strings.TrimRight(strings.Repeat("?,", len(ids)), ",")
+ args := make([]any, len(ids))
+ for i, id := range ids {
+ args[i] = id
+ }
+ rows, err := db.Query(`SELECT fact_id, asset_id FROM project_fact_assets WHERE fact_id IN (`+placeholders+`) ORDER BY asset_id`, args...)
+ if err != nil {
+ return err
+ }
+ for rows.Next() {
+ var factID, assetID string
+ if err = rows.Scan(&factID, &assetID); err != nil {
+ rows.Close()
+ return err
+ }
+ if fact := byID[factID]; fact != nil {
+ fact.AssetIDs = append(fact.AssetIDs, assetID)
+ }
+ }
+ if err = rows.Err(); err != nil {
+ rows.Close()
+ return err
+ }
+ rows.Close()
+ rows, err = db.Query(`SELECT fact_id, execution_id FROM project_fact_receipts WHERE fact_id IN (`+placeholders+`) ORDER BY execution_id`, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var factID, executionID string
+ if err = rows.Scan(&factID, &executionID); err != nil {
+ return err
+ }
+ if fact := byID[factID]; fact != nil {
+ fact.ExecutionIDs = append(fact.ExecutionIDs, executionID)
+ }
+ }
+ return rows.Err()
+}
+
+// ReplaceProjectFactEvidence replaces the sides the caller sent. Omitted sides stay as they are.
+func (db *DB) ReplaceProjectFactEvidence(factID, projectID string, assetIDs, executionIDs []string, replaceAssets, replaceExecutions bool) error {
+ tx, err := db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if err = replaceProjectFactEvidence(tx, factID, projectID, assetIDs, executionIDs, replaceAssets, replaceExecutions); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+func replaceProjectFactEvidence(tx *sql.Tx, factID, projectID string, assetIDs, executionIDs []string, replaceAssets, replaceExecutions bool) error {
+ if replaceAssets {
+ if _, err := tx.Exec(`DELETE FROM project_fact_assets WHERE fact_id=?`, factID); err != nil {
+ return err
+ }
+ seen := map[string]bool{}
+ for _, id := range assetIDs {
+ id = strings.TrimSpace(id)
+ if id == "" || seen[id] {
+ continue
+ }
+ seen[id] = true
+ var assetProject string
+ err := tx.QueryRow(`SELECT COALESCE(project_id,'') FROM assets WHERE id=?`, id).Scan(&assetProject)
+ if err == sql.ErrNoRows {
+ return fmt.Errorf("资产 %s 不存在", id)
+ }
+ if err != nil {
+ return err
+ }
+ if assetProject != "" && assetProject != projectID {
+ return fmt.Errorf("资产 %s 不属于当前项目", id)
+ }
+ if _, err = tx.Exec(`INSERT INTO project_fact_assets(fact_id,asset_id) VALUES(?,?)`, factID, id); err != nil {
+ return err
+ }
+ }
+ }
+ if replaceExecutions {
+ if _, err := tx.Exec(`DELETE FROM project_fact_receipts WHERE fact_id=?`, factID); err != nil {
+ return err
+ }
+ seen := map[string]bool{}
+ for _, id := range executionIDs {
+ id = strings.TrimSpace(id)
+ if id == "" || seen[id] {
+ continue
+ }
+ seen[id] = true
+ var status, conversationID, executionProject string
+ err := tx.QueryRow(`SELECT te.status, COALESCE(te.conversation_id,''), COALESCE(c.project_id,'')
+ FROM tool_executions te LEFT JOIN conversations c ON c.id=te.conversation_id WHERE te.id=?`, id).Scan(&status, &conversationID, &executionProject)
+ if err == sql.ErrNoRows {
+ return fmt.Errorf("工具回执 %s 不存在", id)
+ }
+ if err != nil {
+ return err
+ }
+ if status != "completed" {
+ return fmt.Errorf("工具回执 %s 尚未成功完成", id)
+ }
+ if executionProject != "" && executionProject != projectID {
+ return fmt.Errorf("工具回执 %s 不属于当前项目", id)
+ }
+ if _, err = tx.Exec(`INSERT INTO project_fact_receipts(fact_id,execution_id) VALUES(?,?)`, factID, id); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// FactVisibility is the caller's project and conversation read boundary.
+type FactVisibility struct {
+ UserID string
+ ProjectScope string
+ ConversationScope string
+ CanReadProjects bool
+ CanReadConversations bool
+}
+
+func (db *DB) FactVisibilityFor(userID string) (FactVisibility, error) {
+ access, err := db.ResolveRBACAccess(userID)
+ if err != nil || access == nil {
+ return FactVisibility{}, err
+ }
+ vis := FactVisibility{UserID: access.User.ID, ProjectScope: "none", ConversationScope: "none"}
+ if access.Permissions["project:read"] {
+ vis.CanReadProjects = true
+ vis.ProjectScope = access.Scope
+ if scope := strings.TrimSpace(access.PermissionScopes["project:read"]); scope != "" {
+ vis.ProjectScope = scope
+ }
+ }
+ if access.Permissions["chat:read"] {
+ vis.CanReadConversations = true
+ vis.ConversationScope = access.Scope
+ if scope := strings.TrimSpace(access.PermissionScopes["chat:read"]); scope != "" {
+ vis.ConversationScope = scope
+ }
+ }
+ return vis, nil
+}
+
+func (v FactVisibility) projectSQL(alias string) (string, []any) {
+ if !v.CanReadProjects || v.ProjectScope == "none" {
+ return " AND 1=0", nil
+ }
+ if v.ProjectScope == RBACScopeAll {
+ return "", nil
+ }
+ if v.UserID == "" {
+ return " AND 1=0", nil
+ }
+ if v.ProjectScope == RBACScopeOwn {
+ return fmt.Sprintf(` AND (EXISTS (SELECT 1 FROM projects vp WHERE vp.id=%s.project_id AND vp.owner_user_id=?) OR EXISTS (SELECT 1 FROM rbac_resource_assignments vra WHERE vra.user_id=? AND vra.resource_type='project' AND vra.resource_id=%s.project_id))`, alias, alias), []any{v.UserID, v.UserID}
+ }
+ return fmt.Sprintf(` AND EXISTS (SELECT 1 FROM rbac_resource_assignments vra WHERE vra.user_id=? AND vra.resource_type='project' AND vra.resource_id=%s.project_id)`, alias), []any{v.UserID}
+}
+
+// PresentProjectFacts loads evidence links and removes sources the caller cannot read.
+// Project, asset and vulnerability responses all use this filter.
+func (db *DB) PresentProjectFacts(facts []*ProjectFact, vis FactVisibility) error {
+ if err := db.LoadProjectFactEvidence(facts); err != nil {
+ return err
+ }
+ db.redactFactSources(facts, vis)
+ return nil
+}
+
+func (db *DB) RedactFactEdges(edges []*ProjectFactEdge, vis FactVisibility) {
+ for _, edge := range edges {
+ if edge != nil && !db.canReadConversation(vis, edge.SourceConversationID) {
+ edge.SourceConversationID = ""
+ }
+ }
+}
+
+func (db *DB) redactFactSources(facts []*ProjectFact, vis FactVisibility) {
+ for _, fact := range facts {
+ if fact == nil {
+ continue
+ }
+ if !db.canReadConversation(vis, fact.SourceConversationID) {
+ fact.SourceConversationID = ""
+ fact.SourceMessageID = ""
+ }
+ kept := []string{}
+ for _, id := range fact.ExecutionIDs {
+ if db.canReadExecution(vis, id) {
+ kept = append(kept, id)
+ }
+ }
+ if len(kept) == 0 {
+ fact.ExecutionIDs = nil
+ } else {
+ fact.ExecutionIDs = kept
+ }
+ }
+}
+
+func (db *DB) canReadConversation(vis FactVisibility, id string) bool {
+ if !vis.CanReadConversations || strings.TrimSpace(id) == "" {
+ return false
+ }
+ if vis.ConversationScope == RBACScopeAll {
+ return true
+ }
+ if vis.UserID == "" {
+ return false
+ }
+ return db.UserCanAccessResource(vis.UserID, vis.ConversationScope, "conversation", id)
+}
+
+func (db *DB) canReadExecution(vis FactVisibility, id string) bool {
+ var conversationID string
+ if err := db.QueryRow(`SELECT COALESCE(conversation_id,'') FROM tool_executions WHERE id=?`, id).Scan(&conversationID); err != nil {
+ return false
+ }
+ if conversationID == "" {
+ return false
+ }
+ return db.canReadConversation(vis, conversationID)
+}
+
+func (db *DB) ListFactsForAsset(assetID string, limit int) ([]*ProjectFact, error) {
+ return db.ListVisibleFactsForAsset(assetID, FactVisibility{CanReadProjects: true, ProjectScope: RBACScopeAll, CanReadConversations: true, ConversationScope: RBACScopeAll}, limit)
+}
+
+func (db *DB) ListVisibleFactsForAsset(assetID string, vis FactVisibility, limit int) ([]*ProjectFact, error) {
+ if limit <= 0 || limit > 100 {
+ limit = 50
+ }
+ clause, clauseArgs := vis.projectSQL("f")
+ args := append([]any{strings.TrimSpace(assetID)}, clauseArgs...)
+ args = append(args, limit)
+ rows, err := db.Query(`SELECT f.id, f.project_id, f.fact_key, f.category, f.summary, f.body, f.confidence,
+ COALESCE(f.source_conversation_id,''), COALESCE(f.source_message_id,''), f.pinned, COALESCE(f.related_vulnerability_id,''), COALESCE(f.confirmation_note,''), f.created_at, f.updated_at
+ FROM project_facts f JOIN project_fact_assets a ON a.fact_id=f.id
+ WHERE a.asset_id=?`+clause+` ORDER BY f.updated_at DESC, f.id LIMIT ?`, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []*ProjectFact{}
+ for rows.Next() {
+ fact, err := scanProjectFactPointers(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, fact)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+ if err = db.PresentProjectFacts(out, vis); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+type factScanner interface {
+ Scan(dest ...any) error
+}
+
+func scanProjectFactPointers(row factScanner) (*ProjectFact, error) {
+ var fact ProjectFact
+ var pinned int
+ var conversationID, messageID, vulnID string
+ if err := row.Scan(&fact.ID, &fact.ProjectID, &fact.FactKey, &fact.Category, &fact.Summary, &fact.Body, &fact.Confidence, &conversationID, &messageID, &pinned, &vulnID, &fact.ConfirmationNote, &fact.CreatedAt, &fact.UpdatedAt); err != nil {
+ return nil, err
+ }
+ fact.SourceConversationID = conversationID
+ fact.SourceMessageID = messageID
+ fact.RelatedVulnerabilityID = vulnID
+ fact.Pinned = pinned != 0
+ return &fact, nil
+}
+
+func (db *DB) ProjectFactSummariesForCollection(collectionID string, limit int) ([]ProjectFact, error) {
+ return db.VisibleProjectFactSummaries(collectionID, FactVisibility{CanReadProjects: true, ProjectScope: RBACScopeAll, CanReadConversations: true, ConversationScope: RBACScopeAll}, limit)
+}
+
+func (db *DB) VisibleProjectFactSummaries(collectionID string, vis FactVisibility, limit int) ([]ProjectFact, error) {
+ if limit <= 0 || limit > 20 {
+ limit = 12
+ }
+ clause, clauseArgs := vis.projectSQL("f")
+ args := append([]any{strings.TrimSpace(collectionID)}, clauseArgs...)
+ args = append(args, limit)
+ rows, err := db.Query(`SELECT f.id, f.fact_key, f.summary, f.confidence, COALESCE(f.source_conversation_id,'')
+ FROM project_facts f
+ JOIN project_fact_assets a ON a.fact_id=f.id
+ JOIN asset_collection_members m ON m.asset_id=a.asset_id
+ WHERE m.collection_id=? AND f.confidence<>'deprecated'`+clause+`
+ GROUP BY f.id ORDER BY MAX(f.updated_at) DESC LIMIT ?`, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []ProjectFact{}
+ for rows.Next() {
+ var fact ProjectFact
+ if err = rows.Scan(&fact.ID, &fact.FactKey, &fact.Summary, &fact.Confidence, &fact.SourceConversationID); err != nil {
+ return nil, err
+ }
+ out = append(out, fact)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+ ptrs := make([]*ProjectFact, len(out))
+ for i := range out {
+ ptrs[i] = &out[i]
+ }
+ db.redactFactSources(ptrs, vis)
+ return out, nil
+}
+
+// PublishConfirmedProjectFact upserts one confirmed project fact and replaces its asset and receipt links.
+func PublishConfirmedProjectFact(tx *sql.Tx, fact ProjectFact, assetIDs, executionIDs []string) (string, error) {
+ fact.FactKey = strings.TrimSpace(fact.FactKey)
+ fact.ProjectID = strings.TrimSpace(fact.ProjectID)
+ if err := ValidateFactKey(fact.FactKey); err != nil {
+ return "", err
+ }
+ if fact.ProjectID == "" {
+ return "", fmt.Errorf("项目事实必须属于项目")
+ }
+ fact.Summary = clipEvidenceText(fact.Summary, 500)
+ fact.Body = clipEvidenceText(fact.Body, 8000)
+ if fact.Summary == "" {
+ return "", fmt.Errorf("项目事实摘要不能为空")
+ }
+ if strings.TrimSpace(fact.Category) == "" {
+ fact.Category = "note"
+ }
+ if fact.Confidence == "" {
+ fact.Confidence = "tentative"
+ }
+ if fact.Confidence != "confirmed" && fact.Confidence != "tentative" && fact.Confidence != "deprecated" {
+ return "", fmt.Errorf("项目事实可信度无效")
+ }
+ if fact.Confidence == "confirmed" && strings.TrimSpace(fact.ConfirmationNote) == "" {
+ return "", fmt.Errorf("升级为已确认需要审核说明")
+ }
+ now := time.Now().UTC()
+ var id string
+ err := tx.QueryRow(`SELECT id FROM project_facts WHERE project_id=? AND fact_key=?`, fact.ProjectID, fact.FactKey).Scan(&id)
+ if err == sql.ErrNoRows {
+ id = uuid.NewString()
+ _, err = tx.Exec(`INSERT INTO project_facts(id,project_id,fact_key,category,summary,body,confidence,source_conversation_id,source_message_id,pinned,related_vulnerability_id,confirmation_note,created_at,updated_at)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ id, fact.ProjectID, fact.FactKey, fact.Category, fact.Summary, fact.Body, fact.Confidence,
+ nullIfEmpty(fact.SourceConversationID), nullIfEmpty(fact.SourceMessageID), 0, nullIfEmpty(fact.RelatedVulnerabilityID), strings.TrimSpace(fact.ConfirmationNote), now, now)
+ } else if err == nil {
+ _, err = tx.Exec(`UPDATE project_facts SET category=?, summary=?, body=?, confidence=?,
+ source_conversation_id=COALESCE(?, source_conversation_id), related_vulnerability_id=COALESCE(?, related_vulnerability_id),
+ confirmation_note=CASE WHEN ?<>'' THEN ? ELSE confirmation_note END, updated_at=?
+ WHERE id=?`, fact.Category, fact.Summary, fact.Body, fact.Confidence, nullIfEmpty(fact.SourceConversationID), nullIfEmpty(fact.RelatedVulnerabilityID), strings.TrimSpace(fact.ConfirmationNote), strings.TrimSpace(fact.ConfirmationNote), now, id)
+ }
+ if err != nil {
+ return "", err
+ }
+ if err = replaceProjectFactEvidence(tx, id, fact.ProjectID, assetIDs, executionIDs, true, true); err != nil {
+ return "", err
+ }
+ return id, nil
+}
+
+func clipEvidenceText(value string, max int) string {
+ value = strings.TrimSpace(value)
+ runes := []rune(value)
+ if len(runes) <= max {
+ return value
+ }
+ return string(runes[:max])
+}
+
+func completedExecutionIDs(tx *sql.Tx, conversationID string) ([]string, error) {
+ rows, err := tx.Query(`SELECT id FROM tool_executions WHERE conversation_id=? AND status='completed' ORDER BY created_at, id LIMIT 32`, conversationID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []string{}
+ for rows.Next() {
+ var id string
+ if err = rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ out = append(out, id)
+ }
+ return out, rows.Err()
+}
+
+func escapeLike(value string) string {
+ return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(value)
+}
+
+func assetIDsForTarget(tx *sql.Tx, projectID, target string) ([]string, error) {
+ host := strings.ToLower(strings.TrimSpace(vulnerabilityTargetHost(target)))
+ if projectID == "" || host == "" {
+ return nil, nil
+ }
+ // Match the host exactly, or as the authority of a URL. A suffix such as
+ // example.com.evil must not satisfy example.com.
+ escaped := escapeLike(host)
+ rows, err := tx.Query(`SELECT id FROM assets WHERE project_id=? AND (
+ lower(domain)=? OR lower(ip)=? OR lower(host)=?
+ OR lower(host) LIKE ? ESCAPE '\'
+ OR lower(host) LIKE ? ESCAPE '\'
+ OR lower(host) LIKE ? ESCAPE '\'
+ OR lower(host) LIKE ? ESCAPE '\'
+ OR lower(host) LIKE ? ESCAPE '\'
+ OR lower(host) LIKE ? ESCAPE '\'
+ OR lower(host) LIKE ? ESCAPE '\'
+ ) LIMIT 32`, projectID, host, host, host,
+ escaped+":%",
+ "http://"+escaped, "https://"+escaped,
+ "http://"+escaped+":%", "https://"+escaped+":%",
+ "http://"+escaped+"/%", "https://"+escaped+"/%")
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []string{}
+ for rows.Next() {
+ var id string
+ if err = rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ out = append(out, id)
+ }
+ return out, rows.Err()
+}
+
+// FilterProjectExecutions keeps completed receipts that belong to this project.
+// A receipt from another project is skipped so it cannot roll back the caller's own write.
+func FilterProjectExecutions(tx *sql.Tx, projectID string, ids []string) []string {
+ out := []string{}
+ seen := map[string]bool{}
+ for _, id := range ids {
+ id = strings.TrimSpace(id)
+ if id == "" || seen[id] {
+ continue
+ }
+ seen[id] = true
+ var status, executionProject string
+ err := tx.QueryRow(`SELECT te.status, COALESCE(c.project_id,'')
+ FROM tool_executions te LEFT JOIN conversations c ON c.id=te.conversation_id WHERE te.id=?`, id).Scan(&status, &executionProject)
+ if err != nil || status != "completed" {
+ continue
+ }
+ if projectID != "" && executionProject != "" && executionProject != projectID {
+ continue
+ }
+ out = append(out, id)
+ }
+ return out
+}
+
+// recordRetestEvidence writes a sourced project fact. Vulnerability status remains the disposition record.
+func recordRetestEvidence(tx *sql.Tx, vulnerabilityID, status, notes, conversationID string) error {
+ var projectID, target, title string
+ if err := tx.QueryRow(`SELECT COALESCE(project_id,''), COALESCE(target,''), title FROM vulnerabilities WHERE id=?`, vulnerabilityID).Scan(&projectID, &target, &title); err != nil {
+ return err
+ }
+ if projectID == "" {
+ _ = tx.QueryRow(`SELECT COALESCE(project_id,'') FROM conversations WHERE id=?`, conversationID).Scan(&projectID)
+ }
+ assets, err := assetIDsForTarget(tx, projectID, target)
+ if err != nil {
+ return err
+ }
+ executions, err := completedExecutionIDs(tx, conversationID)
+ if err != nil {
+ return err
+ }
+ executions = FilterProjectExecutions(tx, projectID, executions)
+ if projectID != "" {
+ summary := clipEvidenceText(title+" 复测:"+status, 500)
+ if strings.TrimSpace(notes) != "" {
+ summary = clipEvidenceText(notes, 500)
+ }
+ factKey := "retest/" + vulnerabilityID + "/" + conversationID
+ if len(factKey) > 128 || ValidateFactKey(factKey) != nil {
+ factKey = fmt.Sprintf("retest/%x", sha256.Sum256([]byte(vulnerabilityID+"\n"+conversationID)))
+ }
+ if _, err = PublishConfirmedProjectFact(tx, ProjectFact{
+ ProjectID: projectID, FactKey: factKey, Confidence: "tentative",
+ Category: "note", Summary: summary, Body: notes, SourceConversationID: conversationID, RelatedVulnerabilityID: vulnerabilityID,
+ }, assets, executions); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/database/schemas/application.sql b/internal/database/schemas/application.sql
index 4aea10aa..a49e6b9b 100644
--- a/internal/database/schemas/application.sql
+++ b/internal/database/schemas/application.sql
@@ -101,7 +101,8 @@ CREATE TABLE batch_task_queues (
started_at DATETIME,
completed_at DATETIME,
current_index INTEGER NOT NULL DEFAULT 0,
- owner_user_id TEXT
+ owner_user_id TEXT,
+ collection_id TEXT
);
CREATE TABLE batch_tasks (
@@ -377,6 +378,7 @@ CREATE TABLE project_facts (
source_message_id TEXT,
pinned INTEGER NOT NULL DEFAULT 0,
related_vulnerability_id TEXT,
+ confirmation_note TEXT NOT NULL DEFAULT '',
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
@@ -978,7 +980,8 @@ CREATE TABLE IF NOT EXISTS deep_assessment_facts (
id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES deep_assessments(id) ON DELETE CASCADE,
step_id TEXT NOT NULL, confidence TEXT NOT NULL CHECK(confidence IN ('observed','inferred')),
summary TEXT NOT NULL, body TEXT NOT NULL, evidence_json TEXT NOT NULL,
- assets_json TEXT NOT NULL, sources_json TEXT NOT NULL, created_at DATETIME NOT NULL
+ assets_json TEXT NOT NULL, sources_json TEXT NOT NULL, created_at DATETIME NOT NULL,
+ project_fact_id TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_assessment_facts_task ON deep_assessment_facts(task_id,created_at,id);
CREATE TABLE IF NOT EXISTS deep_assessment_surface_items (
@@ -1013,3 +1016,37 @@ CREATE TABLE IF NOT EXISTS deep_assessment_finding_reviews (
reason TEXT NOT NULL, evidence_json TEXT NOT NULL, created_at DATETIME NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_assessment_finding_reviews ON deep_assessment_finding_reviews(vulnerability_id,created_at,id);
+
+-- A collection is a named set of existing assets. It does not copy asset rows.
+CREATE TABLE IF NOT EXISTS asset_collections (
+ id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT '',
+ source_query TEXT NOT NULL DEFAULT '',
+ created_by TEXT NOT NULL DEFAULT '',
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_asset_collections_project ON asset_collections(project_id, updated_at);
+
+CREATE TABLE IF NOT EXISTS asset_collection_members (
+ collection_id TEXT NOT NULL REFERENCES asset_collections(id) ON DELETE CASCADE,
+ asset_id TEXT NOT NULL REFERENCES assets(id) ON DELETE CASCADE,
+ created_at DATETIME NOT NULL,
+ PRIMARY KEY(collection_id, asset_id)
+);
+CREATE INDEX IF NOT EXISTS idx_asset_collection_members_asset ON asset_collection_members(asset_id, collection_id);
+
+CREATE TABLE IF NOT EXISTS project_fact_assets (
+ fact_id TEXT NOT NULL REFERENCES project_facts(id) ON DELETE CASCADE,
+ asset_id TEXT NOT NULL REFERENCES assets(id) ON DELETE CASCADE,
+ PRIMARY KEY(fact_id, asset_id)
+);
+CREATE INDEX IF NOT EXISTS idx_project_fact_assets_asset ON project_fact_assets(asset_id, fact_id);
+
+CREATE TABLE IF NOT EXISTS project_fact_receipts (
+ fact_id TEXT NOT NULL REFERENCES project_facts(id) ON DELETE CASCADE,
+ execution_id TEXT NOT NULL REFERENCES tool_executions(id) ON DELETE CASCADE,
+ PRIMARY KEY(fact_id, execution_id)
+);
diff --git a/internal/database/shared_evidence_test.go b/internal/database/shared_evidence_test.go
new file mode 100644
index 00000000..a4379c00
--- /dev/null
+++ b/internal/database/shared_evidence_test.go
@@ -0,0 +1,200 @@
+package database
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "go.uber.org/zap"
+)
+
+func TestSharedCollectionCoverageAndRetestFact(t *testing.T) {
+ db, err := NewDB(filepath.Join(t.TempDir(), "shared-evidence.db"), zap.NewNop())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ user, err := db.CreateRBACUser("owner", "Owner", "hash", true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ project, err := db.CreateProject(&Project{Name: "shared"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ asset := &Asset{ProjectID: project.ID, Domain: "example.com", Protocol: "https", Port: 443, Status: "active"}
+ evil := &Asset{ProjectID: project.ID, Host: "https://example.com.evil/a", Status: "active"}
+ if result, err := db.UpsertAssets([]*Asset{asset, evil}, user.ID, true); err != nil || result.Created != 2 || asset.ID == "" {
+ t.Fatal(result, err)
+ }
+ otherProject, err := db.CreateProject(&Project{Name: "other"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ other := &Asset{ProjectID: otherProject.ID, Domain: "other.example", Status: "active"}
+ if _, err = db.UpsertAssets([]*Asset{other}, user.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ collection, err := db.CreateAssetCollection(project.ID, "example", "fofa", "domain=\"example.com\"", user.ID, []string{asset.ID, other.ID, "missing"})
+ if err != nil || collection.MemberCount != 1 {
+ t.Fatalf("collection=%#v err=%v", collection, err)
+ }
+ now := time.Now().UTC()
+ source, err := db.CreateConversation("source", ConversationCreateMeta{ProjectID: project.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ retestConv, err := db.CreateConversation("retest", ConversationCreateMeta{ProjectID: project.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO tool_executions(id,tool_name,arguments,status,start_time,conversation_id) VALUES(?,?,?,?,?,?)`,
+ "exec-retest", "http_request", "{}", "completed", now, retestConv.ID); err != nil {
+ t.Fatal(err)
+ }
+ vuln, err := db.CreateVulnerability(&Vulnerability{ConversationID: source.ID, ProjectID: project.ID, Title: "login", Severity: "high", Status: "open", Target: "https://example.com/login"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO deep_assessments(id,owner_user_id,project_id,name,status,payload,updated_at) VALUES(?,?,?,?,?,?,?)`,
+ "assess-1", user.ID, project.ID, "assess", "draft", "{}", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO vulnerability_assessment_sources(vulnerability_id,assessment_id,assessment_name,step_id,step_title,conversation_id) VALUES(?,?,?,?,?,?)`,
+ vuln.ID, "assess-1", "assess", "step-1", "check", source.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO deep_assessment_nodes(task_id,id,step_id,kind,state,title,body,source,updated_round,updated_at) VALUES(?,?,?,'finding','reported',?,?,?,0,?)`,
+ "assess-1", "finding:"+vuln.ID, "step-1", "login", "original", "{}", now); err != nil {
+ t.Fatal(err)
+ }
+ if err = db.UpdateVulnerabilityRetestResult(vuln.ID, "fixed", "patched in this build", retestConv.ID); err != nil {
+ t.Fatal(err)
+ }
+ facts, err := db.ListFactsForAsset(asset.ID, 20)
+ if err != nil || len(facts) != 1 || facts[0].Confidence != "tentative" || len(facts[0].ExecutionIDs) != 1 || facts[0].RelatedVulnerabilityID != vuln.ID {
+ t.Fatalf("facts=%#v confidence=%q execs=%v vuln=%q err=%v", facts, facts[0].Confidence, facts[0].ExecutionIDs, facts[0].RelatedVulnerabilityID, err)
+ }
+ if evilFacts, err := db.ListFactsForAsset(evil.ID, 20); err != nil || len(evilFacts) != 0 {
+ t.Fatalf("suffix host was linked: %#v %v", evilFacts, err)
+ }
+ total, observed, err := db.ObservationCoverage(RBACListAccess{Scope: RBACScopeAll}, collection.ID)
+ if err != nil || total != 1 || observed != 0 {
+ t.Fatalf("unreviewed retest counted as confirmed coverage: total=%d observed=%d err=%v", total, observed, err)
+ }
+ if _, err = db.SaveProjectFact(&ProjectFact{ProjectID: project.ID, FactKey: "note/reviewed", Summary: "reviewed", Confidence: "confirmed", ConfirmationNote: "人工复核通过", SourceConversationID: retestConv.ID}, []string{asset.ID}, []string{"exec-retest"}, true, true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.SaveProjectFact(&ProjectFact{ProjectID: project.ID, FactKey: "note/reviewed", Summary: "should not replace", Body: "CHANGED", Confidence: "confirmed"}, []string{asset.ID}, []string{"missing-exec"}, true, true); err == nil {
+ t.Fatal("invalid receipt replaced the confirmed fact")
+ }
+ kept, err := db.GetProjectFactByKey(project.ID, "note/reviewed")
+ if err != nil || kept.Summary != "reviewed" || strings.Contains(kept.Body, "CHANGED") {
+ t.Fatalf("failed save changed the fact: %#v %v", kept, err)
+ }
+ _, observed, err = db.ObservationCoverage(RBACListAccess{Scope: RBACScopeAll}, collection.ID)
+ if err != nil || observed != 1 {
+ t.Fatalf("reviewed fact was not counted: %d %v", observed, err)
+ }
+ stats, err := db.GetAssetStats(RBACListAccess{Scope: RBACScopeAll}, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ coverage := stats["coverage"].(map[string]interface{})
+ if coverage["scanned"] != 0 {
+ t.Fatalf("scan coverage changed: %#v", coverage)
+ }
+ observation := stats["observation"].(map[string]interface{})
+ if observation["observed"] != 1 {
+ t.Fatalf("observation=%#v", observation)
+ }
+ var state string
+ if err = db.QueryRow(`SELECT state FROM deep_assessment_nodes WHERE task_id=? AND id=?`, "assess-1", "finding:"+vuln.ID).Scan(&state); err != nil || state != "reported" {
+ t.Fatalf("finding node changed: %s %v", state, err)
+ }
+ var reviews int
+ if err = db.QueryRow(`SELECT COUNT(*) FROM deep_assessment_finding_reviews WHERE vulnerability_id=?`, vuln.ID).Scan(&reviews); err != nil || reviews != 0 {
+ t.Fatalf("retest execution was stored as an assessment review: %d %v", reviews, err)
+ }
+}
+
+func TestSharedAssetFactsStayInsideReadableProjects(t *testing.T) {
+ db, err := NewDB(filepath.Join(t.TempDir(), "shared-boundary.db"), zap.NewNop())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ now := time.Now().UTC()
+ if _, err = db.Exec(`INSERT INTO rbac_roles(id,name,description,scope,is_system,created_at,updated_at) VALUES('role-own','own','','own',0,?,?)`, now, now); err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range []string{"project:read", "project:write", "chat:read", "asset:read"} {
+ if _, err = db.Exec(`INSERT OR IGNORE INTO rbac_permissions(key,description,created_at) VALUES(?,?,?)`, key, key, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT OR IGNORE INTO rbac_role_permissions(role_id,permission_key,created_at) VALUES('role-own',?,?)`, key, now); err != nil {
+ t.Fatal(err)
+ }
+ }
+ userA, err := db.CreateRBACUser("usera", "A", "hash", true, []string{"role-own"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ userB, err := db.CreateRBACUser("userb", "B", "hash", true, []string{"role-own"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ projectA, err := db.CreateProject(&Project{Name: "A"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ projectB, err := db.CreateProject(&Project{Name: "B"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`UPDATE projects SET owner_user_id=? WHERE id=?`, userA.ID, projectA.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`UPDATE projects SET owner_user_id=? WHERE id=?`, userB.ID, projectB.ID); err != nil {
+ t.Fatal(err)
+ }
+ asset := &Asset{Domain: "shared.example", Status: "active"}
+ if _, err = db.UpsertAssets([]*Asset{asset}, userA.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ convA, err := db.CreateConversation("a", ConversationCreateMeta{ProjectID: projectA.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ convB, err := db.CreateConversation("b", ConversationCreateMeta{ProjectID: projectB.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`UPDATE conversations SET owner_user_id=? WHERE id=?`, userA.ID, convA.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`UPDATE conversations SET owner_user_id=? WHERE id=?`, userB.ID, convB.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO tool_executions(id,tool_name,arguments,status,start_time,conversation_id) VALUES('exec-a','http','{}','completed',?,?)`, now, convA.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO tool_executions(id,tool_name,arguments,status,start_time,conversation_id) VALUES('exec-b','http','{}','completed',?,?)`, now, convB.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.SaveProjectFact(&ProjectFact{ProjectID: projectA.ID, FactKey: "note/a", Summary: "from A", Confidence: "tentative", SourceConversationID: convA.ID}, []string{asset.ID}, []string{"exec-a"}, true, true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.SaveProjectFact(&ProjectFact{ProjectID: projectB.ID, FactKey: "note/b", Summary: "from B", Confidence: "tentative", SourceConversationID: convB.ID}, []string{asset.ID}, []string{"exec-b"}, true, true); err != nil {
+ t.Fatal(err)
+ }
+ visA, err := db.FactVisibilityFor(userA.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ visible, err := db.ListVisibleFactsForAsset(asset.ID, visA, 20)
+ if err != nil || len(visible) != 1 || visible[0].ProjectID != projectA.ID || visible[0].SourceConversationID != convA.ID || len(visible[0].ExecutionIDs) != 1 {
+ t.Fatalf("boundary leak: %#v %v", visible, err)
+ }
+}
diff --git a/internal/database/vulnerability_retest.go b/internal/database/vulnerability_retest.go
index 539fea9e..1472c0aa 100644
--- a/internal/database/vulnerability_retest.go
+++ b/internal/database/vulnerability_retest.go
@@ -135,6 +135,36 @@ func (db *DB) CreateVulnerabilityRetest(v *Vulnerability, meta ConversationCreat
return conv, nil
}
+// RetestConclusion separates an operator disposition from a retest that has a saved record and a readable receipt.
+func (db *DB) RetestConclusion(vis FactVisibility, vulnerabilityID string) (string, string, error) {
+ var status, evidence, conversationID string
+ err := db.QueryRow(`SELECT status, COALESCE(evidence,''), COALESCE(conversation_id,'') FROM vulnerability_retest_results WHERE vulnerability_id=? ORDER BY created_at DESC, rowid DESC LIMIT 1`, vulnerabilityID).Scan(&status, &evidence, &conversationID)
+ if err == sql.ErrNoRows {
+ return "尚无复测记录", "", nil
+ }
+ if err != nil {
+ return "", "", err
+ }
+ if status != "fixed" {
+ return "未确认修复", "", nil
+ }
+ var receipts int
+ if conversationID != "" {
+ if err = db.QueryRow(`SELECT COUNT(*) FROM tool_executions WHERE conversation_id=? AND status='completed'`, conversationID).Scan(&receipts); err != nil {
+ return "", "", err
+ }
+ }
+ readable := db.canReadConversation(vis, conversationID)
+ if strings.TrimSpace(evidence) == "" || !readable || receipts == 0 {
+ hint := "复测结论不能记为修复已验证:复测记录缺少可核对的成功回执或证据正文。其余内容仍导出。"
+ if readable && strings.TrimSpace(conversationID) != "" {
+ hint = fmt.Sprintf("复测结论不能记为修复已验证:来源会话 %s 没有可核对的成功回执或证据正文。其余内容仍导出。", conversationID)
+ }
+ return "证据待核对", hint, nil
+ }
+ return "修复已验证", "", nil
+}
+
// UpdateVulnerabilityRetestResult appends evidence to retest_log; retest_notes stays operator-owned.
func (db *DB) UpdateVulnerabilityRetestResult(id, status, notes, conversationID string) error {
tx, err := db.Begin()
@@ -164,6 +194,9 @@ func (db *DB) UpdateVulnerabilityRetestResult(id, status, notes, conversationID
if n != 1 {
return fmt.Errorf("漏洞不存在")
}
+ if err = recordRetestEvidence(tx, id, status, notes, conversationID); err != nil {
+ return err
+ }
if err := tx.Commit(); err != nil {
return err
}
diff --git a/internal/deepassessment/acceptance.go b/internal/deepassessment/acceptance.go
index 6c891bb1..4cf7d111 100644
--- a/internal/deepassessment/acceptance.go
+++ b/internal/deepassessment/acceptance.go
@@ -1,13 +1,18 @@
package deepassessment
import (
+ "crypto/sha256"
"database/sql"
+ "encoding/hex"
"encoding/json"
"fmt"
"slices"
"strings"
)
+// AcceptanceModePerItem requires every acceptance line to have evidence before completion.
+const AcceptanceModePerItem = "per_item"
+
const AcceptanceSourcePageSize = 20
type AcceptanceMapping struct {
@@ -53,6 +58,7 @@ func acceptanceCriteria(t *Task) []string {
type acceptanceQueryer interface {
Query(query string, args ...any) (*sql.Rows, error)
+ QueryRow(query string, args ...any) *sql.Row
}
func queryAcceptanceSources(db acceptanceQueryer, task, kind, suffix string, args ...any) ([]AcceptanceSource, error) {
@@ -111,13 +117,70 @@ func acceptanceSourcesByID(db acceptanceQueryer, task, kind string, ids []string
return out, err
}
+// AcceptanceGate is the completion rule for one saved task version.
+// A task with no per-item mode and no saved mapping is legacy: the model verdict
+// can still finish it. Enabling per-item acceptance, or saving any mapping, keeps
+// the task incomplete while any required line is missing evidence or waiting for review.
+type AcceptanceGate struct {
+ Legacy bool
+ Blocking bool
+ Version string
+ Reason string
+}
+
+func (s *Store) AcceptanceGate(t *Task) (AcceptanceGate, error) {
+ return acceptanceGate(s.DB, t)
+}
+
+func acceptanceGate(db acceptanceQueryer, t *Task) (AcceptanceGate, error) {
+ var saved int
+ if err := db.QueryRow(`SELECT COUNT(*) FROM deep_assessment_acceptance WHERE task_id=?`, t.ID).Scan(&saved); err != nil {
+ return AcceptanceGate{}, err
+ }
+ matrix, err := acceptanceMatrix(db, t)
+ if err != nil {
+ return AcceptanceGate{}, err
+ }
+ gate := AcceptanceGate{Legacy: t.AcceptanceMode != AcceptanceModePerItem && saved == 0, Version: acceptanceVersion(t, matrix)}
+ if gate.Legacy {
+ return gate, nil
+ }
+ for _, row := range matrix {
+ switch row.Status {
+ case "missing":
+ gate.Blocking = true
+ gate.Reason = "仍有必验项没有对应证据"
+ case "needs_review":
+ gate.Blocking = true
+ if gate.Reason == "" {
+ gate.Reason = "仍有必验项待复核"
+ }
+ }
+ }
+ return gate, nil
+}
+
+func acceptanceVersion(t *Task, rows []AcceptanceRow) string {
+ var b strings.Builder
+ fmt.Fprintf(&b, "%s\n%s\n", t.AcceptanceMode, t.Criteria)
+ for _, row := range rows {
+ fmt.Fprintf(&b, "%d\t%s\t%d\t%t\t%s\t%s\t%s\n", row.Number, row.Status, row.Revision, row.NeedsReview, strings.Join(row.FactIDs, ","), strings.Join(row.ReceiptIDs, ","), row.ReviewNote)
+ }
+ sum := sha256.Sum256([]byte(b.String()))
+ return hex.EncodeToString(sum[:])
+}
+
func (s *Store) AcceptanceMatrix(t *Task) ([]AcceptanceRow, error) {
+ return acceptanceMatrix(s.DB, t)
+}
+
+func acceptanceMatrix(db acceptanceQueryer, t *Task) ([]AcceptanceRow, error) {
criteria := acceptanceCriteria(t)
matrix := make([]AcceptanceRow, len(criteria))
for i, text := range criteria {
matrix[i] = AcceptanceRow{Number: i + 1, Text: text, Status: "missing"}
}
- rows, err := s.DB.Query(`SELECT criterion,revision,mapping FROM deep_assessment_acceptance WHERE task_id=? ORDER BY criterion`, t.ID)
+ rows, err := db.Query(`SELECT criterion,revision,mapping FROM deep_assessment_acceptance WHERE task_id=? ORDER BY criterion`, t.ID)
if err != nil {
return nil, err
}
@@ -144,14 +207,14 @@ func (s *Store) AcceptanceMatrix(t *Task) ([]AcceptanceRow, error) {
if err = rows.Err(); err != nil {
return nil, err
}
- facts, err := acceptanceSourcesByID(s.DB, t.ID, "fact", factIDs)
+ facts, err := acceptanceSourcesByID(db, t.ID, "fact", factIDs)
if err != nil {
return nil, err
}
for _, fact := range facts {
receiptIDs = append(receiptIDs, fact.ReceiptIDs...)
}
- receipts, err := acceptanceSourcesByID(s.DB, t.ID, "receipt", receiptIDs)
+ receipts, err := acceptanceSourcesByID(db, t.ID, "receipt", receiptIDs)
if err != nil {
return nil, err
}
diff --git a/internal/deepassessment/acceptance_gate_test.go b/internal/deepassessment/acceptance_gate_test.go
new file mode 100644
index 00000000..ecae38d6
--- /dev/null
+++ b/internal/deepassessment/acceptance_gate_test.go
@@ -0,0 +1,113 @@
+package deepassessment
+
+import (
+ "strings"
+ "testing"
+
+ "cyberstrike-ai/internal/agentruntime"
+)
+
+func TestPerItemAcceptanceFourStatesUseOneVersion(t *testing.T) {
+ s, task := perItemTask(t)
+ if gate := mustGate(t, s, task.ID); !gate.Blocking || gate.Legacy || !strings.Contains(gate.Reason, "没有对应证据") {
+ t.Fatalf("all empty: %+v", gate)
+ }
+ if err := s.BeginCall(task.ID, "s", agentruntime.ToolCall{ID: "receipt-1", Name: "fixture_read"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.FinishCall(agentruntime.ToolCall{ID: "receipt-1"}, agentruntime.ToolResult{Content: "observed"}, false); err != nil {
+ t.Fatal(err)
+ }
+ current := mustTask(t, s, task.ID)
+ if err := s.SaveAcceptanceMapping(current, 1, AcceptanceMapping{ReceiptIDs: []string{"receipt-1"}}); err != nil {
+ t.Fatal(err)
+ }
+ if gate := mustGate(t, s, task.ID); !gate.Blocking || !strings.Contains(gate.Reason, "没有对应证据") {
+ t.Fatalf("partial: %+v", gate)
+ }
+ current = mustTask(t, s, task.ID)
+ if err := s.SaveAcceptanceMapping(current, 2, AcceptanceMapping{ReceiptIDs: []string{"receipt-1"}, NeedsReview: true}); err != nil {
+ t.Fatal(err)
+ }
+ if gate := mustGate(t, s, task.ID); !gate.Blocking || !strings.Contains(gate.Reason, "待复核") {
+ t.Fatalf("needs review: %+v", gate)
+ }
+ current = mustTask(t, s, task.ID)
+ if err := s.SaveAcceptanceMapping(current, 2, AcceptanceMapping{Revision: 1, ReceiptIDs: []string{"receipt-1"}}); err != nil {
+ t.Fatal(err)
+ }
+ satisfied := mustGate(t, s, task.ID)
+ if satisfied.Blocking || satisfied.Legacy || satisfied.Version == "" {
+ t.Fatalf("all satisfied: %+v", satisfied)
+ }
+ current = mustTask(t, s, task.ID)
+ if err := s.SaveAcceptanceMapping(current, 1, AcceptanceMapping{Revision: 1, ReceiptIDs: []string{"receipt-1"}, NeedsReview: true}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.CompleteAtGate(task.ID, 0, current.Revision, "should not finish", satisfied); err != ErrConflict {
+ t.Fatalf("stale acceptance snapshot finished the task: %v", err)
+ }
+ if got := mustTask(t, s, task.ID); got.Status != "running" {
+ t.Fatalf("stale completion changed status to %s", got.Status)
+ }
+ current = mustTask(t, s, task.ID)
+ if err := s.SaveAcceptanceMapping(current, 1, AcceptanceMapping{Revision: 2, ReceiptIDs: []string{"receipt-1"}}); err != nil {
+ t.Fatal(err)
+ }
+ fresh := mustGate(t, s, task.ID)
+ current = mustTask(t, s, task.ID)
+ if err := s.CompleteAtGate(task.ID, 0, current.Revision, "every line has evidence", fresh); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustTask(t, s, task.ID); got.Status != "completed" || got.Summary != "every line has evidence" {
+ t.Fatalf("current acceptance snapshot did not complete: %+v", got)
+ }
+}
+
+func TestLegacyAcceptanceStaysOpenUntilAMappingIsSaved(t *testing.T) {
+ s, task := fixture(t)
+ gate := mustGate(t, s, task.ID)
+ if !gate.Legacy || gate.Blocking {
+ t.Fatalf("old task without a saved mapping: %+v", gate)
+ }
+ if err := s.SaveAcceptanceMapping(task, 1, AcceptanceMapping{NeedsReview: true}); err != nil {
+ t.Fatal(err)
+ }
+ gate = mustGate(t, s, task.ID)
+ if gate.Legacy || !gate.Blocking || !strings.Contains(gate.Reason, "待复核") {
+ t.Fatalf("saved mapping did not enable the gate: %+v", gate)
+ }
+}
+
+func perItemTask(t *testing.T) (*Store, *Task) {
+ t.Helper()
+ s, task := fixture(t)
+ if err := s.Change(task.ID, "", "mode", "", func(v *Task) error {
+ v.AcceptanceMode = AcceptanceModePerItem
+ v.Criteria = "inventory holds\nreview holds"
+ v.Status = "running"
+ v.Steps = []Step{{ID: "s", Status: "completed", Summary: "done", ConversationID: "c"}}
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return s, mustTask(t, s, task.ID)
+}
+
+func mustTask(t *testing.T, s *Store, id string) *Task {
+ t.Helper()
+ task, err := s.Get(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return task
+}
+
+func mustGate(t *testing.T, s *Store, id string) AcceptanceGate {
+ t.Helper()
+ gate, err := s.AcceptanceGate(mustTask(t, s, id))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return gate
+}
diff --git a/internal/deepassessment/engine.go b/internal/deepassessment/engine.go
index 92768d60..4dbafd2d 100644
--- a/internal/deepassessment/engine.go
+++ b/internal/deepassessment/engine.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "strings"
"sync"
"time"
)
@@ -616,19 +617,24 @@ func (e *Engine) run(parent context.Context, id string) {
needPlan = true
continue
}
- if AcceptVerdict(current, r.verdict) {
- err = e.Store.ChangeAtVersion(id, "", "completed", r.verdict.Summary, r.changeVersion, func(latest *Task) error {
- if latest.Status != "running" || latest.Revision != current.Revision {
- return ErrConflict
- }
- latest.Status = "completed"
- latest.Summary = Clip(r.verdict.Summary, 16000)
- return nil
- })
+ gate, missErr := e.Store.AcceptanceGate(current)
+ if missErr != nil {
+ stop("blocked", missErr.Error())
+ return
+ }
+ if gate.Blocking && strings.TrimSpace(r.verdict.Missing) == "" {
+ r.verdict.Missing = gate.Reason
+ }
+ if AcceptVerdict(current, r.verdict) && !gate.Blocking {
+ err = e.Store.CompleteAtGate(id, r.changeVersion, current.Revision, r.verdict.Summary, gate)
if err == ErrConflict {
needPlan = true
continue
}
+ if err != nil {
+ stop("blocked", err.Error())
+ return
+ }
return
}
noProgress++
diff --git a/internal/deepassessment/intents.go b/internal/deepassessment/intents.go
index 990731d1..5a594abc 100644
--- a/internal/deepassessment/intents.go
+++ b/internal/deepassessment/intents.go
@@ -173,6 +173,48 @@ func (s *Store) AddFact(task string, f *Fact) error {
return err
}
}
+ if f.Confidence == "observed" && strings.TrimSpace(t.ProjectID) != "" && len(f.AssetIDs) > 0 {
+ executions := []string{}
+ for _, callID := range receipts {
+ var executionID string
+ err = tx.QueryRow(`SELECT execution_id FROM deep_assessment_calls WHERE id=? AND execution_id<>'' AND status='completed'`, callID).Scan(&executionID)
+ if err == nil && executionID != "" {
+ executions = append(executions, executionID)
+ }
+ }
+ keptAssets := []string{}
+ for _, id := range f.AssetIDs {
+ var assetProject string
+ if err = tx.QueryRow(`SELECT COALESCE(project_id,'') FROM assets WHERE id=?`, id).Scan(&assetProject); err == nil && (assetProject == "" || assetProject == t.ProjectID) {
+ keptAssets = append(keptAssets, id)
+ }
+ }
+ validExecutions := database.FilterProjectExecutions(tx, t.ProjectID, executions)
+ if len(keptAssets) > 0 && len(validExecutions) > 0 {
+ access, accessErr := s.DB.ResolveRBACAccess(t.ExecutorID)
+ canWrite := accessErr == nil && access != nil && access.Permissions["project:write"]
+ if canWrite {
+ scope := access.Scope
+ if value := strings.TrimSpace(access.PermissionScopes["project:write"]); value != "" {
+ scope = value
+ }
+ canWrite = s.DB.UserCanAccessResource(t.ExecutorID, scope, "project", t.ProjectID)
+ }
+ if canWrite {
+ var conversationID string
+ _ = tx.QueryRow(`SELECT conversation_id FROM deep_assessment_sessions WHERE task_id=? AND step_id=? LIMIT 1`, task, f.StepID).Scan(&conversationID)
+ projectFactID, err := database.PublishConfirmedProjectFact(tx, database.ProjectFact{
+ ProjectID: t.ProjectID, FactKey: "observation/" + strings.ReplaceAll(f.ID, ":", "-"), Confidence: "tentative", Category: "note", Summary: f.Summary, Body: f.Body, SourceConversationID: conversationID,
+ }, keptAssets, validExecutions)
+ if err != nil {
+ return err
+ }
+ if _, err = tx.Exec(`UPDATE deep_assessment_facts SET project_fact_id=? WHERE id=?`, projectFactID, f.ID); err != nil {
+ return err
+ }
+ }
+ }
+ }
if err = Signal(tx, task); err != nil {
return err
}
diff --git a/internal/deepassessment/store.go b/internal/deepassessment/store.go
index 3823c5d9..2f2d571c 100644
--- a/internal/deepassessment/store.go
+++ b/internal/deepassessment/store.go
@@ -1,6 +1,7 @@
package deepassessment
import (
+ "database/sql"
"encoding/json"
"errors"
"fmt"
@@ -58,12 +59,32 @@ func (s *Store) Get(id string) (*Task, error) {
// State and lifecycle events commit together, before any dependent run starts.
func (s *Store) Change(id, step, kind, message string, fn func(*Task) error) error {
- return s.change(id, step, kind, message, nil, fn)
+ return s.change(id, step, kind, message, nil, func(_ *sql.Tx, task *Task) error { return fn(task) })
}
func (s *Store) ChangeAtVersion(id, step, kind, message string, version int64, fn func(*Task) error) error {
- return s.change(id, step, kind, message, &version, fn)
+ return s.change(id, step, kind, message, &version, func(_ *sql.Tx, task *Task) error { return fn(task) })
}
-func (s *Store) change(id, step, kind, message string, version *int64, fn func(*Task) error) error {
+
+// CompleteAtGate writes completed only when the acceptance snapshot still matches the one just checked.
+func (s *Store) CompleteAtGate(id string, changeVersion, taskRevision int64, summary string, expected AcceptanceGate) error {
+ return s.change(id, "", "completed", summary, &changeVersion, func(tx *sql.Tx, latest *Task) error {
+ if latest.Status != "running" || latest.Revision != taskRevision {
+ return ErrConflict
+ }
+ gate, err := acceptanceGate(tx, latest)
+ if err != nil {
+ return err
+ }
+ if gate.Version != expected.Version || gate.Blocking || gate.Legacy != expected.Legacy {
+ return ErrConflict
+ }
+ latest.Status = "completed"
+ latest.Summary = Clip(summary, 16000)
+ return nil
+ })
+}
+
+func (s *Store) change(id, step, kind, message string, version *int64, fn func(*sql.Tx, *Task) error) error {
s.mu.Lock()
defer s.mu.Unlock()
tx, err := s.DB.Begin()
@@ -89,7 +110,7 @@ func (s *Store) change(id, step, kind, message string, version *int64, fn func(*
return err
}
t.Continuous()
- if err = fn(&t); err != nil {
+ if err = fn(tx, &t); err != nil {
return err
}
t.Continuous()
diff --git a/internal/deepassessment/types.go b/internal/deepassessment/types.go
index 92574181..96cc1252 100644
--- a/internal/deepassessment/types.go
+++ b/internal/deepassessment/types.go
@@ -20,39 +20,43 @@ type Task struct {
ActiveSeconds int64 `json:"active_seconds"`
// Legacy budget fields are decoded only to normalize old saved tasks.
- Deadline *time.Time `json:"deadline,omitempty"`
- AutoResume bool `json:"auto_resume"`
- RestartPending bool `json:"restart_pending,omitempty"`
- NextWake *time.Time `json:"next_wake,omitempty"`
- RetryCount int `json:"retry_count"`
- TokenBudget int64 `json:"token_budget,omitempty"`
- TokensUsed int64 `json:"tokens_used"`
- Metrics map[string]SessionMetrics `json:"metrics,omitempty"`
- ID string `json:"id"`
- OwnerID string `json:"owner_id"`
- ExecutorID string `json:"executor_id"`
- ProjectID string `json:"project_id"`
- Name string `json:"name"`
- Objective string `json:"objective"`
- Scope string `json:"scope"`
- Criteria string `json:"criteria"`
- Role string `json:"role"`
- Model string `json:"model"`
- HITLPolicy string `json:"hitl_policy"`
- Concurrency int `json:"concurrency"`
- MaxRounds int `json:"max_rounds,omitempty"`
- RemainingSeconds int64 `json:"remaining_seconds,omitempty"`
- Rounds int `json:"rounds"`
- Status string `json:"status"`
- Revision int64 `json:"revision"`
- Strategy string `json:"strategy"`
- Summary string `json:"summary"`
- Question string `json:"question"`
- Guidance []string `json:"guidance"`
- Steps []Step `json:"steps"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
- RunStartedAt *time.Time `json:"run_started_at,omitempty"`
+ Deadline *time.Time `json:"deadline,omitempty"`
+ AutoResume bool `json:"auto_resume"`
+ RestartPending bool `json:"restart_pending,omitempty"`
+ NextWake *time.Time `json:"next_wake,omitempty"`
+ RetryCount int `json:"retry_count"`
+ TokenBudget int64 `json:"token_budget,omitempty"`
+ TokensUsed int64 `json:"tokens_used"`
+ Metrics map[string]SessionMetrics `json:"metrics,omitempty"`
+ ID string `json:"id"`
+ OwnerID string `json:"owner_id"`
+ ExecutorID string `json:"executor_id"`
+ ProjectID string `json:"project_id"`
+ CollectionID string `json:"collection_id,omitempty"`
+ Name string `json:"name"`
+ Objective string `json:"objective"`
+ Scope string `json:"scope"`
+ Criteria string `json:"criteria"`
+ // AcceptanceMode is "per_item" only when this task was created with its own
+ // acceptance lines. Older tasks leave it empty and keep the previous verdict rule.
+ AcceptanceMode string `json:"acceptance_mode,omitempty"`
+ Role string `json:"role"`
+ Model string `json:"model"`
+ HITLPolicy string `json:"hitl_policy"`
+ Concurrency int `json:"concurrency"`
+ MaxRounds int `json:"max_rounds,omitempty"`
+ RemainingSeconds int64 `json:"remaining_seconds,omitempty"`
+ Rounds int `json:"rounds"`
+ Status string `json:"status"`
+ Revision int64 `json:"revision"`
+ Strategy string `json:"strategy"`
+ Summary string `json:"summary"`
+ Question string `json:"question"`
+ Guidance []string `json:"guidance"`
+ Steps []Step `json:"steps"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ RunStartedAt *time.Time `json:"run_started_at,omitempty"`
}
type Step struct {
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index 9439e909..201cf6e0 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -1887,6 +1887,7 @@ type BatchTaskRequest struct {
CronExpr string `json:"cronExpr,omitempty"` // scheduleMode=cron 时必填
ExecuteNow bool `json:"executeNow,omitempty"` // 创建后是否立即执行(默认 false)
ProjectID string `json:"projectId,omitempty"` // 队列内子对话绑定的项目(可选)
+ CollectionID string `json:"collectionId,omitempty"` // 与信息收集、深度测评共用的资产集合
Concurrency int `json:"concurrency,omitempty"` // 同时执行的子任务数,默认 1,最大 8
}
@@ -1934,6 +1935,17 @@ func (h *AgentHandler) CreateBatchQueue(c *gin.Context) {
return
}
}
+ if strings.TrimSpace(req.CollectionID) != "" {
+ collection, err := h.db.GetAssetCollection(strings.TrimSpace(req.CollectionID))
+ if err != nil || collection.ProjectID != strings.TrimSpace(req.ProjectID) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "资产集合不存在,或不属于所选项目"})
+ return
+ }
+ if collection.MemberCount > 5000 {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "资产集合超过 5000 个成员,请先缩小范围"})
+ return
+ }
+ }
agentMode := config.NormalizeAgentMode(req.AgentMode)
scheduleMode := normalizeBatchQueueScheduleMode(req.ScheduleMode)
@@ -1958,6 +1970,12 @@ func (h *AgentHandler) CreateBatchQueue(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": createErr.Error()})
return
}
+ if strings.TrimSpace(req.CollectionID) != "" {
+ if err := h.batchTaskManager.SetQueueCollection(queue.ID, req.CollectionID); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "queueId": queue.ID})
+ return
+ }
+ }
if session, ok := security.CurrentSession(c); ok && h.db != nil {
_ = h.db.SetResourceOwner("batch_task", queue.ID, session.UserID)
_ = h.db.AssignResourceToUser(session.UserID, "batch_task", queue.ID)
diff --git a/internal/handler/asset.go b/internal/handler/asset.go
index 0eb878db..8ed8a816 100644
--- a/internal/handler/asset.go
+++ b/internal/handler/asset.go
@@ -45,6 +45,10 @@ type importAssetsRequest struct {
Assets []*database.Asset `json:"assets" binding:"required"`
Source string `json:"source"`
SourceQuery string `json:"source_query"`
+ Collection *struct {
+ ProjectID string `json:"project_id"`
+ Name string `json:"name"`
+ } `json:"collection"`
}
type assetScanLink struct {
@@ -100,6 +104,13 @@ func (h *AssetHandler) Import(c *gin.Context) {
owner = session.UserID
allowGlobal = session.Scope == database.RBACScopeAll
}
+ if req.Collection != nil && strings.TrimSpace(req.Collection.ProjectID) != "" {
+ projectID := strings.TrimSpace(req.Collection.ProjectID)
+ if session, ok := security.CurrentSession(c); ok && !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", projectID) {
+ c.JSON(http.StatusForbidden, gin.H{"error": "无权把资产归入该项目集合"})
+ return
+ }
+ }
for _, asset := range req.Assets {
if asset == nil {
continue
@@ -128,9 +139,101 @@ func (h *AssetHandler) Import(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
+ if req.Collection != nil && strings.TrimSpace(req.Collection.ProjectID) != "" && len(result.AppliedIDs) > 0 {
+ projectID := strings.TrimSpace(req.Collection.ProjectID)
+ name := strings.TrimSpace(req.Collection.Name)
+ if name == "" {
+ name = strings.TrimSpace(req.SourceQuery)
+ }
+ if name == "" {
+ name = "导入资产"
+ }
+ collection, err := h.db.CreateAssetCollection(projectID, name, req.Source, req.SourceQuery, owner, result.AppliedIDs)
+ if err != nil {
+ h.logger.Error("保存资产集合失败", zap.Error(err))
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "created": result.Created, "updated": result.Updated, "skipped": result.Skipped})
+ return
+ }
+ result.Collection = collection
+ }
c.JSON(http.StatusOK, result)
}
+func (h *AssetHandler) ListCollections(c *gin.Context) {
+ projectID := strings.TrimSpace(c.Query("project_id"))
+ if projectID == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "需要 project_id"})
+ return
+ }
+ if session, ok := security.CurrentSession(c); ok && !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", projectID) {
+ c.JSON(http.StatusForbidden, gin.H{"error": "无权访问项目"})
+ return
+ }
+ list, err := h.db.ListAssetCollections(projectID)
+ if err != nil {
+ h.logger.Error("加载资产集合失败", zap.Error(err))
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+ session, _ := security.CurrentSession(c)
+ vis, _ := h.db.FactVisibilityFor(session.UserID)
+ for i := range list {
+ total, observed, err := h.db.ObservationCoverageVisible(assetAccess(c), vis, list[i].ID)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+ list[i].MemberCount = total
+ list[i].Observed = observed
+ }
+ c.JSON(http.StatusOK, gin.H{"collections": list})
+}
+
+func (h *AssetHandler) GetCollection(c *gin.Context) {
+ item, err := h.db.GetAssetCollection(c.Param("id"))
+ if err != nil {
+ c.JSON(http.StatusNotFound, gin.H{"error": "资产集合不存在"})
+ return
+ }
+ if session, ok := security.CurrentSession(c); ok && !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", item.ProjectID) {
+ c.JSON(http.StatusForbidden, gin.H{"error": "无权访问项目"})
+ return
+ }
+ session, _ := security.CurrentSession(c)
+ vis, _ := h.db.FactVisibilityFor(session.UserID)
+ total, observed, err := h.db.ObservationCoverageVisible(assetAccess(c), vis, item.ID)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+ item.MemberCount = total
+ item.Observed = observed
+ c.JSON(http.StatusOK, gin.H{"collection": item, "meaning": "observed 统计该集合中已有观察证据的资产,扫描覆盖另行计算。"})
+}
+
+func (h *AssetHandler) Facts(c *gin.Context) {
+ asset, err := h.db.GetAsset(c.Param("id"), assetAccessForPermission(c, "asset:read"))
+ if err != nil || asset == nil {
+ c.JSON(http.StatusNotFound, gin.H{"error": "资产不存在"})
+ return
+ }
+ session, _ := security.CurrentSession(c)
+ vis, err := h.db.FactVisibilityFor(session.UserID)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+ facts, err := h.db.ListVisibleFactsForAsset(asset.ID, vis, 50)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+ if facts == nil {
+ facts = []*database.ProjectFact{}
+ }
+ c.JSON(http.StatusOK, gin.H{"facts": facts})
+}
+
func (h *AssetHandler) List(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
@@ -264,6 +367,23 @@ func (h *AssetHandler) Stats(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
+ if session, ok := security.CurrentSession(c); ok {
+ if vis, visErr := h.db.FactVisibilityFor(session.UserID); visErr == nil {
+ total, observed, covErr := h.db.ObservationCoverageVisible(assetAccess(c), vis, "")
+ if covErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": covErr.Error()})
+ return
+ }
+ rate := 0
+ if total > 0 {
+ rate = int(float64(observed) / float64(total) * 100)
+ }
+ stats["observation"] = map[string]interface{}{
+ "total": total, "observed": observed, "rate": rate,
+ "meaning": "只统计当前账号能读取的项目事实。已确认且有成功回执才计入;扫描覆盖另行计算。",
+ }
+ }
+ }
c.JSON(http.StatusOK, stats)
}
diff --git a/internal/handler/batch_queue_executor.go b/internal/handler/batch_queue_executor.go
index d887e7f0..fc3f2ef1 100644
--- a/internal/handler/batch_queue_executor.go
+++ b/internal/handler/batch_queue_executor.go
@@ -86,6 +86,42 @@ func (h *AgentHandler) runBatchQueueWorker(queueID string) {
}
}
+func batchTerminalSummary(tasks []*BatchTask) string {
+ blocked := 0
+ reasons := []string{}
+ seen := map[string]bool{}
+ lastFail := ""
+ for _, task := range tasks {
+ if task == nil {
+ continue
+ }
+ switch task.Status {
+ case BatchTaskStatusBlocked:
+ blocked++
+ reason := strings.TrimSpace(task.Error)
+ if reason == "" {
+ reason = "资产集合无法确认"
+ }
+ if !seen[reason] {
+ seen[reason] = true
+ reasons = append(reasons, reason)
+ }
+ case BatchTaskStatusFailed:
+ if text := strings.TrimSpace(task.Error); text != "" {
+ lastFail = text
+ }
+ }
+ }
+ parts := []string{}
+ if lastFail != "" {
+ parts = append(parts, lastFail)
+ }
+ if blocked > 0 {
+ parts = append(parts, fmt.Sprintf("受阻 %d 项:%s", blocked, strings.Join(reasons, ";")))
+ }
+ return strings.Join(parts, ";")
+}
+
func (h *AgentHandler) tryFinalizeBatchQueue(queueID string) {
queue, exists := h.batchTaskManager.GetBatchQueue(queueID)
if !exists || queue == nil {
@@ -98,13 +134,7 @@ func (h *AgentHandler) tryFinalizeBatchQueue(queueID string) {
return
}
- lastRunErr := ""
- for _, t := range queue.Tasks {
- if t != nil && t.Status == BatchTaskStatusFailed && t.Error != "" {
- lastRunErr = t.Error
- }
- }
- h.batchTaskManager.SetLastRunError(queueID, lastRunErr)
+ h.batchTaskManager.SetLastRunError(queueID, batchTerminalSummary(queue.Tasks))
h.batchTaskManager.UpdateQueueStatus(queueID, BatchQueueStatusCompleted)
h.logger.Info("批量任务队列执行完成", zap.String("queueId", queueID))
}
@@ -118,6 +148,35 @@ func (h *AgentHandler) executeOneBatchSubTask(queueID string, queue *BatchTaskQu
return
}
principal := authctx.NewPrincipalWithScopes(access.User.ID, access.User.Username, access.Scope, access.Permissions, access.PermissionScopes)
+ collectionNote := ""
+ if collectionID := strings.TrimSpace(queue.CollectionID); collectionID != "" {
+ collection, colErr := h.db.GetAssetCollection(collectionID)
+ scope := access.Scope
+ if value := strings.TrimSpace(access.PermissionScopes["project:read"]); value != "" {
+ scope = value
+ }
+ assetScope := access.Scope
+ if value := strings.TrimSpace(access.PermissionScopes["asset:read"]); value != "" {
+ assetScope = value
+ }
+ visible := 0
+ var visErr error
+ if colErr == nil && collection.ProjectID == strings.TrimSpace(queue.ProjectID) && access.Permissions["project:read"] && access.Permissions["asset:read"] && h.db.UserCanAccessResource(access.User.ID, scope, "project", collection.ProjectID) {
+ vis, _ := h.db.FactVisibilityFor(access.User.ID)
+ visible, _, visErr = h.db.ObservationCoverageVisible(database.RBACListAccess{UserID: access.User.ID, Scope: assetScope}, vis, collection.ID)
+ if visErr == nil && visible > 0 {
+ collectionNote = fmt.Sprintf("本次队列选定的资产集合是「%s」(%s)。当前账号可见 %d 个资产,只针对这些资产。", collection.Name, collection.ID, visible)
+ }
+ }
+ if collectionNote == "" {
+ reason := "资产集合无法确认"
+ if colErr != nil {
+ reason = "资产集合无法确认:" + colErr.Error()
+ }
+ h.batchTaskManager.UpdateTaskStatus(queueID, task.ID, BatchTaskStatusBlocked, "", reason)
+ return
+ }
+ }
title := safeTruncateString(task.Message, 50)
batchMeta := batchSubTaskConversationMeta(h.config, queue)
conv, err := h.db.CreateConversation(title, batchMeta)
@@ -148,6 +207,9 @@ func (h *AgentHandler) executeOneBatchSubTask(queueID string, queue *BatchTaskQu
}
}
}
+ if collectionNote != "" {
+ finalMessage = collectionNote + "\n\n" + finalMessage
+ }
if _, err = h.db.AddMessage(conversationID, "user", task.Message, nil); err != nil {
h.logger.Error("保存用户消息失败", zap.String("queueId", queueID), zap.String("taskId", task.ID), zap.String("conversationId", conversationID), zap.Error(err))
diff --git a/internal/handler/batch_task_manager.go b/internal/handler/batch_task_manager.go
index 80e3bfbc..6686645e 100644
--- a/internal/handler/batch_task_manager.go
+++ b/internal/handler/batch_task_manager.go
@@ -40,6 +40,7 @@ const (
BatchTaskStatusCompleted = "completed"
BatchTaskStatusFailed = "failed"
BatchTaskStatusCancelled = "cancelled"
+ BatchTaskStatusBlocked = "blocked"
// MaxBatchTasksPerQueue 单个队列最大任务数
MaxBatchTasksPerQueue = 10000
@@ -84,6 +85,7 @@ type BatchTaskQueue struct {
LastScheduleError string `json:"lastScheduleError,omitempty"`
LastRunError string `json:"lastRunError,omitempty"`
ProjectID string `json:"projectId,omitempty"`
+ CollectionID string `json:"collectionId,omitempty"`
Concurrency int `json:"concurrency"` // 同时执行的子任务数,默认 1
Tasks []*BatchTask `json:"tasks"`
Status string `json:"status"` // pending, running, paused, completed, cancelled
@@ -275,6 +277,27 @@ func (m *BatchTaskManager) CreateBatchQueue(
return queue, nil
}
+// SetQueueCollection records the shared asset collection on an existing queue.
+func (m *BatchTaskManager) SetQueueCollection(queueID, collectionID string) error {
+ collectionID = strings.TrimSpace(collectionID)
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ queue, ok := m.queues[queueID]
+ if !ok {
+ return fmt.Errorf("队列不存在")
+ }
+ queue.CollectionID = collectionID
+ if m.db == nil {
+ return nil
+ }
+ var value any
+ if collectionID != "" {
+ value = collectionID
+ }
+ _, err := m.db.Exec(`UPDATE batch_task_queues SET collection_id=? WHERE id=?`, value, queueID)
+ return err
+}
+
// GetBatchQueue 获取批量任务队列
func (m *BatchTaskManager) GetBatchQueue(queueID string) (*BatchTaskQueue, bool) {
m.mu.RLock()
@@ -361,6 +384,9 @@ func (m *BatchTaskManager) loadQueueFromDB(queueID string) *BatchTaskQueue {
if queueRow.ProjectID.Valid {
queue.ProjectID = strings.TrimSpace(queueRow.ProjectID.String)
}
+ if queueRow.CollectionID.Valid {
+ queue.CollectionID = strings.TrimSpace(queueRow.CollectionID.String)
+ }
queue.Concurrency = batchQueueConcurrencyFromRow(queueRow)
if queueRow.StartedAt.Valid {
queue.StartedAt = &queueRow.StartedAt.Time
@@ -606,6 +632,9 @@ func (m *BatchTaskManager) LoadFromDB() error {
if queueRow.ProjectID.Valid {
queue.ProjectID = strings.TrimSpace(queueRow.ProjectID.String)
}
+ if queueRow.CollectionID.Valid {
+ queue.CollectionID = strings.TrimSpace(queueRow.CollectionID.String)
+ }
queue.Concurrency = batchQueueConcurrencyFromRow(queueRow)
if queueRow.StartedAt.Valid {
queue.StartedAt = &queueRow.StartedAt.Time
@@ -684,7 +713,7 @@ func (m *BatchTaskManager) UpdateTaskStatusWithConversationID(queueID, taskID, s
if status == BatchTaskStatusRunning && task.StartedAt == nil {
task.StartedAt = &now
}
- if status == BatchTaskStatusCompleted || status == BatchTaskStatusFailed || status == BatchTaskStatusCancelled {
+ if status == BatchTaskStatusCompleted || status == BatchTaskStatusFailed || status == BatchTaskStatusCancelled || status == BatchTaskStatusBlocked {
task.CompletedAt = &now
}
break
diff --git a/internal/handler/batch_task_manager_test.go b/internal/handler/batch_task_manager_test.go
index 99863648..57eb38cc 100644
--- a/internal/handler/batch_task_manager_test.go
+++ b/internal/handler/batch_task_manager_test.go
@@ -2,6 +2,7 @@ package handler
import (
"errors"
+ "strings"
"testing"
"go.uber.org/zap"
@@ -117,6 +118,35 @@ func TestDeleteQueueBlockedWhileRunning(t *testing.T) {
}
}
+func TestBlockedTasksEnterQueueSummary(t *testing.T) {
+ h := &AgentHandler{batchTaskManager: NewBatchTaskManager(zap.NewNop()), logger: zap.NewNop()}
+ all, err := h.batchTaskManager.CreateBatchQueue("all blocked", "", "single", "manual", "", "", nil, 1, []string{"one", "two"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.batchTaskManager.UpdateQueueStatus(all.ID, BatchQueueStatusRunning)
+ h.batchTaskManager.UpdateTaskStatus(all.ID, all.Tasks[0].ID, BatchTaskStatusBlocked, "", "资产集合无法确认")
+ h.batchTaskManager.UpdateTaskStatus(all.ID, all.Tasks[1].ID, BatchTaskStatusBlocked, "", "资产集合无法确认")
+ h.tryFinalizeBatchQueue(all.ID)
+ got, ok := h.batchTaskManager.GetBatchQueue(all.ID)
+ if !ok || got.LastRunError == "" || !strings.Contains(got.LastRunError, "受阻 2 项") || !strings.Contains(got.LastRunError, "资产集合无法确认") {
+ t.Fatalf("all blocked finished without a reason: ok=%v err=%q", ok, got.LastRunError)
+ }
+
+ mixed, err := h.batchTaskManager.CreateBatchQueue("mixed", "", "single", "manual", "", "", nil, 1, []string{"done", "held"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.batchTaskManager.UpdateQueueStatus(mixed.ID, BatchQueueStatusRunning)
+ h.batchTaskManager.UpdateTaskStatus(mixed.ID, mixed.Tasks[0].ID, BatchTaskStatusCompleted, "ok", "")
+ h.batchTaskManager.UpdateTaskStatus(mixed.ID, mixed.Tasks[1].ID, BatchTaskStatusBlocked, "", "成员当前不可见")
+ h.tryFinalizeBatchQueue(mixed.ID)
+ got, ok = h.batchTaskManager.GetBatchQueue(mixed.ID)
+ if !ok || got.Status != BatchQueueStatusCompleted || !strings.Contains(got.LastRunError, "受阻 1 项") || !strings.Contains(got.LastRunError, "成员当前不可见") {
+ t.Fatalf("mixed result: ok=%v status=%s err=%q", ok, got.Status, got.LastRunError)
+ }
+}
+
func TestTryMarkQueueExecutorDedupes(t *testing.T) {
t.Parallel()
m := NewBatchTaskManager(zap.NewNop())
diff --git a/internal/handler/deep_assessment.go b/internal/handler/deep_assessment.go
index 47334fb1..305115d3 100644
--- a/internal/handler/deep_assessment.go
+++ b/internal/handler/deep_assessment.go
@@ -149,16 +149,17 @@ func (h *AgentHandler) DeepAssessmentOptions(c *gin.Context) {
func (h *AgentHandler) CreateDeepAssessment(c *gin.Context) {
var req struct {
- Name string `json:"name"`
- Objective string `json:"objective"`
- Scope string `json:"scope"`
- Criteria string `json:"criteria"`
- ProjectID string `json:"project_id"`
- Role string `json:"role"`
- Model string `json:"model"`
- HITLPolicy string `json:"hitl_policy"`
- Concurrency int `json:"concurrency"`
- AutoResume *bool `json:"auto_resume"`
+ Name string `json:"name"`
+ Objective string `json:"objective"`
+ Scope string `json:"scope"`
+ Criteria string `json:"criteria"`
+ ProjectID string `json:"project_id"`
+ CollectionID string `json:"collection_id"`
+ Role string `json:"role"`
+ Model string `json:"model"`
+ HITLPolicy string `json:"hitl_policy"`
+ Concurrency int `json:"concurrency"`
+ AutoResume *bool `json:"auto_resume"`
}
if !deepAssessmentBody(c, &req) {
return
@@ -184,10 +185,34 @@ func (h *AgentHandler) CreateDeepAssessment(c *gin.Context) {
c.JSON(403, gin.H{"error": "无权访问项目"})
return
}
+ var collectionMembers []string
+ if strings.TrimSpace(req.CollectionID) != "" {
+ collection, err := h.db.GetAssetCollection(strings.TrimSpace(req.CollectionID))
+ if err != nil || collection.ProjectID != req.ProjectID {
+ c.JSON(400, gin.H{"error": "资产集合不存在,或不属于所选项目"})
+ return
+ }
+ if collection.MemberCount > 5000 {
+ c.JSON(400, gin.H{"error": "资产集合超过 5000 个成员,请先缩小范围"})
+ return
+ }
+ members, err := h.db.CollectionMemberIDs(collection.ID, 5000)
+ if err != nil {
+ deepAssessmentError(c, err)
+ return
+ }
+ for _, id := range members {
+ if session.ScopeFor("asset:read") == database.RBACScopeAll || h.db.UserCanAccessResource(session.UserID, session.ScopeFor("asset:read"), "asset", id) {
+ collectionMembers = append(collectionMembers, id)
+ }
+ }
+ req.CollectionID = collection.ID
+ }
+ suppliedCriteria := strings.TrimSpace(req.Criteria)
if strings.TrimSpace(req.Scope) == "" {
req.Scope = req.Objective
}
- if strings.TrimSpace(req.Criteria) == "" {
+ if suppliedCriteria == "" {
req.Criteria = req.Objective
}
autoResume := true
@@ -195,7 +220,10 @@ func (h *AgentHandler) CreateDeepAssessment(c *gin.Context) {
autoResume = *req.AutoResume
}
now := time.Now().UTC()
- t := &deepassessment.Task{ID: uuid.NewString(), AutoResume: autoResume, OwnerID: session.UserID, ExecutorID: session.UserID, Name: req.Name, Objective: req.Objective, Scope: strings.TrimSpace(req.Scope), Criteria: strings.TrimSpace(req.Criteria), ProjectID: req.ProjectID, Role: req.Role, Model: req.Model, HITLPolicy: req.HITLPolicy, Concurrency: req.Concurrency, Status: "draft", Steps: []deepassessment.Step{}, Guidance: []string{}, CreatedAt: now, UpdatedAt: now}
+ t := &deepassessment.Task{ID: uuid.NewString(), AutoResume: autoResume, OwnerID: session.UserID, ExecutorID: session.UserID, Name: req.Name, Objective: req.Objective, Scope: strings.TrimSpace(req.Scope), Criteria: strings.TrimSpace(req.Criteria), ProjectID: req.ProjectID, CollectionID: strings.TrimSpace(req.CollectionID), Role: req.Role, Model: req.Model, HITLPolicy: req.HITLPolicy, Concurrency: req.Concurrency, Status: "draft", Steps: []deepassessment.Step{}, Guidance: []string{}, CreatedAt: now, UpdatedAt: now}
+ if suppliedCriteria != "" && suppliedCriteria != strings.TrimSpace(req.Objective) {
+ t.AcceptanceMode = deepassessment.AcceptanceModePerItem
+ }
if _, err := h.deepAssessmentRuntime.configuration(t); err != nil {
deepAssessmentError(c, err)
return
@@ -204,6 +232,12 @@ func (h *AgentHandler) CreateDeepAssessment(c *gin.Context) {
deepAssessmentError(c, err)
return
}
+ if len(collectionMembers) > 0 {
+ if err := h.deepAssessments.Store.BindAssets(t.ID, collectionMembers); err != nil {
+ deepAssessmentError(c, err)
+ return
+ }
+ }
if h.audit != nil {
h.audit.RecordOK(c, "task", "create_deep_assessment", "创建深度测评", "deep_assessment", t.ID, nil)
}
diff --git a/internal/handler/deep_assessment_acceptance.go b/internal/handler/deep_assessment_acceptance.go
index 03d0a129..afc8c04a 100644
--- a/internal/handler/deep_assessment_acceptance.go
+++ b/internal/handler/deep_assessment_acceptance.go
@@ -70,7 +70,7 @@ func (h *AgentHandler) appendAcceptanceReport(c *gin.Context, task *deepassessme
for _, row := range matrix {
counts[row.Status]++
}
- fmt.Fprintf(b, "\n## 验收证据矩阵\n\n已有证据 %d 项,缺证据 %d 项,待人工复核 %d 项。状态反映当前证据关联情况,验收结论由审阅人核对。\n",
+ fmt.Fprintf(b, "\n## 逐项验收\n\n验收证据矩阵:已有证据 %d 项,缺证据 %d 项,待人工复核 %d 项。缺证据的必验项不能视为完成。\n",
counts["has_evidence"], counts["missing"], counts["needs_review"])
matrixURL := assessmentReportLink(c, task.ID, "", "acceptance")
pathURL := assessmentReportLink(c, task.ID, "", "evidence-path")
diff --git a/internal/handler/deep_assessment_acceptance_test.go b/internal/handler/deep_assessment_acceptance_test.go
index 5504ad82..69e87dac 100644
--- a/internal/handler/deep_assessment_acceptance_test.go
+++ b/internal/handler/deep_assessment_acceptance_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"cyberstrike-ai/internal/agentruntime"
+ "cyberstrike-ai/internal/database"
"cyberstrike-ai/internal/deepassessment"
"github.com/gin-gonic/gin"
)
@@ -131,3 +132,33 @@ func TestDeepAssessmentAcceptanceMatrix(t *testing.T) {
t.Fatal(rows)
}
}
+
+func TestReportKeepsLegacyRetestExecutionReference(t *testing.T) {
+ h, task := deepAssessmentFixture(t)
+ conv, err := h.db.CreateConversation("legacy", database.ConversationCreateMeta{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ vuln, err := h.db.CreateVulnerability(&database.Vulnerability{ConversationID: conv.ID, Title: "legacy", Severity: "low", Status: "fixed", Target: "fixture.example"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = h.db.Exec(`UPDATE vulnerabilities SET owner_user_id=? WHERE id=?`, task.OwnerID, vuln.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = h.db.Exec(`INSERT INTO vulnerability_assessment_sources(vulnerability_id,assessment_id,assessment_name,step_id,step_title,conversation_id) VALUES(?,?,?,?,?,?)`, vuln.ID, task.ID, task.Name, "inventory", "inventory", conv.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = h.db.Exec(`INSERT INTO deep_assessment_finding_reviews(id,vulnerability_id,task_id,step_id,verdict,reason,evidence_json,created_at) VALUES(?,?,?,?,?,?,?,?)`, "old-review", vuln.ID, task.ID, "retest", "inconclusive", "old retest", `["exec-not-a-call"]`, task.CreatedAt); err != nil {
+ t.Fatal(err)
+ }
+ r := explorationRouter(h, task.OwnerID, map[string]bool{"assessments:read": true, "vulnerability:read": true})
+ r.GET("/api/deep-assessments/:id/report", h.DeepAssessmentReport)
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/api/deep-assessments/task/report", nil)
+ r.ServeHTTP(w, req)
+ body := w.Body.String()
+ if w.Code != 200 || !strings.Contains(body, "证据不可用") || !strings.Contains(body, "已标记修复") || !strings.Contains(body, "尚无复测记录") || strings.Contains(body, "修复已验证") {
+ t.Fatalf("manual fixed was treated as a verified retest: %d %s", w.Code, body)
+ }
+}
diff --git a/internal/handler/deep_assessment_graph.go b/internal/handler/deep_assessment_graph.go
index dd16e3d7..2325cad4 100644
--- a/internal/handler/deep_assessment_graph.go
+++ b/internal/handler/deep_assessment_graph.go
@@ -149,6 +149,26 @@ func (r *deepAssessmentRuntime) context(t *deepassessment.Task) (string, error)
}
situation["asset_observation_coverage"] = coverage
situation["coverage_meaning"] = "仅统计关联资产中存在 observed 事实及原始回执的数量;不表示测试穷尽、无漏洞或目标完成。"
+ if t.CollectionID != "" {
+ vis, err := r.h.db.FactVisibilityFor(p.UserID)
+ if err != nil {
+ return "", err
+ }
+ total, observed, err := r.h.db.ObservationCoverageVisible(database.RBACListAccess{UserID: p.UserID, Scope: p.ScopeFor("asset:read")}, vis, t.CollectionID)
+ if err != nil {
+ return "", err
+ }
+ facts, err := r.h.db.VisibleProjectFactSummaries(t.CollectionID, vis, 12)
+ if err != nil {
+ return "", err
+ }
+ for i := range facts {
+ facts[i].Summary = deepassessment.Clip(facts[i].Summary, 300)
+ }
+ situation["collection_id"] = t.CollectionID
+ situation["collection_observation"] = map[string]any{"members": total, "observed": observed, "meaning": "与资产库、仪表盘使用同一口径:集合内已有成功回执的观察或已确认项目事实。不是扫描覆盖。"}
+ situation["project_facts"] = facts
+ }
}
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/deep_assessment_report.go b/internal/handler/deep_assessment_report.go
index 185c75ba..d0ea7339 100644
--- a/internal/handler/deep_assessment_report.go
+++ b/internal/handler/deep_assessment_report.go
@@ -12,6 +12,21 @@ import (
"github.com/gin-gonic/gin"
)
+func vulnerabilityDisposition(status string) string {
+ switch strings.TrimSpace(status) {
+ case "fixed":
+ return "已标记修复"
+ case "confirmed":
+ return "已确认"
+ case "false_positive":
+ return "误报"
+ case "ignored":
+ return "已忽略"
+ default:
+ return "待处置"
+ }
+}
+
func assessmentReportLink(c *gin.Context, task, step, tab string) string {
scheme := "http"
if c.Request.TLS != nil {
@@ -41,7 +56,23 @@ func (h *AgentHandler) appendAssessmentCoverageReport(c *gin.Context, t *deepass
return err
}
linked, observed := coverage["linked"], coverage["with_observed_evidence"]
- fmt.Fprintf(b, "\n## 资产观察证据\n\n可读的关联资产 %d 项,已有观察事实 %d 项,暂无观察事实 %d 项。\n\n此处统计关联资产的证据记录,实际测评范围和完成情况见目标、验收条件及回执。\n\n[查看当前缺证据清单](%s&observation=missing)\n", linked, observed, linked-observed, assessmentReportLink(c, t.ID, "", "assets"))
+ fmt.Fprintf(b, "\n## 本次范围\n\n")
+ if t.CollectionID != "" {
+ if !security.SessionHasPermission(c, "project:read") || !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", t.ProjectID) {
+ fmt.Fprintf(b, "本次确认的资产集合当前不可读取。\n\n")
+ } else if item, err := h.db.GetAssetCollection(t.CollectionID); err == nil && item.ProjectID == t.ProjectID {
+ fmt.Fprintf(b, "本次确认的资产集合:%s(%s)。\n\n", item.Name, item.ID)
+ } else {
+ fmt.Fprintf(b, "本次确认的资产集合 %s 当前不可读取。\n\n", t.CollectionID)
+ }
+ } else {
+ b.WriteString("本次没有选定资产集合,范围以目标和补充限制为准。\n\n")
+ }
+ reportLiteral(b, t.Scope)
+ vis, _ := h.db.FactVisibilityFor(session.UserID)
+ histTotal, histObserved, _ := h.db.ObservationCoverageVisible(database.RBACListAccess{UserID: session.UserID, Scope: session.ScopeFor("asset:read")}, vis, t.CollectionID)
+ fmt.Fprintf(b, "\n## 项目历史观察\n\n当前账号能读取的项目事实里,已确认且有成功回执的资产 %d / %d。未审核的观察引用不会升为已确认。\n", histObserved, histTotal)
+ fmt.Fprintf(b, "\n## 本次覆盖\n\n可读的关联资产 %d 项,本次已有观察事实 %d 项,暂无观察事实 %d 项。\n\n这是本次测评覆盖,不是扫描覆盖,也不表示目标已经完成。\n\n[查看当前缺证据清单](%s&observation=missing)\n", linked, observed, linked-observed, assessmentReportLink(c, t.ID, "", "assets"))
return nil
}
func (h *AgentHandler) reportReviews(task, finding string) ([]database.AssessmentFindingReview, error) {
@@ -68,7 +99,8 @@ func (h *AgentHandler) reportReceipt(b *strings.Builder, c *gin.Context, task, s
var id, tool, state, result, execution string
err := h.db.QueryRow("SELECT id,tool,status,result,execution_id FROM deep_assessment_calls WHERE task_id=? AND step_id=? AND (id=? OR execution_id=?)", task, step, ref, ref).Scan(&id, &tool, &state, &result, &execution)
if err != nil {
- return err
+ fmt.Fprintf(b, "\n证据不可用:引用 %s 不是本意图可读取的测评回执,其余内容仍导出。\n", ref)
+ return nil
}
fmt.Fprintf(b, "\n**回执 %s** · %s · %s\n\n[回到来源步骤与回执](%s)\n\n执行记录:%s\n\n已保存的回执摘录(完整执行过程请打开来源会话):\n", id, tool, state, assessmentReportLink(c, task, step, "evidence"), execution)
reportLiteral(b, result)
@@ -106,7 +138,18 @@ func (h *AgentHandler) appendAssessmentFindingsReport(c *gin.Context, t *deepass
return err
}
count++
- fmt.Fprintf(b, "\n### %d. %s\n\n漏洞 ID:%s · 严重程度:%s · 状态:%s\n\n来源意图:%s · %s\n\n[测评中的漏洞与证据](%s)\n", count, strings.ReplaceAll(v.Title, "\n", " "), v.ID, v.Severity, v.Status, v.AssessmentStepID, v.AssessmentStepTitle, assessmentReportLink(c, t.ID, v.AssessmentStepID, "evidence")+"&vulnerability_id="+url.QueryEscape(v.ID))
+ vis, visErr := h.db.FactVisibilityFor(session.UserID)
+ if visErr != nil {
+ vis = database.FactVisibility{}
+ }
+ conclusion, hint, err := h.db.RetestConclusion(vis, v.ID)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintf(b, "\n### %d. %s\n\n漏洞 ID:%s · 严重程度:%s · 状态:%s · 处置:%s · 复测:%s\n\n来源意图:%s · %s\n\n[测评中的漏洞与证据](%s)\n", count, strings.ReplaceAll(v.Title, "\n", " "), v.ID, v.Severity, v.Status, vulnerabilityDisposition(v.Status), conclusion, v.AssessmentStepID, v.AssessmentStepTitle, assessmentReportLink(c, t.ID, v.AssessmentStepID, "evidence")+"&vulnerability_id="+url.QueryEscape(v.ID))
+ if hint != "" {
+ fmt.Fprintf(b, "\n%s\n", hint)
+ }
for _, field := range []struct{ name, text string }{{"目标", v.Target}, {"说明", v.Description}, {"前置条件", v.Preconditions}, {"复现步骤", v.ReproSteps}, {"复现证据", v.Evidence}, {"影响", v.Impact}, {"修复建议", v.Recommendation}, {"复测说明", v.RetestNotes}, {"复测历史", v.RetestLog}} {
if field.text != "" {
fmt.Fprintf(b, "\n#### %s\n", field.name)
@@ -121,9 +164,12 @@ func (h *AgentHandler) appendAssessmentFindingsReport(c *gin.Context, t *deepass
b.WriteString("\n尚无独立复核记录。\n")
}
for _, review := range v.AssessmentReviews {
- label := "独立复核"
- if review.Verdict == "reported" {
+ label := "发现复核"
+ switch review.Verdict {
+ case "reported":
label = "首次登记"
+ case "inconclusive":
+ label = "无法确认"
}
fmt.Fprintf(b, "\n#### %s · %s\n\n意图:%s · 时间:%s\n\n[查看复核步骤与原始回执](%s)\n", label, review.Verdict, review.StepID, review.CreatedAt.Format("2006-01-02T15:04:05Z07:00"), assessmentReportLink(c, t.ID, review.StepID, "evidence"))
reportLiteral(b, review.Reason)
diff --git a/internal/handler/deep_assessment_test.go b/internal/handler/deep_assessment_test.go
index ed5faa6d..bcca0ffb 100644
--- a/internal/handler/deep_assessment_test.go
+++ b/internal/handler/deep_assessment_test.go
@@ -304,6 +304,11 @@ func TestDeepAssessmentCreateOnlySavesDraftAndRejectsOversizedBody(t *testing.T)
}
}
+func suppliedPerItem(extra map[string]string) bool {
+ criteria := strings.TrimSpace(extra["criteria"])
+ return criteria != "" && criteria != "inspect fixture"
+}
+
func TestDeepAssessmentOptionalFieldsInheritObjective(t *testing.T) {
h, owner := deepAssessmentFixture(t)
router := assessmentRouter(h, owner.OwnerID)
@@ -354,6 +359,13 @@ func TestDeepAssessmentOptionalFieldsInheritObjective(t *testing.T) {
if saved.Scope != tc.wantScope || saved.Criteria != tc.wantCriteria || saved.Objective != strings.TrimSpace(tc.objective) {
t.Fatal("optional fields were not inherited or explicit values were changed")
}
+ perItem := suppliedPerItem(tc.extra)
+ if perItem && saved.AcceptanceMode != deepassessment.AcceptanceModePerItem {
+ t.Fatal("explicit acceptance lines did not enable per-item evidence")
+ }
+ if !perItem && saved.AcceptanceMode != "" {
+ t.Fatalf("inherited criteria enabled per-item acceptance: %q", saved.AcceptanceMode)
+ }
wantName := strings.TrimSpace(values["name"])
if wantName == "" {
wantName = deepassessment.Clip(strings.TrimSpace(tc.objective), 80)
diff --git a/internal/handler/project.go b/internal/handler/project.go
index 1c91e5bd..cc885cc9 100644
--- a/internal/handler/project.go
+++ b/internal/handler/project.go
@@ -249,6 +249,9 @@ type upsertFactRequest struct {
Confidence string `json:"confidence"`
Pinned bool `json:"pinned"`
RelatedVulnerabilityID string `json:"related_vulnerability_id"`
+ ConfirmationNote string `json:"confirmation_note"`
+ AssetIDs *[]string `json:"asset_ids"`
+ ExecutionIDs *[]string `json:"execution_ids"`
Links []factLinkRequest `json:"links"`
LinksText *string `json:"links_text"`
}
@@ -262,6 +265,9 @@ type updateFactRequest struct {
Confidence *string `json:"confidence"`
Pinned *bool `json:"pinned"`
RelatedVulnerabilityID *string `json:"related_vulnerability_id"`
+ ConfirmationNote *string `json:"confirmation_note"`
+ AssetIDs *[]string `json:"asset_ids"`
+ ExecutionIDs *[]string `json:"execution_ids"`
ClearBody bool `json:"clear_body"`
Links *[]factLinkRequest `json:"links"`
LinksText *string `json:"links_text"`
@@ -320,12 +326,44 @@ func (h *ProjectHandler) applyFactLinksAfterUpsert(projectID string, fact *datab
return nil
}
-func (h *ProjectHandler) factResponseWithLinks(projectID string, f *database.ProjectFact, includeLinks bool) interface{} {
+func (h *ProjectHandler) replaceFactEvidence(fact *database.ProjectFact, assets, executions *[]string) error {
+ if fact == nil || (assets == nil && executions == nil) {
+ return nil
+ }
+ assetIDs, executionIDs := []string{}, []string{}
+ if assets != nil {
+ assetIDs = *assets
+ }
+ if executions != nil {
+ executionIDs = *executions
+ }
+ return h.db.ReplaceProjectFactEvidence(fact.ID, fact.ProjectID, assetIDs, executionIDs, assets != nil, executions != nil)
+}
+
+func (h *ProjectHandler) factVisibility(c *gin.Context) database.FactVisibility {
+ session, ok := security.CurrentSession(c)
+ if !ok || strings.TrimSpace(session.UserID) == "" {
+ return database.FactVisibility{}
+ }
+ vis, err := h.db.FactVisibilityFor(session.UserID)
+ if err != nil {
+ return database.FactVisibility{}
+ }
+ return vis
+}
+
+func (h *ProjectHandler) factResponseWithLinks(c *gin.Context, projectID string, f *database.ProjectFact, includeLinks bool) interface{} {
+ vis := h.factVisibility(c)
+ if f != nil {
+ _ = h.db.PresentProjectFacts([]*database.ProjectFact{f}, vis)
+ }
if !includeLinks || f == nil {
return f
}
out, _ := h.db.ListOutgoingProjectFactEdges(projectID, f.FactKey)
in, _ := h.db.ListIncomingProjectFactEdges(projectID, f.FactKey)
+ h.db.RedactFactEdges(out, vis)
+ h.db.RedactFactEdges(in, vis)
return &factWithLinksResponse{
ProjectFact: f,
OutgoingLinks: out,
@@ -343,7 +381,7 @@ func (h *ProjectHandler) ListFacts(c *gin.Context) {
return
}
includeLinks := c.Query("include_links") == "1" || c.Query("include_links") == "true"
- c.JSON(http.StatusOK, h.factResponseWithLinks(projectID, f, includeLinks))
+ c.JSON(http.StatusOK, h.factResponseWithLinks(c, projectID, f, includeLinks))
return
}
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "100"))
@@ -365,6 +403,10 @@ func (h *ProjectHandler) ListFacts(c *gin.Context) {
if list == nil {
list = []*database.ProjectFact{}
}
+ if err = h.db.PresentProjectFacts(list, h.factVisibility(c)); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
if sparseOnly := c.Query("sparse_only"); sparseOnly == "1" || sparseOnly == "true" {
filtered := make([]*database.ProjectFact, 0, len(list))
for _, f := range list {
@@ -446,8 +488,16 @@ func (h *ProjectHandler) CreateFact(c *gin.Context) {
Confidence: req.Confidence,
Pinned: req.Pinned,
RelatedVulnerabilityID: req.RelatedVulnerabilityID,
+ ConfirmationNote: req.ConfirmationNote,
}
- created, err := h.db.UpsertProjectFact(f)
+ assetIDs, executionIDs := []string{}, []string{}
+ if req.AssetIDs != nil {
+ assetIDs = *req.AssetIDs
+ }
+ if req.ExecutionIDs != nil {
+ executionIDs = *req.ExecutionIDs
+ }
+ created, err := h.db.SaveProjectFact(f, assetIDs, executionIDs, req.AssetIDs != nil, req.ExecutionIDs != nil)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -458,7 +508,7 @@ func (h *ProjectHandler) CreateFact(c *gin.Context) {
return
}
created, _ = h.db.GetProjectFactByKey(projectID, created.FactKey)
- c.JSON(http.StatusOK, h.factResponseWithLinks(projectID, created, true))
+ c.JSON(http.StatusOK, h.factResponseWithLinks(c, projectID, created, true))
}
// UpdateFact PUT /api/projects/:id/facts/:factId
@@ -508,7 +558,17 @@ func (h *ProjectHandler) UpdateFact(c *gin.Context) {
if req.RelatedVulnerabilityID != nil {
existing.RelatedVulnerabilityID = *req.RelatedVulnerabilityID
}
- updated, err := h.db.UpsertProjectFact(existing)
+ if req.ConfirmationNote != nil {
+ existing.ConfirmationNote = *req.ConfirmationNote
+ }
+ assetIDs, executionIDs := []string{}, []string{}
+ if req.AssetIDs != nil {
+ assetIDs = *req.AssetIDs
+ }
+ if req.ExecutionIDs != nil {
+ executionIDs = *req.ExecutionIDs
+ }
+ updated, err := h.db.SaveProjectFact(existing, assetIDs, executionIDs, req.AssetIDs != nil, req.ExecutionIDs != nil)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -535,7 +595,7 @@ func (h *ProjectHandler) UpdateFact(c *gin.Context) {
}
}
updated, _ = h.db.GetProjectFactByKey(projectID, updated.FactKey)
- c.JSON(http.StatusOK, h.factResponseWithLinks(projectID, updated, true))
+ c.JSON(http.StatusOK, h.factResponseWithLinks(c, projectID, updated, true))
}
// DeleteFact DELETE /api/projects/:id/facts/:factId
diff --git a/internal/handler/project_fact_visibility_test.go b/internal/handler/project_fact_visibility_test.go
new file mode 100644
index 00000000..1d8f63e3
--- /dev/null
+++ b/internal/handler/project_fact_visibility_test.go
@@ -0,0 +1,180 @@
+package handler
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "cyberstrike-ai/internal/database"
+ "cyberstrike-ai/internal/security"
+ "github.com/gin-gonic/gin"
+ "go.uber.org/zap"
+)
+
+func TestReadableProjectHidesUnreadableFactSources(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ agent, task := deepAssessmentFixture(t)
+ db := agent.db
+ now := time.Now().UTC()
+ if _, err := db.Exec(`INSERT INTO rbac_roles(id,name,description,scope,is_system,created_at,updated_at) VALUES('role-reader','reader','','own',0,?,?)`, now, now); err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range []string{"project:read", "project:write", "chat:read", "asset:read", "vulnerability:read", "assessments:read"} {
+ if _, err := db.Exec(`INSERT OR IGNORE INTO rbac_role_permissions(role_id,permission_key,created_at) VALUES('role-reader',?,?)`, key, now); err != nil {
+ t.Fatal(err)
+ }
+ }
+ reader, err := db.CreateRBACUser("reader", "Reader", "hash", true, []string{"role-reader"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ other, err := db.CreateRBACUser("other", "Other", "hash", true, []string{"role-reader"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ project, err := db.CreateProject(&database.Project{Name: "reader project"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`UPDATE projects SET owner_user_id=? WHERE id=?`, reader.ID, project.ID); err != nil {
+ t.Fatal(err)
+ }
+ asset := &database.Asset{ProjectID: project.ID, Domain: "visible.example", Status: "active"}
+ if _, err = db.UpsertAssets([]*database.Asset{asset}, reader.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ readable, err := db.CreateConversation("readable", database.ConversationCreateMeta{ProjectID: project.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ secret, err := db.CreateConversation("secret", database.ConversationCreateMeta{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = db.SetResourceOwner("conversation", readable.ID, reader.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err = db.SetResourceOwner("conversation", secret.ID, other.ID); err != nil {
+ t.Fatal(err)
+ }
+ const secretMessage = "secret-message-id"
+ const secretExecution = "secret-execution-id"
+ if _, err = db.Exec(`INSERT INTO tool_executions(id,tool_name,arguments,status,start_time,conversation_id) VALUES('exec-readable','http','{}','completed',?,?)`, now, readable.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO tool_executions(id,tool_name,arguments,status,start_time,conversation_id) VALUES(?,?,?,?,?,?)`, secretExecution, "http", "{}", "completed", now, secret.ID); err != nil {
+ t.Fatal(err)
+ }
+ manual, err := db.CreateVulnerability(&database.Vulnerability{ConversationID: readable.ID, ProjectID: project.ID, Title: "manual fixed", Severity: "low", Status: "fixed", Target: "https://visible.example/manual"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ verified, err := db.CreateVulnerability(&database.Vulnerability{ConversationID: readable.ID, ProjectID: project.ID, Title: "verified fix", Severity: "low", Status: "open", Target: "https://visible.example/verified"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ unchecked, err := db.CreateVulnerability(&database.Vulnerability{ConversationID: readable.ID, ProjectID: project.ID, Title: "unchecked fix", Severity: "low", Status: "open", Target: "https://visible.example/unchecked"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, vuln := range []*database.Vulnerability{manual, verified, unchecked} {
+ if _, err = db.Exec(`UPDATE vulnerabilities SET owner_user_id=? WHERE id=?`, reader.ID, vuln.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(`INSERT INTO vulnerability_assessment_sources(vulnerability_id,assessment_id,assessment_name,step_id,step_title,conversation_id) VALUES(?,?,?,?,?,?)`, vuln.ID, task.ID, task.Name, "inventory", "inventory", readable.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ visibleFact, err := db.SaveProjectFact(&database.ProjectFact{
+ ProjectID: project.ID, FactKey: "note/visible", Summary: "visible source", Confidence: "tentative",
+ SourceConversationID: readable.ID, SourceMessageID: "msg-readable", RelatedVulnerabilityID: verified.ID,
+ }, []string{asset.ID}, []string{"exec-readable"}, true, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.SaveProjectFact(&database.ProjectFact{
+ ProjectID: project.ID, FactKey: "note/hidden", Summary: "hidden source", Confidence: "tentative",
+ SourceConversationID: secret.ID, SourceMessageID: secretMessage, RelatedVulnerabilityID: verified.ID,
+ }, []string{asset.ID}, []string{secretExecution}, true, true); err != nil {
+ t.Fatal(err)
+ }
+
+ projects := NewProjectHandler(db, zap.NewNop())
+ assets := NewAssetHandler(db, zap.NewNop())
+ router := gin.New()
+ router.Use(func(c *gin.Context) {
+ c.Set(security.ContextSessionKey, security.Session{
+ UserID: reader.ID, Scope: database.RBACScopeOwn,
+ Permissions: map[string]bool{
+ "project:read": true, "project:write": true, "chat:read": true,
+ "asset:read": true, "vulnerability:read": true, "assessments:read": true,
+ },
+ PermissionScopes: map[string]string{
+ "project:read": database.RBACScopeOwn, "project:write": database.RBACScopeOwn,
+ "chat:read": database.RBACScopeOwn, "asset:read": database.RBACScopeOwn,
+ "vulnerability:read": database.RBACScopeOwn, "assessments:read": database.RBACScopeOwn,
+ },
+ })
+ })
+ router.GET("/projects/:id/facts", projects.ListFacts)
+ router.PUT("/projects/:id/facts/:factId", projects.UpdateFact)
+ router.GET("/assets/:id/facts", assets.Facts)
+ router.GET("/deep-assessments/:id/report", agent.DeepAssessmentReport)
+ request := func(method, path, body string, code int) string {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ router.ServeHTTP(w, req)
+ if w.Code != code {
+ t.Fatalf("%s %s: %d %s", method, path, w.Code, w.Body.String())
+ }
+ return w.Body.String()
+ }
+ request(http.MethodPut, "/projects/"+project.ID+"/facts/"+visibleFact.ID, `{"confidence":"confirmed","summary":"visible source"}`, http.StatusBadRequest)
+ confirmed := request(http.MethodPut, "/projects/"+project.ID+"/facts/"+visibleFact.ID, `{"confidence":"confirmed","confirmation_note":"人工核对来源回执后确认","summary":"visible source"}`, http.StatusOK)
+ if !strings.Contains(confirmed, `"confidence":"confirmed"`) || !strings.Contains(confirmed, "人工核对来源回执后确认") || !strings.Contains(confirmed, readable.ID) || strings.Contains(confirmed, secret.ID) {
+ t.Fatalf("review response: %s", confirmed)
+ }
+ for _, path := range []string{
+ "/projects/" + project.ID + "/facts",
+ "/projects/" + project.ID + "/facts?fact_key=note/hidden",
+ "/projects/" + project.ID + "/facts?related_vulnerability_id=" + verified.ID,
+ "/assets/" + asset.ID + "/facts",
+ } {
+ body := request(http.MethodGet, path, "", http.StatusOK)
+ if strings.Contains(body, secret.ID) || strings.Contains(body, secretMessage) || strings.Contains(body, secretExecution) {
+ t.Fatalf("unauthorized source leaked from %s: %s", path, body)
+ }
+ if path != "/projects/"+project.ID+"/facts?fact_key=note/hidden" && (!strings.Contains(body, readable.ID) || !strings.Contains(body, "exec-readable") || !strings.Contains(body, "msg-readable")) {
+ t.Fatalf("authorized source missing from %s: %s", path, body)
+ }
+ }
+ hidden := request(http.MethodGet, "/projects/"+project.ID+"/facts?fact_key=note/hidden", "", http.StatusOK)
+ if strings.Contains(hidden, "source_conversation_id") || strings.Contains(hidden, "source_message_id") || strings.Contains(hidden, "execution_ids") {
+ t.Fatalf("hidden fact still exposes source fields: %s", hidden)
+ }
+
+ bare, err := db.CreateConversation("no receipt", database.ConversationCreateMeta{ProjectID: project.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = db.SetResourceOwner("conversation", bare.ID, reader.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err = db.UpdateVulnerabilityRetestResult(verified.ID, "fixed", "response is now denied", readable.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err = db.UpdateVulnerabilityRetestResult(unchecked.ID, "fixed", "claimed fixed without a receipt", bare.ID); err != nil {
+ t.Fatal(err)
+ }
+ report := request(http.MethodGet, "/deep-assessments/"+task.ID+"/report", "", http.StatusOK)
+ if strings.Count(report, "复测:修复已验证") != 1 || !strings.Contains(report, "尚无复测记录") || !strings.Contains(report, "证据待核对") || !strings.Contains(report, "其余内容仍导出") || !strings.Contains(report, "已标记修复") {
+ t.Fatalf("report conclusions: %s", report)
+ }
+ if strings.Contains(report, secret.ID) || strings.Contains(report, secretExecution) {
+ t.Fatalf("report exposed an unreadable source: %s", report)
+ }
+}
diff --git a/internal/project/scope_block.go b/internal/project/scope_block.go
index b709dad9..482eba66 100644
--- a/internal/project/scope_block.go
+++ b/internal/project/scope_block.go
@@ -95,5 +95,42 @@ func BuildProjectBlackboardBlock(db *database.DB, projectID string, cfg config.P
if strings.TrimSpace(index) != "" {
parts = append(parts, index)
}
+ vis := database.FactVisibility{CanReadProjects: true, ProjectScope: database.RBACScopeAll, CanReadConversations: true, ConversationScope: database.RBACScopeAll}
+ if len(conversationIDs) > 0 {
+ var owner string
+ _ = db.QueryRow(`SELECT COALESCE(owner_user_id,'') FROM conversations WHERE id=?`, conversationIDs[0]).Scan(&owner)
+ if owner != "" {
+ if resolved, err := db.FactVisibilityFor(owner); err == nil {
+ vis = resolved
+ }
+ }
+ }
+ if collections, err := BuildCollectionBlock(db, projectID, vis); err != nil {
+ return "", err
+ } else if strings.TrimSpace(collections) != "" {
+ parts = append(parts, collections)
+ }
return strings.Join(parts, "\n\n"), nil
}
+
+// BuildCollectionBlock lists named asset collections visible to the caller.
+func BuildCollectionBlock(db *database.DB, projectID string, vis database.FactVisibility) (string, error) {
+ items, err := db.ListAssetCollections(projectID)
+ if err != nil || len(items) == 0 {
+ return "", err
+ }
+ if len(items) > 20 {
+ items = items[:20]
+ }
+ var b strings.Builder
+ b.WriteString("## 项目资产集合\n")
+ b.WriteString("以下集合与信息收集、批量任务和深度测评共用。已确认观察只统计当前账号能读取、且有成功回执的项目事实,不等于已经扫描。\n")
+ for _, item := range items {
+ total, observed, err := db.ObservationCoverageVisible(database.RBACListAccess{UserID: vis.UserID, Scope: vis.ProjectScope}, vis, item.ID)
+ if err != nil {
+ return "", err
+ }
+ fmt.Fprintf(&b, "- %s(%s):可见资产 %d 个,已确认观察 %d 个\n", item.Name, item.ID, total, observed)
+ }
+ return b.String(), nil
+}
diff --git a/web/frontend/src/pages/asset-library/components/AssetDetailDrawer.jsx b/web/frontend/src/pages/asset-library/components/AssetDetailDrawer.jsx
index 028b7122..f2ce7f9b 100644
--- a/web/frontend/src/pages/asset-library/components/AssetDetailDrawer.jsx
+++ b/web/frontend/src/pages/asset-library/components/AssetDetailDrawer.jsx
@@ -1,6 +1,8 @@
/** 资产详情抽屉:全字段 + 关联漏洞/项目跳转。 */
+import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Divider, SideSheet, Space, Typography } from '@douyinfe/semi-ui';
+import { api } from '../../../lib/http';
import { CopyButton, KeyValueList } from '../../../components/ui';
import { formatDateTime } from '../../../lib/format';
import { useT } from '../../../lib/i18n';
@@ -13,6 +15,18 @@ const { Text } = Typography;
export default function AssetDetailDrawer({ asset, visible, onClose, onEdit, onDelete, canWrite, canDelete }) {
const t = useT();
const navigate = useNavigate();
+ const [facts, setFacts] = useState([]);
+ useEffect(() => {
+ if (!visible || !asset?.id) {
+ setFacts([]);
+ return undefined;
+ }
+ let cancelled = false;
+ api.get(`/assets/${asset.id}/facts`)
+ .then(data => { if (!cancelled) setFacts(Array.isArray(data?.facts) ? data.facts : []); })
+ .catch(() => { if (!cancelled) setFacts([]); });
+ return () => { cancelled = true; };
+ }, [visible, asset?.id]);
if (!asset) return null;
const openVulnerabilities = () => {
@@ -101,6 +115,31 @@ export default function AssetDetailDrawer({ asset, visible, onClose, onEdit, onD