feat(stdlib): Mid2 M10 stats and log fields

Add thin mean/median/stdev and optional structured fields on log
lines; close Mid2 M7–M10 (zip skipped).

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-09 09:42:13 +08:00
1 parent 955834e453
commit 784d5ec346
22 files changed
+394 -32

No files matched your search

+25 -3
View File
@@ -3,8 +3,8 @@
use std::collections::HashMap;
use crate::host::{
cli, csv, datetime, encoding, fs, hash, html_ops, json, log, math, net, path, re, secrets, sys,
text_ops, time, toml_ops, url_ops, uuid_ops, writeback, HostContext,
cli, csv, datetime, encoding, fs, hash, html_ops, json, log, math, net, path, re, secrets, stats,
sys, text_ops, time, toml_ops, url_ops, uuid_ops, writeback, HostContext,
};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
@@ -195,6 +195,9 @@ pub enum HostFn {
FsRemoveTree = 186,
FsStat = 187,
FsWalk = 188,
StatsMean = 189,
StatsMedian = 190,
StatsStdev = 191,
}
@@ -380,6 +383,9 @@ impl HostFn {
186 => Self::FsRemoveTree,
187 => Self::FsStat,
188 => Self::FsWalk,
189 => Self::StatsMean,
190 => Self::StatsMedian,
191 => Self::StatsStdev,
_ => return None,
})
}
@@ -568,6 +574,9 @@ impl HostFn {
"host_remove_tree" | "remove_tree" => Self::FsRemoveTree,
"host_stat" | "stat" => Self::FsStat,
"host_walk" | "walk" => Self::FsWalk,
"host_stats_mean" | "stats_mean" => Self::StatsMean,
"host_stats_median" | "stats_median" => Self::StatsMedian,
"host_stats_stdev" | "stats_stdev" => Self::StatsStdev,
_ => return None,
})
}
@@ -743,6 +752,9 @@ impl HostFn {
Self::FsRemoveTree => "host_remove_tree",
Self::FsStat => "host_stat",
Self::FsWalk => "host_walk",
Self::StatsMean => "host_stats_mean",
Self::StatsMedian => "host_stats_median",
Self::StatsStdev => "host_stats_stdev",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -867,6 +879,7 @@ impl HostFn {
Self::LogSetLevel => &["level"],
Self::LogLine => &["level", "text"],
Self::UuidV4 => &[],
Self::StatsMean | Self::StatsMedian | Self::StatsStdev => &["list"],
Self::DatetimeNow => &[],
Self::DatetimeFromUnix => &["unix"],
Self::DatetimeToUnix => &["dt"],
@@ -920,6 +933,7 @@ impl HostFn {
Self::DatetimeParse => &["pattern"],
Self::DatetimeFormat => &["style"],
Self::DatetimeAdd => &["days", "hours", "minutes", "seconds"],
Self::LogLine => &["fields"],
_ => &[],
}
}
@@ -1372,7 +1386,15 @@ pub fn call_host(
HostFn::ListFlatten => super::collection::list_flatten(require(bound, "list")?),
HostFn::CliParse => cli::parse(ctx, bound.get("args")),
HostFn::LogSetLevel => log::set_level(ctx, require(bound, "level")?),
HostFn::LogLine => log::line(ctx, require(bound, "level")?, require(bound, "text")?),
HostFn::LogLine => log::line(
ctx,
require(bound, "level")?,
require(bound, "text")?,
bound.get("fields"),
),
HostFn::StatsMean => stats::mean(require(bound, "list")?),
HostFn::StatsMedian => stats::median(require(bound, "list")?),
HostFn::StatsStdev => stats::stdev(require(bound, "list")?),
HostFn::UuidV4 => uuid_ops::v4(),
HostFn::DatetimeNow => datetime::now(),
HostFn::DatetimeFromUnix => {
+34 -2
View File
@@ -46,13 +46,32 @@ pub fn set_level(ctx: &mut HostContext, level: &Value) -> Result<Value, String>
}
/// Return a ready-to-print line, or `None` if filtered out.
pub fn line(ctx: &HostContext, level: &Value, text: &Value) -> Result<Value, String> {
/// Optional `fields` map is appended as `key=value` pairs (stable map order).
pub fn line(
ctx: &HostContext,
level: &Value,
text: &Value,
fields: Option<&Value>,
) -> Result<Value, String> {
let lvl = Level::parse(as_text(level, "level")?)?;
let msg = as_text(text, "text")?;
if (lvl as u8) < ctx.log_min_level {
return Ok(Value::None);
}
Ok(Value::Text(format!("{} {}", lvl.label(), msg)))
let mut out = format!("{} {}", lvl.label(), msg);
match fields {
None | Some(Value::None) => {}
Some(Value::Map(entries)) => {
for (k, v) in entries {
out.push(' ');
out.push_str(k);
out.push('=');
out.push_str(&v.as_display());
}
}
Some(_) => return Err("log: fields must be a map".into()),
}
Ok(Value::Text(out))
}
#[cfg(test)]
@@ -67,6 +86,7 @@ mod tests {
&ctx,
&Value::Text("debug".into()),
&Value::Text("x".into()),
None,
)
.unwrap();
assert_eq!(filtered, Value::None);
@@ -75,8 +95,20 @@ mod tests {
&ctx,
&Value::Text("debug".into()),
&Value::Text("x".into()),
None,
)
.unwrap();
assert_eq!(shown, Value::Text("DEBUG x".into()));
let with = line(
&ctx,
&Value::Text("info".into()),
&Value::Text("hi".into()),
Some(&Value::Map(vec![
("user".into(), Value::Text("a".into())),
("n".into(), Value::Int(1)),
])),
)
.unwrap();
assert_eq!(with, Value::Text("INFO hi user=a n=1".into()));
}
}
+1
View File
@@ -24,6 +24,7 @@ mod net;
mod path;
mod re;
mod secrets;
mod stats;
mod text_ops;
mod time;
mod toml_ops;
+87
View File
@@ -0,0 +1,87 @@
//! Thin statistics for Mid2 M10 (`lib/stats`). Not a dataframe library.
use crate::value::Value;
fn as_nums(list: &Value) -> Result<Vec<f64>, String> {
let Value::List(xs) = list else {
return Err("stats: list of numbers required".into());
};
let mut out = Vec::with_capacity(xs.len());
for (i, x) in xs.iter().enumerate() {
match x {
Value::Int(n) => out.push(*n as f64),
Value::Num(n) => out.push(*n),
_ => return Err(format!("stats: item {i} must be number")),
}
}
Ok(out)
}
fn num_val(n: f64) -> Value {
if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) {
Value::Int(n as i64)
} else {
Value::Num(n)
}
}
pub fn mean(list: &Value) -> Result<Value, String> {
let xs = as_nums(list)?;
if xs.is_empty() {
return Err("stats.mean: empty list".into());
}
let sum: f64 = xs.iter().sum();
Ok(Value::Num(sum / xs.len() as f64))
}
pub fn median(list: &Value) -> Result<Value, String> {
let mut xs = as_nums(list)?;
if xs.is_empty() {
return Err("stats.median: empty list".into());
}
xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
let n = xs.len();
let m = if n % 2 == 1 {
xs[n / 2]
} else {
(xs[n / 2 - 1] + xs[n / 2]) / 2.0
};
Ok(num_val(m))
}
/// Sample standard deviation (n >= 2), matching common `stdev` semantics.
pub fn stdev(list: &Value) -> Result<Value, String> {
let xs = as_nums(list)?;
if xs.len() < 2 {
return Err("stats.stdev: need at least 2 values".into());
}
let n = xs.len() as f64;
let mean = xs.iter().sum::<f64>() / n;
let var = xs.iter().map(|x| {
let d = x - mean;
d * d
}).sum::<f64>()
/ (n - 1.0);
Ok(Value::Num(var.sqrt()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let xs = Value::List(vec![
Value::Int(1),
Value::Int(2),
Value::Int(3),
Value::Int(4),
]);
let m = mean(&xs).unwrap();
assert_eq!(m, Value::Num(2.5));
assert_eq!(median(&xs).unwrap(), Value::Num(2.5));
let s = stdev(&xs).unwrap();
let Value::Num(v) = s else { panic!() };
assert!((v - 1.2909944487358056).abs() < 1e-9);
}
}