feat(projects): share evidence across assets, assessments, and reports
Keep project facts, collections, retests, and exports on the same read boundary, and stop a manual fixed status or a blocked batch from looking complete. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
2fab8b7e11
commit
f689e92678
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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)
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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++
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
|||
<Divider margin="12px" />
|
||||
<KeyValueList items={items} columns={2} />
|
||||
<Divider margin="12px" />
|
||||
<Text strong>项目事实</Text>
|
||||
{facts.length === 0 ? (
|
||||
<Text type="tertiary" size="small">还没有关联到这条资产的项目事实。</Text>
|
||||
) : facts.map(fact => (
|
||||
<div key={fact.id} className="asset-library-detail-target">
|
||||
<Text>{fact.summary || fact.fact_key}</Text>
|
||||
<Space>
|
||||
{fact.source_conversation_id ? (
|
||||
<Button
|
||||
size="small"
|
||||
theme="borderless"
|
||||
onClick={() => navigate(`/chat?conversation=${encodeURIComponent(fact.source_conversation_id)}`)}
|
||||
>
|
||||
打开来源会话
|
||||
</Button>
|
||||
) : null}
|
||||
{fact.project_id ? (
|
||||
<Button size="small" theme="borderless" onClick={() => navigate(`/projects/${fact.project_id}?tab=facts`)}>
|
||||
项目事实
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
</div>
|
||||
))}
|
||||
<Divider margin="12px" />
|
||||
<Space>
|
||||
<Button theme="light" onClick={openVulnerabilities}>
|
||||
{t('assets.viewRelatedVulnerabilities', null, '查看关联漏洞')}
|
||||
|
|
|
|||
|
|
@ -56,23 +56,34 @@ export function fofaRowToAsset(row, fields, provider = 'fofa') {
|
|||
* 将选中的结果行入库。
|
||||
* 返回 { assets, invalidCount, created, updated, skipped }。
|
||||
*/
|
||||
export async function importFofaRows(rows, { fields, provider, query }) {
|
||||
export async function importFofaRows(rows, { fields, provider, query, projectId, collectionName }) {
|
||||
const converted = (rows || []).map(row => fofaRowToAsset(row, fields, provider));
|
||||
const assets = converted.filter(asset => asset.host || asset.ip || asset.domain);
|
||||
const invalidCount = converted.length - assets.length;
|
||||
if (!assets.length) {
|
||||
return { assets, invalidCount, created: 0, updated: 0, skipped: 0 };
|
||||
}
|
||||
const result = await api.post('/assets/import', {
|
||||
if (projectId) {
|
||||
assets.forEach(asset => { asset.project_id = projectId; });
|
||||
}
|
||||
const body = {
|
||||
assets,
|
||||
source: provider || 'fofa',
|
||||
source_query: query || ''
|
||||
});
|
||||
};
|
||||
if (projectId) {
|
||||
body.collection = {
|
||||
project_id: projectId,
|
||||
name: String(collectionName || query || '导入资产').trim()
|
||||
};
|
||||
}
|
||||
const result = await api.post('/assets/import', body);
|
||||
return {
|
||||
assets,
|
||||
invalidCount,
|
||||
created: Number(result?.created || 0),
|
||||
updated: Number(result?.updated || 0),
|
||||
skipped: Number(result?.skipped || 0)
|
||||
skipped: Number(result?.skipped || 0),
|
||||
collection: result?.collection || null
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -247,6 +247,20 @@ export default function AssetOverviewPage() {
|
|||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
<SectionCard
|
||||
className="asset-overview-card"
|
||||
title="观察覆盖"
|
||||
description="有成功回执的测评观察,或带成功工具回执的已确认项目事实。同一资产只计一次,不替代上面的扫描覆盖。"
|
||||
extra={<Text type="tertiary" size="small">{`${stats.observation?.observed || 0} / ${stats.observation?.total || stats.total || 0}`}</Text>}
|
||||
>
|
||||
<div className="asset-overview-coverage">
|
||||
<Text type="tertiary" size="small">已有观察证据</Text>
|
||||
<Progress
|
||||
percent={Number(stats.observation?.rate || 0)}
|
||||
format={percent => `${percent}%`}
|
||||
/>
|
||||
</div>
|
||||
</SectionCard>
|
||||
</div>)}
|
||||
|
||||
{canRead && (<SectionCard
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ async function loadDashboard() {
|
|||
const [
|
||||
agentTasks, vulnStats, pendingVulnStats, vulnList, batchQueues, monitorStats, tokenUsage,
|
||||
knowledgeStats, skillsStats, roles, agents, hitlPending, externalMcp,
|
||||
webshell, c2Listeners, c2Sessions, projectSummary, toolsConfig
|
||||
webshell, c2Listeners, c2Sessions, projectSummary, toolsConfig, assetStats
|
||||
] = await Promise.all([
|
||||
safe('/agent-loop/tasks'),
|
||||
safe('/vulnerabilities/stats'),
|
||||
|
|
@ -47,12 +47,13 @@ async function loadDashboard() {
|
|||
safe('/c2/listeners'),
|
||||
safe('/c2/sessions', { limit: 200 }),
|
||||
safe('/projects/dashboard-summary', { fact_limit: 8 }),
|
||||
safe('/config/tools', { page: 1, page_size: 1, include_external: false })
|
||||
safe('/config/tools', { page: 1, page_size: 1, include_external: false }),
|
||||
safe('/assets/stats', { days: 30 })
|
||||
]);
|
||||
const sources = {
|
||||
agentTasks, vulnStats, pendingVulnStats, vulnList, batchQueues, monitorStats, tokenUsage,
|
||||
knowledgeStats, skillsStats, roles, agents, hitlPending, externalMcp,
|
||||
webshell, c2Listeners, c2Sessions, projectSummary, toolsConfig
|
||||
webshell, c2Listeners, c2Sessions, projectSummary, toolsConfig, assetStats
|
||||
};
|
||||
return {
|
||||
...sources,
|
||||
|
|
@ -199,6 +200,14 @@ export default function DashboardPage() {
|
|||
icon: <IconCheckCircleStroked />,
|
||||
onClick: () => navigate('/mcp-monitor')
|
||||
},
|
||||
{
|
||||
id: 'observation',
|
||||
label: '已有观察证据',
|
||||
value: displayCount(data?.assetStats?.observation?.observed),
|
||||
detail: `资产 ${displayCount(data?.assetStats?.observation?.total)},扫描覆盖另计`,
|
||||
icon: <IconShield />,
|
||||
onClick: () => navigate('/asset-overview')
|
||||
},
|
||||
{
|
||||
id: 'tokens',
|
||||
label: t('dashboard.tokenUsage', null, 'Token 用量(7 天)'),
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ export default function CreateAssessmentDrawer({ visible, onCancel, onCreated })
|
|||
const [error, setError] = useState(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [projectFormOpen, setProjectFormOpen] = useState(false);
|
||||
const [collections, setCollections] = useState([]);
|
||||
const busy = saving || projectFormOpen;
|
||||
|
||||
const loadOptions = useCallback(() => {
|
||||
|
|
@ -43,6 +44,16 @@ export default function CreateAssessmentDrawer({ visible, onCancel, onCreated })
|
|||
loadOptions();
|
||||
}, [visible, loadOptions]);
|
||||
|
||||
const loadCollections = projectId => {
|
||||
if (!projectId) {
|
||||
setCollections([]);
|
||||
return;
|
||||
}
|
||||
api.get('/assets/collections', { project_id: projectId })
|
||||
.then(data => setCollections(Array.isArray(data?.collections) ? data.collections : []))
|
||||
.catch(() => setCollections([]));
|
||||
};
|
||||
|
||||
const submit = async values => {
|
||||
if (busy) return;
|
||||
setSaving(true);
|
||||
|
|
@ -53,6 +64,7 @@ export default function CreateAssessmentDrawer({ visible, onCancel, onCreated })
|
|||
scope: String(values.scope || '').trim(),
|
||||
criteria: String(values.criteria || '').trim(),
|
||||
project_id: values.project_id || '',
|
||||
collection_id: values.collection_id || '',
|
||||
role: values.role || '',
|
||||
model: values.model || '',
|
||||
hitl_policy: values.hitl_policy || '',
|
||||
|
|
@ -74,6 +86,8 @@ export default function CreateAssessmentDrawer({ visible, onCancel, onCreated })
|
|||
if (!project?.id) return;
|
||||
setOptions(current => ({ ...current, projects: [project, ...(current?.projects || [])] }));
|
||||
formApi.current?.setValue('project_id', project.id);
|
||||
formApi.current?.setValue('collection_id', '');
|
||||
loadCollections(project.id);
|
||||
};
|
||||
|
||||
const models = modelChannelOptions((options?.models || []).map(item => [item.id, item]));
|
||||
|
|
@ -173,6 +187,10 @@ export default function CreateAssessmentDrawer({ visible, onCancel, onCreated })
|
|||
label={t('deepAssessments.project', null, '关联项目')}
|
||||
optionList={[{ value: '', label: '不关联' }, ...projects]}
|
||||
style={{ width: '100%' }}
|
||||
onChange={value => {
|
||||
formApi.current?.setValue('collection_id', '');
|
||||
loadCollections(value || '');
|
||||
}}
|
||||
/>
|
||||
{canCreateProject && (
|
||||
<Button
|
||||
|
|
@ -186,6 +204,12 @@ export default function CreateAssessmentDrawer({ visible, onCancel, onCreated })
|
|||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Form.Select
|
||||
field="collection_id"
|
||||
label="资产集合"
|
||||
optionList={[{ value: '', label: '不指定集合' }, ...collections.map(item => ({ value: item.id, label: `${item.name}(${item.member_count || 0})` }))]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.InputNumber
|
||||
field="concurrency"
|
||||
label={t('deepAssessments.concurrency', null, '并行步骤')}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
/** 概览:统计、目标与验收要求、事件时间线。 */
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../../lib/http';
|
||||
import { Button, Empty, Space, Switch, Tag, Timeline, Typography } from '@douyinfe/semi-ui';
|
||||
import { useT } from '../../lib/i18n';
|
||||
import { useInterval } from '../../components/hooks';
|
||||
|
|
@ -24,6 +25,23 @@ function ActiveElapsed({ startedAt, seconds }) {
|
|||
return formatElapsed(seconds + currentRunSeconds);
|
||||
}
|
||||
|
||||
function CollectionNote({ id }) {
|
||||
const [info, setInfo] = useState(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
api.get(`/assets/collections/${id}`)
|
||||
.then(data => { if (!cancelled) setInfo(data?.collection || null); })
|
||||
.catch(() => { if (!cancelled) setInfo(null); });
|
||||
return () => { cancelled = true; };
|
||||
}, [id]);
|
||||
if (!info) return null;
|
||||
return (
|
||||
<Text type="tertiary">
|
||||
本次范围 {info.name}:可见资产 {info.member_count || 0} 个,已确认观察 {info.observed || 0} 个。项目历史观察和逐项验收分开统计,缺证据的必验项保持未完成。
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export default function OverviewTab({
|
||||
task, canWrite, events, eventsError, autoRefresh, onAutoRefreshChange,
|
||||
onRefreshEvents, onGoTab, onGuidance, onAnswer
|
||||
|
|
@ -110,6 +128,7 @@ export default function OverviewTab({
|
|||
return (
|
||||
<div className="assessment-tab">
|
||||
<StatGrid metrics={metrics} columns={5} />
|
||||
{task.collection_id ? <CollectionNote id={task.collection_id} /> : null}
|
||||
|
||||
<SectionCard
|
||||
title="目标与测评要求"
|
||||
|
|
|
|||
|
|
@ -49,10 +49,22 @@ export default function InfoCollectPage() {
|
|||
const [visibleFields, setVisibleFields] = useState([]);
|
||||
const [detailRow, setDetailRow] = useState(null);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [projectId, setProjectId] = useState('');
|
||||
const [collectionName, setCollectionName] = useState('');
|
||||
|
||||
const config = providerConfig(form.provider);
|
||||
const providerLabel = config.label;
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasPermission('project:read')) return undefined;
|
||||
let cancelled = false;
|
||||
api.get('/projects', { limit: 500 })
|
||||
.then(payload => { if (!cancelled) setProjects(Array.isArray(payload?.projects) ? payload.projects : []); })
|
||||
.catch(() => { if (!cancelled) setProjects([]); });
|
||||
return () => { cancelled = true; };
|
||||
}, [hasPermission]);
|
||||
|
||||
useEffect(() => {
|
||||
// provider 切换后字段模板与数量上限需要跟随,避免残留其他 provider 的字段。
|
||||
setVisibleFields([]);
|
||||
|
|
@ -138,7 +150,9 @@ export default function InfoCollectPage() {
|
|||
const outcome = await importFofaRows(rows, {
|
||||
fields,
|
||||
provider: result?.provider || form.provider,
|
||||
query: result?.query || form.query
|
||||
query: result?.query || form.query,
|
||||
projectId,
|
||||
collectionName
|
||||
});
|
||||
if (!outcome.assets.length) {
|
||||
toastWarning(t('assets.noValidImportTarget', null, '所选结果中没有可入库的有效资产目标'));
|
||||
|
|
@ -150,7 +164,10 @@ export default function InfoCollectPage() {
|
|||
}, `已新增 ${outcome.created} 条,更新 ${outcome.updated} 条,跳过 ${outcome.invalidCount} 条无有效目标的结果`)
|
||||
: t('assets.importDone', { created: outcome.created, updated: outcome.updated },
|
||||
`已新增 ${outcome.created} 条,更新 ${outcome.updated} 条`);
|
||||
toastSuccess(message);
|
||||
const saved = outcome.collection?.name
|
||||
? `,并保存为资产集合「${outcome.collection.name}」`
|
||||
: '';
|
||||
toastSuccess(`${message}${saved}`);
|
||||
setSelectedKeys([]);
|
||||
} catch (importError) {
|
||||
toastError(importError, t('assets.importFailed', null, '资产入库失败'));
|
||||
|
|
@ -274,6 +291,23 @@ export default function InfoCollectPage() {
|
|||
))}
|
||||
</Space>
|
||||
|
||||
<Space className="info-collect-form-row">
|
||||
<Select
|
||||
value={projectId}
|
||||
optionList={[{ value: '', label: '不归入项目集合' }, ...projects.map(item => ({ value: item.id, label: item.name || item.id }))]}
|
||||
placeholder="归入项目"
|
||||
style={{ width: 220 }}
|
||||
onChange={value => setProjectId(value || '')}
|
||||
/>
|
||||
<Input
|
||||
value={collectionName}
|
||||
disabled={!projectId}
|
||||
placeholder="集合名称,留空则使用查询语句"
|
||||
style={{ width: 280 }}
|
||||
onChange={setCollectionName}
|
||||
/>
|
||||
</Space>
|
||||
|
||||
<TextArea
|
||||
value={naturalText}
|
||||
rows={2}
|
||||
|
|
@ -285,9 +319,10 @@ export default function InfoCollectPage() {
|
|||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
className="info-collect-results"
|
||||
title={t('infoCollectPage.queryResults', null, '查询结果')}
|
||||
extra={(
|
||||
<Space>
|
||||
<Space className="info-collect-results-actions" wrap>
|
||||
<Text type="tertiary" size="small">{metaText}</Text>
|
||||
<Select
|
||||
multiple
|
||||
|
|
|
|||
|
|
@ -34,4 +34,26 @@
|
|||
@media (max-width: 900px) {
|
||||
.info-collect-form-row { align-items: flex-start; }
|
||||
.info-collect-fields { width: 100% !important; }
|
||||
.info-collect-results.cs-section-card .semi-card-header,
|
||||
.info-collect-results.cs-section-card .semi-card-header-wrapper {
|
||||
flex-direction: column;
|
||||
flex-wrap: nowrap;
|
||||
height: auto;
|
||||
align-items: stretch;
|
||||
}
|
||||
.info-collect-results.cs-section-card .semi-card-header-wrapper-title { order: 1; }
|
||||
.info-collect-results.cs-section-card .semi-card-header-wrapper-extra {
|
||||
order: 2;
|
||||
max-width: 100%;
|
||||
margin-left: 0;
|
||||
}
|
||||
.info-collect-page { padding-bottom: 48px; }
|
||||
.info-collect-results.cs-section-card .semi-card-header-wrapper { scroll-margin-bottom: 24px; }
|
||||
.info-collect-results-actions {
|
||||
flex: 1 1 auto;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin-left: 0;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,6 +59,9 @@ export default function FactDetailSheet({ projectId, factKey, visible, canWrite,
|
|||
fact.related_vulnerability_id
|
||||
? { label: t('projects.relatedVulnIdTitle', null, '关联漏洞 ID'), value: fact.related_vulnerability_id }
|
||||
: null,
|
||||
fact.confirmation_note
|
||||
? { label: t('projects.confirmationNote', null, '审核说明'), value: fact.confirmation_note }
|
||||
: null,
|
||||
fact.source_conversation_id
|
||||
? { label: t('projects.factMetaSourceConversation', { value: '' }, '来源对话'), value: fact.source_conversation_id }
|
||||
: null
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ const EMPTY = {
|
|||
confidence: 'tentative',
|
||||
pinned: false,
|
||||
related_vulnerability_id: '',
|
||||
confirmation_note: '',
|
||||
links_text: ''
|
||||
};
|
||||
|
||||
|
|
@ -57,6 +58,7 @@ export default function FactFormModal({ visible, projectId, factKey, onCancel, o
|
|||
confidence: (fact.confidence || 'tentative').toLowerCase(),
|
||||
pinned: Boolean(fact.pinned),
|
||||
related_vulnerability_id: fact.related_vulnerability_id || '',
|
||||
confirmation_note: fact.confirmation_note || '',
|
||||
links_text: formatIncomingLinks(fact.incoming_links)
|
||||
});
|
||||
})
|
||||
|
|
@ -74,10 +76,15 @@ export default function FactFormModal({ visible, projectId, factKey, onCancel, o
|
|||
const submit = async () => {
|
||||
const key = form.fact_key.trim();
|
||||
const summary = form.summary.trim();
|
||||
const note = form.confirmation_note.trim();
|
||||
if (!key || !summary) {
|
||||
toastError(t('projects.factKeySummaryRequired', null, 'fact_key 与 summary 必填'));
|
||||
return;
|
||||
}
|
||||
if ((form.confidence || 'tentative') === 'confirmed' && !note) {
|
||||
toastError(t('projects.confirmationNoteRequired', null, '升级为已确认需要审核说明'));
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
fact_key: key,
|
||||
category: form.category || 'note',
|
||||
|
|
@ -86,6 +93,7 @@ export default function FactFormModal({ visible, projectId, factKey, onCancel, o
|
|||
confidence: form.confidence || 'tentative',
|
||||
pinned: Boolean(form.pinned),
|
||||
related_vulnerability_id: form.related_vulnerability_id.trim(),
|
||||
confirmation_note: note,
|
||||
links_text: form.links_text
|
||||
};
|
||||
if (editing && !factId) {
|
||||
|
|
@ -118,6 +126,7 @@ export default function FactFormModal({ visible, projectId, factKey, onCancel, o
|
|||
cancelText={t('common.cancel', null, '取消')}
|
||||
confirmLoading={saving}
|
||||
width={720}
|
||||
maskClosable={false}
|
||||
>
|
||||
<Text type="tertiary" size="small">
|
||||
{t('projects.factModalSubtitle', null, '摘要注入黑板索引;body 沉淀攻击链与 POC,供审计复现(与漏洞记录分工)')}
|
||||
|
|
@ -173,6 +182,17 @@ export default function FactFormModal({ visible, projectId, factKey, onCancel, o
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div className="project-form-field">
|
||||
<Text strong size="small">{t('projects.confirmationNote', null, '审核说明')}</Text>
|
||||
<TextArea
|
||||
value={form.confirmation_note}
|
||||
rows={3}
|
||||
disabled={form.confidence !== 'confirmed'}
|
||||
placeholder={t('projects.confirmationNotePlaceholder', null, '说明为何把这条事实标为已确认')}
|
||||
onChange={value => update({ confirmation_note: value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="project-form-field">
|
||||
<Text strong size="small">body</Text>
|
||||
<TextArea
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
/** 事实黑板:筛选、表格与增删改/废弃恢复入口。 */
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Button, Checkbox, Input, Popconfirm, Select, Space, Tag, Typography
|
||||
} from '@douyinfe/semi-ui';
|
||||
|
|
@ -26,6 +27,7 @@ export default function FactsPanel({
|
|||
projectId, canWrite, revision = 0, onAddFact, onEditFact, onViewFact, onMutated
|
||||
}) {
|
||||
const t = useT();
|
||||
const navigate = useNavigate();
|
||||
const [search, setSearch] = useState('');
|
||||
const debounced = useDebounced(search, 300);
|
||||
const [category, setCategory] = useState('all');
|
||||
|
|
@ -161,6 +163,15 @@ export default function FactsPanel({
|
|||
<Button size="small" theme="borderless" onClick={() => onViewFact?.(record.fact_key)}>
|
||||
{t('projects.details', null, '详情')}
|
||||
</Button>
|
||||
{record.source_conversation_id ? (
|
||||
<Button
|
||||
size="small"
|
||||
theme="borderless"
|
||||
onClick={() => navigate(`/chat?conversation=${encodeURIComponent(record.source_conversation_id)}`)}
|
||||
>
|
||||
会话
|
||||
</Button>
|
||||
) : null}
|
||||
<Button size="small" theme="borderless" disabled={!canWrite} onClick={() => onEditFact?.(record.fact_key)}>
|
||||
{t('common.edit', null, '编辑')}
|
||||
</Button>
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@ export const TASK_STATUS = {
|
|||
running: { label: '执行中', color: 'blue' },
|
||||
completed: { label: '已完成', color: 'green' },
|
||||
failed: { label: '失败', color: 'red' },
|
||||
cancelled: { label: '已取消', color: 'grey' }
|
||||
cancelled: { label: '已取消', color: 'grey' },
|
||||
blocked: { label: '受阻', color: 'orange' }
|
||||
};
|
||||
|
||||
export const AGENT_MODES = [
|
||||
|
|
@ -51,11 +52,12 @@ export function queueStats(queue) {
|
|||
const completed = tasks.filter(task => task.status === 'completed').length;
|
||||
const failed = tasks.filter(task => task.status === 'failed').length;
|
||||
const cancelled = tasks.filter(task => task.status === 'cancelled').length;
|
||||
const blocked = tasks.filter(task => task.status === 'blocked').length;
|
||||
const running = tasks.filter(task => task.status === 'running').length;
|
||||
const pending = tasks.filter(task => task.status === 'pending').length;
|
||||
const done = completed + failed + cancelled;
|
||||
const done = completed + failed + cancelled + blocked;
|
||||
const percent = total ? Math.round((done / total) * 100) : 0;
|
||||
return { total, completed, failed, cancelled, running, pending, done, percent };
|
||||
return { total, completed, failed, cancelled, blocked, running, pending, done, percent };
|
||||
}
|
||||
|
||||
export function agentModeLabel(mode) {
|
||||
|
|
@ -69,11 +71,17 @@ export function queueStatusView(queue) {
|
|||
const nextRun = queue?.nextRunAt ? new Date(queue.nextRunAt) : null;
|
||||
const nextText = nextRun && Number.isFinite(nextRun.getTime()) ? nextRun.toLocaleString('zh-CN', { hour12: false }) : '';
|
||||
const stats = queueStats(queue);
|
||||
const blockedNote = stats.blocked > 0 ? (queue?.lastRunError || `${stats.blocked} 项受阻`) : '';
|
||||
if (stats.blocked > 0 && stats.completed === 0 && stats.failed === 0) {
|
||||
return { ...base, label: `受阻(${stats.blocked} 项)`, color: 'orange', sublabel: blockedNote };
|
||||
}
|
||||
if (cronOn && queue?.status === 'completed') {
|
||||
const unfinished = stats.failed > 0 || stats.blocked > 0;
|
||||
return {
|
||||
...base,
|
||||
label: '本轮已完成 · 定时循环中',
|
||||
sublabel: nextText ? `下次执行:${nextText}` : '',
|
||||
label: unfinished ? '本轮已结束 · 定时循环中' : '本轮已完成 · 定时循环中',
|
||||
color: stats.failed > 0 ? 'red' : (stats.blocked > 0 ? 'orange' : base.color),
|
||||
sublabel: blockedNote || (nextText ? `下次执行:${nextText}` : ''),
|
||||
note: '定时队列:子任务已跑完,到点将自动下一轮'
|
||||
};
|
||||
}
|
||||
|
|
@ -81,7 +89,11 @@ export function queueStatusView(queue) {
|
|||
return { ...base, sublabel: `Cron 已排程 · 下次 ${nextText}` };
|
||||
}
|
||||
if (queue?.status === 'completed' && stats.failed > 0) {
|
||||
return { ...base, label: `已结束(${stats.failed} 项失败)`, color: 'red' };
|
||||
const blockedText = stats.blocked > 0 ? `,${stats.blocked} 项受阻` : '';
|
||||
return { ...base, label: `已结束(${stats.failed} 项失败${blockedText})`, color: 'red', sublabel: blockedNote };
|
||||
}
|
||||
if (queue?.status === 'completed' && stats.blocked > 0) {
|
||||
return { ...base, label: `已结束(${stats.blocked} 项受阻)`, color: 'orange', sublabel: blockedNote };
|
||||
}
|
||||
return { ...base, sublabel: '' };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -300,6 +300,7 @@ export default function QueueDetailDrawer({ queueId, visible, canWrite, canDelet
|
|||
<span>{t('tasks.completedLabel', null, '已完成')} {stats.completed}</span>
|
||||
<span>{t('tasks.failedLabel', null, '失败')} {stats.failed}</span>
|
||||
<span>{t('tasks.cancelledLabel', null, '已取消')} {stats.cancelled}</span>
|
||||
<span>受阻 {stats.blocked}</span>
|
||||
</div>
|
||||
<Text type="tertiary" size="small">
|
||||
{cronOn
|
||||
|
|
@ -400,7 +401,9 @@ export default function QueueDetailDrawer({ queueId, visible, canWrite, canDelet
|
|||
/>
|
||||
{resultModal.task?.error ? (
|
||||
<div>
|
||||
<Text strong type="danger">{t('tasks.statusFailed', null, '执行失败')}</Text>
|
||||
<Text strong type="danger">
|
||||
{resultModal.task.status === 'blocked' ? '受阻原因' : t('tasks.statusFailed', null, '执行失败')}
|
||||
</Text>
|
||||
<pre className="task-result-pre">{resultModal.task.error}</pre>
|
||||
</div>
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ const EMPTY = {
|
|||
tasksText: '',
|
||||
role: '',
|
||||
projectId: '',
|
||||
collectionId: '',
|
||||
agentMode: 'single',
|
||||
hitlPolicy: '',
|
||||
scheduleMode: 'manual',
|
||||
|
|
@ -30,6 +31,7 @@ export default function QueueFormModal({ visible, onCancel, onCreated }) {
|
|||
const [form, setForm] = useState(EMPTY);
|
||||
const [roles, setRoles] = useState([]);
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [collections, setCollections] = useState([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -50,6 +52,18 @@ export default function QueueFormModal({ visible, onCancel, onCreated }) {
|
|||
return () => { cancelled = true; };
|
||||
}, [visible, hasPermission]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible || !form.projectId || !hasPermission('asset:read')) {
|
||||
setCollections([]);
|
||||
return undefined;
|
||||
}
|
||||
let cancelled = false;
|
||||
api.get('/assets/collections', { project_id: form.projectId })
|
||||
.then(payload => { if (!cancelled) setCollections(Array.isArray(payload?.collections) ? payload.collections : []); })
|
||||
.catch(() => { if (!cancelled) setCollections([]); });
|
||||
return () => { cancelled = true; };
|
||||
}, [visible, form.projectId, hasPermission]);
|
||||
|
||||
const update = patch => setForm(prev => ({ ...prev, ...patch }));
|
||||
|
||||
const submit = async () => {
|
||||
|
|
@ -78,6 +92,7 @@ export default function QueueFormModal({ visible, onCancel, onCreated }) {
|
|||
tasks,
|
||||
role: form.role || '',
|
||||
projectId: form.projectId || '',
|
||||
collectionId: form.collectionId || '',
|
||||
agentMode: form.agentMode || 'single',
|
||||
hitlPolicy: form.hitlPolicy || '',
|
||||
scheduleMode: form.scheduleMode === 'cron' ? 'cron' : 'manual',
|
||||
|
|
@ -104,6 +119,7 @@ export default function QueueFormModal({ visible, onCancel, onCreated }) {
|
|||
cancelText={t('common.cancel', null, '取消')}
|
||||
confirmLoading={saving}
|
||||
width={760}
|
||||
maskClosable={false}
|
||||
>
|
||||
<div className="task-form-grid">
|
||||
<div className="task-form-field">
|
||||
|
|
@ -136,7 +152,7 @@ export default function QueueFormModal({ visible, onCancel, onCreated }) {
|
|||
style={{ width: '100%' }}
|
||||
optionList={[{ value: '', label: t('batchImportModal.projectNone', null, '(未绑定)') },
|
||||
...projects.map(item => ({ value: item.id, label: item.name || item.id }))]}
|
||||
onChange={value => update({ projectId: value })}
|
||||
onChange={value => update({ projectId: value || '', collectionId: '' })}
|
||||
/>
|
||||
</div>
|
||||
<div className="task-form-field">
|
||||
|
|
@ -151,6 +167,19 @@ export default function QueueFormModal({ visible, onCancel, onCreated }) {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div className="task-form-field">
|
||||
<Text strong size="small">资产集合</Text>
|
||||
<Select
|
||||
value={form.collectionId}
|
||||
style={{ width: '100%' }}
|
||||
disabled={!form.projectId}
|
||||
optionList={[{ value: '', label: '不指定集合' },
|
||||
...collections.map(item => ({ value: item.id, label: `${item.name}(${item.member_count || 0})` }))]}
|
||||
onChange={value => update({ collectionId: value || '' })}
|
||||
/>
|
||||
<Text type="tertiary" size="small">与信息收集、深度测评共用同一批资产。不改变队列的暂停和子任务行为。</Text>
|
||||
</div>
|
||||
|
||||
<div className="task-form-field">
|
||||
<Text strong size="small">{t('batchImportModal.tasksList', null, '任务列表(每行一个任务)')}</Text>
|
||||
<TextArea
|
||||
|
|
|
|||
|
|
@ -25,6 +25,41 @@ function Section({ title, extra, children }) {
|
|||
);
|
||||
}
|
||||
|
||||
function RelatedFacts({ vulnerability }) {
|
||||
const navigate = useNavigate();
|
||||
const [facts, setFacts] = useState([]);
|
||||
useEffect(() => {
|
||||
if (!vulnerability?.project_id || !vulnerability?.id) {
|
||||
setFacts([]);
|
||||
return undefined;
|
||||
}
|
||||
let cancelled = false;
|
||||
api.get(`/projects/${vulnerability.project_id}/facts`, { related_vulnerability_id: vulnerability.id, limit: 20 })
|
||||
.then(data => { if (!cancelled) setFacts(Array.isArray(data) ? data : []); })
|
||||
.catch(() => { if (!cancelled) setFacts([]); });
|
||||
return () => { cancelled = true; };
|
||||
}, [vulnerability?.project_id, vulnerability?.id]);
|
||||
if (!facts.length) return null;
|
||||
return (
|
||||
<Section title="同一项目事实">
|
||||
{facts.map(fact => (
|
||||
<div key={fact.id} className="vulnerability-history-item">
|
||||
<Text>{fact.summary || fact.fact_key}</Text>
|
||||
{fact.source_conversation_id ? (
|
||||
<Button
|
||||
size="small"
|
||||
theme="borderless"
|
||||
onClick={() => navigate(`/chat?conversation=${encodeURIComponent(fact.source_conversation_id)}`)}
|
||||
>
|
||||
打开来源会话
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function Narrative({ title, content, code }) {
|
||||
const text = String(content ?? '').trim();
|
||||
if (!text) return null;
|
||||
|
|
@ -187,6 +222,7 @@ export default function DetailDrawer({
|
|||
<Narrative title={t('vulnerabilityPage.detailEvidence', null, '证据 / POC')} content={vuln.evidence} code />
|
||||
<Narrative title={t('vulnerabilityPage.detailRetestNotes', null, '复测方式')} content={vuln.retest_notes} />
|
||||
<Narrative title={t('vulnerabilityPage.detailRetestLog', null, '复测记录')} content={vuln.retest_log} code />
|
||||
<RelatedFacts vulnerability={vuln} />
|
||||
<Section title={t('vulnerabilityPage.inspector_history', null, '处置历史')}>
|
||||
{history.length ? (
|
||||
<Timeline>
|
||||
|
|
|
|||
|
|
@ -151,7 +151,8 @@ function makeReads(session) {
|
|||
[`/api/deep-assessments/${ASSESSMENT.id}/surface-items`]: { items: [], has_more: false },
|
||||
'/api/deep-assessments/options': { models: [], roles: [], projects: [PROJECT] },
|
||||
'/api/assets': { assets: [], total: 0, page: 1, page_size: 20 },
|
||||
'/api/assets/stats': { total: 0, ips: 0, domains: 0, ports: 0, recent: 0, protocols: [], coverage: { scanned: 0, scanned_30d: 0, never_scanned: 0, stale: 0 } },
|
||||
'/api/assets/stats': { total: 0, ips: 0, domains: 0, ports: 0, recent: 0, protocols: [], coverage: { scanned: 0, scanned_30d: 0, never_scanned: 0, stale: 0 }, observation: { total: 0, observed: 0, rate: 0 } },
|
||||
'/api/assets/collections': { collections: [] },
|
||||
'/api/workflows': { workflows: [] },
|
||||
'/api/workflows/runs/pending': { runs: [] },
|
||||
'/api/rbac/metadata': { permissions: Object.fromEntries(UI_PERMISSIONS.map(key => [key, key])) },
|
||||
|
|
|
|||
|
|
@ -1692,6 +1692,54 @@ test('project: compact pagination supports selection, filtering and a shrinking
|
|||
expect(mockApi.writes()).toEqual([]);
|
||||
});
|
||||
|
||||
test('project: review a tentative fact and only link a readable source', async ({ page, mockApi }) => {
|
||||
const hidden = 'secret-conversation-id';
|
||||
const pending = {
|
||||
...FACT, id: 'fixture-pending-fact', fact_key: 'fixture.pending', confidence: 'tentative',
|
||||
summary: '待审核示例事实', confirmation_note: '', source_conversation_id: '', source_message_id: '', execution_ids: []
|
||||
};
|
||||
const readable = {
|
||||
...FACT, id: 'fixture-readable-fact', fact_key: 'fixture.readable', confidence: 'tentative',
|
||||
summary: '可回看来源', source_conversation_id: CONVERSATION.id, source_message_id: 'fixture-user-message',
|
||||
execution_ids: ['fixture-execution']
|
||||
};
|
||||
const facts = [pending, readable];
|
||||
mockApi.respond('GET', `/api/projects/${PROJECT.id}/facts`, (_entry, url) => {
|
||||
const key = url.searchParams.get('fact_key');
|
||||
return { json: key ? facts.find(item => item.fact_key === key) : facts };
|
||||
});
|
||||
mockApi.respond('PUT', `/api/projects/${PROJECT.id}/facts/${pending.id}`, (entry) => {
|
||||
Object.assign(pending, entry.body);
|
||||
return { json: { ...pending, incoming_links: [], outgoing_links: [] } };
|
||||
});
|
||||
const main = await visit(page, 'projects');
|
||||
await expect(main.getByRole('button', { name: '会话', exact: true })).toHaveCount(1);
|
||||
await expect(main.getByText(hidden)).toHaveCount(0);
|
||||
|
||||
const row = main.locator('tr', { hasText: pending.summary });
|
||||
await button(row, label('common.edit', '编辑')).click();
|
||||
const dialog = page.getByRole('dialog', { name: label('projects.editFact', '编辑事实') });
|
||||
const confidence = dialog.getByRole('combobox').nth(1);
|
||||
await confidence.click();
|
||||
await page.locator('.semi-select-option').filter({ hasText: '已确认' }).click();
|
||||
await expect(confidence).toContainText('已确认');
|
||||
await button(dialog, label('projects.saveChanges', '保存修改')).click();
|
||||
await expect(page.getByText('升级为已确认需要审核说明', { exact: true })).toBeVisible();
|
||||
expect(mockApi.writes()).toEqual([]);
|
||||
|
||||
const note = '人工核对来源回执后确认';
|
||||
await dialog.getByPlaceholder('说明为何把这条事实标为已确认').fill(note);
|
||||
await button(dialog, label('projects.saveChanges', '保存修改')).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
expect(mockApi.calls('PUT', `/api/projects/${PROJECT.id}/facts/${pending.id}`).map(call => call.body)).toEqual([
|
||||
expect.objectContaining({ confidence: 'confirmed', confirmation_note: note, fact_key: pending.fact_key })
|
||||
]);
|
||||
await expect(row.getByText('已确认', { exact: true })).toBeVisible();
|
||||
await button(row, label('common.edit', '编辑')).click();
|
||||
await expect(page.getByRole('dialog').getByPlaceholder('说明为何把这条事实标为已确认')).toHaveValue(note);
|
||||
await expect(main.getByText(hidden)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('project: dashboard jump, fact detail opens/closes and create validates then retries', async ({ page, mockApi }) => {
|
||||
await visit(page, 'dashboard');
|
||||
await button(page.locator('#main-content'), PROJECT.name).click();
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{Et as r,F as i,H as a,L as o,M as s,W as c,i as l,kt as u,lt as d,ot as f,st as p}from"./semi-CYW2cRsN.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-B-REnHjm.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(o,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(o,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(s,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(s,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(o,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(r,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(a,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{Et as r,F as i,H as a,L as o,M as s,W as c,i as l,kt as u,lt as d,ot as f,st as p}from"./semi-CYW2cRsN.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-BU37RGMZ.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(o,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(o,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(s,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(s,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(o,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(r,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(a,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CYW2cRsN.js";import{E as i,P as a,k as o}from"./index-B-REnHjm.js";import"./c2-shared-DaduQsja.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CYW2cRsN.js";import{E as i,P as a,k as o}from"./index-BU37RGMZ.js";import"./c2-shared-CrCOi37z.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
|
|
@ -1 +1 @@
|
|||
import{I as e,L as t}from"./index-B-REnHjm.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
import{I as e,L as t}from"./index-BU37RGMZ.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
.info-collect-page{flex-direction:column;display:flex}.info-collect-permission{margin-bottom:12px}.info-collect-form{flex-direction:column;gap:10px;display:flex}.info-collect-form-row{flex-wrap:wrap;align-items:center;gap:10px;display:flex}.info-collect-size{align-items:center;gap:6px;display:inline-flex}.info-collect-query textarea,.info-collect-natural textarea{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}.info-collect-fields input{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.info-collect-presets{row-gap:4px}.info-collect-warning{margin-bottom:10px}.info-collect-pagination{justify-content:flex-end;padding-top:10px;display:flex}.info-collect-selected-meta{padding-top:6px;display:block}.info-collect-target-link{color:var(--semi-color-link);word-break:break-all;text-decoration:none}.info-collect-target-link:hover{text-decoration:underline}.info-collect-parse-query textarea{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}.info-collect-parse-block{flex-direction:column;gap:4px;display:flex}.info-collect-detail{flex-direction:column;gap:12px;display:flex}@media (max-width:900px){.info-collect-form-row{align-items:flex-start}.info-collect-fields{width:100%!important}}
|
||||
.info-collect-page{flex-direction:column;display:flex}.info-collect-permission{margin-bottom:12px}.info-collect-form{flex-direction:column;gap:10px;display:flex}.info-collect-form-row{flex-wrap:wrap;align-items:center;gap:10px;display:flex}.info-collect-size{align-items:center;gap:6px;display:inline-flex}.info-collect-query textarea,.info-collect-natural textarea{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}.info-collect-fields input{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.info-collect-presets{row-gap:4px}.info-collect-warning{margin-bottom:10px}.info-collect-pagination{justify-content:flex-end;padding-top:10px;display:flex}.info-collect-selected-meta{padding-top:6px;display:block}.info-collect-target-link{color:var(--semi-color-link);word-break:break-all;text-decoration:none}.info-collect-target-link:hover{text-decoration:underline}.info-collect-parse-query textarea{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}.info-collect-parse-block{flex-direction:column;gap:4px;display:flex}.info-collect-detail{flex-direction:column;gap:12px;display:flex}@media (max-width:900px){.info-collect-form-row{align-items:flex-start}.info-collect-fields{width:100%!important}.info-collect-results.cs-section-card .semi-card-header,.info-collect-results.cs-section-card .semi-card-header-wrapper{flex-flow:column;align-items:stretch;height:auto}.info-collect-results.cs-section-card .semi-card-header-wrapper-title{order:1}.info-collect-results.cs-section-card .semi-card-header-wrapper-extra{order:2;max-width:100%;margin-left:0}.info-collect-page{padding-bottom:48px}.info-collect-results.cs-section-card .semi-card-header-wrapper{scroll-margin-bottom:24px}.info-collect-results-actions{flex:auto;width:100%;max-width:100%;margin-bottom:4px;margin-left:0}}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,kt as c,ot as l,st as u}from"./semi-CYW2cRsN.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-B-REnHjm.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,kt as c,ot as l,st as u}from"./semi-CYW2cRsN.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-BU37RGMZ.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CYW2cRsN.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-B-REnHjm.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CYW2cRsN.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-BU37RGMZ.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{Et as r,F as i,H as a,L as o,M as s,W as c,i as l,kt as u,lt as d,ot as f,st as p}from"./semi-CYW2cRsN.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-B-REnHjm.js";var E=e(t(),1),D=e(n(),1),{Text:O}=c;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),c=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(i,{children:[(0,D.jsx)(o,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(o,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(i,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(s,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(i,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(s,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(i,{children:[n&&(0,D.jsx)(o,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(r,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),c&&(0,D.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(u,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(a,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(l,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(l.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(l.Input,{field:`description`,label:`描述`}),(0,D.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(l.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(l.Slot,{label:`启用`,children:(0,D.jsx)(l.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{Et as r,F as i,H as a,L as o,M as s,W as c,i as l,kt as u,lt as d,ot as f,st as p}from"./semi-CYW2cRsN.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-BU37RGMZ.js";var E=e(t(),1),D=e(n(),1),{Text:O}=c;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),c=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(i,{children:[(0,D.jsx)(o,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(o,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(i,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(s,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(i,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(s,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(i,{children:[n&&(0,D.jsx)(o,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(r,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),c&&(0,D.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(u,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(a,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(l,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(l.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(l.Input,{field:`description`,label:`描述`}),(0,D.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(l.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(l.Slot,{label:`启用`,children:(0,D.jsx)(l.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{A as a,Dt as o,F as s,H as c,I as l,L as u,M as d,O as f,W as p,Z as m,Zt as h,c as g,f as _,h as ee,m as v,ot as y,p as b,s as x,st as te,u as S,v as C,x as w,z as T}from"./semi-CYW2cRsN.js";import{A as E,D,E as O,F as k,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as ne,a as R,b as z,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as ae,u as G,x as oe,y as se}from"./index-B-REnHjm.js";import{n as ce,r as le,t as K}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},ue=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,de=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function Y(e){let t=String(e);return!(t===``||de.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||ue.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function fe(e){return JSON.stringify(String(e))}function pe(e){let t=String(e);return Y(t)?t:fe(t)}function me(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):fe(String(e));let t=String(e);return Y(t)?t:fe(t)}function he(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ge(e,t,n,r){let i=` `.repeat(n),a=pe(e);if(he(t))r.push(`${i}${a}: ${me(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),ye(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),_e(t,n+2,r)):r.push(`${i}${a}: {}`)}function _e(e,t,n){for(let[r,i]of Object.entries(e))ge(r,i,t,n)}function ve(e,t,n){let r=` `.repeat(t);if(he(e)){n.push(`${r}- ${me(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),ye(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);he(o)?n.push(`${r}- ${pe(a)}: ${me(o)}`):(n.push(`${r}-`),ge(a,o,t+2,n));for(let[e,r]of s)ge(e,r,t+2,n)}function ye(e,t,n){for(let r of e)ve(r,t,n)}function be(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{A as a,Dt as o,F as s,H as c,I as l,L as u,M as d,O as f,W as p,Z as m,Zt as h,c as g,f as _,h as ee,m as v,ot as y,p as b,s as x,st as te,u as S,v as C,x as w,z as T}from"./semi-CYW2cRsN.js";import{A as E,D,E as O,F as k,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as ne,a as R,b as z,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as ae,u as G,x as oe,y as se}from"./index-BU37RGMZ.js";import{n as ce,r as le,t as K}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},ue=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,de=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function Y(e){let t=String(e);return!(t===``||de.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||ue.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function fe(e){return JSON.stringify(String(e))}function pe(e){let t=String(e);return Y(t)?t:fe(t)}function me(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):fe(String(e));let t=String(e);return Y(t)?t:fe(t)}function he(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ge(e,t,n,r){let i=` `.repeat(n),a=pe(e);if(he(t))r.push(`${i}${a}: ${me(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),ye(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),_e(t,n+2,r)):r.push(`${i}${a}: {}`)}function _e(e,t,n){for(let[r,i]of Object.entries(e))ge(r,i,t,n)}function ve(e,t,n){let r=` `.repeat(t);if(he(e)){n.push(`${r}- ${me(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),ye(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);he(o)?n.push(`${r}- ${pe(a)}: ${me(o)}`):(n.push(`${r}-`),ge(a,o,t+2,n));for(let[e,r]of s)ge(e,r,t+2,n)}function ye(e,t,n){for(let r of e)ve(r,t,n)}function be(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
||||
`).split(`
|
||||
`))n.push(`# ${e}`.trimEnd());n.length&&n.push(``)}return he(e)?(n.push(me(e)),`${n.join(`
|
||||
`)}\n`):Array.isArray(e)?(e.length?ye(e,0,n):n.push(`[]`),`${n.join(`
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,kt as i,st as a}from"./semi-CYW2cRsN.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-B-REnHjm.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,kt as i,st as a}from"./semi-CYW2cRsN.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-BU37RGMZ.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -18,7 +18,7 @@
|
|||
} catch (error) { /* first paint fallback */ }
|
||||
})();
|
||||
</script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-B-REnHjm.js"></script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-BU37RGMZ.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-CYW2cRsN.js">
|
||||
|
|
|
|||
Loading…
Reference in New Issue