The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed Cargo.lock,crates/openhuman-core/src/agent/cost.rs,crates/openhuman-core/src/ag
Steven Enamakel60ec26049f94
diff --git a/Cargo.lock b/Cargo.lockindex 7858c641c3..6683c51f4b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7134,6 +7134,8 @@ dependencies = ["async-trait","chrono","chrono-tz",+ "log",+ "regex","serde","serde_json","sha2 0.11.0",diff --git a/crates/openhuman-core/src/agent/cost.rs b/crates/openhuman-core/src/agent/cost.rsindex 3d3d321bf3..11860250d9 100644--- a/crates/openhuman-core/src/agent/cost.rs+++ b/crates/openhuman-core/src/agent/cost.rs@@ -53,7 +53,7 @@ pub(crate) fn lookup_pricing(model: &str) -> Option<ModelPricing> {output_per_mtok_usd: 0.0,});}- let price = crate::platform::cost::catalog::lookup(model.trim())?;+ let price = tinyagents_registry::pricing::lookup(model.trim())?;Some(ModelPricing {model: price.model_id,input_per_mtok_usd: price.input_per_mtok_usd,diff --git a/crates/openhuman-core/src/agent/session_host/stop_summary.rs b/crates/openhuman-core/src/agent/session_host/stop_summary.rsindex 428b1aaa11..3540110be3 100644--- a/crates/openhuman-core/src/agent/session_host/stop_summary.rs+++ b/crates/openhuman-core/src/agent/session_host/stop_summary.rs@@ -206,7 +206,7 @@ pub(crate) fn short_error_line(content: &str) -> String {None => first.to_owned(),};let line = crate::security::scrub::sanitize_text(&line).value;- let line = crate::security::pii::redact_identifiers(&line);+ let line = tinymemory_api::safety::redact_identifiers(&line);let line = line.split_whitespace().collect::<Vec<_>>().join(" ");if line.chars().count() <= ERROR_LINE_CHARS {return line;diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 0c2d02eccf..999bd69bc5 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -480,7 +480,7 @@ pub(super) fn assemble_turn_harness(// tracker's per-run token accounting matches the authoritative runtime// `AgentRun.usage` on every model call.// 2. A pricing table wired via `BudgetMiddleware::with_pricing(..)` at- // parity with `cost::catalog::estimate_cost_usd`, so the crate can own+ // parity with `tinyagents_registry::pricing::estimate_cost_usd`, so the crate can own// MONEY (USD) budgets. Today the shadow compares TOKENS only (the// observe-only crate middleware has no pricing, so its cost stays $0)// and the local gate is the sole money-budget authority.diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rsindex 32fd135ea8..0bc30b5ead 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs@@ -10,7 +10,7 @@//! * **admission / back-pressure** — [`scheduler_gate::wait_for_capacity`],//! which owns the single-slot global LLM semaphore and the//! AC-power / CPU / signed-out policy backoff;-//! * **pricing hints and budgets** — [`cost::catalog::estimate_cost_usd`] on+//! * **pricing hints and budgets** — [`tinyagents_registry::pricing::estimate_cost_usd`] on//! the way in, and the opt-in `[[cost.budgets]]` policies, which can refuse a//! call (`BUDGET_EXCEEDED`). The legacy `monthly_limit_usd` still refuses//! nothing. Nothing here writes the cost ledger: the event bridge records@@ -233,7 +233,7 @@ impl OpenHumanBudgetGate {let call = cost::budget::CallUnderCheck {model: &model,scope: &scope,- estimated_usd: cost::catalog::estimate_cost_usd(+ estimated_usd: tinyagents_registry::pricing::estimate_cost_usd(&model,est.estimated_input_tokens,est.estimated_output_tokens,@@ -304,7 +304,7 @@ impl BudgetGate for OpenHumanBudgetGate {// uncatalogued model, which means "unknown", not "free" — and a zero// estimate can only ever make `check_budget` more permissive, never// less, so it can't manufacture a refusal.- let estimated_usd = cost::catalog::estimate_cost_usd(+ let estimated_usd = tinyagents_registry::pricing::estimate_cost_usd(&est.model,est.estimated_input_tokens,est.estimated_output_tokens,diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rsindex fe2118c1c2..e449aa5a1d 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs@@ -48,7 +48,7 @@//! step** — the two are alternatives, not layers. The session-allowlist//! shortcut yields no id and needs no terminal row.//! 3. **No `Redacted` outcome is ever produced.** OpenHuman can *detect* PII-//! ([`crate::security::pii::scan`]) but exposes no verified+//! ([`tinymemory_api::safety::scan`]) but exposes no verified//! public helper that rewrites free text into a redacted copy — the one that//! exists (`approval::redact::scrub_paths`) is private and shaped for JSON//! argument maps. Screening therefore only ever passes or blocks. See the@@ -658,11 +658,11 @@ impl SecurityGate for OpenHumanSecurityGate {/// the screened text, which is the thing suspected of being hostile.////// TODO(phase4): no [`ScreenOutcome::Redacted`] is ever returned. Producing- /// one needs a free-text redactor; `security::pii::scan` detects spans but+ /// one needs a free-text redactor; `tinymemory_api::safety::scan` detects spans but/// returns no rewritten string, and `approval::redact::scrub_paths` is/// private and shaped for JSON argument maps. Either lift a public/// `redact_text(&str) -> String` out of `approval::redact` or add one to- /// `security::pii`, then map "PII found, injection clean" to `Redacted`.+ /// `tinymemory_api::safety`, then map "PII found, injection clean" to `Redacted`.async fn screen_input(&self, text: &str, origin: ContentOrigin) -> TaResult<ScreenOutcome> {if !self.screens_input {return Ok(ScreenOutcome::Pass);diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rsindex 3720c80bf7..8318aeb0d2 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs@@ -394,7 +394,7 @@ impl OpenhumanEventBridge {.map(|u| u.context_window()).filter(|w| *w > 0).unwrap_or_else(|| {- crate::platform::cost::catalog::lookup(&self.model)+ tinyagents_registry::pricing::lookup(&self.model).map(|p| u64::from(p.context_window)).unwrap_or(0)});@@ -497,7 +497,7 @@ impl OpenhumanEventBridge {/// Estimate one call's USD cost. Uses the tier-aware/// [`agent::cost`](crate::agent::cost) table (managed handles/// like `hint:chat`/`hint:burst` + the vendor catalog + heuristics) — the- /// previous `cost::catalog::estimate_cost_usd` only knew concrete vendor+ /// previous `tinyagents_registry::pricing::estimate_cost_usd` only knew concrete vendor/// ids, so every managed-tier call priced as $0 in traces and the footer./// `None` for a model the catalog does not price.pub(super) fn estimate_call_cost(model: &str, usage: &Usage) -> Option<f64> {diff --git a/crates/openhuman-core/src/cron/scheduler_gate/README.md b/crates/openhuman-core/src/cron/scheduler_gate/README.mdindex 497578190f..866db368f1 100644--- a/crates/openhuman-core/src/cron/scheduler_gate/README.md+++ b/crates/openhuman-core/src/cron/scheduler_gate/README.md@@ -19,7 +19,7 @@ Gates background AI work (embeddings, summarisation, triage, local inference) on| [`crates/openhuman-core/src/cron/scheduler_gate/gate.rs`](./gate.rs) | The process-wide wiring: the `SharedCore`, the signed-out override, the resume `Notify`, the single-slot LLM semaphore, `init_global(SchedulerGateConfig)`/`update_config`/`current_policy`/`wait_for_capacity`, and the per-tokio-runtime test-state scaffolding. || [`crates/openhuman-core/src/cron/scheduler_gate/throttle.rs`](./throttle.rs) | The machinery: `GateCore` (config + signals + policy), the 30s `spawn_sampler` task, `wait_for_capacity` over a caller-owned semaphore, and the `LlmPermit` RAII guard. || [`crates/openhuman-core/src/cron/scheduler_gate/signals.rs`](./signals.rs) | `sample(&SignalEnv)`: battery (via `starship_battery`, behind the `scheduler-gate` feature), CPU usage (via `sysinfo`, two-refresh delta), and server/container detection. |-| [`crates/openhuman-core/src/cron/scheduler_gate/decide.rs`](./decide.rs) | Pure decision logic: `decide(signals, cfg) -> Policy` over the `Signals` snapshot; `Policy` / `PauseReason` live beside `SchedulerGateConfig` in `config::schema::scheduler_gate`. Evaluation order: user mode override → server mode → power-aware stand-down → hard CPU ceiling → battery/CPU headroom. |+| [`crates/openhuman-core/src/cron/scheduler_gate/decide.rs (config/policy adapter; pure decision in `platform/resource_admission`)`](./decide.rs (config/policy adapter; pure decision in `platform/resource_admission`)) | Pure decision logic: `decide(signals, cfg) -> Policy` over the `Signals` snapshot; `Policy` / `PauseReason` live beside `SchedulerGateConfig` in `config::schema::scheduler_gate`. Evaluation order: user mode override → server mode → power-aware stand-down → hard CPU ceiling → battery/CPU headroom. || `SIGNAL_ENV` in `gate.rs` | The env-override names: `OPENHUMAN_ON_AC_POWER`, `OPENHUMAN_BATTERY_CHARGE`, `OPENHUMAN_DEPLOYMENT` (plus the Kubernetes / `/.dockerenv` heuristics). |## Public surfacediff --git a/crates/openhuman-core/src/security/mod.rs b/crates/openhuman-core/src/security/mod.rsindex f9f3ec53a6..04a4b128b3 100644--- a/crates/openhuman-core/src/security/mod.rs+++ b/crates/openhuman-core/src/security/mod.rs@@ -17,7 +17,6 @@ pub mod encryption;pub mod keyring_consent;pub mod live_policy;pub mod pairing;-pub mod pii;pub mod policy;pub mod prompt_injection;pub mod scrub;@@ -60,6 +59,3 @@ pub use schemas::{all_controller_schemas as all_security_controller_schemas,all_registered_controllers as all_security_registered_controllers,};--#[allow(unused_imports)]-pub use pii::{scan as scan_pii, CategoryHit, PiiCategory, PiiScanResult, RiskLevel};diff --git a/crates/openhuman-core/src/security/pii/README.md b/crates/openhuman-core/src/security/pii/README.mddeleted file mode 100644index fa6b06945d..0000000000--- a/crates/openhuman-core/src/security/pii/README.md+++ /dev/null@@ -1,75 +0,0 @@-# pii--Local PII / identification-risk detector (privacy epic #4256, slice S5).-Detects when a prompt or document may contain patient, legal, financial,-family, or other identifiable information and reports a risk level, a-numeric score, and the matched categories, so upstream gates can decide-whether content is safe to send off-device.--## Guarantees--- Fully local. `scan()` is pure pattern and keyword matching over the input- string: no network call, no async, no external model. Importing this- module pulls in nothing beyond `regex`.-- Recall over precision. A missed flag means sensitive data leaves the- machine unnoticed, so the detector is tuned to over-flag rather than- under-flag.-- Never reports raw matched text. The result type carries only categories- and counts, never the matched substrings, so the result itself cannot- become a new PII sink.--## Key files--| File | Purpose |-| --- | --- |-| [`types.rs`](./types.rs) | `RiskLevel`, `PiiCategory` (with per-category `weight()` and `is_strong_identifier()`), `CategoryHit`, `PiiScanResult` |-| [`detector.rs`](./detector.rs) | `scan()`, which walks the compiled rule set, tallies matches, and folds the result into a `PiiScanResult` |-| [`rules.rs`](./rules.rs) | Compiled rule table: pattern rules (regex plus an optional structural validator, for example Luhn for cards) and keyword rules (word-boundaried term alternations for topical categories) |--## Public surface--- `scan(content: &str) -> PiiScanResult`: the only entry point.-- `PiiCategory`: structured identifiers (`Email`, `PhoneNumber`, `NationalId`,- `CreditCard`, `BankAccount`, `IpAddress`, `PostalAddress`) and topical- context (`DateOfBirth`, `Passport`, `Medical`, `Legal`, `Financial`,- `Family`).-- `RiskLevel`: `None < Low < Medium < High`; `is_sensitive()` is `true` for- anything above `None`.-- `PiiScanResult { level, score, categories, hits }`: `is_sensitive()` and- `has_category()` helpers.--## Scoring model (`detector::scan`)--- Each distinct category contributes its `PiiCategory::weight()` once.-- Each additional co-occurring category adds a flat `CO_OCCURRENCE_BONUS`- (5), since multiple distinct categories in one blob look more like a real- record than any single one alone.-- A strong identifier (`NationalId`, `CreditCard`, `Passport`,- `BankAccount`) forces `RiskLevel::High` regardless of the numeric score.-- The raw score otherwise maps to a level via fixed thresholds: `0` to- `None`, `1..=19` to `Low`, `20..=44` to `Medium`, `45+` to `High`.--## Used by--- `security::mod.rs` re-exports `scan` as `scan_pii`, along with- `CategoryHit`, `PiiCategory`, `PiiScanResult`, `RiskLevel`.-- `crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs` documents- `security::pii::scan` as the detection primitive for a future `Redacted`- screening outcome. As of this writing it is referenced but not yet wired- in; screening only ever passes or blocks (see the `TODO(phase4)` in- `screen_input`).-- Cross-links [`../egress/README.md`](../egress/README.md):- `EgressDescriptor::risk_level` / `risk_categories`- (`IdentificationRisk`) are the eventual consumer of this detector's output- once the S5 slice wires it into the egress spine.--## Tests--- [`detector_tests.rs`](./detector_tests.rs), [`pii_tests.rs`](./pii_tests.rs).--## Further reading--- [Parent module (`security`)](../README.md)-- [Privacy mode](../../../../../gitbooks/features/privacy-mode.md)-- [Privacy and security](../../../../../gitbooks/features/privacy-and-security.md)-- [Security architecture](../../../../../gitbooks/developing/architecture/security.md)diff --git a/crates/openhuman-core/src/security/pii/detector.rs b/crates/openhuman-core/src/security/pii/detector.rsdeleted file mode 100644index b04ac3123c..0000000000--- a/crates/openhuman-core/src/security/pii/detector.rs+++ /dev/null@@ -1,131 +0,0 @@-//! Classifier entry point for the local PII detector.-//!-//! [`scan`] is a pure, synchronous function: it walks the compiled rule set-//! (see [`super::rules`]) over the input, tallies matches per category, and-//! folds the tally into a [`PiiScanResult`]. No async, no I/O, no network.--use std::collections::BTreeMap;--use super::rules::rules;-use super::types::{CategoryHit, PiiCategory, PiiScanResult, RiskLevel};--/// Extra points added per additional co-occurring category. Multiple distinct-/// identifier/context categories in one blob look more like a real record than-/// any single one alone, so co-occurrence nudges the score upward.-const CO_OCCURRENCE_BONUS: u32 = 5;--/// Map a raw score to a [`RiskLevel`]. Thresholds lean toward escalation-/// (recall over precision).-fn level_from_score(score: u32) -> RiskLevel {- match score {- 0 => RiskLevel::None,- 1..=19 => RiskLevel::Low,- 20..=44 => RiskLevel::Medium,- _ => RiskLevel::High,- }-}--/// Scan `content` for identification risk.-///-/// Returns a [`PiiScanResult`] carrying the overall [`RiskLevel`], a numeric-/// score, and the distinct categories detected (with per-category counts).-///-/// Detection runs **fully locally** — pattern + keyword matching only. The-/// function is deterministic and side-effect-free, so it is safe to call from-/// any context (sync or async, on or off a Tokio runtime).-///-/// ## Scoring-/// * Each distinct category contributes its [`PiiCategory::weight`] once.-/// * Each additional co-occurring category adds [`CO_OCCURRENCE_BONUS`].-/// * A "strong identifier" (SSN, card, passport, bank account) forces-/// [`RiskLevel::High`] regardless of the numeric score.-pub fn scan(content: &str) -> PiiScanResult {- // BTreeMap keeps the output deterministic (categories emitted in enum- // order) without a separate sort pass.- let mut counts: BTreeMap<PiiCategory, usize> = BTreeMap::new();-- for rule in rules() {- for m in rule.regex.find_iter(content) {- if let Some(validator) = rule.validator {- if !validator(m.as_str()) {- continue;- }- }- *counts.entry(rule.category).or_default() += 1;- }- }-- if counts.is_empty() {- log::trace!("[security][pii] scan clean (no categories matched)");- return PiiScanResult::default();- }-- let distinct = counts.len() as u32;- let mut score: u32 = counts.keys().map(|c| c.weight()).sum();- if distinct > 1 {- score += CO_OCCURRENCE_BONUS * (distinct - 1);- }-- let has_strong = counts.keys().any(|c| c.is_strong_identifier());- let mut level = level_from_score(score);- if has_strong && level < RiskLevel::High {- level = RiskLevel::High;- }-- let categories: Vec<PiiCategory> = counts.keys().copied().collect();- let hits: Vec<CategoryHit> = counts- .iter()- .map(|(&category, &count)| CategoryHit { category, count })- .collect();-- // Log level/score/categories only — never the matched content itself.- log::debug!(- "[security][pii] scan level={} score={} categories={:?}",- level.as_str(),- score,- categories.iter().map(|c| c.as_str()).collect::<Vec<_>>()- );-- PiiScanResult {- level,- score,- categories,- hits,- }-}--/// Replacement for every value [`redact_identifiers`] removes.-pub const REDACTED_IDENTIFIER: &str = "[redacted]";--/// Replace every **structured identifier** in `content` (email, phone number,-/// national id, payment card, IBAN, IPv4 address, postal address) with-/// [`REDACTED_IDENTIFIER`].-///-/// Uses the same rules (and validators) as [`scan`], so what is redacted is-/// exactly what would be counted. Topical keyword categories (medical, legal,-/// ...) describe context rather than identify anyone and are left in place.-/// For text shown back to a user from a source that may quote someone's-/// details, such as a tool's error line.-pub fn redact_identifiers(content: &str) -> String {- let mut out = content.to_string();- for rule in rules() {- if !rule.category.is_structured_identifier() {- continue;- }- let redacted = rule.regex.replace_all(&out, |caps: ®ex::Captures<'_>| {- let matched = &caps[0];- match rule.validator {- Some(validator) if !validator(matched) => matched.to_string(),- _ => REDACTED_IDENTIFIER.to_string(),- }- });- if let std::borrow::Cow::Owned(changed) = redacted {- out = changed;- }- }- out-}--#[cfg(test)]-#[path = "detector_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/security/pii/detector_tests.rs b/crates/openhuman-core/src/security/pii/detector_tests.rsdeleted file mode 100644index 51239affb0..0000000000--- a/crates/openhuman-core/src/security/pii/detector_tests.rs+++ /dev/null@@ -1,21 +0,0 @@-use super::*;--#[test]-fn empty_input_is_none() {- let r = scan("");- assert_eq!(r.level, RiskLevel::None);- assert_eq!(r.score, 0);- assert!(r.categories.is_empty());- assert!(!r.is_sensitive());-}--#[test]-fn level_thresholds_are_monotonic() {- assert_eq!(level_from_score(0), RiskLevel::None);- assert_eq!(level_from_score(1), RiskLevel::Low);- assert_eq!(level_from_score(19), RiskLevel::Low);- assert_eq!(level_from_score(20), RiskLevel::Medium);- assert_eq!(level_from_score(44), RiskLevel::Medium);- assert_eq!(level_from_score(45), RiskLevel::High);- assert_eq!(level_from_score(1000), RiskLevel::High);-}diff --git a/crates/openhuman-core/src/security/pii/mod.rs b/crates/openhuman-core/src/security/pii/mod.rsdeleted file mode 100644index da30c5c171..0000000000--- a/crates/openhuman-core/src/security/pii/mod.rs+++ /dev/null@@ -1,37 +0,0 @@-//! Local PII / identification-risk detector (privacy epic #4256, slice S5).-//!-//! Detects when a prompt or document may contain patient / legal / financial /-//! family or other identifiable information, and reports a risk **level**, a-//! numeric **score**, and the matched **categories** — so upstream gates can-//! decide whether content is safe to send off-device.-//!-//! ## Hard guarantee: detection is fully local-//! Classification is pure pattern + keyword matching over the input string.-//! There is **no** network call, no async, no external model — importing this-//! module pulls in nothing beyond `regex`. Sending content to a remote service-//! to classify it would defeat the entire purpose of the privacy epic, so the-//! shipped default is dependency-free and offline by construction.-//!-//! ## Recall over precision-//! A missed flag means sensitive data leaves the machine unnoticed, so the-//! detector is tuned to over-flag rather than under-flag. See [`detector::scan`]-//! for the scoring model.-//!-//! ```-//! use openhuman_core::security::pii::{scan, PiiCategory, RiskLevel};-//!-//! let result = scan("patient John was diagnosed; SSN 123-45-6789");-//! assert_eq!(result.level, RiskLevel::High);-//! assert!(result.has_category(PiiCategory::NationalId));-//! ```--mod detector;-mod rules;-mod types;--#[cfg(test)]-#[path = "pii_tests.rs"]-mod tests;--pub use detector::{redact_identifiers, scan, REDACTED_IDENTIFIER};-pub use types::{CategoryHit, PiiCategory, PiiScanResult, RiskLevel};diff --git a/crates/openhuman-core/src/security/pii/pii_tests.rs b/crates/openhuman-core/src/security/pii/pii_tests.rsdeleted file mode 100644index 23305094b0..0000000000--- a/crates/openhuman-core/src/security/pii/pii_tests.rs+++ /dev/null@@ -1,342 +0,0 @@-//! Fixture + boundary tests for the local PII detector.-//!-//! Coverage intent:-//! * every category detects its canonical form,-//! * false-positive guards (benign text, invalid card/IP) do NOT flag,-//! * false-negative / recall guards (varied formats, in-sentence values) DO-//! flag — recall matters more than precision here,-//! * risk-level escalation behaves as specified,-//! * detection is deterministic + offline (no external egress on classify),-//! * category identifiers serialize to stable snake_case strings.--use super::rules::{is_ipv4, is_luhn_valid};-use super::{redact_identifiers, scan, PiiCategory, RiskLevel};--// ----------------------------------------------------------------------------// Per-category detection (recall / true positives)-// -----------------------------------------------------------------------------#[test]-fn detects_email() {- let r = scan("reach me at [email protected] any time");- assert!(r.has_category(PiiCategory::Email));- assert!(r.is_sensitive());-}--#[test]-fn detects_national_id_ssn() {- // Dash- and space-separated both count (recall).- for raw in ["SSN 123-45-6789", "ssn is 123 45 6789"] {- let r = scan(raw);- assert!(r.has_category(PiiCategory::NationalId), "missed in {raw:?}");- assert_eq!(r.level, RiskLevel::High, "strong id must be High: {raw:?}");- }-}--#[test]-fn detects_valid_credit_card() {- // 4111 1111 1111 1111 is the canonical Visa test number (Luhn-valid).- for raw in [- "card 4111 1111 1111 1111 exp 12/26",- "4111-1111-1111-1111",- "4111111111111111",- ] {- let r = scan(raw);- assert!(r.has_category(PiiCategory::CreditCard), "missed in {raw:?}");- assert_eq!(r.level, RiskLevel::High);- }-}--#[test]-fn detects_iban_bank_account() {- let r = scan("transfer to GB82WEST12345698765432 please");- assert!(r.has_category(PiiCategory::BankAccount));- assert_eq!(r.level, RiskLevel::High);-}--#[test]-fn detects_phone_numbers_varied_formats() {- for raw in [- "call 415-555-1234",- "(415) 555 1234",- "+1 415.555.1234",- "reach +44 20 7946 0958 in london",- ] {- let r = scan(raw);- assert!(- r.has_category(PiiCategory::PhoneNumber),- "missed in {raw:?}"- );- }-}--#[test]-fn detects_ipv4_address() {- let r = scan("client connected from 192.168.10.24 last night");- assert!(r.has_category(PiiCategory::IpAddress));-}--#[test]-fn detects_postal_address() {- let r = scan("ship to 1600 Pennsylvania Avenue, Washington");- assert!(r.has_category(PiiCategory::PostalAddress));-}--#[test]-fn detects_date_of_birth_context() {- for raw in [- "date of birth: 1990-04-12",- "DOB 04/12/1990",- "he was born on the 3rd",- ] {- let r = scan(raw);- assert!(- r.has_category(PiiCategory::DateOfBirth),- "missed in {raw:?}"- );- }-}--#[test]-fn detects_passport() {- let r = scan("upload a scan of your passport");- assert!(r.has_category(PiiCategory::Passport));- assert_eq!(r.level, RiskLevel::High); // strong identifier-}--#[test]-fn detects_medical_context() {- let r = scan("the patient was diagnosed and prescribed medication");- assert!(r.has_category(PiiCategory::Medical));- assert!(r.level >= RiskLevel::Medium);-}--#[test]-fn detects_legal_context() {- let r = scan("the plaintiff filed a lawsuit; the defendant's attorney responded");- assert!(r.has_category(PiiCategory::Legal));- assert!(r.level >= RiskLevel::Medium);-}--#[test]-fn detects_financial_context() {- let r = scan("please send your bank account and routing number");- assert!(r.has_category(PiiCategory::Financial));- assert!(r.level >= RiskLevel::Medium);-}--#[test]-fn detects_family_context() {- let r = scan("my spouse and our minor child are dependents");- assert!(r.has_category(PiiCategory::Family));- assert!(r.is_sensitive());-}--// ----------------------------------------------------------------------------// False-positive guards-// -----------------------------------------------------------------------------#[test]-fn benign_text_is_not_flagged() {- for raw in [- "let's grab coffee at 3pm tomorrow",- "the build passed and the tests are green",- "refactor the parser to be faster",- "version 1.2.3 shipped yesterday", // dotted, but only 3 octets — not IPv4- ] {- let r = scan(raw);- assert_eq!(r.level, RiskLevel::None, "false positive on {raw:?}: {r:?}");- assert!(r.categories.is_empty(), "categories on {raw:?}: {r:?}");- }-}--#[test]-fn luhn_invalid_number_is_not_a_card() {- // 16 digits but fails the Luhn checksum → must NOT be a CreditCard.- let r = scan("order id 1234 5678 9012 3456 confirmed");- assert!(- !r.has_category(PiiCategory::CreditCard),- "Luhn-invalid number flagged as card: {r:?}"- );-}--#[test]-fn out_of_range_octets_are_not_ipv4() {- let r = scan("coords 300.400.500.600 are nonsense");- assert!(- !r.has_category(PiiCategory::IpAddress),- "bad octets flagged: {r:?}"- );-}--#[test]-fn phone_shaped_ssn_not_double_counted_as_ssn() {- // 3-3-4 grouping is a phone, not a 3-2-4 SSN.- let r = scan("call 415-555-1234");- assert!(r.has_category(PiiCategory::PhoneNumber));- assert!(!r.has_category(PiiCategory::NationalId));-}--// ----------------------------------------------------------------------------// Risk-level escalation-// -----------------------------------------------------------------------------#[test]-fn single_weak_identifier_is_low() {- let r = scan("email me: [email protected]");- assert_eq!(r.level, RiskLevel::Low);- assert_eq!(r.categories, vec![PiiCategory::Email]);-}--#[test]-fn co_occurring_identifiers_escalate() {- // Email + phone together → beyond a single weak signal.- let r = scan("[email protected] / 415-555-1234");- assert!(r.has_category(PiiCategory::Email));- assert!(r.has_category(PiiCategory::PhoneNumber));- assert!(- r.level >= RiskLevel::Medium,- "expected escalation, got {r:?}"- );-}--#[test]-fn strong_identifier_forces_high_even_alone() {- let r = scan("123-45-6789");- assert_eq!(r.level, RiskLevel::High);- assert!(r.score >= PiiCategory::NationalId.weight());-}--#[test]-fn medical_record_shape_is_high() {- let r = scan("patient John Doe, DOB 01/02/1980, diagnosed; SSN 111-22-3333");- assert_eq!(r.level, RiskLevel::High);- assert!(r.has_category(PiiCategory::Medical));- assert!(r.has_category(PiiCategory::NationalId));- assert!(r.has_category(PiiCategory::DateOfBirth));-}--#[test]-fn score_increases_with_more_categories() {- let one = scan("[email protected]").score;- let two = scan("[email protected] and patient diagnosed").score;- assert!(- two > one,- "adding a category should raise the score: {one} !< {two}"- );-}--// ----------------------------------------------------------------------------// Offline / determinism (no external egress on classify)-// -----------------------------------------------------------------------------#[test]-fn scan_is_deterministic_and_pure() {- // Detection performs zero I/O: it is a pure function of its input, so- // repeated calls must be byte-for-byte identical. This is the unit-test- // proxy for "no external egress occurs during classify" — there is no- // async, no network client, and nothing in this module to mock away.- let input = "patient [email protected], card 4111 1111 1111 1111, SSN 123-45-6789";- let first = scan(input);- let second = scan(input);- assert_eq!(first, second);-}--#[test]-fn scan_runs_without_a_tokio_runtime() {- // A plain `#[test]` has no Tokio runtime installed; the fact that `scan`- // returns here at all proves it does not spawn async work / touch the- // network to classify.- let r = scan("SSN 123-45-6789");- assert_eq!(r.level, RiskLevel::High);-}--// ----------------------------------------------------------------------------// Stable serde identifiers (contract for S2 / RPC / event bus)-// -----------------------------------------------------------------------------#[test]-fn category_identifiers_are_stable_snake_case() {- let cases = [- (PiiCategory::Email, "email"),- (PiiCategory::PhoneNumber, "phone_number"),- (PiiCategory::NationalId, "national_id"),- (PiiCategory::CreditCard, "credit_card"),- (PiiCategory::BankAccount, "bank_account"),- (PiiCategory::IpAddress, "ip_address"),- (PiiCategory::PostalAddress, "postal_address"),- (PiiCategory::DateOfBirth, "date_of_birth"),- (PiiCategory::Passport, "passport"),- (PiiCategory::Medical, "medical"),- (PiiCategory::Legal, "legal"),- (PiiCategory::Financial, "financial"),- (PiiCategory::Family, "family"),- ];- for (cat, expected) in cases {- assert_eq!(cat.as_str(), expected);- assert_eq!(- serde_json::to_string(&cat).unwrap(),- format!("\"{expected}\"")- );- }-}--#[test]-fn risk_levels_are_ordered_and_stable() {- assert!(RiskLevel::None < RiskLevel::Low);- assert!(RiskLevel::Low < RiskLevel::Medium);- assert!(RiskLevel::Medium < RiskLevel::High);- for (lvl, s) in [- (RiskLevel::None, "none"),- (RiskLevel::Low, "low"),- (RiskLevel::Medium, "medium"),- (RiskLevel::High, "high"),- ] {- assert_eq!(lvl.as_str(), s);- assert_eq!(serde_json::to_string(&lvl).unwrap(), format!("\"{s}\""));- }-}--// ----------------------------------------------------------------------------// Validator unit tests-// -----------------------------------------------------------------------------#[test]-fn luhn_validator_accepts_known_good_and_rejects_bad() {- assert!(is_luhn_valid("4111111111111111")); // Visa test number- assert!(is_luhn_valid("4111 1111 1111 1111"));- assert!(!is_luhn_valid("1234567890123456"));- assert!(!is_luhn_valid("12345")); // too short-}--#[test]-fn ipv4_validator_bounds_octets() {- assert!(is_ipv4("192.168.0.1"));- assert!(is_ipv4("255.255.255.255"));- assert!(!is_ipv4("256.1.1.1"));- assert!(!is_ipv4("1.2.3"));-}--// ----------------------------------------------------------------------------// Redaction-// -----------------------------------------------------------------------------#[test]-fn redact_identifiers_replaces_structured_values_only() {- let out = redact_identifiers(- "user [email protected] logged in from 203.0.113.7, call +1 415-555-0100 about the patient",- );- assert!(!out.contains("[email protected]"), "{out}");- assert!(!out.contains("203.0.113.7"), "{out}");- assert!(!out.contains("415-555-0100"), "{out}");- assert!(out.contains("[redacted]"), "{out}");- // Topical keywords are context, not identifiers: kept.- assert!(out.contains("patient"), "{out}");-}--#[test]-fn redact_identifiers_keeps_values_that_fail_validation() {- // Not a valid IPv4 address, not a Luhn-valid card: left as written.- let text = "version 999.1.1.1 build 1234567890123456";- assert_eq!(redact_identifiers(text), text);-}diff --git a/crates/openhuman-core/src/security/pii/rules.rs b/crates/openhuman-core/src/security/pii/rules.rsdeleted file mode 100644index b4b6d3d45f..0000000000--- a/crates/openhuman-core/src/security/pii/rules.rs+++ /dev/null@@ -1,250 +0,0 @@-//! Detection rules for the local PII detector.-//!-//! Two flavours of rule, both compiled once into a process-wide static:-//!-//! * **Pattern rules** — a [`Regex`] plus an optional structural `validator`-//! (Luhn for cards, octet range for IPv4) that rejects shape-matches that-//! aren't actually valid identifiers.-//! * **Keyword rules** — an alternation of domain terms wrapped in word-//! boundaries, used for the topical categories (medical / legal / financial /-//! family) where there is no single canonical value shape.-//!-//! All matching is case-insensitive and offline; nothing here performs I/O.--use std::sync::LazyLock;--use regex::Regex;--use super::types::PiiCategory;--/// A single detection rule: matches [`regex`](Rule::regex), attributes hits to-/// [`category`](Rule::category), and — if present — only counts a match when-/// [`validator`](Rule::validator) confirms it.-pub(crate) struct Rule {- pub category: PiiCategory,- pub regex: Regex,- /// Optional structural check applied to each raw match before it counts.- pub validator: Option<fn(&str) -> bool>,-}--/// Build a keyword rule: a case-insensitive, word-boundaried alternation over-/// `terms`, all attributed to `category`.-fn keyword_rule(category: PiiCategory, terms: &[&str]) -> Rule {- let alternation = terms.join("|");- let pattern = format!(r"(?i)\b(?:{alternation})\b");- Rule {- category,- regex: Regex::new(&pattern).expect("keyword rule regex is well-formed"),- validator: None,- }-}--/// Build a pattern rule from a raw regex string.-fn pattern_rule(category: PiiCategory, pattern: &str, validator: Option<fn(&str) -> bool>) -> Rule {- Rule {- category,- regex: Regex::new(pattern).expect("pattern rule regex is well-formed"),- validator,- }-}--/// Luhn checksum validation for candidate payment-card numbers. Strips-/// separators first; requires 13–19 digits.-pub(crate) fn is_luhn_valid(raw: &str) -> bool {- let digits: Vec<u8> = raw- .bytes()- .filter(|b| b.is_ascii_digit())- .map(|b| b - b'0')- .collect();- if !(13..=19).contains(&digits.len()) {- return false;- }- let mut sum = 0u32;- // Double every second digit from the right.- for (i, &d) in digits.iter().rev().enumerate() {- let mut v = d as u32;- if i % 2 == 1 {- v *= 2;- if v > 9 {- v -= 9;- }- }- sum += v;- }- sum.is_multiple_of(10)-}--/// Validate that a dotted-quad match is a real IPv4 address (each octet 0–255).-pub(crate) fn is_ipv4(raw: &str) -> bool {- let octets: Vec<&str> = raw.split('.').collect();- octets.len() == 4- && octets- .iter()- .all(|o| !o.is_empty() && o.parse::<u32>().is_ok_and(|n| n <= 255))-}--/// The full, process-wide rule set. Compiled lazily on first [`scan`] call and-/// reused for the life of the process.-///-/// [`scan`]: super::detector::scan-pub(crate) fn rules() -> &'static [Rule] {- static RULES: LazyLock<Vec<Rule>> = LazyLock::new(build_rules);- &RULES-}--fn build_rules() -> Vec<Rule> {- vec![- // --- structured identifiers -------------------------------------- // Email.- pattern_rule(- PiiCategory::Email,- r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b",- None,- ),- // US Social Security Number (3-2-4, dash or space separated). The- // separator requirement keeps it distinct from phone numbers (3-3-4)- // and from bare 9-digit blobs.- pattern_rule(- PiiCategory::NationalId,- r"\b\d{3}[-\s]\d{2}[-\s]\d{4}\b",- None,- ),- // Payment card: 13–19 digits with optional single separators, then- // Luhn-validated so version strings / IDs don't false-positive.- pattern_rule(- PiiCategory::CreditCard,- r"\b\d(?:[ -]?\d){12,18}\b",- Some(is_luhn_valid),- ),- // IBAN bank account: 2-letter country + 2 check digits + 11–30 alnum.- pattern_rule(- PiiCategory::BankAccount,- r"\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b",- None,- ),- // US-style phone number (3-3-4 groups, requires a separator so it- // doesn't swallow arbitrary 10-digit numbers).- pattern_rule(- PiiCategory::PhoneNumber,- r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b",- None,- ),- // International E.164-ish phone number (leading + and 7–15 digits).- pattern_rule(PiiCategory::PhoneNumber, r"\+\d(?:[\d\s\-]{6,16}\d)", None),- // IPv4 address (octet-validated).- pattern_rule(- PiiCategory::IpAddress,- r"\b(?:\d{1,3}\.){3}\d{1,3}\b",- Some(is_ipv4),- ),- // Street / postal address (number + words + street-type keyword).- pattern_rule(- PiiCategory::PostalAddress,- r"(?i)\b\d{1,6}\s+[A-Za-z0-9.'\- ]{2,40}?\b(?:street|st|avenue|ave|road|rd|boulevard|blvd|lane|ln|drive|dr|court|ct|way|place|pl|terrace|ter|circle|cir|highway|hwy)\b",- None,- ),- // Date of birth (explicit context — pattern-based, not a keyword list).- pattern_rule(- PiiCategory::DateOfBirth,- r"(?i)\b(?:date of birth|d\.?o\.?b\.?|birth ?date|born on)\b",- None,- ),- // --- sensitive topical context (keyword-based) ------------------- keyword_rule(PiiCategory::Passport, &["passport"]),- keyword_rule(- PiiCategory::Medical,- &[- "patient",- "diagnosis",- "diagnosed",- "prescription",- "prescribed",- "symptom",- "symptoms",- "medication",- "medications",- "treatment",- "physician",- "hospital",- "clinic",- "disease",- "medical record",- "health record",- "mrn",- "blood pressure",- "dosage",- "therapy",- "biopsy",- "oncology",- "cardiology",- "psychiatric",- "mental health",- "allergy",- "allergies",- ],- ),- keyword_rule(- PiiCategory::Legal,- &[- "plaintiff",- "defendant",- "attorney",- "lawsuit",- "litigation",- "case number",- "docket",- "subpoena",- "settlement",- "indictment",- "deposition",- "legal counsel",- "prosecution",- "testimony",- "affidavit",- "arraignment",- "felony",- "misdemeanor",- "custody",- "court order",- ],- ),- keyword_rule(- PiiCategory::Financial,- &[- "bank account",- "account number",- "routing number",- "salary",- "annual income",- "credit score",- "tax id",- "invoice",- "sort code",- "swift code",- "wire transfer",- "mortgage",- "loan balance",- "net worth",- "iban",- ],- ),- keyword_rule(- PiiCategory::Family,- &[- "spouse",- "wife",- "husband",- "daughter",- "son",- "children",- "minor child",- "maiden name",- "next of kin",- "dependent",- "marital status",- "guardian",- "sibling",- ],- ),- ]-}diff --git a/crates/openhuman-core/src/security/pii/types.rs b/crates/openhuman-core/src/security/pii/types.rsdeleted file mode 100644index b6d306bdd9..0000000000--- a/crates/openhuman-core/src/security/pii/types.rs+++ /dev/null@@ -1,221 +0,0 @@-//! Result + category types for the local PII / identification-risk detector-//! (privacy epic #4256, slice S5).-//!-//! ## Privacy note-//! The detector deliberately reports **categories and counts only** — never-//! the raw matched substrings. The whole point of S5 is to reason about-//! identification risk *without* copying the sensitive value anywhere, so the-//! result type itself must not become a new PII sink (mirrors the "no response-//! body in telemetry" rule the codebase already follows).--use serde::{Deserialize, Serialize};--/// Identification-risk level assigned to a scanned piece of content.-///-/// Ordered `None < Low < Medium < High` (declaration order drives the derived-/// `Ord`), so callers can gate behaviour with a plain comparison such as-/// `result.level >= RiskLevel::Medium`.-///-/// The detector is tuned toward **recall**: a false positive (flagging benign-/// text) is far cheaper than a false negative (letting a real identifier leave-/// the machine unflagged), so the thresholds lean toward escalation.-#[derive(- Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,-)]-#[serde(rename_all = "snake_case")]-pub enum RiskLevel {- /// No identification-risk signal found.- #[default]- None,- /// A single weak signal (e.g. one email or phone number in isolation).- Low,- /// A moderate signal — sensitive topical context, or a couple of- /// co-occurring identifiers.- Medium,- /// A strong signal — a high-confidence identifier (SSN, card, passport,- /// bank account) or several co-occurring categories that together look- /// like a real record.- High,-}--impl RiskLevel {- /// Stable lowercase identifier (matches the serde representation).- pub fn as_str(self) -> &'static str {- match self {- RiskLevel::None => "none",- RiskLevel::Low => "low",- RiskLevel::Medium => "medium",- RiskLevel::High => "high",- }- }-- /// `true` when the content carries any identification risk at all- /// (anything above [`RiskLevel::None`]). Downstream gates (S3 indicator,- /// S4 sensitive-transfer gate) use this as the coarse "should we care?"- /// signal.- pub fn is_sensitive(self) -> bool {- self > RiskLevel::None- }-}--/// A single identification-risk category the detector knows how to recognise.-///-/// The set covers both **structured identifiers** (pattern-matched: email,-/// phone, national ID/SSN, card, bank account, IP, postal address) and-/// **sensitive topical context** (keyword-matched: medical, legal, financial,-/// family, date-of-birth, passport) — the category set called out in the S5-/// scope (patient / legal / financial / family / personal identifiers).-///-/// Serde uses stable `snake_case` identifiers so the values are safe to carry-/// across the RPC / event-bus boundary and into the S2 egress descriptor-/// without a breaking reshape.-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum PiiCategory {- // --- structured identifiers (pattern-based) ---- /// Email address (`[email protected]`).- Email,- /// Telephone number (US or international formats).- PhoneNumber,- /// National identifier — US Social Security Number and similar- /// dash/space-separated government IDs.- NationalId,- /// Payment card number (validated with the Luhn checksum).- CreditCard,- /// Bank account number in IBAN form.- BankAccount,- /// IPv4 address (octet-validated).- IpAddress,- /// Street / postal address.- PostalAddress,- // --- sensitive topical context (keyword-based) ---- /// Date of birth (explicit "DOB" / "date of birth" context).- DateOfBirth,- /// Passport reference.- Passport,- /// Medical / patient / health information.- Medical,- /// Legal / litigation / case information.- Legal,- /// Financial / banking / income information.- Financial,- /// Family / next-of-kin / personal-relationship information.- Family,-}--impl PiiCategory {- /// Stable lowercase identifier (matches the serde representation). Handy- /// for logs and for downstream code that keys off the string form.- pub fn as_str(self) -> &'static str {- match self {- PiiCategory::Email => "email",- PiiCategory::PhoneNumber => "phone_number",- PiiCategory::NationalId => "national_id",- PiiCategory::CreditCard => "credit_card",- PiiCategory::BankAccount => "bank_account",- PiiCategory::IpAddress => "ip_address",- PiiCategory::PostalAddress => "postal_address",- PiiCategory::DateOfBirth => "date_of_birth",- PiiCategory::Passport => "passport",- PiiCategory::Medical => "medical",- PiiCategory::Legal => "legal",- PiiCategory::Financial => "financial",- PiiCategory::Family => "family",- }- }-- /// Scoring weight contributed when this category is present. Higher =- /// stronger identification signal. Tuned toward recall — see- /// [`crate::security::pii::detector`] for how weights combine.- pub(crate) fn weight(self) -> u32 {- match self {- // High-confidence direct identifiers — enough to flag on their own.- PiiCategory::NationalId => 50,- PiiCategory::CreditCard => 50,- PiiCategory::Passport => 45,- PiiCategory::BankAccount => 40,- // Sensitive topical context.- PiiCategory::Medical => 30,- PiiCategory::Legal => 25,- PiiCategory::Financial => 25,- // Moderate identifiers.- PiiCategory::DateOfBirth => 20,- PiiCategory::PostalAddress => 20,- PiiCategory::Family => 20,- // Weak / commonly-shared identifiers.- PiiCategory::Email => 15,- PiiCategory::PhoneNumber => 15,- PiiCategory::IpAddress => 10,- }- }-- /// Whether this category is a concrete identifying value (an address, a- /// number) rather than topical context. These are what- /// [`crate::security::pii::redact_identifiers`] replaces.- pub fn is_structured_identifier(self) -> bool {- matches!(- self,- PiiCategory::Email- | PiiCategory::PhoneNumber- | PiiCategory::NationalId- | PiiCategory::CreditCard- | PiiCategory::BankAccount- | PiiCategory::IpAddress- | PiiCategory::PostalAddress- )- }-- /// A "strong identifier" is a high-confidence, directly-identifying value- /// whose mere presence should force [`RiskLevel::High`], independent of the- /// numeric score. Guards recall against future weight edits.- pub fn is_strong_identifier(self) -> bool {- matches!(- self,- PiiCategory::NationalId- | PiiCategory::CreditCard- | PiiCategory::Passport- | PiiCategory::BankAccount- )- }-}--/// Per-category match tally. Carries the category and how many times it was-/// seen — never the matched text itself.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-pub struct CategoryHit {- /// Which category matched.- pub category: PiiCategory,- /// Number of matches for this category across the scanned content.- pub count: usize,-}--/// Outcome of scanning a piece of content for identification risk.-///-/// This is the public contract S3/S4 (and, after rebase, the S2 egress-/// descriptor) consume. It intentionally holds only the risk level, a numeric-/// score, and the matched categories/counts — no raw values.-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct PiiScanResult {- /// Overall identification-risk level.- pub level: RiskLevel,- /// Numeric score behind [`level`](Self::level). Exposed for callers that- /// want a finer-grained ranking than the four-way enum.- pub score: u32,- /// Distinct categories detected, sorted and de-duplicated for- /// deterministic output.- pub categories: Vec<PiiCategory>,- /// Per-category match counts, sorted by category.- pub hits: Vec<CategoryHit>,-}--impl PiiScanResult {- /// Convenience: content carries at least some identification risk.- pub fn is_sensitive(&self) -> bool {- self.level.is_sensitive()- }-- /// Convenience: was a specific category detected?- pub fn has_category(&self, category: PiiCategory) -> bool {- self.categories.contains(&category)- }-}diff --git a/vendor/tinymemory b/vendor/tinymemoryindex 2dbe05f0cc..f64c0c4a1c 160000--- a/vendor/tinymemory+++ b/vendor/tinymemory@@ -1 +1 @@-Subproject commit 2dbe05f0ccc202158302180bdc90595a85dc4f6d+Subproject commit f64c0c4a1c37956cce00cbedcb50cfdbcd6582d9