Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore(memory): make checksum validators pub(super) for reuse

Steven Enamakel93bb34b49fc7
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/request.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/request.rs
new file mode 100644
index 0000000000..68e6b6d3b8
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/request.rs
@@ -0,0 +1,75 @@
+//! Request parsing and structural validation for `spawn_parallel_agents`,
+//! before any policy or workspace decision is made.
+
+/// One requested worker in a `spawn_parallel_agents` call.
+#[derive(Debug, Clone, serde::Deserialize)]
+pub(crate) struct ParallelAgentTask {
+ pub(crate) agent_id: String,
+ pub(crate) prompt: String,
+ #[serde(default)]
+ pub(crate) context: Option<String>,
+ #[serde(default)]
+ pub(crate) toolkit: Option<String>,
+ #[serde(default)]
+ pub(crate) ownership: Option<String>,
+ /// File-isolation strategy for this worker: `"none"` (default) or
+ /// `"worktree"` (dedicated git worktree checkout).
+ #[serde(default)]
+ pub(crate) isolation: Option<String>,
+ /// Worktree base ref: `"head"` (default) or `"fresh"`.
+ #[serde(default)]
+ pub(crate) base_ref: Option<String>,
+}
+
+/// Decode and validate the request batch before the live worker fanout.
+///
+/// This is the first real `validate`-node responsibility moved out of the tool
+/// wrapper. Effectful worktree creation now runs in the graph path after the
+/// action root and worker definitions are resolved.
+fn validate_spawn_parallel_tasks(
+ args: &serde_json::Value,
+ max_parallel: Option<usize>,
+) -> Result<Vec<ParallelAgentTask>, String> {
+ let tasks_value = args
+ .get("tasks")
+ .cloned()
+ .ok_or_else(|| "Missing 'tasks' parameter".to_string())?;
+ let tasks: Vec<ParallelAgentTask> =
+ serde_json::from_value(tasks_value).map_err(|e| format!("Invalid tasks array: {e}"))?;
+
+ if tasks.len() < 2 {
+ return Err("spawn_parallel_agents requires at least two tasks".to_string());
+ }
+ if let Some(max_parallel) = max_parallel {
+ if tasks.len() > max_parallel {
+ return Err(format!(
+ "spawn_parallel_agents received {} tasks but max_parallel_tools is {}",
+ tasks.len(),
+ max_parallel
+ ));
+ }
+ }
+
+ Ok(tasks)
+}
+
+pub(crate) enum SpawnParallelTaskValidationError {
+ MissingTasks(String),
+ InvalidTasks(String),
+ Rejected(String),
+}
+
+pub(crate) fn validate_spawn_parallel_tool_request(
+ args: &serde_json::Value,
+ max_parallel: Option<usize>,
+) -> Result<Vec<ParallelAgentTask>, SpawnParallelTaskValidationError> {
+ validate_spawn_parallel_tasks(args, max_parallel).map_err(|message| {
+ if message == "Missing 'tasks' parameter" {
+ SpawnParallelTaskValidationError::MissingTasks(message)
+ } else if message.starts_with("Invalid tasks array:") {
+ SpawnParallelTaskValidationError::InvalidTasks(message)
+ } else {
+ SpawnParallelTaskValidationError::Rejected(message)
+ }
+ })
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
new file mode 100644
index 0000000000..f4db552407
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
@@ -0,0 +1,178 @@
+//! Tool + agent capability-registry projection for
+//! [`assemble_turn_harness`](super::harness_assembly::assemble_turn_harness):
+//! register every admitted tool onto the harness and project the visible
+//! agent set into the [`CapabilityRegistry`] for the health-diagnostics gate.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use tinyagents_harness::runtime::AgentHarness;
+use tinyagents_registry::{CapabilityRegistry, ComponentKind, RegistryDiagnostic, RegistrySnapshot};
+
+use crate::agent::tinyagents::tools::{EarlyExitHook, SharedToolAdapter};
+use crate::agent::tinyagents::turn_policy::is_subagent_spawn_or_delegate_tool;
+
+/// Register every admitted tool from `tool_sets` onto `harness` (and its
+/// `capability_registry` projection), project the visible agent set as
+/// name-only descriptors, and return `(tool_count, registry_diagnostics,
+/// registry_snapshot)`.
+///
+/// Allowlist semantics are **fail-closed** (issue #4452): `allowed == None` →
+/// no filter, every visible tool registers; `allowed == Some(set)` → register
+/// *exactly* the named tools, so `Some(empty)` denies all. This is what keeps
+/// a deliberately tool-less sub-agent (`ToolScope::Named([])`, a zero-match
+/// `skill_filter`, or a `named` list that resolves to nothing) from silently
+/// inheriting the parent's full tool surface (shell/file-write/spawn) — the
+/// old `allowed.is_empty() || allowed.contains(name)` predicate was
+/// fail-open.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn register_turn_tools_and_agents(
+ harness: &mut AgentHarness<()>,
+ capability_registry: &mut CapabilityRegistry<()>,
+ tool_sets: &[Arc<Vec<Box<dyn crate::tools::Tool>>>],
+ allowed: &Option<HashSet<String>>,
+ early_exit_set: &HashSet<&str>,
+ early_exit_hook: Option<&EarlyExitHook>,
+ is_subagent_run: bool,
+) -> (usize, Vec<RegistryDiagnostic>, RegistrySnapshot) {
+ if let Some(set) = allowed {
+ if set.is_empty() {
+ tracing::warn!(
+ subagent = is_subagent_run,
+ "[subagent] tool allowlist resolved empty — registering no tools"
+ );
+ }
+ }
+ let mut seen_candidates: HashSet<String> = HashSet::new();
+ let candidate_names: Vec<String> = tool_sets
+ .iter()
+ .flat_map(|set| set.iter())
+ .map(|tool| tool.name())
+ .filter(|&name| seen_candidates.insert(name.to_string()))
+ .map(|name| name.to_string())
+ .collect();
+ let mut registered: HashSet<String> = HashSet::new();
+ for name in candidate_names.iter().map(String::as_str) {
+ // Fail-closed allowlist: `None` admits everything, `Some(set)` admits only
+ // its members (empty set → nothing).
+ let admitted = match allowed {
+ None => true,
+ Some(set) => set.contains(name),
+ };
+ // Defense-in-depth (issue #4452): a sub-agent must NEVER be handed a
+ // spawn/delegate tool whatever the allowlist says — re-assert it here at
+ // registration, not just on the caller's `allowed_indices`. Warn only when
+ // the allowlist actually readmitted one (issue #6157); the caller strips
+ // them first, so a bare `spawn_stripped` warn fired on every healthy run.
+ let spawn_stripped = is_subagent_run && is_subagent_spawn_or_delegate_tool(name);
+ if spawn_stripped && admitted {
+ tracing::warn!(
+ tool = name,
+ "[subagent] refusing to register spawn/delegate tool on sub-agent run"
+ );
+ }
+ if !registered.contains(name) && admitted && !spawn_stripped {
+ if let Some(mut adapter) = SharedToolAdapter::for_name(tool_sets.to_vec(), name) {
+ if early_exit_set.contains(name) {
+ if let Some(hook) = early_exit_hook {
+ adapter = adapter.with_early_exit(hook.clone());
+ }
+ }
+ registered.insert(name.to_string());
+ let adapter = Arc::new(adapter);
+ capability_registry.replace_tool(adapter.clone());
+ harness.register_tool(adapter);
+ }
+ }
+ }
+ let tool_count = registered.len();
+ for report in crate::agent::tinyagents::topology::all_graph_topologies() {
+ let _ = capability_registry.register_descriptor(ComponentKind::Graph, report.name);
+ }
+
+ // Project the agents visible to this turn into the registry as name-only
+ // `ComponentKind::Agent` descriptors (issue #4249, Workstream 10.1). This is
+ // metadata only: no executable `HarnessAgent` is attached (sub-agent
+ // dispatch still flows through the openhuman sub-agent runner), so the
+ // registration is cheap and leaves the turn hot path unchanged. Agents are
+ // sourced from BOTH the runtime `AgentDefinitionRegistry` global (built-ins
+ // plus any workspace/config custom overrides, already merged by id) AND the
+ // `agent_registry` built-in loader, deduped by id — the runtime registry is
+ // registered first and wins, since it carries the richer, override-aware
+ // `when_to_use`. Registering here keeps the ids in
+ // `capability_registry.snapshot()` so the 10.3 `agent.registry_snapshot` RPC
+ // and the fail-closed diagnostics (10.2) observe them.
+ //
+ // DEFERRED (rich metadata): tinyagents 1.3.0 exposes no public API to attach
+ // a `ComponentMetadata` description/tags to a name-only descriptor — only
+ // `register_agent(Arc<dyn HarnessAgent>)` carries a full executable blueprint
+ // we do not have at this layer. Until the crate grows a
+ // `register_descriptor_with_meta` (or we thread real `HarnessAgent`s through
+ // `assemble_turn_harness`), the `when_to_use` descriptions and
+ // `display_name`/`source` tags cannot be persisted onto the snapshot entry;
+ // only the ids are projected. The runtime-registry → executable-agent
+ // projection (so `register_agent`/`.rag` sub-agent resolution can bind these)
+ // remains the deferred follow-up.
+ let mut registered_agents: HashSet<String> = HashSet::new();
+ let mut runtime_agent_count = 0usize;
+ if let Some(runtime) = crate::agent::harness::definition::AgentDefinitionRegistry::global() {
+ for def in runtime.list() {
+ if registered_agents.insert(def.id.clone()) {
+ let _ =
+ capability_registry.register_descriptor(ComponentKind::Agent, def.id.clone());
+ runtime_agent_count += 1;
+ }
+ }
+ }
+ // agent_registry built-ins as a supplement/fallback (deduped by id). When the
+ // runtime global is uninitialised this is the sole source; otherwise it only
+ // contributes ids the runtime registry did not already cover.
+ let mut builtin_supplement_count = 0usize;
+ match crate::agent::registry::agents::load_builtins() {
+ Ok(builtins) => {
+ for def in builtins {
+ if registered_agents.insert(def.id.clone()) {
+ let _ = capability_registry
+ .register_descriptor(ComponentKind::Agent, def.id.clone());
+ builtin_supplement_count += 1;
+ }
+ }
+ }
+ Err(err) => {
+ tracing::debug!(
+ %err,
+ "[registry] agent_registry builtin load failed; \
+ registered runtime-registry agents only"
+ );
+ }
+ }
+
+ let registry_diagnostics = capability_registry.diagnostics();
+ let registry_snapshot = capability_registry.snapshot();
+
+ // Validation/projection pass (issue #4249, Workstream 10.1): exercise the
+ // model/tool projection helpers that are slated to eventually replace the
+ // live `harness.register_model`/`register_tool` glue. Today they are
+ // infallible projections — they cannot themselves surface diagnostics — so
+ // invoking them here is a non-fatal cross-check that every registered model
+ // and tool projects into a harness registry cleanly. The authoritative,
+ // fail-closed health signal stays `capability_registry.diagnostics()`
+ // (captured in `registry_diagnostics` above and enforced by 10.2); a benign
+ // projection difference must never abort a turn, so nothing here is folded
+ // into that stream. The harness is deliberately NOT switched over to these
+ // projections yet — that glue swap is explicitly deferred.
+ let projected_models = capability_registry.to_model_registry();
+ let projected_tools = capability_registry.to_tool_registry();
+ tracing::debug!(
+ models = projected_models.names().len(),
+ tools = projected_tools.names().len(),
+ graphs = capability_registry.names(ComponentKind::Graph).len(),
+ agents = registered_agents.len(),
+ runtime_agents = runtime_agent_count,
+ builtin_supplement_agents = builtin_supplement_count,
+ diagnostics = registry_diagnostics.len(),
+ "[registry] per-turn capability projection summary"
+ );
+
+ (tool_count, registry_diagnostics, registry_snapshot)
+}
diff --git a/crates/openhuman-core/src/memory/safety/checksums.rs b/crates/openhuman-core/src/memory/safety/checksums.rs
deleted file mode 100644
index 4f754497c4..0000000000
--- a/crates/openhuman-core/src/memory/safety/checksums.rs
+++ /dev/null
@@ -1,240 +0,0 @@
-//! Checksum and structural validators for PII candidates: Luhn (credit
-//! cards), IBAN mod-97, Verhoeff (Aadhaar), the CPF/CNPJ/CUIT digit
-//! algorithms, and the Spanish DNI/NIE check letters.
-//!
-//! Split out of `pii.rs`. Consumed by the candidate matching in
-//! [`super::pii_patterns`], which gates a formatted-looking match on the
-//! matching validator before treating it as a confirmed hit.
-
-// ---------- Checksum and structural validators for PII candidates ----------
-
-fn digits(s: &str) -> Vec<u32> {
- s.chars()
- .filter(|c| c.is_ascii_digit())
- .map(|c| c.to_digit(10).expect("ascii digit"))
- .collect()
-}
-
-fn valid_cpf(d: &[u32]) -> bool {
- if d.len() != 11 || d.iter().all(|x| *x == d[0]) {
- return false;
- }
- let s1: u32 = (0..9).map(|i| d[i] * (10 - i as u32)).sum();
- let dv1 = (s1 * 10) % 11 % 10;
- if dv1 != d[9] {
- return false;
- }
- let s2: u32 = (0..10).map(|i| d[i] * (11 - i as u32)).sum();
- let dv2 = (s2 * 10) % 11 % 10;
- dv2 == d[10]
-}
-
-fn valid_cnpj(d: &[u32]) -> bool {
- if d.len() != 14 || d.iter().all(|x| *x == d[0]) {
- return false;
- }
- let w1: [u32; 12] = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
- let s1: u32 = (0..12).map(|i| d[i] * w1[i]).sum();
- let r1 = s1 % 11;
- let dv1 = if r1 < 2 { 0 } else { 11 - r1 };
- if dv1 != d[12] {
- return false;
- }
- let w2: [u32; 13] = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
- let s2: u32 = (0..13).map(|i| d[i] * w2[i]).sum();
- let r2 = s2 % 11;
- let dv2 = if r2 < 2 { 0 } else { 11 - r2 };
- dv2 == d[13]
-}
-
-fn valid_cuit(d: &[u32]) -> bool {
- if d.len() != 11 {
- return false;
- }
- let w: [u32; 10] = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
- let s: u32 = (0..10).map(|i| d[i] * w[i]).sum();
- let r = s % 11;
- let dv = match r {
- 0 => 0,
- 1 => return false,
- _ => 11 - r,
- };
- dv == d[10]
-}
-
-// Luhn — used for credit-card validation.
-fn valid_luhn(s: &str) -> bool {
- let d = digits(s);
- if d.len() < 13 || d.len() > 19 {
- return false;
- }
- let mut sum = 0u32;
- let mut alt = false;
- for x in d.iter().rev() {
- let v = if alt {
- let doubled = x * 2;
- if doubled > 9 {
- doubled - 9
- } else {
- doubled
- }
- } else {
- *x
- };
- sum += v;
- alt = !alt;
- }
- sum.is_multiple_of(10)
-}
-
-// IBAN mod-97. Steps: strip spaces, move first 4 chars to end, expand letters
-// (A=10..Z=35), divide as a big-integer mod 97, require remainder == 1.
-fn valid_iban(s: &str) -> bool {
- let cleaned: String = s.chars().filter(|c| !c.is_whitespace()).collect();
- if cleaned.len() < 15 || cleaned.len() > 34 {
- return false;
- }
- if !cleaned.chars().take(2).all(|c| c.is_ascii_alphabetic()) {
- return false;
- }
- if !cleaned[2..4].chars().all(|c| c.is_ascii_digit()) {
- return false;
- }
- let rotated: String = cleaned[4..].chars().chain(cleaned[..4].chars()).collect();
- let mut remainder: u64 = 0;
- for c in rotated.chars() {
- let chunk = if let Some(d) = c.to_digit(10) {
- d as u64
- } else if c.is_ascii_alphabetic() {
- (c.to_ascii_uppercase() as u64) - ('A' as u64) + 10
- } else {
- return false;
- };
- // Expand into the running remainder digit-by-digit so we never need
- // u128. Each letter contributes 2 decimal digits.
- if chunk >= 10 {
- remainder = (remainder * 100 + chunk) % 97;
- } else {
- remainder = (remainder * 10 + chunk) % 97;
- }
- }
- remainder == 1
-}
-
-// Verhoeff — used for Aadhaar.
-const VERHOEFF_D: [[u8; 10]; 10] = [
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
- [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
- [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
- [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
- [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
- [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
- [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
- [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
- [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
- [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
-];
-const VERHOEFF_P: [[u8; 10]; 8] = [
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
- [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
- [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
- [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
- [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
- [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
- [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
- [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
-];
-
-fn valid_verhoeff(d: &[u32]) -> bool {
- if d.len() != 12 {
- return false;
- }
- // Aadhaar can't start with 0 or 1.
- if d[0] < 2 {
- return false;
- }
- let mut c: u8 = 0;
- for (i, digit) in d.iter().rev().enumerate() {
- c = VERHOEFF_D[c as usize][VERHOEFF_P[i % 8][*digit as usize] as usize];
- }
- c == 0
-}
-
-// US SSN reserved/invalid ranges per SSA.
-fn valid_ssn(s: &str) -> bool {
- let d = digits(s);
- if d.len() != 9 {
- return false;
- }
- let area = d[0] * 100 + d[1] * 10 + d[2];
- let group = d[3] * 10 + d[4];
- let serial = d[5] * 1000 + d[6] * 100 + d[7] * 10 + d[8];
- if area == 0 || area == 666 || area >= 900 {
- return false;
- }
- if group == 0 || serial == 0 {
- return false;
- }
- true
-}
-
-// Spain DNI check letter — 8 digits mod 23 indexes into a fixed letter table.
-const DNI_LETTERS: &[u8; 23] = b"TRWAGMYFPDXBNJZSQVHLCKE";
-
-fn valid_dni_es(s: &str) -> bool {
- let upper = s.to_ascii_uppercase();
- let bytes = upper.as_bytes();
- if bytes.len() != 9 {
- return false;
- }
- let num_str = &upper[..8];
- let letter = bytes[8];
- let Ok(num) = num_str.parse::<u32>() else {
- return false;
- };
- DNI_LETTERS[(num % 23) as usize] == letter
-}
-
-fn valid_nie_es(s: &str) -> bool {
- let upper = s.to_ascii_uppercase();
- let bytes = upper.as_bytes();
- if bytes.len() != 9 {
- return false;
- }
- let prefix = match bytes[0] {
- b'X' => 0u32,
- b'Y' => 1,
- b'Z' => 2,
- _ => return false,
- };
- let Ok(rest) = std::str::from_utf8(&bytes[1..8]) else {
- return false;
- };
- let Ok(num) = rest.parse::<u32>() else {
- return false;
- };
- let composed = prefix * 10_000_000 + num;
- DNI_LETTERS[(composed % 23) as usize] == bytes[8]
-}
-
-// UK NINO reserved-prefix blacklist.
-fn valid_nino(s: &str) -> bool {
- let upper = s.to_ascii_uppercase();
- let bytes = upper.as_bytes();
- if bytes.len() != 9 {
- return false;
- }
- // First char cannot be D F I Q U V; second cannot be D F I O Q U V.
- let bad_first = b"DFIQUV";
- let bad_second = b"DFIOQUV";
- if bad_first.contains(&bytes[0]) || bad_second.contains(&bytes[1]) {
- return false;
- }
- // Reserved two-letter prefixes.
- let reserved = ["BG", "GB", "KN", "NK", "NT", "TN", "ZZ"];
- let prefix = &upper[..2];
- if reserved.contains(&prefix) {
- return false;
- }
- true
-}