mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-06 05:01:50 +08:00
feat: add optional credential processing with dependent switches and traffic evidence
This commit is contained in:
1 parent
7c2efbc1ca
commit
851e3f99ed
16 files changed
+1881
-38
No files matched your search
@@ -0,0 +1,224 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const SettingCredentialAgent = "credential_agent_enabled"
|
||||
const SettingCredentialTraffic = "credential_traffic_binding"
|
||||
const CredentialAgentKey = "credential_processor"
|
||||
|
||||
type CredentialAccount struct {
|
||||
Label string `json:"label,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
Cookie string `json:"cookie,omitempty"`
|
||||
Endpoint string `json:"endpoint,omitempty"`
|
||||
Protocol string `json:"protocol,omitempty"`
|
||||
}
|
||||
|
||||
// These are verified references and bounded excerpts, not full packet snapshots.
|
||||
// The original capture can be opened while it remains in the traffic store.
|
||||
type CredentialTraffic struct {
|
||||
ID string `json:"id"`
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
Status int `json:"status"`
|
||||
Side string `json:"side"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
Accounts []int `json:"accounts"`
|
||||
}
|
||||
type CredentialAnalysis struct {
|
||||
ForceExtract bool `json:"force_extract,omitempty"`
|
||||
TrafficNote string `json:"traffic_note,omitempty"`
|
||||
State string `json:"state"`
|
||||
Lease string `json:"lease,omitempty"`
|
||||
LeaseUntil time.Time `json:"lease_until,omitempty"`
|
||||
SourceHash string `json:"source_hash,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Accounts []CredentialAccount `json:"accounts"`
|
||||
Traffic []CredentialTraffic `json:"traffic"`
|
||||
TrafficState string `json:"traffic_state"`
|
||||
Note string `json:"note,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
ProcessedAt *time.Time `json:"processed_at,omitempty"`
|
||||
}
|
||||
|
||||
func CredentialSourceHash(content string) string {
|
||||
sum := sha256.Sum256([]byte(content))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// The dependent switch and its parent are committed atomically. Turning the
|
||||
// parent off also clears binding, so re-enabling never silently enables binding.
|
||||
func (d *DB) SetCredentialAgentSettings(ctx context.Context, enabled, binding *bool) error {
|
||||
return d.SetIntelligenceSettings(ctx, nil, enabled, binding)
|
||||
}
|
||||
func (d *DB) SetIntelligenceSettings(ctx context.Context, recording, enabled, binding *bool) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(7337741006)`); err != nil {
|
||||
return err
|
||||
}
|
||||
record, on, bind := false, false, false
|
||||
var value string
|
||||
err = tx.QueryRowContext(ctx, `SELECT value FROM settings WHERE key=$1`, SettingTaskIntelligence).Scan(&value)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
record = value == "true" || value == "1"
|
||||
if recording != nil {
|
||||
record = *recording
|
||||
}
|
||||
value = ""
|
||||
err = tx.QueryRowContext(ctx, `SELECT value FROM settings WHERE key=$1`, SettingCredentialAgent).Scan(&value)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
on = value == "true" || value == "1"
|
||||
value = ""
|
||||
err = tx.QueryRowContext(ctx, `SELECT value FROM settings WHERE key=$1`, SettingCredentialTraffic).Scan(&value)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
bind = value == "true" || value == "1"
|
||||
if enabled != nil {
|
||||
on = *enabled
|
||||
}
|
||||
if binding != nil {
|
||||
bind = *binding
|
||||
}
|
||||
if !record {
|
||||
if enabled != nil && *enabled {
|
||||
return fmt.Errorf("%w: 请先开启 Agent 自动记录,再开启 Agent 开关", ErrIntelligenceInvalid)
|
||||
}
|
||||
if binding != nil && *binding {
|
||||
return fmt.Errorf("%w: 请依次开启 Agent 自动记录和 Agent 开关", ErrIntelligenceInvalid)
|
||||
}
|
||||
on = false
|
||||
bind = false
|
||||
}
|
||||
if !on {
|
||||
if binding != nil && *binding {
|
||||
return fmt.Errorf("%w: 请先开启 Agent 开关,再启用绑定流量", ErrIntelligenceInvalid)
|
||||
}
|
||||
bind = false
|
||||
}
|
||||
for key, val := range map[string]bool{SettingTaskIntelligence: record, SettingCredentialAgent: on, SettingCredentialTraffic: bind} {
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO settings(key,value) VALUES($1,$2) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value,updated_at=now()`, key, strconv.FormatBool(val)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// One durable lease per record, shared by all application processes. Errors do
|
||||
// not retry every tick; explicit retry queues the record again. Expired leases
|
||||
// recover interrupted runs after restart. No task lock is held during LLM I/O.
|
||||
func (d *DB) ClaimCredentialJob(ctx context.Context, bind bool, taskID int64) (*Intelligence, error) {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var id int64
|
||||
err = tx.QueryRowContext(ctx, `SELECT i.id FROM task_intelligence i JOIN tasks t ON t.id=i.task_id
|
||||
WHERE i.kind='credential' AND EXISTS(SELECT 1 FROM settings WHERE key='credential_agent_enabled' AND value IN ('true','1')) AND EXISTS(SELECT 1 FROM settings WHERE key='task_intelligence_enabled' AND value IN ('true','1')) AND ($2::bigint=0 OR i.task_id=$2) AND t.deleted_at IS NULL AND t.archived_at IS NULL
|
||||
AND NOT EXISTS(SELECT 1 FROM task_archives a WHERE a.task_id=t.id AND a.state IN ('archive_queued','archiving','restore_queued','restoring','delete_queued','deleting'))
|
||||
AND (i.credential_analysis IS NULL OR i.credential_analysis->>'state'='queued'
|
||||
OR (i.credential_analysis->>'state'='processing' AND (i.credential_analysis->>'lease_until')::timestamptz < now())
|
||||
OR ($1 AND i.credential_analysis->>'state'='ready' AND i.credential_analysis->>'traffic_state'='off'))
|
||||
ORDER BY i.id FOR UPDATE OF i SKIP LOCKED LIMIT 1`, bind, taskID).Scan(&id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
token := make([]byte, 16)
|
||||
if _, err = rand.Read(token); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
patch, _ := json.Marshal(map[string]any{"state": "processing", "lease": hex.EncodeToString(token), "lease_until": time.Now().UTC().Add(3 * time.Minute)})
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE task_intelligence SET credential_analysis=COALESCE(credential_analysis,'{}'::jsonb)||$2::jsonb WHERE id=$1`, id, string(patch)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.GetIntelligence(ctx, id)
|
||||
}
|
||||
func (d *DB) FinishCredentialJob(ctx context.Context, item *Intelligence, result CredentialAnalysis) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// Serialize completion with both settings toggles. A disabled feature cannot
|
||||
// publish a newly derived result or newly matched traffic after switching off.
|
||||
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(7337741006)`); err != nil {
|
||||
return err
|
||||
}
|
||||
var enabled, binding bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT (EXISTS(SELECT 1 FROM settings WHERE key=$1 AND value IN ('true','1')) AND EXISTS(SELECT 1 FROM settings WHERE key='task_intelligence_enabled' AND value IN ('true','1'))),EXISTS(SELECT 1 FROM settings WHERE key=$2 AND value IN ('true','1'))`, SettingCredentialAgent, SettingCredentialTraffic).Scan(&enabled, &binding); err != nil {
|
||||
return err
|
||||
}
|
||||
if !enabled {
|
||||
_, err = tx.ExecContext(ctx, `UPDATE task_intelligence SET credential_analysis=credential_analysis||'{"state":"queued"}'::jsonb WHERE id=$1 AND credential_analysis->>'lease'=$2`, item.ID, item.Credentials.Lease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
if !binding {
|
||||
result.Traffic = item.Credentials.Traffic
|
||||
result.TrafficState = "off"
|
||||
result.TrafficNote = ""
|
||||
}
|
||||
result.Lease = ""
|
||||
result.LeaseUntil = time.Time{}
|
||||
now := time.Now().UTC()
|
||||
result.ProcessedAt = &now
|
||||
raw, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE task_intelligence i SET credential_analysis=$3::jsonb
|
||||
WHERE i.id=$1 AND i.credential_analysis->>'lease'=$2
|
||||
AND EXISTS(SELECT 1 FROM tasks t WHERE t.id=i.task_id AND t.deleted_at IS NULL AND t.archived_at IS NULL)
|
||||
AND NOT EXISTS(SELECT 1 FROM task_archives a WHERE a.task_id=i.task_id AND a.state IN ('archive_queued','archiving','restore_queued','restoring','delete_queued','deleting'))`, item.ID, item.Credentials.Lease, string(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (d *DB) RetryCredentialJob(ctx context.Context, taskID, id int64) error {
|
||||
result, err := d.ExecContext(ctx, `UPDATE task_intelligence i SET credential_analysis=COALESCE(credential_analysis,'{}'::jsonb)||'{"state":"queued","error":"","force_extract":true}'::jsonb
|
||||
WHERE id=$1 AND task_id=$2 AND kind='credential'
|
||||
AND COALESCE(credential_analysis->>'state','')<>'processing'
|
||||
AND EXISTS(SELECT 1 FROM tasks t WHERE t.id=i.task_id AND t.deleted_at IS NULL AND t.archived_at IS NULL)`, id, taskID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := result.RowsAffected()
|
||||
if n == 0 {
|
||||
return ErrIntelligenceNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCredentialSwitchDependencyAndLeases(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
oldRecording := d.GetBool(SettingTaskIntelligence, false)
|
||||
oldAgent, oldBinding := d.GetBool(SettingCredentialAgent, false), d.GetBool(SettingCredentialTraffic, false)
|
||||
defer func() {
|
||||
_ = d.SetBool(SettingTaskIntelligence, oldRecording)
|
||||
_ = d.SetCredentialAgentSettings(t.Context(), &oldAgent, nil)
|
||||
if oldAgent {
|
||||
_ = d.SetCredentialAgentSettings(t.Context(), nil, &oldBinding)
|
||||
}
|
||||
}()
|
||||
off, on := false, true
|
||||
_ = d.SetIntelligenceSettings(t.Context(), &off, nil, nil)
|
||||
if err = d.SetCredentialAgentSettings(t.Context(), &on, nil); err == nil {
|
||||
t.Fatal("agent enabled without recording")
|
||||
}
|
||||
_ = d.SetIntelligenceSettings(t.Context(), &on, nil, nil)
|
||||
if err = d.SetCredentialAgentSettings(t.Context(), &off, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = d.SetCredentialAgentSettings(t.Context(), nil, &on); err == nil {
|
||||
t.Fatal("binding allowed without parent")
|
||||
}
|
||||
if err = d.SetCredentialAgentSettings(t.Context(), &on, &on); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = d.SetCredentialAgentSettings(t.Context(), &off, nil); err != nil || d.GetBool(SettingCredentialTraffic, true) {
|
||||
t.Fatal("parent off did not clear dependent switch", err)
|
||||
}
|
||||
_ = d.SetCredentialAgentSettings(t.Context(), &on, nil)
|
||||
_ = d.SetIntelligenceSettings(t.Context(), &off, nil, nil)
|
||||
if d.GetBool(SettingCredentialAgent, true) || d.GetBool(SettingCredentialTraffic, true) {
|
||||
t.Fatal("recording off did not cascade")
|
||||
}
|
||||
_ = d.SetIntelligenceSettings(t.Context(), &on, &on, nil)
|
||||
task, err := d.CreateTask("credential queue", "local fixture", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.DeleteTask(task.ID)
|
||||
in := testIntelligenceInput()
|
||||
in.Status = "verified"
|
||||
item, err := d.RecordIntelligence(t.Context(), task.ID, 0, "qa", in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := d.ClaimCredentialJob(t.Context(), false, task.ID)
|
||||
if err != nil || first == nil || first.ID != item.ID {
|
||||
t.Fatalf("claim %+v %v", first, err)
|
||||
}
|
||||
if duplicate, err := d.ClaimCredentialJob(t.Context(), false, task.ID); err != nil || duplicate != nil {
|
||||
t.Fatal("same lease claimed twice", duplicate, err)
|
||||
}
|
||||
result := CredentialAnalysis{State: "ready", Method: "rules", SourceHash: CredentialSourceHash(in.Content), Accounts: []CredentialAccount{{Username: "qa", Password: "local-fixture-secret"}}, TrafficState: "off"}
|
||||
if err = d.FinishCredentialJob(t.Context(), first, result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := d.GetIntelligence(t.Context(), item.ID)
|
||||
if err != nil || got.Credentials == nil || got.Credentials.State != "ready" || got.Status != "verified" || got.Content != in.Content {
|
||||
t.Fatalf("result: %+v %v", got, err)
|
||||
}
|
||||
if duplicate, err := d.ClaimCredentialJob(t.Context(), false, task.ID); err != nil || duplicate != nil {
|
||||
t.Fatal("ready record reprocessed")
|
||||
}
|
||||
// Binding can be added later without rerunning extraction. Stale lease writes
|
||||
// must not overwrite the newly claimed run.
|
||||
second, err := d.ClaimCredentialJob(t.Context(), true, task.ID)
|
||||
if err != nil || second == nil {
|
||||
t.Fatal("late binding not queued", err)
|
||||
}
|
||||
stale := result
|
||||
stale.State = "error"
|
||||
_ = d.FinishCredentialJob(t.Context(), first, stale)
|
||||
got, _ = d.GetIntelligence(t.Context(), item.ID)
|
||||
if got.Credentials.State != "processing" || got.Credentials.Lease != second.Credentials.Lease {
|
||||
t.Fatal("stale completion overwrote newer lease")
|
||||
}
|
||||
_ = d.SetCredentialAgentSettings(t.Context(), &off, nil)
|
||||
if err = d.FinishCredentialJob(t.Context(), second, result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = d.GetIntelligence(t.Context(), item.ID)
|
||||
if got.Credentials.State != "queued" {
|
||||
t.Fatal("disabled job published")
|
||||
}
|
||||
_ = d.SetCredentialAgentSettings(t.Context(), &on, nil)
|
||||
third, err := d.ClaimCredentialJob(t.Context(), false, task.ID)
|
||||
if err != nil || third == nil {
|
||||
t.Fatal("interrupted job not recoverable", err)
|
||||
}
|
||||
expiry := time.Now().UTC().Add(-time.Minute).Format(time.RFC3339)
|
||||
raw, _ := json.Marshal(expiry)
|
||||
_, err = d.Exec(`UPDATE task_intelligence SET credential_analysis=jsonb_set(credential_analysis,'{lease_until}',$2::jsonb) WHERE id=$1`, item.ID, string(raw))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovered, err := d.ClaimCredentialJob(t.Context(), false, task.ID)
|
||||
if err != nil || recovered == nil || recovered.Credentials.Lease == third.Credentials.Lease {
|
||||
t.Fatal("expired lease not recovered", err)
|
||||
}
|
||||
}
|
||||
+27
-17
@@ -30,14 +30,15 @@ type IntelligenceInput struct {
|
||||
}
|
||||
type Intelligence struct {
|
||||
IntelligenceInput
|
||||
ID int64 `json:"id"`
|
||||
TaskID int64 `json:"task_id"`
|
||||
NodeID *int64 `json:"node_id,omitempty"`
|
||||
Worker string `json:"worker"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Inherited bool `json:"inherited"`
|
||||
SourceSession string `json:"source_session,omitempty"`
|
||||
ID int64 `json:"id"`
|
||||
TaskID int64 `json:"task_id"`
|
||||
NodeID *int64 `json:"node_id,omitempty"`
|
||||
Worker string `json:"worker"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Inherited bool `json:"inherited"`
|
||||
SourceSession string `json:"source_session,omitempty"`
|
||||
Credentials *CredentialAnalysis `json:"credentials,omitempty"`
|
||||
}
|
||||
type IntelligenceFilter struct {
|
||||
TaskID int64
|
||||
@@ -49,10 +50,12 @@ type IntelligenceFilter struct {
|
||||
Offset int
|
||||
}
|
||||
type IntelligencePage struct {
|
||||
Items []*Intelligence `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Counts map[string]int `json:"counts"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Items []*Intelligence `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Counts map[string]int `json:"counts"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CredentialAgentEnabled bool `json:"credential_agent_enabled"`
|
||||
CredentialTrafficBinding bool `json:"credential_traffic_binding"`
|
||||
}
|
||||
|
||||
func ValidIntelligenceStatus(kind, status string) bool {
|
||||
@@ -132,7 +135,7 @@ func intelligenceFingerprint(in IntelligenceInput) string {
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
const intelligenceCols = `id,task_id,node_id,kind,title,content,evidence,confidence,status,asset_ids,worker,created_at,updated_at`
|
||||
const intelligenceCols = `id,task_id,node_id,kind,title,content,evidence,confidence,status,asset_ids,worker,created_at,updated_at,credential_analysis`
|
||||
|
||||
// Resolve provenance from the graph, never from a worker's display number.
|
||||
// A fact with ambiguous/missing parents deliberately has no exact session link.
|
||||
@@ -144,8 +147,8 @@ const intelligenceSourceSession = `, COALESCE(
|
||||
|
||||
func scanIntelligence(row interface{ Scan(...any) error }, withSource ...bool) (*Intelligence, error) {
|
||||
item := &Intelligence{}
|
||||
var assets []byte
|
||||
dest := []any{&item.ID, &item.TaskID, &item.NodeID, &item.Kind, &item.Title, &item.Content, &item.Evidence, &item.Confidence, &item.Status, &assets, &item.Worker, &item.CreatedAt, &item.UpdatedAt}
|
||||
var assets, credentials []byte
|
||||
dest := []any{&item.ID, &item.TaskID, &item.NodeID, &item.Kind, &item.Title, &item.Content, &item.Evidence, &item.Confidence, &item.Status, &assets, &item.Worker, &item.CreatedAt, &item.UpdatedAt, &credentials}
|
||||
if len(withSource) > 0 && withSource[0] {
|
||||
dest = append(dest, &item.SourceSession)
|
||||
}
|
||||
@@ -156,6 +159,11 @@ func scanIntelligence(row interface{ Scan(...any) error }, withSource ...bool) (
|
||||
if err = json.Unmarshal(assets, &item.AssetIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(credentials) > 0 && string(credentials) != "null" {
|
||||
if err = json.Unmarshal(credentials, &item.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
@@ -230,6 +238,8 @@ func (d *DB) ListIntelligence(ctx context.Context, f IntelligenceFilter) (*Intel
|
||||
f.Offset = 0
|
||||
}
|
||||
page := &IntelligencePage{Items: []*Intelligence{}, Counts: map[string]int{"credential": 0, "lead": 0, "sensitive_data": 0}, Enabled: d.GetBool(SettingTaskIntelligence, false)}
|
||||
page.CredentialAgentEnabled = d.GetBool(SettingCredentialAgent, false)
|
||||
page.CredentialTrafficBinding = page.CredentialAgentEnabled && d.GetBool(SettingCredentialTraffic, false)
|
||||
scope := intelligenceScope()
|
||||
args := []any{f.TaskID, f.AssetID}
|
||||
rows, err := d.QueryContext(ctx, `SELECT kind,count(*)`+scope+` GROUP BY kind`, args...)
|
||||
@@ -257,7 +267,7 @@ func (d *DB) ListIntelligence(ctx context.Context, f IntelligenceFilter) (*Intel
|
||||
return nil, err
|
||||
}
|
||||
args = append(args, f.Limit, f.Offset)
|
||||
cols := `i.id,i.task_id,i.node_id,i.kind,i.title,i.content,i.evidence,i.confidence,i.status,i.asset_ids,i.worker,i.created_at,i.updated_at`
|
||||
cols := `i.id,i.task_id,i.node_id,i.kind,i.title,i.content,i.evidence,i.confidence,i.status,i.asset_ids,i.worker,i.created_at,i.updated_at,i.credential_analysis`
|
||||
rows, err = d.QueryContext(ctx, `SELECT `+cols+intelligenceSourceSession+where+` ORDER BY i.id DESC LIMIT $6 OFFSET $7`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -274,7 +284,7 @@ func (d *DB) ListIntelligence(ctx context.Context, f IntelligenceFilter) (*Intel
|
||||
return page, rows.Err()
|
||||
}
|
||||
func (d *DB) GetIntelligence(ctx context.Context, id int64) (*Intelligence, error) {
|
||||
item, err := scanIntelligence(d.QueryRowContext(ctx, `SELECT i.id,i.task_id,i.node_id,i.kind,i.title,i.content,i.evidence,i.confidence,i.status,i.asset_ids,i.worker,i.created_at,i.updated_at`+intelligenceSourceSession+` FROM task_intelligence i JOIN tasks t ON t.id=i.task_id AND t.deleted_at IS NULL WHERE i.id=$1`, id), true)
|
||||
item, err := scanIntelligence(d.QueryRowContext(ctx, `SELECT i.id,i.task_id,i.node_id,i.kind,i.title,i.content,i.evidence,i.confidence,i.status,i.asset_ids,i.worker,i.created_at,i.updated_at,i.credential_analysis`+intelligenceSourceSession+` FROM task_intelligence i JOIN tasks t ON t.id=i.task_id AND t.deleted_at IS NULL WHERE i.id=$1`, id), true)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrIntelligenceNotFound
|
||||
}
|
||||
|
||||
@@ -1568,3 +1568,6 @@ CREATE TABLE IF NOT EXISTS task_intelligence (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_intelligence_task ON task_intelligence(task_id,id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_intelligence_assets ON task_intelligence USING gin(asset_ids);
|
||||
|
||||
-- Optional derived credential presentation; raw intelligence remains authoritative.
|
||||
ALTER TABLE task_intelligence ADD COLUMN IF NOT EXISTS credential_analysis JSONB;
|
||||
@@ -208,6 +208,9 @@ VALUES($1,$2,0,'quota_exhausted','balance exhausted',$3,$4,$3)`, task.ID, llmPro
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = d.Exec(`UPDATE task_intelligence SET credential_analysis='{"state":"ready","method":"rules","accounts":[{"username":"qa","password":"archive-fixture"}],"traffic":[{"id":"archive-flow","url":"http://fixture.invalid","method":"POST","status":200,"side":"request","excerpt":"archive-fixture","accounts":[0]}],"traffic_state":"ready"}'::jsonb WHERE id=$1`, intel.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := d.QueueTaskArchive(task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -278,7 +281,7 @@ VALUES($1,$2,0,'quota_exhausted','balance exhausted',$3,$4,$3)`, task.ID, llmPro
|
||||
t.Fatal(err)
|
||||
}
|
||||
restoredIntel, err := d.GetIntelligence(t.Context(), intel.ID)
|
||||
if err != nil || restoredIntel.Content != "archive-fixture" {
|
||||
if err != nil || restoredIntel.Content != "archive-fixture" || restoredIntel.Credentials == nil || len(restoredIntel.Credentials.Accounts) != 1 || len(restoredIntel.Credentials.Traffic) != 1 {
|
||||
t.Fatalf("intelligence lost after archive: %+v %v", restoredIntel, err)
|
||||
}
|
||||
warningFound := false
|
||||
|
||||
Reference in new issue
Block a user