K5: byte caps become generous guards; the fill is length-neutral (map 16.8, I16.5)

- Defaults: identity_bytes 700, bond_summary_bytes 600, item_bytes 700,
  context_bytes 4500, the engineered tuning's values made the code's. They are
  guards a seed written to the standard's targets never meets; focus stays with
  the pool caps, the word budgets and the frame.
- The scored fill stops at the first candidate that would pass the context
  budget instead of skipping it for a shorter one, so which notes reach the
  packet never depends on an item's length.
- The packet reports what a guard cut: `clipped` holds `(identity)` when the
  name or voice was clipped and the ids of clipped bonds and items; the
  select-only report carries it, so a seed's clips are visible for free.
- Tests: the old skip-to-shorter test becomes its negative (a long high-score
  item and a short low-score one under a tight budget: never the short one
  alone); a rich seed at the authoring targets reports no clip; every clip of
  the adversarial state is reported; budget asserts read the default guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-20 14:18:53 +01:00
commit ca62d6c918
4 changed files with 77 additions and 23 deletions

View file

@ -232,6 +232,7 @@ fn packet_json(packet: &Packet) -> Value {
"selected": packet.selected,
"bytes": { "identity": packet.identity().len(), "context": packet.context.len(), "identity_and_context": packet.identity().len() + packet.context.len(), "stimulus": packet.stimulus.len(), "heard": packet.heard.len() },
"overflow": packet.overflow,
"clipped": packet.clipped,
"name": packet.name,
"voice": packet.voice,
"context": packet.context,

View file

@ -264,6 +264,9 @@ pub(crate) struct Packet {
pub bodies: Vec<String>,
/// The words of each private item this packet shows her as known privately: none of them may be said in this room.
pub private: Vec<String>,
/// What a byte guard cut (map 16.8): the ids of the bonds and items whose words it clipped, and `(identity)` when it
/// clipped her name or voice. Empty for a seed written to the standard's targets.
pub clipped: Vec<String>,
}
/// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the
@ -283,6 +286,8 @@ struct Candidate {
log_score: f64,
/// The item's words, when the line shows them as known privately.
private: Option<String>,
/// Whether `item_bytes` cut its words.
clipped: bool,
}
// ---------------------------------------------------------------------------------------------
@ -524,7 +529,7 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet<String>, touc
Scope::Plain => (words.to_owned(), None),
};
let log_score = salience.ln() + recency + touch.ln() + unresolved.ln() + freshness_log(id, inputs.history, tuning);
out.push(Candidate { id: id.to_owned(), pool, line: line(&clip(&shown, item_bytes)), log_score, private });
out.push(Candidate { id: id.to_owned(), pool, line: line(&clip(&shown, item_bytes)), log_score, private, clipped: shown.trim().len() > item_bytes });
};
let scoped = |item: &Value| scope(inputs, concerns(&inputs.people, item).as_ref(), present);
@ -947,8 +952,9 @@ fn joined(name: &str, voice: &str) -> String {
if voice.is_empty() { name.to_owned() } else { format!("{name}. {voice}") }
}
/// Her name with her pronouns, and her voice, together within `identity_bytes`: the name first, the voice in what is left.
fn identity_of(state: &Value, tuning: &Tuning) -> (String, String) {
/// Her name with her pronouns, and her voice, together within `identity_bytes`: the name first, the voice in what is left;
/// and whether the guard cut either.
fn identity_of(state: &Value, tuning: &Tuning) -> (String, String, bool) {
let name = text(state, &["publicName"]);
let pronouns = text(state, &["presentation", "pronouns"]);
let whole = if pronouns.is_empty() { name.to_owned() } else { format!("{name} ({pronouns})") };
@ -956,8 +962,9 @@ fn identity_of(state: &Value, tuning: &Tuning) -> (String, String) {
let voice = one_line(text(state, &["presentation", "voiceSummary"]));
// A name the guard clipped took all the room: no voice after it.
let room = if head.len() < whole.trim().len() { 0 } else { tuning.select.identity_bytes.saturating_sub(head.len() + ". ".len()) };
let voice = if voice.is_empty() || room <= '…'.len_utf8() { String::new() } else { clip(&voice, room) };
(head, voice)
let shown = if voice.is_empty() || room <= '…'.len_utf8() { String::new() } else { clip(&voice, room) };
let clipped = head.len() < whole.trim().len() || shown != voice;
(head, shown, clipped)
}
/// The names of unbonded people present, as many as fit `ALSO_HERE_BYTES`, then how many more.
@ -1301,7 +1308,8 @@ impl Context {
pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
let mut draw = Draw(inputs.seed);
let (name, voice) = identity_of(inputs.state, tuning);
let (name, voice, identity_clipped) = identity_of(inputs.state, tuning);
let mut clipped: Vec<String> = if identity_clipped { vec!["(identity)".to_owned()] } else { Vec::new() };
let (stimulus, heard, overflow) = match inputs.kind {
TurnKind::Chat => chat_stimulus(inputs, tuning),
TurnKind::Beat => (beat_stimulus(inputs, tuning), String::new(), Overflow::default()),
@ -1332,6 +1340,9 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
if context.push(Section::People, bond_line(bond, name, tuning, scope, her)) {
full += 1;
ids.push(text(bond, &["id"]).to_owned());
if scope != Scope::Omitted && one_line(text(bond, &["summary"])).len() > tuning.select.bond_summary_bytes {
clipped.push(text(bond, &["id"]).to_owned());
}
if scope == Scope::Framed && !text(bond, &["summary"]).is_empty() {
private.push(one_line(text(bond, &["summary"])));
}
@ -1368,8 +1379,10 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
if !include || taken.iter().filter(|kept| kept.pool == candidate.pool).count() >= cap_of(candidate.pool, tuning) {
continue;
}
// Length-neutral (I16.5): the fill stops at the first candidate that would pass the budget, so a shorter item with
// a lower score never takes a longer one's place.
if !context.push(Section::Notes, candidate.line.clone()) {
continue;
break;
}
taken.push(candidate);
}
@ -1381,11 +1394,12 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
let lens = draw_lens(&tuning.lens, &present_names, &taken, &mut draw);
ids.extend(taken.iter().map(|candidate| candidate.id.clone()));
private.extend(taken.iter().filter_map(|candidate| candidate.private.clone()));
clipped.extend(taken.iter().filter(|candidate| candidate.clipped).map(|candidate| candidate.id.clone()));
let bodies = match inputs.kind {
TurnKind::Chat => inputs.room.messages.iter().map(|line| line.text.clone()).collect(),
TurnKind::Beat => beat_tail(inputs, tuning).iter().map(|line| line.text.clone()).collect(),
TurnKind::FollowUp | TurnKind::Reflection => Vec::new(),
};
let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect();
Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), stimulus, heard, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), bodies, private }
Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), stimulus, heard, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), bodies, private, clipped }
}

