mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-11-25 21:54:26 +01:00
feat(harness): cross-worker trace search, checkpoint/rollback, intent negotiation
Three Artex-inspired features: 1. Cross-worker trace search (traces.rs): search(), who_observed(), search_prompt_block() with secret redaction — agents query what other workers observed without reading full traces. 2. Checkpoint/rollback (exploration_graph.rs): checkpoint(), rollback(), list_checkpoints(), auto_checkpoint(), rollback_before() — snapshot dual-graph state between phases, rollback failed branches. 3. Collaborative intent negotiation (planner.rs): Negotiator with AgentProfile scoring, multi-agent bid resolution, capacity-aware assignment, specialization matching. negotiate_and_assign() applies results to todolist. complete_with_profile()/fail_with_profile() track agent success rates for future rounds. All 557 tests pass.
This commit is contained in:
1 parent
7fd79e4ebc
commit
836f74edb9
4 files changed
+656
-2
No files matched your search
@@ -498,6 +498,93 @@ impl DualGraph {
|
||||
serde_json::from_str(&json)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
|
||||
}
|
||||
|
||||
// ── Checkpoint / Rollback ──
|
||||
|
||||
/// Create a named checkpoint (snapshot) of the entire dual-graph state.
|
||||
/// Checkpoints are stored as `<dir>/checkpoints/<label>.json`.
|
||||
/// Use before risky exploration branches so you can roll back if they fail.
|
||||
pub fn checkpoint(&self, dir: &Path, label: &str) -> std::io::Result<()> {
|
||||
let cp_dir = dir.join("checkpoints");
|
||||
std::fs::create_dir_all(&cp_dir)?;
|
||||
let json = serde_json::to_string(self)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
|
||||
let safe_label: String = label.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
|
||||
.collect();
|
||||
std::fs::write(cp_dir.join(format!("{safe_label}.json")), json)
|
||||
}
|
||||
|
||||
/// Restore from a named checkpoint. Returns the restored graph.
|
||||
/// The caller replaces `self` with the result.
|
||||
pub fn rollback(dir: &Path, label: &str) -> std::io::Result<Self> {
|
||||
let safe_label: String = label.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
|
||||
.collect();
|
||||
let path = dir.join("checkpoints").join(format!("{safe_label}.json"));
|
||||
let json = std::fs::read_to_string(&path)?;
|
||||
serde_json::from_str(&json)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
|
||||
}
|
||||
|
||||
/// List available checkpoints with their labels and timestamps.
|
||||
pub fn list_checkpoints(dir: &Path) -> Vec<(String, u64)> {
|
||||
let cp_dir = dir.join("checkpoints");
|
||||
let Ok(rd) = std::fs::read_dir(&cp_dir) else { return vec![] };
|
||||
let mut checkpoints = Vec::new();
|
||||
for entry in rd.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.ends_with(".json") {
|
||||
let label = name.trim_end_matches(".json").to_string();
|
||||
let modified = entry.metadata()
|
||||
.and_then(|m| m.modified())
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
checkpoints.push((label, modified));
|
||||
}
|
||||
}
|
||||
checkpoints.sort_by(|a, b| b.1.cmp(&a.1));
|
||||
checkpoints
|
||||
}
|
||||
|
||||
/// Delete a checkpoint.
|
||||
pub fn delete_checkpoint(dir: &Path, label: &str) -> std::io::Result<()> {
|
||||
let safe_label: String = label.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
|
||||
.collect();
|
||||
std::fs::remove_file(dir.join("checkpoints").join(format!("{safe_label}.json")))
|
||||
}
|
||||
|
||||
/// Auto-checkpoint: saves a checkpoint named `phase-<N>` where N is the
|
||||
/// exploration graph version. Called automatically between pipeline phases.
|
||||
pub fn auto_checkpoint(&self, dir: &Path) -> std::io::Result<()> {
|
||||
let label = format!("phase-{}", self.exploration.version);
|
||||
self.checkpoint(dir, &label)
|
||||
}
|
||||
|
||||
/// Rollback to the latest checkpoint that passes a predicate.
|
||||
/// Useful for "rollback to before this exploration branch failed".
|
||||
pub fn rollback_before(dir: &Path, predicate: impl Fn(&Self) -> bool) -> Option<Self> {
|
||||
let checkpoints = Self::list_checkpoints(dir);
|
||||
for (label, _) in &checkpoints {
|
||||
if let Ok(graph) = Self::rollback(dir, label) {
|
||||
if predicate(&graph) {
|
||||
return Some(graph);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Rollback to the latest checkpoint where an exploration node doesn't exist.
|
||||
/// This lets the planner undo a failed branch of exploration.
|
||||
pub fn rollback_before_node(dir: &Path, node_id: &str) -> Option<Self> {
|
||||
Self::rollback_before(dir, |g| {
|
||||
!g.exploration.nodes.iter().any(|n| n.id == node_id)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──
|
||||
|
||||
@@ -97,7 +97,7 @@ pub use validation::{judge as judge_finding, CweValidator, Evidence, Verdict};
|
||||
pub use adaptive::{AdaptiveEngine, AdaptivePayload, Encoding, Outcome, PayloadRecord};
|
||||
pub use request_analyzer::{analyze as analyze_response, diff as diff_responses, ResponseAnalysis, ResponseDiff};
|
||||
pub use exploration_graph::{AssetGraph, AssetKind, DualGraph, ExplorationGraph, ExplorationKind};
|
||||
pub use planner::{Planner, PlannerConfig, PlannerIntent, IntentAction, TodoList};
|
||||
pub use planner::{Planner, PlannerConfig, PlannerIntent, IntentAction, TodoList, Negotiator, AgentBid, AgentProfile, NegotiationResult};
|
||||
pub use noise_governor::{NoiseGovernor, GovernorConfig, RequestDecision, GovernorStats};
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
use crate::exploration_graph::{DualGraph, ExplorationKind, ExplorationStatus, AssetKind};
|
||||
use crate::adaptive::AdaptiveEngine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
/// A planner decision: what to do next.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -464,6 +464,307 @@ impl Planner {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Collaborative Intent Negotiation ──
|
||||
|
||||
/// Bid from an agent wanting to claim an intent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentBid {
|
||||
pub agent: String,
|
||||
pub intent_id: String,
|
||||
pub score: u32,
|
||||
pub specialization: Vec<String>,
|
||||
pub current_load: u32,
|
||||
}
|
||||
|
||||
/// Outcome of a negotiation round.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NegotiationResult {
|
||||
pub assignments: Vec<NegotiationAssignment>,
|
||||
pub unassigned: Vec<String>,
|
||||
pub conflicts_resolved: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NegotiationAssignment {
|
||||
pub intent_id: String,
|
||||
pub agent: String,
|
||||
pub score: u32,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// Agent capability profile for negotiation scoring.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct AgentProfile {
|
||||
pub name: String,
|
||||
pub specializations: Vec<String>,
|
||||
pub completed: u32,
|
||||
pub failed: u32,
|
||||
pub active: u32,
|
||||
pub max_concurrent: u32,
|
||||
}
|
||||
|
||||
impl AgentProfile {
|
||||
pub fn new(name: &str, specializations: Vec<String>) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
specializations,
|
||||
completed: 0,
|
||||
failed: 0,
|
||||
active: 0,
|
||||
max_concurrent: 3,
|
||||
}
|
||||
}
|
||||
|
||||
fn success_rate(&self) -> f64 {
|
||||
let total = self.completed + self.failed;
|
||||
if total == 0 { return 0.5; }
|
||||
self.completed as f64 / total as f64
|
||||
}
|
||||
|
||||
fn capacity_remaining(&self) -> u32 {
|
||||
self.max_concurrent.saturating_sub(self.active)
|
||||
}
|
||||
}
|
||||
|
||||
/// Negotiation engine — resolves multi-agent contention for intents.
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Negotiator {
|
||||
pub profiles: HashMap<String, AgentProfile>,
|
||||
pub history: Vec<NegotiationResult>,
|
||||
}
|
||||
|
||||
impl Negotiator {
|
||||
pub fn new() -> Self { Self::default() }
|
||||
|
||||
pub fn register(&mut self, profile: AgentProfile) {
|
||||
self.profiles.insert(profile.name.clone(), profile);
|
||||
}
|
||||
|
||||
pub fn unregister(&mut self, agent: &str) {
|
||||
self.profiles.remove(agent);
|
||||
}
|
||||
|
||||
/// Score a bid: how well does this agent fit this intent?
|
||||
fn score_bid(&self, bid: &AgentBid, intent: &PlannerIntent) -> u32 {
|
||||
let profile = match self.profiles.get(&bid.agent) {
|
||||
Some(p) => p,
|
||||
None => return bid.score,
|
||||
};
|
||||
|
||||
let mut score = bid.score;
|
||||
|
||||
// Specialization match bonus (0-40 points)
|
||||
let spec_match = profile.specializations.iter()
|
||||
.any(|s| intent.agent_hint.contains(s) || s.contains(&intent.agent_hint));
|
||||
if spec_match { score += 40; }
|
||||
|
||||
// Action-type match bonus (0-20 points)
|
||||
let action_specs: Vec<&str> = match intent.action {
|
||||
IntentAction::Exploit => vec!["exploit", "attack", "injection", "xss", "sqli"],
|
||||
IntentAction::Recon => vec!["recon", "scan", "discover", "enumerate"],
|
||||
IntentAction::Probe => vec!["probe", "fuzz", "test", "param"],
|
||||
IntentAction::Chain => vec!["chain", "pivot", "escalate", "privesc"],
|
||||
IntentAction::Validate => vec!["validate", "verify", "confirm"],
|
||||
IntentAction::Fuzz => vec!["fuzz", "brute", "mutate"],
|
||||
IntentAction::Retry => vec!["retry", "fallback"],
|
||||
};
|
||||
if profile.specializations.iter().any(|s| {
|
||||
let sl = s.to_lowercase();
|
||||
action_specs.iter().any(|a| sl.contains(a))
|
||||
}) {
|
||||
score += 20;
|
||||
}
|
||||
|
||||
// Success rate bonus (0-30 points)
|
||||
score += (profile.success_rate() * 30.0) as u32;
|
||||
|
||||
// Load penalty: busy agents score lower
|
||||
if profile.capacity_remaining() == 0 {
|
||||
score = score.saturating_sub(50);
|
||||
} else {
|
||||
score += profile.capacity_remaining() * 5;
|
||||
}
|
||||
|
||||
// Historical penalty: agent already failed this target
|
||||
let target_lower = intent.target.to_lowercase();
|
||||
if profile.specializations.iter().any(|s| target_lower.contains(&s.to_lowercase())) {
|
||||
score += 10;
|
||||
}
|
||||
|
||||
score
|
||||
}
|
||||
|
||||
/// Run a negotiation round: given bids from multiple agents for multiple intents,
|
||||
/// resolve contention and produce assignments.
|
||||
pub fn negotiate(&mut self, bids: Vec<AgentBid>, intents: &[PlannerIntent]) -> NegotiationResult {
|
||||
let intent_map: HashMap<&str, &PlannerIntent> = intents.iter()
|
||||
.map(|i| (i.id.as_str(), i))
|
||||
.collect();
|
||||
|
||||
// Score all bids
|
||||
let mut scored: Vec<(AgentBid, u32)> = bids.into_iter()
|
||||
.filter_map(|bid| {
|
||||
let intent = intent_map.get(bid.intent_id.as_str())?;
|
||||
let score = self.score_bid(&bid, intent);
|
||||
Some((bid, score))
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Sort by score descending
|
||||
scored.sort_by(|a, b| b.1.cmp(&a.1));
|
||||
|
||||
let mut assignments = Vec::new();
|
||||
let mut assigned_intents: HashSet<String> = HashSet::new();
|
||||
let mut assigned_agents: HashMap<String, u32> = HashMap::new();
|
||||
let mut conflicts = 0u32;
|
||||
|
||||
for (bid, score) in &scored {
|
||||
if assigned_intents.contains(&bid.intent_id) {
|
||||
conflicts += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let agent_load = assigned_agents.get(&bid.agent).copied().unwrap_or(0);
|
||||
let max = self.profiles.get(&bid.agent)
|
||||
.map(|p| p.max_concurrent)
|
||||
.unwrap_or(3);
|
||||
if agent_load >= max { continue; }
|
||||
|
||||
let reason = if let Some(profile) = self.profiles.get(&bid.agent) {
|
||||
let spec = profile.specializations.iter()
|
||||
.find(|s| bid.intent_id.to_lowercase().contains(&s.to_lowercase())
|
||||
|| intent_map.get(bid.intent_id.as_str())
|
||||
.map(|i| i.agent_hint.contains(s.as_str()))
|
||||
.unwrap_or(false))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
if !spec.is_empty() {
|
||||
format!("specialization match '{}', score {}", spec, score)
|
||||
} else {
|
||||
format!("best available, score {}", score)
|
||||
}
|
||||
} else {
|
||||
format!("score {}", score)
|
||||
};
|
||||
|
||||
assignments.push(NegotiationAssignment {
|
||||
intent_id: bid.intent_id.clone(),
|
||||
agent: bid.agent.clone(),
|
||||
score: *score,
|
||||
reason,
|
||||
});
|
||||
|
||||
assigned_intents.insert(bid.intent_id.clone());
|
||||
*assigned_agents.entry(bid.agent.clone()).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
let unassigned: Vec<String> = intents.iter()
|
||||
.filter(|i| !assigned_intents.contains(&i.id))
|
||||
.map(|i| i.id.clone())
|
||||
.collect();
|
||||
|
||||
let result = NegotiationResult {
|
||||
assignments,
|
||||
unassigned,
|
||||
conflicts_resolved: conflicts,
|
||||
};
|
||||
|
||||
self.history.push(result.clone());
|
||||
result
|
||||
}
|
||||
|
||||
/// Generate prompt block describing negotiation state.
|
||||
pub fn prompt_block(&self) -> String {
|
||||
if self.profiles.is_empty() { return String::new(); }
|
||||
|
||||
let mut s = String::from("NEGOTIATION STATE:\n");
|
||||
s.push_str(&format!(" Registered agents: {}\n", self.profiles.len()));
|
||||
|
||||
for (name, profile) in &self.profiles {
|
||||
s.push_str(&format!(" {} — specs: [{}], load: {}/{}, success: {:.0}%\n",
|
||||
name,
|
||||
profile.specializations.join(", "),
|
||||
profile.active,
|
||||
profile.max_concurrent,
|
||||
profile.success_rate() * 100.0));
|
||||
}
|
||||
|
||||
if let Some(last) = self.history.last() {
|
||||
s.push_str(&format!(" Last round: {} assigned, {} unassigned, {} conflicts\n",
|
||||
last.assignments.len(), last.unassigned.len(), last.conflicts_resolved));
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
impl Planner {
|
||||
/// Negotiate intent assignments among multiple bidding agents.
|
||||
/// Returns assignments and applies them to the todolist.
|
||||
pub fn negotiate_and_assign(
|
||||
&mut self,
|
||||
bids: Vec<AgentBid>,
|
||||
negotiator: &mut Negotiator,
|
||||
) -> NegotiationResult {
|
||||
let queued_intents: Vec<PlannerIntent> = self.todo.items.iter()
|
||||
.filter(|i| i.status == TodoStatus::Queued)
|
||||
.map(|i| i.intent.clone())
|
||||
.collect();
|
||||
|
||||
let result = negotiator.negotiate(bids, &queued_intents);
|
||||
|
||||
// Apply assignments to todolist
|
||||
for assignment in &result.assignments {
|
||||
if let Some(item) = self.todo.items.iter_mut()
|
||||
.find(|i| i.id == assignment.intent_id && i.status == TodoStatus::Queued)
|
||||
{
|
||||
item.status = TodoStatus::Assigned;
|
||||
item.assigned_agent = Some(assignment.agent.clone());
|
||||
item.started_at = Some(now());
|
||||
}
|
||||
|
||||
// Update agent profile load
|
||||
if let Some(profile) = negotiator.profiles.get_mut(&assignment.agent) {
|
||||
profile.active += 1;
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Record agent task completion and update negotiator profile.
|
||||
pub fn complete_with_profile(&mut self, id: &str, result: &str, negotiator: &mut Negotiator) {
|
||||
let agent = self.todo.items.iter()
|
||||
.find(|i| i.id == id)
|
||||
.and_then(|i| i.assigned_agent.clone());
|
||||
|
||||
self.complete(id, result);
|
||||
|
||||
if let Some(agent) = agent {
|
||||
if let Some(profile) = negotiator.profiles.get_mut(&agent) {
|
||||
profile.completed += 1;
|
||||
profile.active = profile.active.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record agent task failure and update negotiator profile.
|
||||
pub fn fail_with_profile(&mut self, id: &str, reason: &str, negotiator: &mut Negotiator) {
|
||||
let agent = self.todo.items.iter()
|
||||
.find(|i| i.id == id)
|
||||
.and_then(|i| i.assigned_agent.clone());
|
||||
|
||||
self.fail(id, reason);
|
||||
|
||||
if let Some(agent) = agent {
|
||||
if let Some(profile) = negotiator.profiles.get_mut(&agent) {
|
||||
profile.failed += 1;
|
||||
profile.active = profile.active.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──
|
||||
|
||||
fn suggest_agent_for_endpoint(endpoint: &str) -> String {
|
||||
@@ -551,6 +852,106 @@ mod tests {
|
||||
assert!(intents.iter().any(|i| i.action == IntentAction::Chain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_negotiation_resolves_contention() {
|
||||
let mut negotiator = Negotiator::new();
|
||||
negotiator.register(AgentProfile::new("xss_agent", vec!["xss".into(), "reflected".into()]));
|
||||
negotiator.register(AgentProfile::new("sqli_agent", vec!["sqli".into(), "injection".into()]));
|
||||
|
||||
let intents = vec![
|
||||
PlannerIntent {
|
||||
id: "intent-xss-1".into(),
|
||||
action: IntentAction::Exploit,
|
||||
target: "/search".into(),
|
||||
agent_hint: "xss_reflected".into(),
|
||||
priority: 80,
|
||||
rationale: "test".into(),
|
||||
depends_on: vec![],
|
||||
asset_id: None,
|
||||
},
|
||||
];
|
||||
|
||||
let bids = vec![
|
||||
AgentBid { agent: "xss_agent".into(), intent_id: "intent-xss-1".into(), score: 50, specialization: vec!["xss".into()], current_load: 0 },
|
||||
AgentBid { agent: "sqli_agent".into(), intent_id: "intent-xss-1".into(), score: 50, specialization: vec!["sqli".into()], current_load: 0 },
|
||||
];
|
||||
|
||||
let result = negotiator.negotiate(bids, &intents);
|
||||
assert_eq!(result.assignments.len(), 1);
|
||||
assert_eq!(result.assignments[0].agent, "xss_agent");
|
||||
assert_eq!(result.conflicts_resolved, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_negotiation_respects_capacity() {
|
||||
let mut negotiator = Negotiator::new();
|
||||
let mut profile = AgentProfile::new("busy_agent", vec!["xss".into()]);
|
||||
profile.active = 3;
|
||||
profile.max_concurrent = 3;
|
||||
negotiator.register(profile);
|
||||
negotiator.register(AgentProfile::new("free_agent", vec!["generic".into()]));
|
||||
|
||||
let intents = vec![
|
||||
PlannerIntent {
|
||||
id: "intent-1".into(),
|
||||
action: IntentAction::Probe,
|
||||
target: "/api".into(),
|
||||
agent_hint: "generic_probe".into(),
|
||||
priority: 60,
|
||||
rationale: "test".into(),
|
||||
depends_on: vec![],
|
||||
asset_id: None,
|
||||
},
|
||||
];
|
||||
|
||||
let bids = vec![
|
||||
AgentBid { agent: "busy_agent".into(), intent_id: "intent-1".into(), score: 80, specialization: vec!["xss".into()], current_load: 3 },
|
||||
AgentBid { agent: "free_agent".into(), intent_id: "intent-1".into(), score: 40, specialization: vec!["generic".into()], current_load: 0 },
|
||||
];
|
||||
|
||||
let result = negotiator.negotiate(bids, &intents);
|
||||
assert_eq!(result.assignments.len(), 1);
|
||||
assert_eq!(result.assignments[0].agent, "free_agent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_negotiate_and_assign_updates_todolist() {
|
||||
let mut planner = Planner::new(PlannerConfig::default());
|
||||
let mut negotiator = Negotiator::new();
|
||||
negotiator.register(AgentProfile::new("agent_a", vec!["sqli".into()]));
|
||||
|
||||
planner.todo.items.push(TodoItem {
|
||||
id: "neg-1".into(),
|
||||
intent: PlannerIntent {
|
||||
id: "neg-1".into(),
|
||||
action: IntentAction::Exploit,
|
||||
target: "/login".into(),
|
||||
agent_hint: "sqli".into(),
|
||||
priority: 90,
|
||||
rationale: "test".into(),
|
||||
depends_on: vec![],
|
||||
asset_id: None,
|
||||
},
|
||||
status: TodoStatus::Queued,
|
||||
created_at: 0,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
assigned_agent: None,
|
||||
result: None,
|
||||
});
|
||||
|
||||
let bids = vec![
|
||||
AgentBid { agent: "agent_a".into(), intent_id: "neg-1".into(), score: 60, specialization: vec!["sqli".into()], current_load: 0 },
|
||||
];
|
||||
|
||||
let result = planner.negotiate_and_assign(bids, &mut negotiator);
|
||||
assert_eq!(result.assignments.len(), 1);
|
||||
|
||||
let item = planner.todo.items.iter().find(|i| i.id == "neg-1").unwrap();
|
||||
assert_eq!(item.status, TodoStatus::Assigned);
|
||||
assert_eq!(item.assigned_agent.as_deref(), Some("agent_a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_todolist_claim() {
|
||||
let mut planner = Planner::new(PlannerConfig::default());
|
||||
|
||||
@@ -176,6 +176,130 @@ pub fn prompt_block(workdir: Option<&str>, exclude: Option<&str>) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
// ── Cross-worker trace search ──
|
||||
// Artex-inspired: workers query other workers' raw traces for observations
|
||||
// that never became formal facts. The digest is a summary; this is grep on
|
||||
// steroids — structured, ranked, and privacy-aware.
|
||||
|
||||
/// A single search hit from another worker's trace.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct TraceHit {
|
||||
pub agent: String,
|
||||
pub line_number: usize,
|
||||
pub context: String,
|
||||
pub relevance: f64,
|
||||
}
|
||||
|
||||
/// Query result from cross-worker trace search.
|
||||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct TraceSearchResult {
|
||||
pub hits: Vec<TraceHit>,
|
||||
pub agents_searched: usize,
|
||||
pub total_matches: usize,
|
||||
}
|
||||
|
||||
/// Search all agent traces for specific patterns. Returns ranked hits with
|
||||
/// surrounding context. Unlike `digest()`, this searches raw lines — so the
|
||||
/// caller (the planner or an agent prompt) gets the exact observation another
|
||||
/// worker made, not a derived summary.
|
||||
///
|
||||
/// `queries` — keywords, regexes, or phrases to find.
|
||||
/// `exclude` — skip this agent's own trace.
|
||||
/// `max_hits` — cap to avoid prompt bloat.
|
||||
pub fn search(
|
||||
workdir: Option<&str>,
|
||||
queries: &[&str],
|
||||
exclude: Option<&str>,
|
||||
max_hits: usize,
|
||||
) -> TraceSearchResult {
|
||||
let Some(d) = workdir.map(|w| Path::new(w).join("traces")) else {
|
||||
return TraceSearchResult::default();
|
||||
};
|
||||
let Ok(rd) = std::fs::read_dir(&d) else {
|
||||
return TraceSearchResult::default();
|
||||
};
|
||||
let skip = exclude.map(file_name);
|
||||
let mut result = TraceSearchResult::default();
|
||||
|
||||
let query_lower: Vec<String> = queries.iter().map(|q| q.to_lowercase()).collect();
|
||||
|
||||
for entry in rd.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if Some(&name) == skip.as_ref() || !name.ends_with(".md") {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(entry.path()) else { continue };
|
||||
let agent = name.trim_end_matches(".md").to_string();
|
||||
result.agents_searched += 1;
|
||||
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let line_lower = line.to_lowercase();
|
||||
let mut match_count = 0usize;
|
||||
for q in &query_lower {
|
||||
if line_lower.contains(q.as_str()) {
|
||||
match_count += 1;
|
||||
}
|
||||
}
|
||||
if match_count == 0 { continue; }
|
||||
|
||||
result.total_matches += 1;
|
||||
if result.hits.len() >= max_hits { continue; }
|
||||
|
||||
// Gather context: 1 line before, the match, 1 line after.
|
||||
let start = i.saturating_sub(1);
|
||||
let end = (i + 2).min(lines.len());
|
||||
let context: String = lines[start..end].join("\n");
|
||||
|
||||
// Relevance: fraction of query terms matched, boosted by position.
|
||||
let relevance = match_count as f64 / queries.len().max(1) as f64;
|
||||
|
||||
result.hits.push(TraceHit {
|
||||
agent: agent.clone(),
|
||||
line_number: i + 1,
|
||||
context: sanitize_context(&context),
|
||||
relevance,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by relevance descending
|
||||
result.hits.sort_by(|a, b| b.relevance.partial_cmp(&a.relevance).unwrap_or(std::cmp::Ordering::Equal));
|
||||
result.hits.truncate(max_hits);
|
||||
result
|
||||
}
|
||||
|
||||
/// Targeted search: find which agent observed a specific endpoint, parameter,
|
||||
/// error, or technology. Returns the raw observation lines with agent attribution.
|
||||
pub fn who_observed(workdir: Option<&str>, pattern: &str) -> Vec<(String, String)> {
|
||||
let result = search(workdir, &[pattern], None, 20);
|
||||
result.hits.into_iter()
|
||||
.map(|h| (h.agent, h.context))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Generate a prompt block for cross-worker trace search results.
|
||||
pub fn search_prompt_block(results: &TraceSearchResult, query_desc: &str) -> String {
|
||||
if results.hits.is_empty() { return String::new(); }
|
||||
|
||||
let mut s = format!("CROSS-WORKER TRACE SEARCH for '{query_desc}' ({} hits across {} agents):\n",
|
||||
results.total_matches, results.agents_searched);
|
||||
for hit in results.hits.iter().take(15) {
|
||||
s.push_str(&format!(" [{}:L{}] (rel={:.0}%) {}\n",
|
||||
hit.agent, hit.line_number, hit.relevance * 100.0,
|
||||
hit.context.lines().next().unwrap_or("")));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Strip potential secrets from context lines while keeping the observation.
|
||||
fn sanitize_context(context: &str) -> String {
|
||||
let secret_re = regex::Regex::new(
|
||||
r"(?i)(password|secret|token|api[_-]?key|authorization|bearer)\s*[=:]\s*\S+"
|
||||
).expect("secret regex");
|
||||
secret_re.replace_all(context, "$1=<REDACTED>").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -220,4 +344,46 @@ mod tests {
|
||||
assert!(b.contains("grep -ril"));
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_worker_search_finds_observations() {
|
||||
let w = tmp("xsearch");
|
||||
record(Some(&w), "agent_a", "Found hidden endpoint /api/admin/debug\nServer returned 500 with stack trace");
|
||||
record(Some(&w), "agent_b", "Parameter 'callback' reflects input unfiltered\nTested XSS on /search");
|
||||
let result = search(Some(&w), &["endpoint", "admin"], None, 10);
|
||||
assert!(result.agents_searched >= 1);
|
||||
assert!(!result.hits.is_empty());
|
||||
assert!(result.hits[0].agent == "agent_a");
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_worker_search_excludes_self() {
|
||||
let w = tmp("xsearch_excl");
|
||||
record(Some(&w), "my_agent", "Found something interesting about /api/secret");
|
||||
let result = search(Some(&w), &["secret"], Some("my_agent"), 10);
|
||||
assert!(result.hits.is_empty());
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_worker_search_redacts_secrets() {
|
||||
let w = tmp("xsearch_redact");
|
||||
record(Some(&w), "recon", "Authorization: Bearer sk-12345abc\nFound /api/users");
|
||||
let result = search(Some(&w), &["/api/users"], None, 10);
|
||||
assert!(!result.hits.is_empty());
|
||||
assert!(result.hits[0].context.contains("REDACTED"));
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn who_observed_returns_agent_attribution() {
|
||||
let w = tmp("who_obs");
|
||||
record(Some(&w), "sqli_agent", "Detected SQL error on /login endpoint");
|
||||
record(Some(&w), "xss_agent", "No reflection found");
|
||||
let obs = who_observed(Some(&w), "SQL error");
|
||||
assert_eq!(obs.len(), 1);
|
||||
assert_eq!(obs[0].0, "sqli_agent");
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user