Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/wire.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ jobs:
run: cargo build -p thrum-core
- name: Generated mirrors are byte-identical to views.rs
run: cargo run -p codegen -- --check
- name: The kernel speaks in code
run: python3 tools/speech.py
- name: Codegen unit tests
run: cargo test -p codegen --lib
- name: Golden fixture round-trips through views
Expand Down
10 changes: 5 additions & 5 deletions hum-nest/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,27 +566,27 @@ impl WireListener {
"content_block_delta" => {
let delta = msg.get("delta").cloned().unwrap_or(json!({}));
let idx = msg.get("index").and_then(Value::as_i64);
let is_tool_block = match idx {
let bridge_reports_tool_whole = match idx {
Some(i) => self.tool_use_blocks.lock().await.contains(&i),
None => false,
};
let block_idx_v = msg.get("index").cloned().unwrap_or(Value::Null);
match delta.get("type").and_then(Value::as_str).unwrap_or("") {
"thinking_delta" => self.chunk("reasoning_delta", json!({"blockIdx": block_idx_v, "delta": delta.get("thinking")})).await,
"text_delta" => self.chunk("text_delta", json!({"blockIdx": block_idx_v, "delta": delta.get("text")})).await,
"input_json_delta" if !is_tool_block => {
"input_json_delta" if !bridge_reports_tool_whole => {
self.chunk("tool_input_delta", json!({"blockIdx": block_idx_v, "partialJson": delta.get("partial_json")})).await
}
_ => {} // tool-block input_json_delta: suppressed (bridge ships chunk:tool_executed instead)
_ => {}
}
}
"content_block_stop" => {
let idx = msg.get("index").and_then(Value::as_i64);
let is_tool_block = match idx {
let bridge_reports_tool_whole = match idx {
Some(i) => self.tool_use_blocks.lock().await.remove(&i),
None => false,
};
if !is_tool_block {
if !bridge_reports_tool_whole {
self.chunk("content_block_stop", json!({"blockIdx": msg.get("index")})).await;
}
}
Expand Down
5 changes: 3 additions & 2 deletions hum-paths/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,13 @@ mod tests {
}

#[test]
fn nest_section_partial() {
fn nest_section_partial_takes_defaults() {
let cfg: HumConfig =
serde_json::from_str(r#"{"nest": {"maxActiveCells": 8, "default": "claude-cli"}}"#).unwrap();
assert_eq!(cfg.nest.max_active_cells, 8);
assert_eq!(cfg.nest.default, "claude-cli");
assert_eq!(cfg.nest.cell_idle_prune_threshold_ms, 300_000); // default fills
let default_threshold = HumConfig::default().nest.cell_idle_prune_threshold_ms;
assert_eq!(cfg.nest.cell_idle_prune_threshold_ms, default_threshold);
}

#[test]
Expand Down
42 changes: 17 additions & 25 deletions humd/src/comb.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
//! Comb — the kernel's measure of what has flowed through it.
//! Comb — the kernel's measure of what crossed it.
//!
//! A comb is a ledger of quantities: a flat map of named counters that
//! accumulates for the life of the install. Two families live in it.
//!
//! **Activity** — what crossed the kernel, by chi:
//! `chi:finish`, `chi:tool-call`, and `bee:claude-cli:chi:finish` for the
//! same count scoped to one hive kind.
//! **Activity** — what crossed the kernel, by chi: `chi:finish`,
//! `chi:tool-call`, and `bee:claude-cli:chi:finish` for the same count
//! scoped to one hive kind. The scoped counts cover the work chis — a
//! turn finished, a tool was called, a tool answered, something went
//! wrong — because those are the ones that name what was done.
//!
//! **Nectar** — what was consumed, by metric: `nectar:in`, `nectar:out`,
//! `nectar:cacheRead`, `nectar:cacheCreate`, and the same scoped to a bee
//! as `bee:claude-cli:nectar:in`. Nectar is the kernel's raw intake —
//! tokens in, tokens out, cache reads and writes. What the kernel
//! produces is honey, and that side belongs to whoever earns it.
//! tokens in, tokens out, cache reads and writes. A hive may name its
//! tokens any of the ways the wilds do: `input_tokens` and `prompt_tokens`
//! are the same measure, and so are their output counterparts. What the
//! kernel produces is honey, and that side belongs to whoever earns it.
//!
//! Only the kernel writes the comb. The daemon sees every tone that
//! crosses it, so the measure is observed rather than self-reported: a bee
//! metering itself would be reporting on itself. Each humd keeps its own
//! comb, so a session that crosses two humds is accounted by each of them
//! rather than counted once globally.
//! metering itself would be reporting on itself. A tone that crossed the
//! mesh has no bee here to answer for it, so it lands in the global family
//! alone. Each humd keeps its own comb, so a session that touches two
//! humds is accounted by each of them rather than counted once.
//!
//! Nothing is measured that was not measured: a hive that reports no
//! usage is measured as having used nothing.
//!
//! Persisted at `${XDG_RUNTIME_DIR}/hum/comb.json`, write-through every
//! `comb_persist_interval`.
Expand All @@ -32,14 +40,8 @@ use parking_lot::RwLock;
use serde_json::Value;
use tracing::{trace, warn};

/// The chis whose counts are also attributed to the hive that sent them.
/// These are the ones that name work done: a turn finished, a tool was
/// called, a tool answered, something went wrong.
pub const WORK_CHIS: [&str; 4] = ["finish", "tool-call", "tool-result", "error"];

/// Token metrics, each with the field names hives use for it. Anthropic
/// calls them `input_tokens`; OpenAI calls them `prompt_tokens`. Both are
/// nectar, and the comb measures them the same way.
pub const TOKEN_METRICS: [(&str, &[&str]); 4] = [
(
"in",
Expand Down Expand Up @@ -89,8 +91,6 @@ pub fn bee_nectar_key(bee: &str, metric: &str) -> String {
format!("bee:{bee}:nectar:{metric}")
}

/// Pull the token counts out of a `chi:"finish"` usage object. A hive that
/// reports no usage measures nothing — the comb does not guess.
pub fn usage_of(usage: Option<&Value>) -> Vec<(&'static str, u64)> {
let Some(obj) = usage.and_then(Value::as_object) else {
return Vec::new();
Expand Down Expand Up @@ -119,14 +119,6 @@ impl Comb {
})
}

/// Record one tone that crossed the kernel.
///
/// `bee` is the hive kind that sent it, when the kernel can attribute
/// it to a bee registered here. A tone that arrived over the mesh has
/// no such attribution: it lands in the global family only.
///
/// `usage` is the token report on a `chi:"finish"`, and is only read
/// for that chi.
pub fn record(&self, chi: &str, bee: Option<&str>, usage: Option<&Value>) {
self.incr(&chi_key(chi));
let tokens = if chi == "finish" {
Expand Down
2 changes: 1 addition & 1 deletion humd/src/drift.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ mod tests {
let d = Drift::new();
d.mark("s1", "first_petal");
std::thread::sleep(std::time::Duration::from_millis(2));
d.mark("s1", "first_petal"); // ignored
d.mark("s1", "first_petal");
d.mark("s2", "first_petal");
let agg = d.aggregates();
assert_eq!(agg.blooms, 2);
Expand Down
2 changes: 1 addition & 1 deletion humd/src/drone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,7 @@ mod tests {

#[test]
fn noop_classifier_never_swallows() {
let d = Drone::new(); // NoopClassifier
let d = Drone::new();
d.observed(
"s1",
Observed::TextDelta {
Expand Down
2 changes: 1 addition & 1 deletion humd/src/thrumd/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async fn read_loop(
loop {
let line = match lines.next_line().await {
Ok(Some(l)) => l,
Ok(None) => break, // EOF
Ok(None) => break,
Err(e) => {
trace!(client_id = %short(client_id), err = %e, "thrum.read.failed");
break;
Expand Down
9 changes: 8 additions & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,16 @@ fmt:
fmt-file file:
rustfmt --edition 2024 {{file}}

# The kernel speaks in code: no `//` and no `///` in the kernel's own
# Rust. `//!` is the module header and is the only comment allowed.
# The hives are exempt — each is a separate workspace, and a kind any
# third party may write in any language.
speech:
python3 tools/speech.py

# Clippy over the crates CI gates on. Same scope, same flags as
# .github/workflows/wire.yml — if this passes, CI passes.
lint:
lint: speech
cargo clippy -p ensemble -p hum-paths --all-targets -- -D warnings -A clippy::type_complexity -A clippy::double_must_use

# Clippy over everything. The daemon and the drone still carry dead
Expand Down
8 changes: 7 additions & 1 deletion thehum/src/anchor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@
//! Real submission needs a funded signer (the chain-side address) and is
//! intentionally deferred — production users wire their own wallet
//! (Foundry script, metamask-snap, etc) and call `prepare_calldata`.
//!
//! The calldata opens with `PLACEHOLDER_SELECTOR` — the real selector is
//! the keccak of the signature, truncated, and is a placeholder until the
//! contract is deployed and its selector is known.

use anyhow::Result;
use async_trait::async_trait;

use crate::{StateRoot, TheHum};

const PLACEHOLDER_SELECTOR: [u8; 4] = [0x4e, 0x71, 0xd9, 0x2d];

#[derive(Debug, Clone)]
pub struct AnchorReceipt {
pub network: String,
Expand Down Expand Up @@ -110,7 +116,7 @@ pub struct EvmAnchor {
impl EvmAnchor {
pub fn prepare_calldata(&self, hid: &str, root: &StateRoot, height: u64, sig_hex: &str) -> Vec<u8> {
let mut bytes = Vec::with_capacity(4 + 32 * 5);
bytes.extend_from_slice(&[0x4e, 0x71, 0xd9, 0x2d]); // placeholder selector
bytes.extend_from_slice(&PLACEHOLDER_SELECTOR);
let mut hid_bytes = [0u8; 32];
let raw = hex::decode(hid.trim_start_matches("humd_")).unwrap_or_default();
let n = raw.len().min(32);
Expand Down
143 changes: 143 additions & 0 deletions tools/speech.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""Check that the kernel speaks in code.

hum's rule: `//` and `///` are forbidden in the kernel's own Rust. `//!`
is the module header and is the only comment form allowed. The name of
every thing should carry its meaning, so a reader never has to scroll
past a wall of prose to find out what a function does.

The hives are exempt. Each one is a separate workspace and a kind any
third party may write in any language, so they are held to their own
community's conventions rather than ours.

Usage: python3 tools/speech.py [--fix-list]

Exits 1 when a forbidden comment is found.
"""

import re
import subprocess
import sys

EXEMPT_PREFIXES = ("hives/", "thrum-clients/")


def strip_literals(src):
"""Blank out string and char literal contents, preserving line count.

A `//` inside a URL or a path is not a comment, so the scanner must
not see it as one.
"""
out = []
i = 0
n = len(src)
while i < n:
c = src[i]
m = re.match(r'r(#*)"', src[i:])
if m:
hashes = m.group(1)
end = src.find('"' + hashes, i + len(m.group(0)))
end = n if end == -1 else end
out.append(" " * (end - i))
i = end + 1 + len(hashes)
continue
if src.startswith('b"', i) or src.startswith('br"', i):
out.append(" ")
i += 1
continue
if c == '"':
out.append(" ")
i += 1
while i < n and src[i] != '"':
if src[i] == "\\":
out.append(" ")
i += 1
if i < n:
out.append(" ")
i += 1
continue
out.append("\n" if src[i] == "\n" else " ")
i += 1
if i < n:
out.append(" ")
i += 1
continue
if c == "'":
j = i + 1
j = j + 2 if (j < n and src[j] == "\\") else j + 1
if j < n and src[j] == "'":
out.append("''")
i = j + 1
continue
out.append("'")
i += 1
continue
out.append(c)
i += 1
return "".join(out)


def scan(src):
"""Return the forbidden comments in src as (lineno, text) pairs."""
found = []
i = 0
n = len(src)
line = 1
while i < n:
c = src[i]
if c == "\n":
line += 1
i += 1
continue
if c == "/" and i + 1 < n and src[i + 1] == "*":
depth = 1
i += 2
while i < n and depth:
if src.startswith("/*", i):
depth += 1
i += 2
continue
if src.startswith("*/", i):
depth -= 1
i += 2
continue
if src[i] == "\n":
line += 1
i += 1
found.append((line, "/* block comment */"))
continue
if c == "/" and i + 1 < n and src[i + 1] == "/":
j = i
while j < n and src[j] != "\n":
j += 1
text = src[i:j]
if not text.startswith("//!"):
found.append((line, text.strip()))
i = j
continue
i += 1
return found


def main():
files = subprocess.run(
["git", "ls-files", "*.rs"], capture_output=True, text=True
).stdout.split()
total = 0
for path in files:
if path.startswith(EXEMPT_PREFIXES):
continue
src = open(path, errors="ignore").read()
found = scan(strip_literals(src))
for lineno, text in found:
print(f"{path}:{lineno}: {text[:100]}")
total += len(found)
if total:
print(f"\n{total} comment(s) in the kernel. The kernel speaks in code.")
return 1
print("the kernel speaks in code — no comments")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading