From dfe6f7bab667b7d08e889f6002e78bf49becc791 Mon Sep 17 00:00:00 2001 From: CyberSecurityUP Date: Tue, 1 Dec 2026 11:17:57 -0300 Subject: [PATCH] feat: step-level worker activity + cost-governed worker tool loop - activity store: append-only per-step log under /activity with cross-worker search/list/get and a prompt block (Artex-style process-level exchange) - wire reactive workers to record tool steps and model observations by intent - --worker-tools: bounded agentic tool loop per reactive worker (opt-in, off by default) with a shared ToolBudget (calls/rounds/concurrency), priority-weighted rounds, and cross-worker dedupe that reuses identical command output - CLI + web /api/runs/:id/{activity,todolist} and a new Workers tab (planner todolist + worker tape) - no behavior change when the flag is off --- .env.example | 10 + neurosploit-rs/app/src/activitycli.rs | 120 ++++++ neurosploit-rs/app/src/main.rs | 18 + neurosploit-rs/crates/harness/src/activity.rs | 384 ++++++++++++++++++ .../crates/harness/src/agentic_tools.rs | 139 ++++++- neurosploit-rs/crates/harness/src/lib.rs | 1 + neurosploit-rs/crates/harness/src/pipeline.rs | 2 + neurosploit-rs/crates/harness/src/reactive.rs | 45 +- .../crates/harness/src/reactive_bridge.rs | 124 +++++- .../crates/harness/src/toolbox/mod.rs | 2 +- .../crates/harness/src/toolbox/runner.rs | 47 ++- web/public/app.js | 64 ++- web/server.js | 69 ++++ 13 files changed, 1004 insertions(+), 21 deletions(-) create mode 100644 neurosploit-rs/app/src/activitycli.rs create mode 100644 neurosploit-rs/crates/harness/src/activity.rs diff --git a/.env.example b/.env.example index 424d221..4f93f6d 100755 --- a/.env.example +++ b/.env.example @@ -172,3 +172,13 @@ TYPESAFE_API_KEY= # State, generated phishlets and captures live under .neurosploit/phish/. #NEUROSPLOIT_PHISH_DIR=.neurosploit/phish #NEUROSPLOIT_PHISH_OUTPUT_CAP=65536 + +# ------------------------------------------------------------------ +# Reactive worker tool loop (opt-in with --worker-tools). Cost control: +# a single shared budget across all workers bounds total LLM rounds, tool +# executions and concurrency. Identical tool commands are deduped/reused. +#NEUROSPLOIT_WORKER_TOOL_MAX_CALLS=60 +#NEUROSPLOIT_WORKER_TOOL_MAX_ROUNDS=80 +#NEUROSPLOIT_WORKER_TOOL_CONCURRENCY=3 +# Per-intent round cap (priority-weighted, <= this). Default 4. +#NEUROSPLOIT_WORKER_TOOL_ROUNDS=4 diff --git a/neurosploit-rs/app/src/activitycli.rs b/neurosploit-rs/app/src/activitycli.rs new file mode 100644 index 0000000..453e80c --- /dev/null +++ b/neurosploit-rs/app/src/activitycli.rs @@ -0,0 +1,120 @@ +//! `neurosploit activity …` — step-level worker activity store. +//! +//! Workers query each other's execution steps (Artex-style process-level +//! information exchange) without reading the whole transcript: +//! `list` (intents), `search` (keyword across tool/args/output), `get` (one +//! intent's steps, optionally specific step ids). + +use clap::Subcommand; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +#[derive(Subcommand)] +pub enum ActivityCmd { + /// List the run's intents and their step/worker summary (newest first). + List { + /// Run directory or run id under ./runs (default: newest run). + #[arg(long)] + run: Option, + #[arg(long, default_value_t = 50)] + limit: usize, + #[arg(long)] + json: bool, + }, + /// Search every worker's steps for a keyword (tool / command / output). + Search { + #[arg(long)] + run: Option, + #[arg(long)] + q: String, + /// Skip this worker's own steps (the caller's name). + #[arg(long)] + exclude: Option, + #[arg(long, default_value_t = 50)] + limit: usize, + #[arg(long)] + json: bool, + }, + /// Full steps for one intent (optionally only specific step ids). + Get { + #[arg(long)] + run: Option, + #[arg(long)] + intent: String, + /// Restrict to these step ids (repeatable). Empty = all. + #[arg(long = "step")] + steps: Vec, + #[arg(long)] + json: bool, + }, +} + +fn resolve_run(spec: Option<&str>) -> Option { + if let Some(s) = spec { + let p = PathBuf::from(s); + if p.is_dir() { + return Some(p.display().to_string()); + } + for base in ["runs", ".neurosploit/runs"] { + let q = Path::new(base).join(s); + if q.is_dir() { + return Some(q.display().to_string()); + } + } + return None; + } + latest_run() +} + +fn latest_run() -> Option { + let rd = std::fs::read_dir("runs").ok()?; + let mut best: Option<(SystemTime, String)> = None; + for e in rd.flatten() { + let p = e.path(); + if !p.is_dir() { + continue; + } + let name = e.file_name().to_string_lossy().to_string(); + if !name.starts_with("ns-") { + continue; + } + let Ok(md) = e.metadata() else { continue }; + let Ok(m) = md.modified() else { continue }; + if best.as_ref().map(|(t, _)| m > *t).unwrap_or(true) { + best = Some((m, p.display().to_string())); + } + } + best.map(|(_, p)| p) +} + +pub async fn handle_activity(cmd: ActivityCmd) -> anyhow::Result<()> { + let out: Value = match cmd { + ActivityCmd::List { run, limit, .. } => { + let wd = resolve_run(run.as_deref()); + let all = harness::activity::list(wd.as_deref()); + let total = all.len(); + let intents: Vec<_> = all.into_iter().take(limit).collect(); + json!({ "run": wd, "total": total, "intents": intents }) + } + ActivityCmd::Search { + run, q, exclude, limit, .. + } => { + let wd = resolve_run(run.as_deref()); + let hits = harness::activity::search(wd.as_deref(), &q, exclude.as_deref(), limit); + json!({ "run": wd, "query": q, "hits": hits }) + } + ActivityCmd::Get { + run, intent, steps, .. + } => { + let wd = resolve_run(run.as_deref()); + let steps = harness::activity::get(wd.as_deref(), &intent, Some(&steps)); + json!({ "run": wd, "intent": intent, "steps": steps }) + } + }; + println!( + "{}", + serde_json::to_string_pretty(&out).unwrap_or_else(|_| "{}".into()) + ); + Ok(()) +} diff --git a/neurosploit-rs/app/src/main.rs b/neurosploit-rs/app/src/main.rs index 166bd38..2ade7a4 100644 --- a/neurosploit-rs/app/src/main.rs +++ b/neurosploit-rs/app/src/main.rs @@ -1,5 +1,6 @@ //! NeuroSploit — interactive harness + CLI (`run` / `whitebox` / `agents` / `models`). +mod activitycli; mod c2cli; mod economycli; mod phishcli; @@ -156,6 +157,11 @@ struct Cli { /// Opt-in: let API-model agents request cataloged tools in a bounded loop. #[arg(long = "agent-tools", global = true)] agent_tools: bool, + /// Opt-in (reactive engine): give each worker a bounded, cost-governed tool + /// loop (plan → run real tools → observe) with cross-worker dedupe. Off by + /// default; budget via NEUROSPLOIT_WORKER_TOOL_* env vars. + #[arg(long = "worker-tools", global = true)] + worker_tools: bool, /// Explicitly allow the toolbox to install missing tools (apt/pipx/go/...). #[arg(long = "provision", global = true)] provision: bool, @@ -427,6 +433,12 @@ enum Cmd { #[command(subcommand)] cmd: economycli::EconomyCmd, }, + /// Step-level worker activity (Artex-style): list intents, search across + /// workers' execution steps, fetch one intent's steps. + Activity { + #[command(subcommand)] + cmd: activitycli::ActivityCmd, + }, /// Run NeuroSploit as an MCP server (stdio) so Claude Code, Codex, Cursor /// and other MCP clients can drive it as a set of tools. Mcp, @@ -1206,6 +1218,11 @@ async fn main() -> anyhow::Result<()> { if cli.agent_tools { std::env::set_var("NEUROSPLOIT_AGENT_TOOLS", "1"); } + if cli.worker_tools { + // Reactive workers run bounded tool loops; needs the catalog doctrine. + std::env::set_var("NEUROSPLOIT_TOOLS", "1"); + std::env::set_var("NEUROSPLOIT_WORKER_TOOLS", "1"); + } if cli.provision { std::env::set_var("NEUROSPLOIT_PROVISION", "1"); } @@ -1386,6 +1403,7 @@ async fn main() -> anyhow::Result<()> { Cmd::Webshell { cmd } => { c2cli::handle_webshell(cmd).await?; } Cmd::Phish { cmd } => { phishcli::handle_phish(cmd).await?; } Cmd::Economy { cmd } => { economycli::handle_economy(cmd).await?; } + Cmd::Activity { cmd } => { activitycli::handle_activity(cmd).await?; } Cmd::Mcp => { mcp::serve()?; } Cmd::Rebuild { run } => { // Accept either a path or a bare run id, resolved against the same diff --git a/neurosploit-rs/crates/harness/src/activity.rs b/neurosploit-rs/crates/harness/src/activity.rs new file mode 100644 index 0000000..de32c6f --- /dev/null +++ b/neurosploit-rs/crates/harness/src/activity.rs @@ -0,0 +1,384 @@ +//! Step-level worker activity store (Artex-inspired). +//! +//! ARTEX lets a worker search the *execution process* of other workers, not +//! just the formal facts in the graph. NeuroSploit already shares whole-agent +//! transcripts ([`crate::traces`]); this module adds the finer, durable layer: +//! every tool/command step is appended with its intent id, worker, command and +//! a clipped output to `/activity/activity.jsonl`, and workers can +//! search/list/retrieve those steps across intents. +//! +//! * Append-only (never overwrites history, unlike the per-agent transcript). +//! * The current `(workdir, intent_id, worker)` is a tokio task-local, so the +//! tool runner records automatically without threading it through every call. +//! * Secrets are not redacted here on purpose: this is engagement evidence in +//! the run directory, the same trust boundary as `traces/` and `evidence/`. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +pub(crate) const STEP_OUTPUT_CAP: usize = 16 * 1024; + +static STEP_SEQ: AtomicU64 = AtomicU64::new(1); + +fn write_lock() -> &'static Mutex<()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +fn new_step_id() -> String { + let n = STEP_SEQ.fetch_add(1, Ordering::Relaxed); + format!("st_{:x}{n:x}", now_ms()) +} + +/// Where the activity store lives for a run. +pub fn dir(workdir: Option<&str>) -> Option { + Some(Path::new(workdir?).join("activity")) +} + +fn log_file(workdir: &str) -> PathBuf { + Path::new(workdir).join("activity").join("activity.jsonl") +} + +// --------------------------------------------------------------------------- +// Records +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ActivityStep { + pub step_id: String, + pub intent_id: String, + pub worker: String, + pub ts: i64, + /// tool id, "shell", or "intent" (an executor-level summary). + pub tool: String, + pub args: String, + pub output: String, + pub exit: i32, + pub ok: bool, +} + +#[derive(Debug, Clone, Serialize)] +pub struct TraceSummary { + pub intent_id: String, + pub workers: Vec, + pub steps: usize, + pub first_ts: i64, + pub last_ts: i64, + pub tools: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct Hit { + pub intent_id: String, + pub step_id: String, + pub worker: String, + pub tool: String, + pub ts: i64, + pub snippet: String, +} + +// --------------------------------------------------------------------------- +// Task-local context +// --------------------------------------------------------------------------- + +#[derive(Clone)] +struct ActivityCtx { + workdir: Option, + intent_id: String, + worker: String, +} + +tokio::task_local! { + static CTX: ActivityCtx; +} + +/// Run `fut` with the current worker/intent bound, so tool calls inside it are +/// attributed to the right intent and searchable by other workers. +pub async fn with_ctx(workdir: Option, intent_id: String, worker: String, fut: F) -> F::Output +where + F: std::future::Future, +{ + CTX.scope(ActivityCtx { workdir, intent_id, worker }, fut).await +} + +fn current_ctx() -> Option { + CTX.try_with(|c| c.clone()).ok() +} + +/// Record a tool/command step under the current task-local intent. No-op when +/// there is no worker context (e.g. a standalone `neurosploit tools run`). +pub fn record_step(tool: &str, args: &str, output: &str, exit: i32, ok: bool) { + if let Some(ctx) = current_ctx() { + append( + ctx.workdir.as_deref(), + &ctx.intent_id, + &ctx.worker, + tool, + args, + output, + exit, + ok, + ); + } +} + +/// Append a step with an explicit workdir/intent/worker. +pub fn append( + workdir: Option<&str>, + intent_id: &str, + worker: &str, + tool: &str, + args: &str, + output: &str, + exit: i32, + ok: bool, +) { + let Some(wd) = workdir.filter(|w| !w.trim().is_empty()) else { + return; + }; + let step = ActivityStep { + step_id: new_step_id(), + intent_id: intent_id.to_string(), + worker: worker.to_string(), + ts: now_ms(), + tool: tool.to_string(), + args: clip(args), + output: clip(output), + exit, + ok, + }; + let Ok(line) = serde_json::to_string(&step) else { return }; + let path = log_file(wd); + let _g = write_lock().lock(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) { + let _ = writeln!(f, "{line}"); + } +} + +fn clip(s: &str) -> String { + crate::limits::clip(s, STEP_OUTPUT_CAP) +} + +// --------------------------------------------------------------------------- +// Read / search +// --------------------------------------------------------------------------- + +fn read_steps(workdir: &str) -> Vec { + let Ok(text) = std::fs::read_to_string(log_file(workdir)) else { + return Vec::new(); + }; + text.lines() + .filter_map(|l| serde_json::from_str::(l.trim()).ok()) + .collect() +} + +/// Group the run's steps by intent, newest intent first. +pub fn list(workdir: Option<&str>) -> Vec { + let Some(wd) = workdir else { return Vec::new() }; + let steps = read_steps(wd); + let mut map: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for s in &steps { + let e = map.entry(s.intent_id.clone()).or_insert_with(|| TraceSummary { + intent_id: s.intent_id.clone(), + workers: Vec::new(), + steps: 0, + first_ts: s.ts, + last_ts: s.ts, + tools: Vec::new(), + }); + e.steps += 1; + e.first_ts = e.first_ts.min(s.ts); + e.last_ts = e.last_ts.max(s.ts); + if !e.workers.contains(&s.worker) { + e.workers.push(s.worker.clone()); + } + if !e.tools.contains(&s.tool) { + e.tools.push(s.tool.clone()); + } + } + let mut out: Vec = map.into_values().collect(); + out.sort_by_key(|t| std::cmp::Reverse(t.last_ts)); + out +} + +/// Search every step's tool/args/output for `query`, skipping `exclude_worker`. +pub fn search(workdir: Option<&str>, query: &str, exclude_worker: Option<&str>, limit: usize) -> Vec { + let Some(wd) = workdir else { return Vec::new() }; + let needle = query.trim().to_lowercase(); + if needle.is_empty() { + return Vec::new(); + } + let limit = limit.clamp(1, 500); + let mut hits = Vec::new(); + for s in read_steps(wd) { + if hits.len() >= limit { + break; + } + if let Some(ex) = exclude_worker { + if !ex.is_empty() && s.worker == ex { + continue; + } + } + let hay = format!("{}\n{}\n{}", s.tool, s.args, s.output).to_lowercase(); + if let Some(pos) = hay.find(&needle) { + hits.push(Hit { + intent_id: s.intent_id.clone(), + step_id: s.step_id.clone(), + worker: s.worker.clone(), + tool: s.tool.clone(), + ts: s.ts, + snippet: snippet(&hay, pos, needle.len()), + }); + } + } + hits +} + +fn snippet(hay: &str, pos: usize, len: usize) -> String { + let start = pos.saturating_sub(60); + let end = (pos + len + 120).min(hay.len()); + let mut s: String = hay.get(start..end).unwrap_or("").replace('\n', " ⏎ "); + if start > 0 { + s.insert(0, '…'); + } + if end < hay.len() { + s.push('…'); + } + s +} + +/// Reuse the output of an identical tool command already run in this run +/// (cross-worker memoization). Returns the recorded `(combined_output, exit)`. +/// Only successful tool steps are eligible; `cache`/`llm`/`intent` markers are +/// never cache sources (they are not real tool executions). +pub fn lookup_cached_output(workdir: Option<&str>, tool: &str, command: &str) -> Option<(String, i32)> { + let wd = workdir?; + let cmd = command.trim(); + if cmd.is_empty() || matches!(tool, "cache" | "llm" | "intent") { + return None; + } + for s in read_steps(wd).into_iter().rev() { + if s.ok && s.tool == tool && s.args.trim() == cmd && !s.output.trim().is_empty() { + return Some((s.output, s.exit)); + } + } + None +} + +/// Full steps for one intent, optionally only the given step ids. +pub fn get(workdir: Option<&str>, intent_id: &str, step_ids: Option<&[String]>) -> Vec { + let Some(wd) = workdir else { return Vec::new() }; + read_steps(wd) + .into_iter() + .filter(|s| s.intent_id == intent_id) + .filter(|s| match step_ids { + Some(ids) if !ids.is_empty() => ids.iter().any(|id| id == &s.step_id), + _ => true, + }) + .collect() +} + +/// Prompt block: what other workers have done, and how to query it. +pub fn prompt_block(workdir: Option<&str>, exclude_worker: Option<&str>) -> String { + let Some(wd) = workdir else { return String::new() }; + let summaries = list(Some(wd)); + if summaries.is_empty() { + return String::new(); + } + let rows: Vec = summaries + .iter() + .filter(|t| { + exclude_worker.map(|ex| !t.workers.iter().all(|w| w == ex)).unwrap_or(true) + }) + .take(12) + .map(|t| { + format!( + "- intent {} · worker(s) {} · {} step(s) · tools: {}", + t.intent_id, + t.workers.join(","), + t.steps, + t.tools.iter().take(6).cloned().collect::>().join(",") + ) + }) + .collect(); + if rows.is_empty() { + return String::new(); + } + let excl = exclude_worker.map(|e| format!(" --exclude {e}")).unwrap_or_default(); + format!( + "\n\nWORKER ACTIVITY (other workers' execution steps — reuse their observations):\n{}\n\ +Search another worker's process before repeating work: \ +`neurosploit activity search --run {wd} --q \"\"{excl} --json`; \ +pull one intent's steps: `neurosploit activity get --run {wd} --intent --json`.\n", + rows.join("\n"), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmp() -> PathBuf { + let d = std::env::temp_dir().join(format!("ns_activity_{}_{}", std::process::id(), new_step_id())); + let _ = std::fs::create_dir_all(&d); + d + } + + #[test] + fn append_list_search_get_roundtrip() { + let d = tmp(); + let wd = d.display().to_string(); + append(Some(&wd), "i1", "worker-0", "curl", "curl https://x/api?id=1", "HTTP 200 admin panel", 0, true); + append(Some(&wd), "i1", "worker-0", "nmap", "nmap -sV x", "22/tcp open ssh", 0, true); + append(Some(&wd), "i2", "worker-1", "gobuster", "gobuster dir x", "found /backup.sql", 0, true); + + let list = self::list(Some(&wd)); + assert_eq!(list.len(), 2); + let i1 = list.iter().find(|t| t.intent_id == "i1").unwrap(); + assert_eq!(i1.steps, 2); + assert_eq!(i1.tools.len(), 2); + + let hits = search(Some(&wd), "backup", None, 50); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].intent_id, "i2"); + + // Excluding the only worker that matched yields nothing. + assert!(search(Some(&wd), "backup", Some("worker-1"), 50).is_empty()); + + let steps = get(Some(&wd), "i1", None); + assert_eq!(steps.len(), 2); + let one = get(Some(&wd), "i1", Some(&[steps[0].step_id.clone()])); + assert_eq!(one.len(), 1); + + // Cross-worker memoization: the exact same tool+command is reusable. + let cmd = "gobuster dir x"; + let cached = lookup_cached_output(Some(&wd), "gobuster", cmd).expect("cache hit"); + assert_eq!(cached.1, 0); + assert!(cached.0.contains("backup")); + assert!(lookup_cached_output(Some(&wd), "gobuster", "gobuster dir y").is_none()); + + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn no_workdir_is_noop() { + append(None, "i1", "w", "t", "a", "o", 0, true); + assert!(list(None).is_empty()); + assert!(search(None, "x", None, 10).is_empty()); + } +} diff --git a/neurosploit-rs/crates/harness/src/agentic_tools.rs b/neurosploit-rs/crates/harness/src/agentic_tools.rs index 8c96e7c..e93006b 100644 --- a/neurosploit-rs/crates/harness/src/agentic_tools.rs +++ b/neurosploit-rs/crates/harness/src/agentic_tools.rs @@ -20,6 +20,8 @@ use crate::pool::{ModelPool, Task}; use crate::toolbox::{self, ToolRun, ToolRunConfig}; use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use tokio::sync::mpsc::Sender; #[derive(Debug, Clone)] @@ -27,11 +29,69 @@ pub struct AgenticConfig { pub max_rounds: usize, pub stealth: bool, pub timeout_secs: u64, + /// Reuse an identical tool command already run in this engagement instead + /// of executing it again (cross-worker memoization). Off for the pipeline. + pub dedupe: bool, + /// Run directory holding the activity store the cache reads/writes. + pub workdir: Option, + /// Shared, run-wide cost governor (rounds / tool calls / concurrency). + pub budget: Option>, } impl AgenticConfig { pub fn new(stealth: bool) -> Self { - Self { max_rounds: if stealth { 6 } else { 10 }, stealth, timeout_secs: if stealth { 240 } else { 120 } } + Self { + max_rounds: if stealth { 6 } else { 10 }, + stealth, + timeout_secs: if stealth { 240 } else { 120 }, + dedupe: false, + workdir: None, + budget: None, + } + } +} + +/// Shared budget for worker tool loops across a whole run. Bounds the total +/// LLM rounds, total tool executions and concurrent executions so N workers +/// cannot multiply spend without limit. +#[derive(Debug)] +pub struct ToolBudget { + max_calls: usize, + max_rounds: usize, + calls: AtomicUsize, + rounds: AtomicUsize, + cache_hits: AtomicUsize, + permits: tokio::sync::Semaphore, +} + +impl ToolBudget { + pub fn new(max_calls: usize, max_rounds: usize, max_concurrent: usize) -> Arc { + Arc::new(Self { + max_calls: max_calls.max(1), + max_rounds: max_rounds.max(1), + calls: AtomicUsize::new(0), + rounds: AtomicUsize::new(0), + cache_hits: AtomicUsize::new(0), + permits: tokio::sync::Semaphore::new(max_concurrent.max(1)), + }) + } + fn try_round(&self) -> bool { + self.rounds.fetch_add(1, Ordering::Relaxed) < self.max_rounds + } + fn try_call(&self) -> bool { + self.calls.fetch_add(1, Ordering::Relaxed) < self.max_calls + } + fn note_cache_hit(&self) { + self.cache_hits.fetch_add(1, Ordering::Relaxed); + } + /// (tool_calls, rounds, cache_hits, max_calls) + pub fn stats(&self) -> (usize, usize, usize, usize) { + ( + self.calls.load(Ordering::Relaxed), + self.rounds.load(Ordering::Relaxed), + self.cache_hits.load(Ordering::Relaxed), + self.max_calls, + ) } } @@ -80,6 +140,12 @@ pub async fn run( if pool.stop_exploiting() { return AgenticResult { final_text: transcript, runs, rounds_used: round - 1, stopped_reason: "budget exhausted".into() }; } + // Run-wide cost governor: cap total LLM rounds across all workers. + if let Some(b) = &cfg.budget { + if !b.try_round() { + return AgenticResult { final_text: transcript, runs, rounds_used: round - 1, stopped_reason: "run-wide round budget exhausted".into() }; + } + } let reply = match pool.complete_routed(Task::Exploit, label, &sys, &turn_user).await { Ok((_, text)) => text, Err(e) => { @@ -119,6 +185,32 @@ pub async fn run( return AgenticResult { final_text: transcript, runs, rounds_used: round, stopped_reason: "repeated action — loop detected".into() }; } + // Cross-worker memoization: if another worker already ran the exact same + // command in this engagement, reuse its output instead of paying for it + // again (both tool cost and a network hit). This is the process-level + // sharing ARTEX lacks — there, workers duplicate each other's probing. + if cfg.dedupe { + let preview = toolbox::preview_command(tool, Some(&args), target).ok(); + if let (Some(wd), Some(cmd)) = (cfg.workdir.as_deref(), preview.as_deref()) { + if let Some((out, code)) = crate::activity::lookup_cached_output(Some(wd), tool, cmd) { + if let Some(b) = &cfg.budget { + b.note_cache_hit(); + } + crate::activity::record_step("cache", cmd, &out, code, true); + let _ = tx.send(format!("agentic[{label}] round {round}: {tool} cache-hit — reused an identical run, no execution")).await; + let obs = format!( + "tool={tool} args={args:?} exit={code} (CACHE HIT — this exact command already ran in this engagement; reused output)\nstdout:\n{}", + out.chars().take(4000).collect::() + ); + transcript.push_str(&format!("\n--- round {round}: {tool} {args} (cache) ---\n{obs}\n")); + turn_user = format!( + "Previous action: {tool} {args} (this re-used a prior result)\nRESULT:\n{obs}\n\nWhat's your next action? Reply with the SAME JSON protocol (one tool call, or {{\"action\":\"done\",...}})." + ); + continue; + } + } + } + // Stealth pacing: shared across the whole engagement via the global // governor, so two agentic agents hitting the same host are actually // coordinated rather than racing each other's rate limit. @@ -129,9 +221,22 @@ pub async fn run( return AgenticResult { final_text: transcript, runs, rounds_used: round, stopped_reason: format!("{host} blocked by stealth governor") }; } } + // Run-wide cost governor: cap total tool executions; bound concurrency so + // N workers do not stampede the target or the tool host. + if let Some(b) = &cfg.budget { + if !b.try_call() { + let _ = tx.send(format!("agentic[{label}] tool-call budget exhausted — stopping the loop")).await; + return AgenticResult { final_text: transcript, runs, rounds_used: round, stopped_reason: "run-wide tool-call budget exhausted".into() }; + } + } + let _permit = match &cfg.budget { + Some(b) => b.permits.acquire().await.ok(), + None => None, + }; let mut rc = run_cfg.clone(); rc.timeout_secs = rc.timeout_secs.or(Some(cfg.timeout_secs)); let outcome = toolbox::run(tool, Some(&args), target, &rc).await; + drop(_permit); if cfg.stealth && !host.is_empty() { crate::noise_governor::release(true); } @@ -179,4 +284,36 @@ mod tests { assert!(s.max_rounds < n.max_rounds); assert!(s.timeout_secs > n.timeout_secs); // slower pacing needs more wall-clock room per call } + + #[test] + fn tool_budget_bounds_rounds_calls_and_counts_hits() { + let b = ToolBudget::new(2, 3, 1); + assert!(b.try_round()); + assert!(b.try_round()); + assert!(b.try_round()); + assert!(!b.try_round()); // 4th round over the cap + assert!(b.try_call()); + assert!(b.try_call()); + assert!(!b.try_call()); // 3rd call over the cap + b.note_cache_hit(); + let (calls, rounds, hits, max_calls) = b.stats(); + assert_eq!((calls, rounds, hits, max_calls), (3, 4, 1, 2)); + } + + #[test] + fn preview_command_matches_run_key() { + // The cache key is the exact command `run` would execute. + let cmd = crate::toolbox::preview_command("nmap", Some("-Pn -p 443"), "10.0.0.5") + .expect("preview"); + assert!(cmd.starts_with("nmap -Pn -p 443")); + assert!(cmd.contains("10.0.0.5")); + } + + #[test] + fn defaults_do_not_enable_dedupe_or_budget() { + let c = AgenticConfig::new(false); + assert!(!c.dedupe); + assert!(c.workdir.is_none()); + assert!(c.budget.is_none()); + } } diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index d5f64c8..65a8b91 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -6,6 +6,7 @@ //! the specialist agents in parallel, then validates every candidate finding by //! **N-model voting** before scoring and reporting. +pub mod activity; pub mod adaptive; pub mod agents; pub mod assurance; diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index 0492140..83083ed 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -349,6 +349,8 @@ fn operator_directives(cfg: &RunConfig) -> String { } // What the other agents already observed (structured digest + where to grep). s.push_str(&crate::traces::prompt_block(cfg.workdir.as_deref(), None)); + // Step-level worker activity: what other workers actually executed. + s.push_str(&crate::activity::prompt_block(cfg.workdir.as_deref(), None)); // Adaptive payload intelligence: WAF bypass history, target stack, parameter profiles. if let Some(ref workdir) = cfg.workdir { let adapt_path = std::path::Path::new(workdir).join("adaptive-engine.json"); diff --git a/neurosploit-rs/crates/harness/src/reactive.rs b/neurosploit-rs/crates/harness/src/reactive.rs index 9627b37..c380089 100644 --- a/neurosploit-rs/crates/harness/src/reactive.rs +++ b/neurosploit-rs/crates/harness/src/reactive.rs @@ -75,6 +75,8 @@ pub struct ReactiveConfig { pub max_total_intents: usize, pub max_failures_per_target: u32, pub state_dir: Option, + /// Run directory, for the step-level worker activity store (`/activity`). + pub workdir: Option, pub planner: PlannerConfig, } @@ -85,6 +87,7 @@ impl ReactiveConfig { intent_timeout: Duration::from_secs(600), debounce: Duration::from_millis(300), heartbeat: Duration::from_secs(30), drain_grace: Duration::from_secs(20), max_total_intents: 200, max_failures_per_target: 3, state_dir: None, + workdir: None, planner: PlannerConfig::default(), } } @@ -420,7 +423,15 @@ async fn worker_loop(name: String, s: Arc, cfg: Arc, exe }; let ctx = WorkCtx { intent_id: intent.id.clone(), wrap: s.wrap.clone(), steer: s.steer.clone() }; - let fut = exec(intent.clone(), ctx); + // Bind the (workdir, intent, worker) so tool calls inside the executor are + // recorded step-by-step and become searchable by other workers. + let wd = cfg.workdir.as_ref().and_then(|p| p.to_str()).map(|s| s.to_string()); + let fut = crate::activity::with_ctx( + wd.clone(), + intent.id.clone(), + name.clone(), + exec(intent.clone(), ctx), + ); enum R { Out(WorkOutcome), TimedOut, Cancelled } let r = tokio::select! { o = fut => R::Out(o), @@ -462,6 +473,18 @@ async fn worker_loop(name: String, s: Arc, cfg: Arc, exe let retry = q.fail(&intent.id, &name, &o.summary).unwrap_or(false); if !retry { c.failed += 1; } } + drop(q); + drop(c); + crate::activity::append( + wd.as_deref(), + &intent.id, + &name, + "intent", + &format!("{:?} {}", intent.action, intent.target), + &o.summary, + if o.ok { 0 } else { 1 }, + o.ok, + ); } R::TimedOut | R::Cancelled => { let mut g = s.graph.lock().unwrap(); @@ -485,6 +508,26 @@ async fn worker_loop(name: String, s: Arc, cfg: Arc, exe let _ = q.release(&intent.id, &name); c.released += 1; } + drop(g); + drop(q); + drop(c); + let label = if was_stopped { + "stopped" + } else if matches!(r, R::TimedOut) { + "timed out" + } else { + "released" + }; + crate::activity::append( + wd.as_deref(), + &intent.id, + &name, + "intent", + &format!("{:?} {}", intent.action, intent.target), + label, + 124, + false, + ); } } s.heartbeats.lock().unwrap().remove(&intent.id); diff --git a/neurosploit-rs/crates/harness/src/reactive_bridge.rs b/neurosploit-rs/crates/harness/src/reactive_bridge.rs index 1c4a4aa..95a0c04 100644 --- a/neurosploit-rs/crates/harness/src/reactive_bridge.rs +++ b/neurosploit-rs/crates/harness/src/reactive_bridge.rs @@ -25,6 +25,27 @@ fn operator_constraints(cfg: &RunConfig) -> crate::constraints::ConstraintSet { crate::constraints::extract(&text, &cfg.target, None) } +fn env_usize(key: &str, default: usize) -> usize { + std::env::var(key) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&v| v > 0) + .unwrap_or(default) +} + +/// Rounds a worker may take for an intent, weighted by planner priority so the +/// budget goes to the intents that matter (cost control). +fn rounds_for(priority: u32) -> usize { + let base = env_usize("NEUROSPLOIT_WORKER_TOOL_ROUNDS", 4).clamp(1, 10); + if priority >= 80 { + base + } else if priority >= 40 { + base.min(3).max(1) + } else { + base.min(2).max(1) + } +} + /// Entry point for the reactive engine, matching pipeline::run()'s signature. pub async fn run_reactive( mut cfg: RunConfig, @@ -195,6 +216,7 @@ pub async fn run_reactive( workers: cfg.concurrency.min(8).max(1), deadline: None, // use token budget instead of wall-clock for now state_dir: Some(graph_dir.clone()), + workdir: Some(std::path::PathBuf::from(&workdir)), planner: PlannerConfig::default(), ..ReactiveConfig::new(&cfg.target) }; @@ -257,8 +279,21 @@ pub async fn run_reactive( } let pool_handle = Arc::new(PoolHandle(pool as *const ModelPool)); let cfg_arc = Arc::new(cfg.clone()); - let _constraints = Arc::new(operator_constraints(&cfg)); + let constraints = Arc::new(operator_constraints(&cfg)); + // Cost-aware worker tool loop (opt-in): one shared budget across all workers + // bounds total LLM rounds, tool executions and concurrency. + let tool_budget: Option> = + if std::env::var("NEUROSPLOIT_WORKER_TOOLS").ok().as_deref() == Some("1") { + Some(crate::agentic_tools::ToolBudget::new( + env_usize("NEUROSPLOIT_WORKER_TOOL_MAX_CALLS", 60), + env_usize("NEUROSPLOIT_WORKER_TOOL_MAX_ROUNDS", 80), + env_usize("NEUROSPLOIT_WORKER_TOOL_CONCURRENCY", 3), + )) + } else { + None + }; let tx2 = tx.clone(); + let budget_for_exec = tool_budget.clone(); let probe_context: Arc = Arc::new(if probe_loot.is_empty() { String::new() } else { @@ -275,6 +310,8 @@ pub async fn run_reactive( let kb = kb.clone(); let mcp_context = mcp_context.clone(); let probe_context = probe_context.clone(); + let constraints = constraints.clone(); + let tool_budget = budget_for_exec.clone(); async move { let _ = tx.send(format!("[reactive] worker: {:?} on {}", intent.action, intent.target)).await; @@ -303,10 +340,18 @@ pub async fn run_reactive( let methodology = kb.methodology_for(&task_desc, 2, 3000); let mcp_block = if mcp_context.is_empty() { String::new() } else { format!("\n{}\n", *mcp_context) }; let probe_block = if probe_context.is_empty() { String::new() } else { (*probe_context).clone() }; + let activity_block = crate::activity::prompt_block(cfg.workdir.as_deref(), None); + // With the worker tool loop on, the model must see the real catalog so + // it calls existing tool IDs instead of hallucinating (and burning rounds). + let catalog_block = if tool_budget.is_some() { + format!("\n\nTOOL CATALOG (call only these IDs):\n{}", crate::toolbox::agent_catalog("run")) + } else { + String::new() + }; let user = format!( "Target: {}\nTask: {:?}\nSpecific target: {}\nRationale: {}\ - {}{}{}\n\ + {}{}{}{}{}\n\ Execute this task. Report results using the prefixes: Finding:, Fact:, Negative:\n\ {}", cfg.target, @@ -316,10 +361,64 @@ pub async fn run_reactive( if methodology.is_empty() { String::new() } else { format!("\n\n{}", methodology) }, mcp_block, probe_block, + activity_block, + catalog_block, if ctx.wrapping() { "\nWRAP-UP: Time is running out. Persist your results NOW and stop." } else { "" }, ); - let result = pool_handle.get().complete(system, &user).await; + let result = if let Some(budget) = tool_budget.clone() { + // Impactful, cost-aware worker: plan → run real tools → observe → + // decide, bounded by the shared budget. Every tool call is recorded + // by the activity store, and identical commands are reused. + let run_cfg = crate::toolbox::ToolRunConfig { + sandbox: cfg.sandbox.clone(), + provision: std::env::var("NEUROSPLOIT_PROVISION").ok().as_deref() == Some("1"), + timeout_secs: Some(120), + audit_dir: cfg.workdir.as_ref().map(|w| std::path::PathBuf::from(w).join("toolbox")), + scope: Some(crate::pipeline::effective_scope(&cfg)), + constraints: (*constraints).clone(), + }; + let mut ac = crate::agentic_tools::AgenticConfig::new(cfg.stealth); + ac.max_rounds = rounds_for(intent.priority); + ac.dedupe = true; + ac.workdir = cfg.workdir.clone(); + ac.budget = Some(budget.clone()); + let label = format!("reactive:{}", intent.id); + let ar = crate::agentic_tools::run( + pool_handle.get(), + &label, + system, + &user, + &cfg.target, + run_cfg, + ac, + &tx, + ) + .await; + let _ = tx + .send(format!( + "[reactive] worker tools: {} round(s), {} execution(s) — {}{}", + ar.rounds_used, + ar.runs.len(), + ar.stopped_reason, + if ar.final_text.trim().is_empty() { "; falling back to single-shot" } else { "" } + )) + .await; + if ar.final_text.trim().is_empty() { + pool_handle.get().complete(system, &user).await + } else { + Ok(( + crate::models::ModelRef { + provider: "worker-tools".into(), + model: "agentic".into(), + force_backend: None, + }, + ar.final_text, + )) + } + } else { + pool_handle.get().complete(system, &user).await + }; let response = match result { Ok((model, text)) => { let _ = tx.send(format!("[reactive] {} responded ({} chars)", model.model, text.len())).await; @@ -361,6 +460,17 @@ pub async fn run_reactive( } }; + // Record what this worker actually observed (the raw model output, + // including observations the parser discards) so other workers can + // search it — Artex-style process-level exchange. + crate::activity::record_step( + "llm", + &format!("{:?} {} :: {}", intent.action, intent.target, intent.rationale), + &response, + 0, + !response.trim().is_empty(), + ); + // Parse structured output let mut facts = Vec::new(); let mut negatives = Vec::new(); @@ -406,6 +516,14 @@ pub async fn run_reactive( // --- Run --- let (report, final_graph) = reactive::run(reactive_cfg, handle, exec).await; + if let Some(b) = &tool_budget { + let (calls, rounds, hits, max_calls) = b.stats(); + let _ = tx + .send(format!( + "[reactive] worker-tool budget: {calls}/{max_calls} tool calls, {rounds} rounds, {hits} cache hit(s)" + )) + .await; + } // Save final graph let _ = final_graph.save(&graph_dir); diff --git a/neurosploit-rs/crates/harness/src/toolbox/mod.rs b/neurosploit-rs/crates/harness/src/toolbox/mod.rs index 179cb24..b1cf531 100644 --- a/neurosploit-rs/crates/harness/src/toolbox/mod.rs +++ b/neurosploit-rs/crates/harness/src/toolbox/mod.rs @@ -18,7 +18,7 @@ pub mod runner; pub use catalog::{all, categories, find, mode_plan, prompt_summary, search, ToolSpec}; pub use mcp_catalog::{McpServerSpec, add_to_file, remove_from_file, servers_path}; -pub use runner::{check, install, run, ToolCheck, ToolRun, ToolRunConfig}; +pub use runner::{check, install, preview_command, run, ToolCheck, ToolRun, ToolRunConfig}; /// Prompt doctrine injected when `--tools` / agent tools are enabled. pub fn doctrine() -> String { diff --git a/neurosploit-rs/crates/harness/src/toolbox/runner.rs b/neurosploit-rs/crates/harness/src/toolbox/runner.rs index 39c3a23..17fa8cc 100644 --- a/neurosploit-rs/crates/harness/src/toolbox/runner.rs +++ b/neurosploit-rs/crates/harness/src/toolbox/runner.rs @@ -311,17 +311,16 @@ pub async fn install(spec: &ToolSpec, cfg: &ToolRunConfig) -> Result<(bool, Stri } } -/// Run a catalog tool. -pub async fn run( - tool_id: &str, - args: Option<&str>, - target: &str, - cfg: &ToolRunConfig, -) -> Result { - let spec = find(tool_id).ok_or_else(|| format!("unknown tool '{tool_id}' (try `neurosploit tools search {tool_id}`)"))?; - scope_allows(cfg.scope.as_ref(), target)?; +/// The exact command `run` would execute, without running it. Used to key the +/// cross-worker tool-result cache so two workers choosing the same tool+args+ +/// target reuse one execution instead of paying for it twice. +pub fn preview_command(tool_id: &str, args: Option<&str>, target: &str) -> Result { + let spec = find(tool_id).ok_or_else(|| format!("unknown tool '{tool_id}'"))?; + build_command(spec, args, target) +} - let cmd = match args.map(|a| a.trim()).filter(|a| !a.is_empty()) { +fn build_command(spec: &ToolSpec, args: Option<&str>, target: &str) -> Result { + match args.map(|a| a.trim()).filter(|a| !a.is_empty()) { Some(a) => { let a = substitute(a, target)?; let mut cmd = format!("{} {}", spec.binary, a); @@ -332,10 +331,23 @@ pub async fn run( cmd.push(' '); cmd.push_str(target); } - cmd + Ok(cmd) } - None => substitute(&spec.usage, target)?, - }; + None => substitute(&spec.usage, target), + } +} + +/// Run a catalog tool. +pub async fn run( + tool_id: &str, + args: Option<&str>, + target: &str, + cfg: &ToolRunConfig, +) -> Result { + let spec = find(tool_id).ok_or_else(|| format!("unknown tool '{tool_id}' (try `neurosploit tools search {tool_id}`)"))?; + scope_allows(cfg.scope.as_ref(), target)?; + + let cmd = build_command(spec, args, target)?; if let Some(c) = cfg.constraints.check_command(&cmd) { return Err(format!("operator constraint blocked this command: {}", c.text)); } @@ -370,6 +382,15 @@ pub async fn run( stdout: clip(stdout), stderr: clip(stderr), }; + // Record this tool/command as a worker activity step when a run context is + // bound (reactive worker); standalone `tools run` has no context and no-ops. + crate::activity::record_step( + &run.tool, + &run.command, + &format!("{}\n{}", run.stdout, run.stderr), + run.code, + !run.timed_out && run.code == 0, + ); audit(cfg, &run); Ok(run) } diff --git a/web/public/app.js b/web/public/app.js index 3fa0f35..0135b19 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -4617,7 +4617,7 @@ function showOutput(title, text) { const EXTRAS_TABS = [ ['graph', 'Attack graph'], ['chains', 'Chains'], ['todo', 'Dependencies'], - ['traffic', 'Traffic'], ['traces', 'Traces'], ['deliverables', 'Deliverables'], + ['traffic', 'Traffic'], ['traces', 'Traces'], ['activity', 'Workers'], ['deliverables', 'Deliverables'], ]; const STATUS_LABEL = { confirmed: 'confirmed', needs_validation: 'needs validation', hypothesis: 'hypothesis', needs_review: 'needs review' }; @@ -4666,6 +4666,14 @@ function extrasPanelsHtml(uid) {
    + `; @@ -4681,7 +4689,7 @@ function makeExtras(viewSel, uid, getRunId) { b.className = 'run-tab'; b.dataset.tab = tab; // Only tabs with a meaningful number carry a counter. - b.innerHTML = ['chains', 'todo', 'traces', 'deliverables'].includes(tab) ? `${esc(label)} 0` : esc(label); + b.innerHTML = ['chains', 'todo', 'traces', 'activity', 'deliverables'].includes(tab) ? `${esc(label)} 0` : esc(label); nav.appendChild(b); } body.insertAdjacentHTML('beforeend', extrasPanelsHtml(uid)); @@ -4709,6 +4717,7 @@ function makeExtras(viewSel, uid, getRunId) { x.q('t-q').addEventListener('input', debounce('t', () => extrasTraffic(x))); x.q('t-method').addEventListener('change', () => extrasTraffic(x)); x.q('tr-q').addEventListener('input', debounce('tr', () => extrasTraces(x))); + x.q('ac-q')?.addEventListener('input', debounce('ac', () => extrasActivity(x))); x.q('full').addEventListener('change', () => renderGraphMemory(x)); x.q('killchain').addEventListener('change', () => { x.drawnSig = null; renderGraphMemory(x); }); bindGraphInteractions(x); @@ -4764,6 +4773,7 @@ function extrasCounts(x) { x.count('chains', (g.chains?.chains || []).length); x.count('todo', (g.todo || []).filter((t) => t.state === 'ready').length); x.count('traces', x.extras.traces || 0); + x.count('activity', x.extras.activity || 0); x.count('deliverables', (x.extras.deliverables || []).length); } @@ -4792,6 +4802,7 @@ async function extrasLoad(x, tab, quiet) { } else if (tab === 'traffic') await extrasTraffic(x); else if (tab === 'traces') await extrasTraces(x); + else if (tab === 'activity') await extrasActivity(x); else if (tab === 'deliverables') renderDeliverables(x); } catch (e) { if (!quiet) toast(`Could not load ${tab}: ${e.message}`, 'error'); @@ -5525,6 +5536,55 @@ async function showTranscript(x, agent, file, highlight) { /// Strip ANSI escapes client-side (traces are served raw). function stripAnsiJs(s) { return String(s || '').replace(/\u001b\[[0-9;]*m/g, ''); } +// ---- worker activity (step-level, Artex-style) ----------------------------- + +async function extrasActivity(x) { + const id = x.getRunId(); + if (!id) return; + const qv = x.q('ac-q').value.trim(); + const [a, td] = await Promise.all([ + api(`/api/runs/${encodeURIComponent(id)}/activity?q=${encodeURIComponent(qv)}&limit=300`), + api(`/api/runs/${encodeURIComponent(id)}/todolist`).catch(() => ({ entries: [], counts: {} })), + ]); + x.extras.activity = a.total_steps || 0; + x.count('activity', a.total_steps || 0); + show(x.q('ac-empty'), !(a.steps || []).length); + + const counts = td.counts || {}; + const summary = Object.keys(counts).map((k) => `${k} ${counts[k]}`).join(' · '); + const entries = td.entries || []; + x.q('ac-todo').innerHTML = entries.length ? ` +
    +
    Planner todolist — dependencies
    +
    ${esc(summary || 'no entries')}
    +
    + + ${entries.map((e) => ` + + + + + + + `).join('')} +
    IntentActionTargetStateWorkerDepends on
    ${esc(e.id || '')}${esc(e.action || '')}${esc((e.target || '').slice(0, 90))}${esc(e.state || '')}${esc(e.claimed_by || '—')}${esc((e.depends_on || []).join(', ') || '—')}
    +
    ` : ''; + + const rows = (a.steps || []).map((s) => ` + ${esc(c2Time(s.ts))} + ${esc(s.worker || '')} + ${esc(s.intent_id || '')} + ${esc(s.tool || '')} + ${esc((s.args || '').slice(0, 140))} + ${esc((s.output || '').replace(/\n/g, ' ⏎ ').slice(0, 220))} + ${esc(s.exit)} + `).join(''); + x.q('ac-body').innerHTML = rows; + x.q('ac-note').textContent = qv + ? `${(a.steps || []).length} hit(s) for “${qv}”` + : `${a.total_steps || 0} step(s) across ${(a.intents || []).length} intent(s)`; +} + // ---- deliverables ---------------------------------------------------------- const DELIV_INFO = { diff --git a/web/server.js b/web/server.js index 9d21279..d718c04 100644 --- a/web/server.js +++ b/web/server.js @@ -1101,6 +1101,63 @@ async function searchTraces(dir, needle) { return { traces: list, hits, query: needle || '' }; } +/// Step-level worker activity written by the reactive engine (/activity/activity.jsonl). +async function readActivity(dir, needle, limit) { + const file = path.join(dir, 'activity', 'activity.jsonl'); + const text = await fsp.readFile(file, 'utf8').catch(() => ''); + const n = (needle || '').trim().toLowerCase(); + const lim = Math.max(1, Math.min(Number(limit) || 300, 2000)); + const steps = []; + const intents = new Map(); + let total = 0; + for (const line of text.split('\n')) { + const l = line.trim(); + if (!l) continue; + let s; + try { s = JSON.parse(l); } catch { continue; } + total += 1; + const cur = intents.get(s.intent_id) || { intent_id: s.intent_id, workers: new Set(), steps: 0, tools: new Set(), last_ts: 0 }; + cur.steps += 1; + cur.workers.add(s.worker); + cur.tools.add(s.tool); + cur.last_ts = Math.max(cur.last_ts, s.ts || 0); + intents.set(s.intent_id, cur); + if (n) { + const hay = `${s.tool}\n${s.args}\n${s.output}`.toLowerCase(); + if (!hay.includes(n)) continue; + } + steps.push({ + step_id: s.step_id, intent_id: s.intent_id, worker: s.worker, ts: s.ts, tool: s.tool, + args: String(s.args || '').slice(0, 2000), output: String(s.output || '').slice(0, 4000), + exit: s.exit, ok: s.ok, + }); + } + steps.sort((a, b) => (b.ts || 0) - (a.ts || 0)); + return { + query: needle || '', + total_steps: total, + intents: [...intents.values()] + .map((i) => ({ intent_id: i.intent_id, workers: [...i.workers], steps: i.steps, tools: [...i.tools], last_ts: i.last_ts })) + .sort((a, b) => b.last_ts - a.last_ts), + steps: steps.slice(0, lim), + }; +} + +/// The reactive planner's persisted todolist (/graphs/reactive-state.json). +async function readTodolist(dir) { + const raw = await readJsonSafe(path.join(dir, 'graphs', 'reactive-state.json'), null); + const entries = raw?.queue?.entries || []; + const rows = entries.map((e) => ({ + id: e.intent?.id, action: e.intent?.action, target: e.intent?.target, + priority: e.intent?.priority, depends_on: e.intent?.depends_on || [], + state: e.state, claimed_by: e.claimed_by, attempts: e.attempts, + result: String(e.result || '').slice(0, 300), + })); + const counts = {}; + for (const r of rows) counts[r.state] = (counts[r.state] || 0) + 1; + return { entries: rows, counts }; +} + /// The CLI prints progress before the `--json` payload; take the last line that /// parses as JSON so a banner or a warning never breaks the parse. function lastJsonLine(buf) { @@ -2494,6 +2551,18 @@ const server = http.createServer(async (req, res) => { if (!dir || !fs.existsSync(dir)) return sendJson(res, 404, { error: 'run not found' }); return sendJson(res, 200, await searchTraces(dir, u.searchParams.get('q'))); } + m = p.match(/^\/api\/runs\/([^/]+)\/activity$/); + if (req.method === 'GET' && m) { + const dir = safeRunDir(decodeURIComponent(m[1])); + if (!dir || !fs.existsSync(dir)) return sendJson(res, 404, { error: 'run not found' }); + return sendJson(res, 200, await readActivity(dir, u.searchParams.get('q'), u.searchParams.get('limit'))); + } + m = p.match(/^\/api\/runs\/([^/]+)\/todolist$/); + if (req.method === 'GET' && m) { + const dir = safeRunDir(decodeURIComponent(m[1])); + if (!dir || !fs.existsSync(dir)) return sendJson(res, 404, { error: 'run not found' }); + return sendJson(res, 200, await readTodolist(dir)); + } // ---- PoC re-test (the CLI re-runs each finding's recorded proof) ---- m = p.match(/^\/api\/runs\/([^/]+)\/retest$/); if (req.method === 'POST' && m) {