View file

@ -453,7 +453,8 @@ fn budgets_hold_under_adversarial_sizes() {
for seed in 1..=10 {
let packet = packet_of(kind, &big, &room, &History::default(), seed);
assert!(packet.identity().len() <= tuning.select.identity_bytes, "identity {}", packet.identity().len());
assert!(packet.identity().len() + packet.context.len() <= 2500, "{kind:?}: packet {} bytes", packet.identity().len() + packet.context.len());
assert!(packet.identity().len() + packet.context.len() <= tuning.select.context_bytes, "{kind:?}: packet {} bytes", packet.identity().len() + packet.context.len());
assert!(packet.clipped.first().is_some_and(|first| first == "(identity)") && packet.selected.iter().filter(|pick| pick.id[1..].parse::<u32>().is_ok()).all(|pick| packet.clipped.contains(&pick.id)), "every clip is reported: {:?}", packet.clipped);
assert!(packet.stimulus.len() <= 1500 && packet.heard.len() <= 1500, "{kind:?}: stimulus {} heard {}", packet.stimulus.len(), packet.heard.len());
}
}
@ -478,13 +479,13 @@ fn a_crowd_or_a_huge_label_never_squeezes_out_the_mood() {
let messages: Vec<RoomLine> = (0..300).map(|at| message("#swarm:gamecult.org", &format!("@stranger{at}:gamecult.org"), &format!("Stranger {at}"), "hi", 300 - at, false)).collect();
let packet = packet_of(TurnKind::Chat, &state(), &Room { messages, ..Room::default() }, &History::default(), 1);
assert!(packet.context.contains("- mood") && packet.context.contains("- also here: \"Stranger 299\" (@stranger299:gamecult.org)") && packet.context.contains(" more"), "{}", packet.context);
assert!(packet.identity().len() + packet.context.len() <= 2500);
assert!(packet.identity().len() + packet.context.len() <= Tuning::default().select.context_bytes);
let mut huge = state();
huge["affect"]["socialBonds"] = json!([{ "id": "bond-libby", "object": { "id": "libby", "kind": "person", "label": "L".repeat(3000) }, "relationshipKind": "k".repeat(3000), "status": "active", "summary": "s" }]);
let room = Room { messages: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", "hi", 1, true)], ..Room::default() };
let packet = packet_of(TurnKind::Chat, &huge, &room, &History::default(), 1);
assert!(packet.context.contains("- mood") && packet.context.contains("- bond [bond-libby]"), "{}", packet.context);
assert!(packet.identity().len() + packet.context.len() <= 2500 && packet.heard.len() < 3000);
assert!(packet.identity().len() + packet.context.len() <= Tuning::default().select.context_bytes && packet.heard.len() < 3000);
}
#[test]
@ -498,21 +499,55 @@ fn the_identity_cap_holds_on_its_own() {
}
#[test]
fn a_candidate_that_does_not_fit_is_skipped_and_a_shorter_one_still_fits() {
fn the_fill_stops_at_the_first_candidate_that_does_not_fit_and_never_takes_a_shorter_one_in_its_place() {
// A long value with a high score and a short one with a low score, under a budget the short one alone would fit.
let state = json!({ "publicName": "Eureka", "values": [
{ "id": "long", "label": "Long", "priority": 0.9, "summary": "y".repeat(380) },
{ "id": "short", "label": "Short", "priority": 0.9, "summary": "fits" },
{ "id": "short", "label": "Short", "priority": 0.05, "summary": "fits" },
] });
let mut tuning = Tuning::default();
tuning.select.caps.value = 2;
tuning.select.inclusion_score = 1e-9;
// Ordered by score alone: the long one is always drawn first.
tuning.select.temperature = 0.01;
let fixed = packet_tuned(TurnKind::Beat, &json!({ "publicName": "Eureka" }), &Room::default(), &History::default(), 1, &tuning);
tuning.select.context_bytes = fixed.identity().len() + fixed.context.len() + 1 + "Notes about them, set down at another time:\n".len() + 60;
for seed in 1..=10 {
let mut neither = 0;
for seed in 1..=40 {
let packet = packet_tuned(TurnKind::Beat, &state, &Room::default(), &History::default(), seed, &tuning);
assert_eq!(ids(&packet), ["short"], "seed {seed}: {}", packet.context);
let taken = ids(&packet);
assert!(taken != ["short"], "seed {seed}: the short one took the long one's place: {}", packet.context);
neither += usize::from(taken.is_empty());
assert!(packet.identity().len() + packet.context.len() <= tuning.select.context_bytes);
}
assert_eq!(neither, 40, "the long one, drawn first, stops the fill");
// Under the guard, both are taken.
tuning.select.context_bytes = Tuning::default().select.context_bytes;
let packet = packet_tuned(TurnKind::Beat, &state, &Room::default(), &History::default(), 1, &tuning);
assert_eq!(ids(&packet).len(), 2, "{}", packet.context);
}
#[test]
fn the_guards_are_generous_and_a_seed_within_them_reports_no_clip() {
let guards = Tuning::default().select;
assert_eq!((guards.identity_bytes, guards.bond_summary_bytes, guards.item_bytes, guards.context_bytes), (700, 600, 700, 4500));
// A rich seed at the standard's upper targets: a 500-byte voice, 450-byte bonds and thoughts.
let mut rich = state();
rich["presentation"]["voiceSummary"] = json!("v".repeat(500));
for bond in rich["affect"]["socialBonds"].as_array_mut().unwrap() {
bond["summary"] = json!("b".repeat(450));
}
rich["thoughtMemory"]["memories"] = Value::Array((0..6).map(|at| json!({ "id": format!("m{at}"), "summary": "m".repeat(400), "tension": "t".repeat(49), "createdAt": hours_ago(1), "status": "crystallized" })).collect());
for seed in 1..=20 {
let packet = packet_of(TurnKind::Chat, &rich, &chat_room(), &History::default(), seed);
assert!(packet.clipped.is_empty() && !packet.context.contains('\u{2026}'), "seed {seed}: {:?}", packet.clipped);
assert!(packet.identity().len() + packet.context.len() <= guards.context_bytes);
}
let mut long = rich.clone();
long["affect"]["socialBonds"][0]["summary"] = json!("b".repeat(601));
long["presentation"]["voiceSummary"] = json!("v".repeat(700));
let packet = packet_of(TurnKind::Chat, &long, &chat_room(), &History::default(), 1);
assert_eq!(packet.clipped[..2], ["(identity)".to_owned(), "bond-libby".to_owned()], "{:?}", packet.clipped);
}
#[test]
@ -522,7 +557,7 @@ fn clipping_never_splits_a_grapheme() {
let packet = packet_of(TurnKind::Beat, &family, &Room::default(), &History::default(), 1);
let identity = packet.identity();
let body = identity.trim_end_matches('…');
assert!(identity.len() <= 300 && !body.ends_with('\u{200d}') && body.ends_with('👦'), "{identity:?}");
assert!(identity.len() <= Tuning::default().select.identity_bytes && body.len() < identity.len() && !body.ends_with('\u{200d}') && body.ends_with('👦'), "{identity:?}");
}
#[test]
@ -573,7 +608,7 @@ fn tuning_absent_is_the_defaults_and_a_file_overrides_and_an_unknown_key_refuses
std::fs::write(&path, "[select]\ntemperature = 0.3\n\n[select.caps]\nvalue = 3\n\n[projector]\nwords = 120\n").unwrap();
let file = tuning::load(&path).unwrap();
assert_eq!((file.tuning.select.temperature, file.tuning.select.caps.value, file.tuning.projector.words, file.source), (0.3, 3, 120, "file"));
assert_eq!(file.tuning.select.context_bytes, 2500, "an unnamed key keeps its default");
assert_eq!(file.tuning.select.context_bytes, 4500, "an unnamed key keeps its default");
assert_ne!(file.sha256, absent.sha256);
std::fs::write(&path, "[select]\ntemprature = 0.3\n").unwrap();
assert!(format!("{:#}", tuning::load(&path).unwrap_err()).contains("temprature"), "a mistyped knob refuses the file");
@ -584,7 +619,7 @@ fn the_hash_is_of_the_effective_tuning() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(TUNING_FILE);
let absent = tuning::load(&path).unwrap();
std::fs::write(&path, "[select]\ntemperature = 0.7\ncontext_bytes = 2500\n\n[projector]\nwords = 150\n").unwrap();
std::fs::write(&path, "[select]\ntemperature = 0.7\ncontext_bytes = 4500\n\n[projector]\nwords = 150\n").unwrap();
let spelled = tuning::load(&path).unwrap();
assert_eq!((absent.source, spelled.source), ("defaults", "file"));
assert_eq!(absent.sha256, spelled.sha256, "a file that spells out the defaults is the defaults");

View file

@ -104,6 +104,10 @@ pub struct PersonaTuning {
}
/// The selection: its temperature and inclusion, its budgets, its half-life, the freshness decay and the pool caps.
///
/// The `*_bytes` of the identity, a bond, an item and the context are guards, not focus controls (map 16.8): a seed
/// written to the Persona State Standard's targets never meets them. Focus is the pool caps', the word budgets' and the
/// Projector frame's.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SelectTuning {
@ -111,7 +115,7 @@ pub struct SelectTuning {
pub temperature: f64,
/// The score at which a candidate is included 63% of the time: inclusion is `1 - exp(-score / inclusion_score)`.
pub inclusion_score: f64,
/// Identity plus typed context, in bytes.
/// Identity plus typed context, in bytes. The fill stops at the first candidate that would pass it.
pub context_bytes: usize,
pub stimulus_bytes: usize,
/// What was said to her, verbatim, for the Persona stage.
@ -198,13 +202,13 @@ impl Default for SelectTuning {
Self {
temperature: 0.7,
inclusion_score: 0.5,
context_bytes: 2500,
context_bytes: 4500,
stimulus_bytes: 1500,
heard_bytes: 1500,
addressed_bytes: 8 * 1024,
identity_bytes: 300,
bond_summary_bytes: 300,
item_bytes: 400,
identity_bytes: 700,
bond_summary_bytes: 600,
item_bytes: 700,
memory_tau_h: 24.0,
freshness_base: 0.5,
freshness_window: 5,