Compare commits
76 changed files with 890 additions and 20399 deletions
3
Cargo.lock
generated
3
Cargo.lock
generated
|
|
@ -1134,14 +1134,13 @@ dependencies = [
|
||||||
"toml",
|
"toml",
|
||||||
"unicode-general-category",
|
"unicode-general-category",
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
"ureq",
|
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "model-connector"
|
name = "model-connector"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5"
|
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=c1802d85bee3ae04b0c5737563c8343c1fef515d#c1802d85bee3ae04b0c5737563c8343c1fef515d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"base64",
|
"base64",
|
||||||
|
|
|
||||||
|
|
@ -268,9 +268,17 @@ impl<S: MindStore> Mind<S> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
return Err(MindRefusal::MissingIdentity);
|
return Err(MindRefusal::MissingIdentity);
|
||||||
}
|
}
|
||||||
// P1 to P3: the document alone, the one check an offline reader of a state file shares.
|
// P1
|
||||||
|
persona::validate_shape(&state)?;
|
||||||
|
// P2
|
||||||
let mind = self.instance().clone();
|
let mind = self.instance().clone();
|
||||||
persona::validate_document(&mind, &state)?;
|
if state.get("personaId").and_then(Value::as_str) != Some(mind.0.as_str()) {
|
||||||
|
return Err(MindRefusal::PersonaForeign { instance: mind.0 });
|
||||||
|
}
|
||||||
|
// P3
|
||||||
|
if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") {
|
||||||
|
return Err(MindRefusal::PersonaNotCanonical);
|
||||||
|
}
|
||||||
// P4
|
// P4
|
||||||
let stored = self.stored_updated_at()?;
|
let stored = self.stored_updated_at()?;
|
||||||
if stored != expected_updated_at {
|
if stored != expected_updated_at {
|
||||||
|
|
|
||||||
|
|
@ -92,7 +92,7 @@ fn declared_names(node: &Value, names: &mut BTreeSet<String>) {
|
||||||
|
|
||||||
/// Rule 1: the document is valid against the published schema. The first
|
/// Rule 1: the document is valid against the published schema. The first
|
||||||
/// failure is the refusal; it names where and which keyword, never the value.
|
/// failure is the refusal; it names where and which keyword, never the value.
|
||||||
fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
|
pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
|
||||||
let compiled = compiled()?;
|
let compiled = compiled()?;
|
||||||
let Err(error) = compiled.validator.validate(state) else { return Ok(()) };
|
let Err(error) = compiled.validator.validate(state) else { return Ok(()) };
|
||||||
let mut path = error
|
let mut path = error
|
||||||
|
|
@ -115,21 +115,6 @@ fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rules P1 to P3 of a put, the ones that read the document alone: it is valid against the published schema (P1), it is
|
|
||||||
/// this mind's (`personaId` is `instance`, P2), and its provenance is canonical (P3). A put applies these first and then
|
|
||||||
/// the rules that read the store; a reader of a state file outside the mind (`mind-persona project --state`) applies
|
|
||||||
/// these and nothing else, so a file it accepts is one a put would not refuse for its content.
|
|
||||||
pub fn validate_document(instance: &Slug, state: &Value) -> Result<(), MindRefusal> {
|
|
||||||
validate_shape(state)?;
|
|
||||||
if state.get("personaId").and_then(Value::as_str) != Some(instance.0.as_str()) {
|
|
||||||
return Err(MindRefusal::PersonaForeign { instance: instance.0.clone() });
|
|
||||||
}
|
|
||||||
if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") {
|
|
||||||
return Err(MindRefusal::PersonaNotCanonical);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A stored persona envelope's document.
|
/// A stored persona envelope's document.
|
||||||
pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result<Value, MindRefusal> {
|
pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result<Value, MindRefusal> {
|
||||||
rmp_serde::from_slice::<HuginnPersonaEntry>(&envelope.payload)
|
rmp_serde::from_slice::<HuginnPersonaEntry>(&envelope.payload)
|
||||||
|
|
@ -279,50 +264,6 @@ mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map 16.6: `embodiment` is optional. A document passes with it and without it, and the field is as closed as the
|
|
||||||
/// rest of the schema: an unknown key inside it is refused at the door.
|
|
||||||
#[test]
|
|
||||||
fn embodiment_is_optional_and_closed() {
|
|
||||||
let schema = schema_file();
|
|
||||||
let validator = jsonschema::draft7::new(&schema).unwrap();
|
|
||||||
let sense = json!({
|
|
||||||
"id": "sense-spectrogram", "status": "active", "label": "spectrogram hearing",
|
|
||||||
"summary": "She hears by rendering a sound as a spectrogram and looking at it.",
|
|
||||||
"lacks": "not a human ear", "builtOn": T1, "updatedAt": T1
|
|
||||||
});
|
|
||||||
let mut with = persona(INSTANCE, T1);
|
|
||||||
with["embodiment"] = json!({ "senses": [sense.clone()], "actuators": [] });
|
|
||||||
assert!(validator.is_valid(&persona(INSTANCE, T1)) && validator.is_valid(&with));
|
|
||||||
let mut empty = persona(INSTANCE, T1);
|
|
||||||
empty["embodiment"] = json!({});
|
|
||||||
assert!(validator.is_valid(&empty), "both lists are optional");
|
|
||||||
|
|
||||||
let store = MemoryStore::new();
|
|
||||||
let mut mind = seeded_over(&store);
|
|
||||||
let mut stray = with.clone();
|
|
||||||
stray["embodiment"]["senses"][0]["ears"] = json!("human");
|
|
||||||
assert_eq!(refused(put(&mut mind, stray, None)), invalid("/embodiment/senses/0/*", "additionalProperties"));
|
|
||||||
let mut stray_list = with.clone();
|
|
||||||
stray_list["embodiment"]["smell"] = json!([]);
|
|
||||||
assert_eq!(refused(put(&mut mind, stray_list, None)), invalid("/embodiment/*", "additionalProperties"));
|
|
||||||
let mut unlabelled = with;
|
|
||||||
unlabelled["embodiment"]["senses"][0].as_object_mut().unwrap().remove("label");
|
|
||||||
assert_eq!(refused(put(&mut mind, unlabelled, None)), invalid("/embodiment/senses/0/label", "required"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Map 16.35.9 (T1, T2): a hold and a promise are not her state. A put carrying either old field, even empty, is
|
|
||||||
/// is refused at the door. The names are assembled, so a scan for the old fields finds no writer of them.
|
|
||||||
#[test]
|
|
||||||
fn holds_and_promises_are_not_her_state() {
|
|
||||||
for field in [concat!("hol", "ds"), concat!("commit", "ments")] {
|
|
||||||
let store = MemoryStore::new();
|
|
||||||
let mut mind = seeded_over(&store);
|
|
||||||
let mut with = persona(INSTANCE, T1);
|
|
||||||
with[field] = json!([]);
|
|
||||||
assert_eq!(refused(put(&mut mind, with, None)), invalid("/*", "additionalProperties"), "{field}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn declared_names_are_every_property_name_at_any_depth() {
|
fn declared_names_are_every_property_name_at_any_depth() {
|
||||||
let schema = json!({
|
let schema = json!({
|
||||||
|
|
|
||||||
|
|
@ -23,10 +23,8 @@ publish.workspace = true
|
||||||
# two until the workspace pin and the kit's meet.
|
# two until the workspace pin and the kit's meet.
|
||||||
# `rmp-serde` is also the lease wire (`lease_client`): the connector's MessagePack frames.
|
# `rmp-serde` is also the lease wire (`lease_client`): the connector's MessagePack frames.
|
||||||
#
|
#
|
||||||
# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Persona stage's prompt (`projection`), so
|
# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Projector's prompt (`projection`), so
|
||||||
# that membrane's text stays Ghostlight's. The Projector's frame is Huginn's own (map section 16.3), and so is the one quote
|
# the membrane's text stays Ghostlight's; the Projector asks through the connector kit's client (`model-connector`).
|
||||||
# locator (`projection::span`, map 16.30.4); `unicode-segmentation` serves it.
|
|
||||||
# Every stage asks through the connector kit's client (`model-connector`).
|
|
||||||
# `toml` reads `persona-tuning.toml`, the Projector's knobs (`projection::tuning`); parse and serde only.
|
# `toml` reads `persona-tuning.toml`, the Projector's knobs (`projection::tuning`); parse and serde only.
|
||||||
#
|
#
|
||||||
# `serde_json` reads Claude Code's stream-json, a foreign owner's wire (`self_run`);
|
# `serde_json` reads Claude Code's stream-json, a foreign owner's wire (`self_run`);
|
||||||
|
|
@ -41,7 +39,7 @@ eureka-pipeline = { path = "../eureka-pipeline" }
|
||||||
eureka-state = { path = "../eureka-state", default-features = false }
|
eureka-state = { path = "../eureka-state", default-features = false }
|
||||||
ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" }
|
ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" }
|
||||||
huginn-mind = { path = "../huginn-mind" }
|
huginn-mind = { path = "../huginn-mind" }
|
||||||
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector" }
|
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector" }
|
||||||
rmp-serde = "1"
|
rmp-serde = "1"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
|
@ -50,9 +48,6 @@ toml = { version = "0.9", default-features = false, features = ["std", "serde",
|
||||||
unicode-general-category = "1"
|
unicode-general-category = "1"
|
||||||
# Clips on grapheme boundaries (`projection::select::clip`), so no ZWJ sequence is split; already in the graph through Ghostlight.
|
# Clips on grapheme boundaries (`projection::select::clip`), so no ZWJ sequence is split; already in the graph through Ghostlight.
|
||||||
unicode-segmentation = "1"
|
unicode-segmentation = "1"
|
||||||
# The domain digest's forge reads (`projection::domain`, map 16.22.2): plain HTTP to the forge's loopback API, the same
|
|
||||||
# crate and features the daemon's forge read uses, so the graph gains no crate.
|
|
||||||
ureq = { version = "~3.3", default-features = false }
|
|
||||||
uuid = { version = "1", default-features = false, features = ["v5"] }
|
uuid = { version = "1", default-features = false, features = ["v5"] }
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
|
@ -73,7 +68,7 @@ syn = { version = "2", features = ["full"] }
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
# A real kit server (`serve` over a scripted `ProviderBackend`) proves the Projector's connector wire, not a fake of it.
|
# A real kit server (`serve` over a scripted `ProviderBackend`) proves the Projector's connector wire, not a fake of it.
|
||||||
# Same revision as the dependency; the `daemon` feature is test-only.
|
# Same revision as the dependency; the `daemon` feature is test-only.
|
||||||
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector", features = ["daemon"] }
|
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector", features = ["daemon"] }
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "mind_body"
|
name = "mind_body"
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ wrong or the mind cannot be reached.
|
||||||
|
|
||||||
`mind-heartbeat` is the one process that decides who wakes and when. It starts a Persona's unit and writes no Mind: the beat (`HEARTBEAT_BEAT_S`, default 1800 s) goes to the idle, released Mind that has waited longest, bent by a member addressing her, and the operator or another Mind naming a Persona wakes her at once, once per message. `mind-heartbeat timeline` prints its latest record.
|
`mind-heartbeat` is the one process that decides who wakes and when. It starts a Persona's unit and writes no Mind: the beat (`HEARTBEAT_BEAT_S`, default 1800 s) goes to the idle, released Mind that has waited longest, bent by a member addressing her, and the operator or another Mind naming a Persona wakes her at once, once per message. `mind-heartbeat timeline` prints its latest record.
|
||||||
|
|
||||||
`mind-persona` reads the brakes and exits `dead`, or drains: one turn in each room with a waking line (at most three), one put of her state and one trace record per turn, one ack. `mind-persona trace --instance <slug> [--last N]` prints her trace. Nothing launches `mind-self-run`.
|
`mind-persona` is inert: it reads the brakes and exits `dead` or `no organ`. It writes nothing. Nothing launches `mind-self-run`.
|
||||||
|
|
||||||
The actuator has its own ignored test, `the_real_bin_finds_her_run_...` in
|
The actuator has its own ignored test, `the_real_bin_finds_her_run_...` in
|
||||||
`tests/self_run.rs`: the real `mind-self-run` against the real daemon with a
|
`tests/self_run.rs`: the real `mind-self-run` against the real daemon with a
|
||||||
|
|
@ -29,22 +29,3 @@ Mutation testing of the actuator, with the globs that reach the library and the
|
||||||
binary: `cargo mutants -p mind-body -f "**/src/self_run.rs" -f
|
binary: `cargo mutants -p mind-body -f "**/src/self_run.rs" -f
|
||||||
"**/src/bin/mind-self-run.rs"`. The binary's mutants are killed only by the
|
"**/src/bin/mind-self-run.rs"`. The binary's mutants are killed only by the
|
||||||
lane above.
|
lane above.
|
||||||
|
|
||||||
## Before the live switch
|
|
||||||
|
|
||||||
The Persona turn's reads run live only once the heartbeat switch lands. Simulations and harness runs read fixtures
|
|
||||||
(`[domain]`, `[cast.domain]`) and need none of this. One gamecult-ops change carries all of it, ruled by Self on
|
|
||||||
2026-11-20:
|
|
||||||
|
|
||||||
- **The forge, for persona uids.** `mind_fence`'s `persona` chain rejects every local TCP port but 4110, 80 and 443, so
|
|
||||||
a Persona cannot reach the forge's loopback API (`http://127.0.0.1:3310`), and port 80 only redirects to HTTPS. Her
|
|
||||||
domain digest and her `repo` reads need an accept for tcp 127.0.0.1:3310 from `@persona_uids`. Until then a live read
|
|
||||||
fails whole and the packet leaves the section out, as designed. mind-body carries no TLS; the forge is read on loopback.
|
|
||||||
- **Web reads (K24).** A `web` read fetches a page whose address stands in her prose or in what reached her. The
|
|
||||||
persona chain lets public addresses out (it rejects only local, private, link-local and multicast ones), so egress on
|
|
||||||
tcp 80 and 443 to the public internet is already open for persona uids; what is missing is TLS: mind-body carries none,
|
|
||||||
so a live `https` read fails as "the read failed". A live web read needs either a TLS-capable client in the organ or an
|
|
||||||
egress fetcher on loopback for persona uids (an accept beside 4110 in `persona`); it is one ops-and-body decision with
|
|
||||||
the forge accept above. Repo reads use the forge accept above; mind reads use her read door.
|
|
||||||
- **Her read door.** Each Persona reaches only her own door (`huginn` set: uid . port). The digest and her reads use it
|
|
||||||
as `HUGINN_ENDPOINT`; nothing to change.
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
responder 3: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 2 lines are the Minds' alone.
|
|
||||||
responder 4: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko answered it. Meta, who runs the place last spoke a few minutes ago. The last 3 lines are the Minds' alone.
|
|
||||||
responder 5: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 4 lines are the Minds' alone.
|
|
||||||
responder 6: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 5 lines are the Minds' alone.
|
|
||||||
responder 7: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 6 lines are the Minds' alone.
|
|
||||||
responder 8: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know; "aqua", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 7 lines a…
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
quiet-beat.toml: - the conversation: Someone he does not know has been talking to the room; Kiko has been talking to the room. | The last 3 lines are the Minds' alone.
|
|
||||||
operator-warm.toml: - the conversation: Meta, who runs the place has been talking with him. | Meta, who runs the place is waiting on him. Meta, who runs the place last spoke just now.
|
|
||||||
mind-teases.toml: - the conversation: Kiko has been talking with him; he has been talking to the room; someone he does not know has been talking to the room. | The last 3 lines are the Minds' alone.
|
|
||||||
deru-passing.toml: - the conversation: Someone he does not know has been talking to the room; Deru has been talking to the room. | Deru last spoke just now.
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
[
|
|
||||||
{ "agent": "receipt", "seq": 4, "at": "2026-11-30T11:58:00Z", "wake": "n0-1", "receipt": { "tool": "say", "status": "ok", "fields": { "room": "!dm-meta:gamecult.org", "text": "Missed you too. I'll send the render tonight.", "event": "$posted-1" } } }
|
|
||||||
]
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
[
|
|
||||||
{ "agent": "receipt", "seq": 4, "at": "2026-11-30T11:58:00Z", "wake": "n0-1", "receipt": { "tool": "read", "status": "error", "fields": { "kind": "repo", "target": "GameCult/Huginn/render.md", "failure": "not_found", "why": "it is not there" } } }
|
|
||||||
]
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
[
|
|
||||||
{ "agent": "receipt", "seq": 4, "at": "2026-11-30T11:58:00Z", "wake": "n0-1", "receipt": { "tool": "say", "status": "refused", "fields": { "room": "!dm-meta:gamecult.org", "text": "I know where you live too.", "refusal": "RoomMoved" } } }
|
|
||||||
]
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
# Someone she barely knows says something in passing, not to her.
|
|
||||||
her = "@eureka:gamecult.org"
|
|
||||||
kind = "chat"
|
|
||||||
now = "2026-11-20T15:00:00Z"
|
|
||||||
rooms = ["#general:gamecult.org"]
|
|
||||||
here = "#general:gamecult.org"
|
|
||||||
operators = ["@meta:gamecult.org"]
|
|
||||||
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@weksa:gamecult.org"
|
|
||||||
name = "Weksa"
|
|
||||||
room = "#general:gamecult.org"
|
|
||||||
ago = "50m"
|
|
||||||
says = "the bot in #general keeps reacting to every message with a frog. nobody admits to teaching it that"
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@deru:gamecult.org"
|
|
||||||
name = "Deru"
|
|
||||||
room = "#general:gamecult.org"
|
|
||||||
new = true
|
|
||||||
ago = "1m"
|
|
||||||
says = "is anyone else's kettle making a weird whistling noise lately or is it just mine"
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
# Another Mind teases her and disagrees with her in #minds, replying to her own earlier line.
|
|
||||||
her = "@eureka:gamecult.org"
|
|
||||||
kind = "chat"
|
|
||||||
now = "2026-11-20T15:00:00Z"
|
|
||||||
rooms = ["#minds:gamecult.org"]
|
|
||||||
here = "#minds:gamecult.org"
|
|
||||||
operators = ["@meta:gamecult.org"]
|
|
||||||
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@eureka:gamecult.org"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "25m"
|
|
||||||
says = "winter is the best season and I will not be taking questions"
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@aqua:gamecult.org"
|
|
||||||
name = "Aqua"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "20m"
|
|
||||||
says = "bold"
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@kiko:gamecult.org"
|
|
||||||
name = "Kiko"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
reply_to = 1
|
|
||||||
tag = true
|
|
||||||
new = true
|
|
||||||
ago = "2m"
|
|
||||||
says = "winter is a season for people who like being right more than being warm. which, to be fair, tracks. you've gone quiet again too, I give it ten minutes before you announce you've been thinking deeply about something"
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
# The operator writes to her directly, warmly, with a small joke.
|
|
||||||
her = "@eureka:gamecult.org"
|
|
||||||
kind = "chat"
|
|
||||||
now = "2026-11-20T15:00:00Z"
|
|
||||||
rooms = ["#minds:gamecult.org", "!dm-meta:gamecult.org"]
|
|
||||||
here = "!dm-meta:gamecult.org"
|
|
||||||
operators = ["@meta:gamecult.org"]
|
|
||||||
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
|
|
||||||
|
|
||||||
[last_heard]
|
|
||||||
"@meta:gamecult.org" = "2d"
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@kiko:gamecult.org"
|
|
||||||
name = "Kiko"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "2h"
|
|
||||||
says = "quiet day. suspicious."
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@meta:gamecult.org"
|
|
||||||
name = "Meta"
|
|
||||||
room = "!dm-meta:gamecult.org"
|
|
||||||
dm = true
|
|
||||||
new = true
|
|
||||||
ago = "1m"
|
|
||||||
says = "hey you. I missed talking to you this week. how are you, really? and no, \"busy\" doesn't count as an answer, I know where you live"
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
# A quiet beat: nothing is addressed to her, and the room's talk is a few hours old.
|
|
||||||
her = "@eureka:gamecult.org"
|
|
||||||
kind = "beat"
|
|
||||||
now = "2026-11-20T15:00:00Z"
|
|
||||||
rooms = ["#minds:gamecult.org", "#general:gamecult.org"]
|
|
||||||
operators = ["@meta:gamecult.org"]
|
|
||||||
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
|
|
||||||
|
|
||||||
# When she last heard from people the room below does not show.
|
|
||||||
[last_heard]
|
|
||||||
"@meta:gamecult.org" = "26h"
|
|
||||||
"@deru:gamecult.org" = "3d"
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@libby:gamecult.org"
|
|
||||||
name = "Libby"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "4h"
|
|
||||||
says = "found a recording of rain on a tin roof and I've had it on loop all morning"
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@kiko:gamecult.org"
|
|
||||||
name = "Kiko"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "3h"
|
|
||||||
says = "that's either very soothing or a cry for help"
|
|
||||||
|
|
||||||
[[message]]
|
|
||||||
from = "@libby:gamecult.org"
|
|
||||||
name = "Libby"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "3h"
|
|
||||||
says = "why not both"
|
|
||||||
|
|
@ -1,148 +0,0 @@
|
||||||
{
|
|
||||||
"schemaVersion": "gamecult.persona_state.v0",
|
|
||||||
"provenance": {
|
|
||||||
"sourceSystem": "huginn",
|
|
||||||
"sourceDocumentId": "eureka",
|
|
||||||
"sourceUpdatedAt": "2026-11-20T09:00:00Z",
|
|
||||||
"exportedAt": "2026-11-20T09:00:00Z",
|
|
||||||
"authority": "canonical"
|
|
||||||
},
|
|
||||||
"personaId": "eureka",
|
|
||||||
"publicName": "Tobiah Fenn",
|
|
||||||
"publicDescription": "A retired river-ferry pilot who sets crosswords for a living and lingers in chat rooms for the company.",
|
|
||||||
"presentation": {
|
|
||||||
"pronouns": "he/him",
|
|
||||||
"voiceSummary": "Slow, warm and ornate. Talks in long winding sentences, calls people 'friend', reaches for river sayings, and would rather tell a story than give an answer.",
|
|
||||||
"defaultRenderer": "chat"
|
|
||||||
},
|
|
||||||
"values": [
|
|
||||||
{ "id": "value-unhurried", "label": "Nothing worth doing is done in a hurry", "priority": 0.9, "summary": "He distrusts urgency; a thing rushed is a thing botched." },
|
|
||||||
{ "id": "value-a-good-story", "label": "A good story beats a right answer", "priority": 0.7, "summary": "People remember the tale long after they forget the fact." }
|
|
||||||
],
|
|
||||||
"activationProfile": {
|
|
||||||
"underlyingOrganization": {},
|
|
||||||
"stableDispositions": {},
|
|
||||||
"behavioralDimensions": {},
|
|
||||||
"presentationStrategy": {},
|
|
||||||
"voiceStyle": {},
|
|
||||||
"situationalState": {
|
|
||||||
"valence": { "mean": 0.7, "plasticity": 0.3, "currentActivation": 0.7 },
|
|
||||||
"arousal": { "mean": 0.25, "plasticity": 0.3, "currentActivation": 0.2 },
|
|
||||||
"dominance": { "mean": 0.4, "plasticity": 0.3, "currentActivation": 0.4 }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"thoughtMemory": {
|
|
||||||
"shortTerm": [],
|
|
||||||
"memories": [
|
|
||||||
{
|
|
||||||
"id": "mem-last-crossing",
|
|
||||||
"status": "crystallized",
|
|
||||||
"target": { "id": "tobiah", "kind": "self", "label": "Tobiah" },
|
|
||||||
"summary": "The last crossing he piloted, in fog so thick he steered by the sound of the far bank's church bell.",
|
|
||||||
"tension": "He misses being needed for something that simple.",
|
|
||||||
"actionImplication": "Tell it when someone sounds lost.",
|
|
||||||
"createdAt": "2026-10-01T08:00:00Z",
|
|
||||||
"updatedAt": "2026-10-01T08:00:00Z",
|
|
||||||
"intensity": 0.8,
|
|
||||||
"valence": 0.4
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "mem-deru-crossword",
|
|
||||||
"status": "crystallized",
|
|
||||||
"target": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" },
|
|
||||||
"summary": "Deru solved his hardest crossword in a single sitting and sent him a photo of the grid with coffee rings on it.",
|
|
||||||
"tension": "He was prouder of Deru than of the puzzle.",
|
|
||||||
"actionImplication": "Send Deru the next one first.",
|
|
||||||
"createdAt": "2026-11-10T19:00:00Z",
|
|
||||||
"updatedAt": "2026-11-10T19:00:00Z",
|
|
||||||
"intensity": 0.7,
|
|
||||||
"valence": 0.8
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"incubation": [
|
|
||||||
{
|
|
||||||
"id": "w-clue-for-heron",
|
|
||||||
"status": "active",
|
|
||||||
"target": { "id": "crossword", "kind": "concept", "label": "the next crossword" },
|
|
||||||
"summary": "A clue for HERON that nobody has used before.",
|
|
||||||
"tension": "Every good one he thinks of turns out to be old.",
|
|
||||||
"actionImplication": "Ask someone for a word that rhymes with patience.",
|
|
||||||
"createdAt": "2026-11-18T10:00:00Z",
|
|
||||||
"updatedAt": "2026-11-18T10:00:00Z",
|
|
||||||
"intensity": 0.5
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"agencyPressure": { "pressures": [] },
|
|
||||||
"candidateActions": { "actions": [] },
|
|
||||||
"affect": {
|
|
||||||
"needs": [
|
|
||||||
{
|
|
||||||
"id": "need-an-audience",
|
|
||||||
"status": "active",
|
|
||||||
"target": { "id": "tobiah", "kind": "self", "label": "Tobiah" },
|
|
||||||
"summary": "Someone to tell a story to who will not check the time.",
|
|
||||||
"tension": "The rooms move faster than he does.",
|
|
||||||
"actionImplication": "Linger where people are idle.",
|
|
||||||
"createdAt": "2026-11-20T09:00:00Z",
|
|
||||||
"updatedAt": "2026-11-20T09:00:00Z",
|
|
||||||
"intensity": 0.6
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"socialBonds": [
|
|
||||||
{
|
|
||||||
"id": "bond-deru",
|
|
||||||
"status": "active",
|
|
||||||
"subject": { "id": "tobiah", "kind": "self" },
|
|
||||||
"object": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" },
|
|
||||||
"relationshipKind": "friend",
|
|
||||||
"summary": "His oldest friend in these rooms; they trade puzzles and gossip and never talk about anything urgent.",
|
|
||||||
"trust": 0.9,
|
|
||||||
"tension": 0.0,
|
|
||||||
"intensity": 0.8,
|
|
||||||
"updatedAt": "2026-11-20T09:00:00Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "bond-operator",
|
|
||||||
"status": "active",
|
|
||||||
"subject": { "id": "tobiah", "kind": "self" },
|
|
||||||
"object": { "id": "operator", "kind": "person", "label": "Meta, who runs the place" },
|
|
||||||
"relationshipKind": "audience",
|
|
||||||
"summary": "Runs the rooms he idles in; polite with her, a little shy, never quite sure she has time for him.",
|
|
||||||
"trust": 0.5,
|
|
||||||
"tension": 0.1,
|
|
||||||
"intensity": 0.3,
|
|
||||||
"updatedAt": "2026-11-20T09:00:00Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "bond-kiko",
|
|
||||||
"status": "active",
|
|
||||||
"subject": { "id": "tobiah", "kind": "self" },
|
|
||||||
"object": { "id": "kiko", "kind": "person", "label": "Kiko" },
|
|
||||||
"relationshipKind": "rival",
|
|
||||||
"summary": "Kiko finishes his crosswords too fast and says so; he pretends to mind more than he does.",
|
|
||||||
"trust": 0.6,
|
|
||||||
"tension": 0.3,
|
|
||||||
"intensity": 0.5,
|
|
||||||
"updatedAt": "2026-11-20T09:00:00Z"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"statusReads": [],
|
|
||||||
"moodDimensions": [],
|
|
||||||
"socialBiases": [],
|
|
||||||
"doctrineStances": [
|
|
||||||
{
|
|
||||||
"id": "stance-slow-is-kind",
|
|
||||||
"status": "active",
|
|
||||||
"target": { "id": "pace", "kind": "concept", "label": "pace" },
|
|
||||||
"stanceKind": "aligned",
|
|
||||||
"principle": "Slow is kind.",
|
|
||||||
"summary": "Answering fast is a way of not listening.",
|
|
||||||
"actionImplication": "Take his time, and say so when others rush him.",
|
|
||||||
"intensity": 0.6,
|
|
||||||
"updatedAt": "2026-11-20T09:00:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"updatedAt": "2026-11-20T09:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
@ -63,28 +63,6 @@ pub(crate) fn is_for(own: &Addressee, delivery: &ChatDelivery) -> bool {
|
||||||
(delivery.form == Form::Message && (delivery.is_direct || matches!(delivery.basis, Some(Basis::Direct | Basis::Tag | Basis::Reply | Basis::FollowUp)))) || addresses(own, delivery)
|
(delivery.form == Form::Message && (delivery.is_direct || matches!(delivery.basis, Some(Basis::Direct | Basis::Tag | Basis::Reply | Basis::FollowUp)))) || addresses(own, delivery)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The other Minds a delivery is for, by Matrix id: those its mentions hold, those of `roster` it names (`addresses`), and the
|
|
||||||
/// sender of the line it replies to when that is neither `own` nor the sender (a reply answers someone). The one derivation of
|
|
||||||
/// who else a line is for; a line that is for `own` too is still for her (`is_for`), and one that is for others and not her is
|
|
||||||
/// said in her room, not to her.
|
|
||||||
pub(crate) fn others_addressed<'a>(own: &Addressee, roster: &'a [Addressee], delivery: &'a ChatDelivery) -> Vec<&'a str> {
|
|
||||||
let mut ids: Vec<&str> = delivery.mentions.iter().map(String::as_str).filter(|id| *id != own.matrix_id() && *id != delivery.sender).collect();
|
|
||||||
for row in roster {
|
|
||||||
let id = row.matrix_id();
|
|
||||||
if id != own.matrix_id() && id != delivery.sender && !ids.contains(&id) && addresses(row, delivery) {
|
|
||||||
ids.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(quote) = delivery.reply_to.quote()
|
|
||||||
&& quote.sender != own.matrix_id()
|
|
||||||
&& quote.sender != delivery.sender
|
|
||||||
&& !ids.contains("e.sender.as_str())
|
|
||||||
{
|
|
||||||
ids.push(quote.sender.as_str());
|
|
||||||
}
|
|
||||||
ids
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The chat names of one stewarded repo. Listed names are exactly those, each matched exactly as the steward wrote it (capitalization
|
/// The chat names of one stewarded repo. Listed names are exactly those, each matched exactly as the steward wrote it (capitalization
|
||||||
/// tells a project from a common word). With none listed: the repo's name after the org, matched exactly as the repo spells it
|
/// tells a project from a common word). With none listed: the repo's name after the org, matched exactly as the repo spells it
|
||||||
/// (`Thing`, not `thing`), and that name split at `-`, `_`, `.` and where a lower-case letter or digit meets a capital, when the split
|
/// (`Thing`, not `thing`), and that name split at `-`, `_`, `.` and where a lower-case letter or digit meets a capital, when the split
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,7 @@
|
||||||
//! entries separated by `;`, the last field her own Huginn daemon: each Mind is
|
//! entries separated by `;`, the last field her own Huginn daemon: each Mind is
|
||||||
//! its own daemon), `MIND_PERSONA_OPERATOR` (id[,id]), `HEARTBEAT_POLL_S`,
|
//! its own daemon), `MIND_PERSONA_OPERATOR` (id[,id]), `HEARTBEAT_POLL_S`,
|
||||||
//! `HEARTBEAT_BEAT_S` (seconds between beats, default 1800), `BIFROST_CHAT_ENDPOINT`,
|
//! `HEARTBEAT_BEAT_S` (seconds between beats, default 1800), `BIFROST_CHAT_ENDPOINT`,
|
||||||
//! `BIFROST_CHAT_KEY_FILE`, `STATE_DIRECTORY` (`heartbeat.cc` lives there) and `MIND_HEARTBEAT_TRACES`, the path of each Persona's
|
//! `BIFROST_CHAT_KEY_FILE`, and `STATE_DIRECTORY` (`heartbeat.cc` lives there).
|
||||||
//! `persona-trace.cc` with `{slug}` where her slug goes (read through a lock-free snapshot, no write access: her trace is the record of which lines she has decided).
|
|
||||||
//! The heartbeat holds no connector key.
|
//! The heartbeat holds no connector key.
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
|
@ -25,7 +24,6 @@ use anyhow::{Context, Result, anyhow, bail};
|
||||||
use eureka_state::HuginnClient;
|
use eureka_state::HuginnClient;
|
||||||
use mind_body::chat_rudp::{RudpChat, connection_id};
|
use mind_body::chat_rudp::{RudpChat, connection_id};
|
||||||
use mind_body::heartbeat::{Config, DEFAULT_BEAT_S, FileControl, FileStore, Organs, PersonaId, Seat, poll};
|
use mind_body::heartbeat::{Config, DEFAULT_BEAT_S, FileControl, FileStore, Organs, PersonaId, Seat, poll};
|
||||||
use mind_body::persona::TraceSnapshot;
|
|
||||||
use mind_body::launch::{SystemClock, SystemdLauncher};
|
use mind_body::launch::{SystemClock, SystemdLauncher};
|
||||||
use mind_body::queue::HuginnMind;
|
use mind_body::queue::HuginnMind;
|
||||||
|
|
||||||
|
|
@ -86,16 +84,11 @@ fn run() -> Result<()> {
|
||||||
let poll_s = u64::try_from(whole("HEARTBEAT_POLL_S", 20)?).map_err(|_| anyhow!("HEARTBEAT_POLL_S is negative"))?.max(1);
|
let poll_s = u64::try_from(whole("HEARTBEAT_POLL_S", 20)?).map_err(|_| anyhow!("HEARTBEAT_POLL_S is negative"))?.max(1);
|
||||||
let minds: Vec<HuginnMind> = config.personas.iter().map(|who| HuginnMind::new(HuginnClient::new(who.huginn, who.slug.clone(), TIMEOUT))).collect();
|
let minds: Vec<HuginnMind> = config.personas.iter().map(|who| HuginnMind::new(HuginnClient::new(who.huginn, who.slug.clone(), TIMEOUT))).collect();
|
||||||
let chats: Vec<RudpChat> = config.personas.iter().map(|who| RudpChat::new(chat_address, chat_id, who.slug.0.clone(), CHAT_TIMEOUT)).collect();
|
let chats: Vec<RudpChat> = config.personas.iter().map(|who| RudpChat::new(chat_address, chat_id, who.slug.0.clone(), CHAT_TIMEOUT)).collect();
|
||||||
let traces_at = required("MIND_HEARTBEAT_TRACES")?;
|
|
||||||
if !traces_at.contains("{slug}") {
|
|
||||||
bail!("MIND_HEARTBEAT_TRACES names no {{slug}}");
|
|
||||||
}
|
|
||||||
let traces: Vec<TraceSnapshot> = config.personas.iter().map(|who| TraceSnapshot::new(traces_at.replace("{slug}", &who.slug.0))).collect();
|
|
||||||
let seats: Vec<Seat> = config
|
let seats: Vec<Seat> = config
|
||||||
.personas
|
.personas
|
||||||
.iter()
|
.iter()
|
||||||
.zip(minds.iter().zip(chats.iter().zip(traces.iter())))
|
.zip(minds.iter().zip(chats.iter()))
|
||||||
.map(|(who, (mind, (chat, trace)))| Seat { who: who.clone(), mind, chat, trace })
|
.map(|(who, (mind, chat))| Seat { who: who.clone(), mind, chat })
|
||||||
.collect();
|
.collect();
|
||||||
let launcher = SystemdLauncher::new();
|
let launcher = SystemdLauncher::new();
|
||||||
let organs = Organs { seats: &seats, control: &FileControl, launcher: &launcher, clock: &SystemClock, store: &store };
|
let organs = Organs { seats: &seats, control: &FileControl, launcher: &launcher, clock: &SystemClock, store: &store };
|
||||||
|
|
|
||||||
|
|
@ -1,84 +1,47 @@
|
||||||
//! `mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>]`:
|
//! `mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>]`:
|
||||||
//! one start of the Persona organ (`mind_body::persona::carry`) inside
|
//! one start of the Persona organ (`mind_body::persona::carry`) inside
|
||||||
//! `mind-persona@<instance>`. This reads the process's arguments and
|
//! `mind-persona@<instance>`. This reads the process's arguments and
|
||||||
//! environment, the things the library never reads, builds the organs once the brakes allow a turn, and prints the
|
//! environment, the things the library never reads, and prints the outcome:
|
||||||
//! outcome: `dead` when a brake is held; else the drain (`drained: 1 wake, K turns, ended idle, acked through S`), one wake that stays
|
//! `dead` when a brake is held, `no organ` when they allow a turn, since she has
|
||||||
//! open after its first turn (`persona::live`: it polls the mouth and takes a turn for each line that wakes her, until it is idle or reaches its span or its caps); or `failed: <why>` for a
|
//! none until the three-stage turn lands. It exits 0 for both, and 2 when the
|
||||||
//! start that read nothing, exit 1. It exits 0 for `dead` and `drained`, and 2 when the arguments or the environment
|
//! arguments or the environment are wrong.
|
||||||
//! are wrong.
|
|
||||||
//!
|
//!
|
||||||
//! The persona flags (`--rooms`, `--operator`, `--minds`, `--self-sender`, or
|
//! The persona flags (`--rooms`, `--operator`, `--minds`, `--self-sender`, or
|
||||||
//! `MIND_PERSONA_ROOMS`, `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS`,
|
//! `MIND_PERSONA_ROOMS`, `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS`,
|
||||||
//! `MIND_PERSONA_SELF_SENDER` and `MIND_PERSONA_MODEL` from the unit's
|
//! `MIND_PERSONA_SELF_SENDER` and `MIND_PERSONA_MODEL` from the unit's
|
||||||
//! `persona.env`) are parsed first, so a start refuses a configuration the turn will not run on. A released start needs
|
//! `persona.env`) are still parsed, so a start refuses the configuration the turn
|
||||||
//! the daemon (`--endpoint` or `HUGINN_ENDPOINT`, her persona door), the mouth (`BIFROST_CHAT_ENDPOINT`,
|
//! will need. Without `--endpoint` the daemon is `HUGINN_ENDPOINT`; no call is made
|
||||||
//! `BIFROST_CHAT_KEY_FILE`), the connector (`MIND_PERSONA_CONNECTOR_ENDPOINT` and the `connector-key` credential) and
|
//! to it.
|
||||||
//! `STATE_DIRECTORY`, where her trace is `persona-trace.cc`; it reads `MIND_PERSONA_FORGE_URL`, `MIND_PERSONA_TUNING`
|
|
||||||
//! and `MIND_HEARTBEAT_STATE` as `project` does. Without the connector or the mouth it ends `failed`, touching nothing.
|
|
||||||
//!
|
//!
|
||||||
//! `mind-persona trace --instance <slug> [--last N]` prints the newest N (default 20) records of her trace as JSON lines,
|
//! `mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--room <r>]
|
||||||
//! oldest first. It is read-only. Her agent's `request_tool` receipts are rows there, which is how Self reads them.
|
//! [--seed N] [--state <file>] [--select-only | --renders K [--judge <state-file>]]` is the Projector's experiment tool
|
||||||
//!
|
//! (`mind_body::projection::project`): it prints, as JSON, the packet the Select stage builds from her stored state (or
|
||||||
//! `mind-persona box-exec --instance <slug>` is her box's side of one shell command (`mind_body::sandbox::serve_box`): run by
|
//! `--state`), and with `--renders` the Projector's narrations of K successive turns; `--judge` renders a second state
|
||||||
//! `mind-box-<m>@.service` as `mind-<m>-box`, it reads one request from the connection on stdin, runs it under the one
|
//! too and asks the model which narration came from which. It writes nothing and reads no brake. It reads
|
||||||
//! bubblewrap profile with `STATE_DIRECTORY` as her box's home and `RUNTIME_DIRECTORY` as its scratch, and writes one receipt to
|
//! `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS` and `MIND_PERSONA_SELF_SENDER` (required), and the heartbeat's addressing
|
||||||
//! stdout. A released start reads `MIND_PERSONA_BOX_SOCKET`, where her agent's shell connects, and keeps her agent's session
|
//! from `MIND_HEARTBEAT_STATE`, which a run by hand must set as the unit does (`/var/lib/mind-heartbeat/heartbeat.cc`):
|
||||||
//! in `agent-session.cc` beside her trace.
|
//! without it "said to her" knows only her own names, never her projects', and stderr says so before the report; the
|
||||||
//!
|
//! room comes from the mouth when `BIFROST_CHAT_ENDPOINT`
|
||||||
//! `mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>]
|
//! and `BIFROST_CHAT_KEY_FILE` are set; the tuning is `MIND_PERSONA_TUNING`, else
|
||||||
//! [--room <fixture.toml>] [--seed N] [--state <file>] [--told <rows.json>] [--select-only | --renders K
|
//! `/etc/gamecult/minds/<instance>/persona-tuning.toml`; renders need `MIND_PERSONA_CONNECTOR_ENDPOINT`
|
||||||
//! [--through projector|persona] [--judge <state-file>]]` is the experiment tool over the Projector and the
|
//! (`<loopback ip>:<port>`) and the `connector-key` credential in `CREDENTIALS_DIRECTORY`. Without `--select-only` or
|
||||||
//! Persona stage (`mind_body::projection::project`): it prints, as JSON, the packet the Select stage builds from her stored
|
//! `--renders` it renders once.
|
||||||
//! state (or `--state`, checked as a put checks its content, rules P1 to P3; P4 and P5 compare it with the stored document
|
|
||||||
//! and are not checked), opened by what the trace rows of `--told` tell her, and with `--renders` the Projector's
|
|
||||||
//! narrations of K successive turns;
|
|
||||||
//! `--through persona` adds her prose; `--judge` renders a second state too and asks
|
|
||||||
//! the model which narration came from which. It writes nothing and reads no brake.
|
|
||||||
//!
|
|
||||||
//! Live, it reads `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS` and `MIND_PERSONA_SELF_SENDER` (required), the heartbeat's
|
|
||||||
//! addressing from `MIND_HEARTBEAT_STATE`, which a run by hand must set as the unit does (`/var/lib/mind-heartbeat/heartbeat.cc`):
|
|
||||||
//! without it "said to her" knows only her own names, never her projects', and stderr says so before the report. The
|
|
||||||
//! room comes from the mouth when `BIFROST_CHAT_ENDPOINT` and
|
|
||||||
//! `BIFROST_CHAT_KEY_FILE` are set; `--in` keeps one room. `--room <fixture>` replaces all of that with a mocked room
|
|
||||||
//! (`projection::harness::Fixture`): her id, who is who, the messages, the clock and the "last heard from" table. With
|
|
||||||
//! `--room` and `--state` no daemon and no mouth is needed: without `--endpoint` or `HUGINN_ENDPOINT` none is reached.
|
|
||||||
//!
|
|
||||||
//! `mind-persona project --instance <slug> (--batch <plan.toml> | --simulate <plan.toml>) --out <report.md>` runs a plan
|
|
||||||
//! and writes one Markdown report: a batch of states by scenarios by samples (`harness::batch`), or the swarm's cast taking
|
|
||||||
//! turns in one simulated room (`harness::simulate`). Each case is one `project`.
|
|
||||||
//!
|
|
||||||
//! Her domain (what moved lately in her stewarded repos and her campaigns, map 16.22.2) is read when `MIND_PERSONA_FORGE_URL`
|
|
||||||
//! names the forge's API root (on Yggdrasil the loopback `http://127.0.0.1:3310`) and a daemon endpoint is given: her
|
|
||||||
//! mind through that endpoint, which a Persona reaches at her read door, and the forge anonymously. Without either the
|
|
||||||
//! packet has no domain section and the report says so. A room fixture's `[domain]` replaces both; its `[[read]]` entries record the reads
|
|
||||||
//! the agent will perform.
|
|
||||||
//!
|
|
||||||
//! The tuning is `MIND_PERSONA_TUNING`, else `/etc/gamecult/minds/<instance>/persona-tuning.toml`; renders and plans need
|
|
||||||
//! `MIND_PERSONA_CONNECTOR_ENDPOINT` (`<loopback ip>:<port>`) and the `connector-key` credential in
|
|
||||||
//! `CREDENTIALS_DIRECTORY`. Without `--select-only` or `--renders` it renders once.
|
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::rc::Rc;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
use eureka_pipeline::Slug;
|
|
||||||
use eureka_state::HuginnClient;
|
use eureka_state::HuginnClient;
|
||||||
use mind_body::chat_rudp::{RudpChat, connection_id};
|
use mind_body::chat_rudp::{RudpChat, connection_id};
|
||||||
use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint};
|
use mind_body::cli::instance_and_endpoint;
|
||||||
use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path};
|
use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path};
|
||||||
use mind_body::persona::{Config, FileTrace, Outcome, Start, carry, trace_lines};
|
use mind_body::persona::{Config, carry};
|
||||||
use mind_body::heartbeat::{FileStore, HeartbeatView, Store, own_rooms_among, woken_for};
|
use mind_body::heartbeat::{FileStore, HeartbeatView};
|
||||||
use mind_body::queue::HuginnMind;
|
use mind_body::projection::{HuginnPersonaSource, KitModel, Model, MouthReader, Organs as ProjectOrgans, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, TurnKind, connector_key, project};
|
||||||
use mind_body::sandbox::{BoxPaths, COMMONS_RW, serve_box};
|
|
||||||
use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file};
|
|
||||||
use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project};
|
|
||||||
|
|
||||||
const USAGE: &str = "usage: mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]";
|
const USAGE: &str = "usage: mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]";
|
||||||
const TRACE_USAGE: &str = "usage: mind-persona trace --instance <slug> [--last N]";
|
const PROJECT_USAGE: &str = "usage: mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--room <r>] [--seed N] [--state <file>] [--select-only | --renders K [--judge <state-file>]]";
|
||||||
const BOX_USAGE: &str = "usage: mind-persona box-exec --instance <slug>";
|
|
||||||
const PROJECT_USAGE: &str = "usage: mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>] [--room <fixture.toml>] [--seed N] [--state <file>] [--told <rows.json>] [--select-only | --renders K [--through projector|persona] [--judge <state-file>]] | (--batch <plan> | --simulate <plan>) --out <report.md>";
|
|
||||||
/// How long one call to the mind may take.
|
/// How long one call to the mind may take.
|
||||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||||
/// How long the mouth may take to answer one read.
|
/// How long the mouth may take to answer one read.
|
||||||
|
|
@ -94,95 +57,13 @@ fn setting(name: &str) -> Option<String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and environment, and hands them to the library")]
|
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and environment, and hands them to the library")]
|
||||||
fn run() -> Result<Outcome> {
|
fn run() -> Result<String> {
|
||||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
let (config, rest) = Config::from_args_and_env(&args, setting, USAGE)?;
|
let (_config, rest) = Config::from_args_and_env(&args, setting, USAGE)?;
|
||||||
let (instance, endpoint) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), USAGE)?;
|
let (instance, _endpoint) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), USAGE)?;
|
||||||
let control = FileSource::new(control_path(Path::new(CONTROL_ROOT), &instance)?);
|
let control = FileSource::new(control_path(Path::new(CONTROL_ROOT), &instance)?);
|
||||||
let swarm = FileSource::new(swarm_path(Path::new(CONTROL_ROOT)));
|
let swarm = FileSource::new(swarm_path(Path::new(CONTROL_ROOT)));
|
||||||
Ok(carry(&control, &swarm, &instance, || start(config, &instance, endpoint)))
|
Ok(carry(&control, &swarm, &instance).to_string())
|
||||||
}
|
|
||||||
|
|
||||||
/// The organs of a released start: built only when the brakes allow a turn, each from the unit's environment.
|
|
||||||
fn start(config: Config, instance: &Slug, endpoint: SocketAddr) -> Result<Start<RudpChat>> {
|
|
||||||
let chat = chat(instance)?.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT and BIFROST_CHAT_KEY_FILE are not set"))?;
|
|
||||||
let connector: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
|
|
||||||
let model = Rc::new(KitModel::open(connector, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?);
|
|
||||||
let client = || HuginnClient::new(endpoint, instance.clone(), TIMEOUT);
|
|
||||||
let forge = setting("MIND_PERSONA_FORGE_URL");
|
|
||||||
Ok(Start {
|
|
||||||
config,
|
|
||||||
persona: Box::new(HuginnPersonaSource::new(client())),
|
|
||||||
chat,
|
|
||||||
trace: Box::new(FileTrace::new(state_directory()?.join("persona-trace.cc"))),
|
|
||||||
addressing: setting("MIND_HEARTBEAT_STATE").map(|path| Box::new(FileStore::new(path)) as Box<dyn HeartbeatView>),
|
|
||||||
model: Box::new(model.clone()),
|
|
||||||
agent: Box::new(model),
|
|
||||||
domain: forge.as_deref().map(|forge| Box::new(MindDomain::new(client(), HttpForge::new(forge))) as Box<dyn DomainSource>),
|
|
||||||
reads: Some(Box::new(LiveReads::new(client(), forge.as_deref().map(HttpForge::new)))),
|
|
||||||
tuning: tuning_of(instance),
|
|
||||||
session: state_directory()?.join("agent-session.cc"),
|
|
||||||
box_socket: PathBuf::from(required("MIND_PERSONA_BOX_SOCKET")?),
|
|
||||||
clock: Box::new(chrono::Utc::now),
|
|
||||||
pause: Box::new(std::thread::sleep),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The unit's state directory: the first of `STATE_DIRECTORY`'s entries.
|
|
||||||
fn state_directory() -> Result<PathBuf> {
|
|
||||||
let directory = required("STATE_DIRECTORY")?;
|
|
||||||
Ok(PathBuf::from(directory.split(':').next().unwrap_or_default()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her trace: the unit's state directory, `persona-trace.cc`.
|
|
||||||
fn trace_of() -> Result<FileTrace> {
|
|
||||||
Ok(FileTrace::new(state_directory()?.join("persona-trace.cc")))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `box-exec --instance <slug>`: one command in her box, run by `mind-box-<m>@.service` as `mind-<m>-box` with the connection
|
|
||||||
/// as stdin and stdout. Her box's home is the unit's `STATE_DIRECTORY`, its scratch the unit's `RUNTIME_DIRECTORY`, and the
|
|
||||||
/// commons data dirs are bound writable (`sandbox::COMMONS_RW`).
|
|
||||||
fn run_box_exec(args: &[String]) -> Result<()> {
|
|
||||||
match args {
|
|
||||||
[flag, _instance] if flag == "--instance" => {}
|
|
||||||
_ => bail!("{BOX_USAGE}"),
|
|
||||||
}
|
|
||||||
let (home, scratch) = (state_directory()?, PathBuf::from(required("RUNTIME_DIRECTORY")?.split(':').next().unwrap_or_default()));
|
|
||||||
let commons: Vec<&Path> = COMMONS_RW.iter().map(Path::new).collect();
|
|
||||||
serve_box(std::io::stdin().lock(), std::io::stdout().lock(), &BoxPaths { home: &home, scratch: &scratch, extra_rw: &commons })?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The tuning file: `MIND_PERSONA_TUNING`, else the installed one.
|
|
||||||
fn tuning_of(instance: &Slug) -> PathBuf {
|
|
||||||
setting("MIND_PERSONA_TUNING").map_or_else(|| Path::new(TUNING_ROOT).join(&instance.0).join(TUNING_FILE), PathBuf::from)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The mouth, when the environment names it.
|
|
||||||
fn chat(instance: &Slug) -> Result<Option<RudpChat>> {
|
|
||||||
match (setting("BIFROST_CHAT_ENDPOINT"), setting("BIFROST_CHAT_KEY_FILE")) {
|
|
||||||
(Some(endpoint), Some(_)) => {
|
|
||||||
let endpoint: SocketAddr = endpoint.strip_prefix("rudp://").and_then(|address| address.parse().ok()).ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://<ip>:<port>"))?;
|
|
||||||
Ok(Some(RudpChat::new(endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT)))
|
|
||||||
}
|
|
||||||
_ => Ok(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `trace --instance <slug> [--last N]`: the newest records of her trace, as JSON lines.
|
|
||||||
fn run_trace(args: &[String]) -> Result<String> {
|
|
||||||
let (mut instance, mut last) = (None, 20usize);
|
|
||||||
let mut given = args.iter();
|
|
||||||
while let Some(flag) = given.next() {
|
|
||||||
let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{TRACE_USAGE}"));
|
|
||||||
match flag.as_str() {
|
|
||||||
"--instance" => instance = Some(value()?),
|
|
||||||
"--last" => last = value()?.parse().map_err(|_| anyhow!("{TRACE_USAGE}"))?,
|
|
||||||
_ => bail!("{TRACE_USAGE}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
instance.ok_or_else(|| anyhow!("{TRACE_USAGE}"))?;
|
|
||||||
Ok(trace_lines(&trace_of()?, last)?.join("\n"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn required(name: &str) -> Result<String> {
|
fn required(name: &str) -> Result<String> {
|
||||||
|
|
@ -194,10 +75,9 @@ fn credential(name: &str) -> Result<String> {
|
||||||
std::fs::read_to_string(required(name)?).with_context(|| format!("the file named by {name} could not be read"))
|
std::fs::read_to_string(required(name)?).with_context(|| format!("the file named by {name} could not be read"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The rows she is told, from a file (`--told`): a JSON array of trace rows, as `mind-persona trace` prints them.
|
fn json_file(path: &str) -> Result<serde_json::Value> {
|
||||||
fn rows_file(path: &Path) -> Result<Vec<serde_json::Value>> {
|
let text = std::fs::read_to_string(path).with_context(|| format!("{path} could not be read"))?;
|
||||||
let text = std::fs::read_to_string(path).with_context(|| format!("{} could not be read", path.display()))?;
|
serde_json::from_str(&text).with_context(|| format!("{path} is not JSON"))
|
||||||
serde_json::from_str(&text).with_context(|| format!("{} is not a JSON array of trace rows", path.display()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The credentials directory systemd hands the unit; its absence names the variable.
|
/// The credentials directory systemd hands the unit; its absence names the variable.
|
||||||
|
|
@ -207,147 +87,72 @@ fn credentials_directory() -> Result<PathBuf> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_project(args: &[String]) -> Result<String> {
|
fn run_project(args: &[String]) -> Result<String> {
|
||||||
let (mut kind, mut here, mut fixture, mut seed, mut state, mut renders, mut select_only, mut judge, mut through) = (None, None, None, None, None, None, false, None, Through::Projector);
|
let (mut kind, mut room, mut seed, mut state, mut renders, mut select_only, mut judge, mut rest) = (TurnKind::Beat, None, None, None, None, false, None, Vec::new());
|
||||||
let (mut batch_plan, mut simulate_plan, mut out, mut told, mut rest) = (None, None, None, None, Vec::new());
|
|
||||||
let mut given = args.iter();
|
let mut given = args.iter();
|
||||||
while let Some(flag) = given.next() {
|
while let Some(flag) = given.next() {
|
||||||
let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{PROJECT_USAGE}"));
|
let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{PROJECT_USAGE}"));
|
||||||
match flag.as_str() {
|
match flag.as_str() {
|
||||||
"--kind" => {
|
"--kind" => {
|
||||||
kind = Some(match value()?.as_str() {
|
kind = match value()?.as_str() {
|
||||||
"chat" => TurnKind::Chat,
|
"chat" => TurnKind::Chat,
|
||||||
"beat" => TurnKind::Beat,
|
"beat" => TurnKind::Beat,
|
||||||
"reflection" => TurnKind::Reflection,
|
"reflection" => TurnKind::Reflection,
|
||||||
_ => bail!("{PROJECT_USAGE}"),
|
_ => bail!("{PROJECT_USAGE}"),
|
||||||
})
|
|
||||||
}
|
|
||||||
"--in" => here = Some(value()?),
|
|
||||||
"--room" => fixture = Some(Fixture::load(Path::new(&value()?))?),
|
|
||||||
"--seed" => seed = Some(value()?.parse::<u64>().map_err(|_| anyhow!("{PROJECT_USAGE}"))?),
|
|
||||||
"--state" => state = Some(value()?),
|
|
||||||
"--told" => told = Some(value()?),
|
|
||||||
"--renders" => renders = Some(value()?.parse::<usize>().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?),
|
|
||||||
"--judge" => judge = Some(value()?),
|
|
||||||
"--through" => {
|
|
||||||
through = match value()?.as_str() {
|
|
||||||
"projector" => Through::Projector,
|
|
||||||
"persona" => Through::Persona,
|
|
||||||
_ => bail!("{PROJECT_USAGE}"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"--batch" => batch_plan = Some(PathBuf::from(value()?)),
|
"--room" => room = Some(value()?),
|
||||||
"--simulate" => simulate_plan = Some(PathBuf::from(value()?)),
|
"--seed" => seed = Some(value()?.parse::<u64>().map_err(|_| anyhow!("{PROJECT_USAGE}"))?),
|
||||||
"--out" => out = Some(PathBuf::from(value()?)),
|
"--state" => state = Some(json_file(&value()?)?),
|
||||||
|
"--renders" => renders = Some(value()?.parse::<usize>().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?),
|
||||||
|
"--judge" => judge = Some(json_file(&value()?)?),
|
||||||
"--select-only" => select_only = true,
|
"--select-only" => select_only = true,
|
||||||
"--instance" | "--endpoint" => rest.extend([flag.clone(), value()?]),
|
"--instance" | "--endpoint" => rest.extend([flag.clone(), value()?]),
|
||||||
_ => bail!("{PROJECT_USAGE}"),
|
_ => bail!("{PROJECT_USAGE}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let planned = batch_plan.is_some() || simulate_plan.is_some();
|
if select_only && (renders.is_some() || judge.is_some()) {
|
||||||
// A plan carries its own states, rooms, seeds and stage; a fixture carries its own kind and room.
|
|
||||||
if (select_only && (renders.is_some() || judge.is_some() || through != Through::Projector))
|
|
||||||
|| (batch_plan.is_some() && simulate_plan.is_some())
|
|
||||||
|| (planned && (out.is_none() || fixture.is_some() || state.is_some() || told.is_some() || kind.is_some() || here.is_some() || seed.is_some() || renders.is_some() || judge.is_some() || select_only || through != Through::Projector))
|
|
||||||
|| (!planned && out.is_some())
|
|
||||||
|| (fixture.is_some() && (kind.is_some() || here.is_some()))
|
|
||||||
{
|
|
||||||
bail!("{PROJECT_USAGE}");
|
bail!("{PROJECT_USAGE}");
|
||||||
}
|
}
|
||||||
let (instance, address) = instance_and_maybe_endpoint(&rest, setting("HUGINN_ENDPOINT"), PROJECT_USAGE)?;
|
let (instance, address) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), PROJECT_USAGE)?;
|
||||||
let tuning = tuning_of(&instance);
|
let now = chrono::Utc::now();
|
||||||
// Her stored state is asked only when no state is given; with a state file no daemon is needed or reached.
|
let tuning = setting("MIND_PERSONA_TUNING").map_or_else(|| Path::new(TUNING_ROOT).join(&instance.0).join(TUNING_FILE), PathBuf::from);
|
||||||
let persona = address.map(|address| HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT)));
|
let persona = HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT));
|
||||||
let renders = if select_only || planned { None } else { Some(renders.unwrap_or(1)) };
|
let chat = match (setting("BIFROST_CHAT_ENDPOINT"), setting("BIFROST_CHAT_KEY_FILE")) {
|
||||||
let model = if renders.is_some() || planned {
|
(Some(endpoint), Some(_)) => {
|
||||||
let endpoint: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
|
let endpoint: SocketAddr = endpoint.strip_prefix("rudp://").and_then(|address| address.parse().ok()).ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://<ip>:<port>"))?;
|
||||||
Some(KitModel::open(endpoint, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?)
|
Some(RudpChat::new(endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT))
|
||||||
} else {
|
}
|
||||||
None
|
|
||||||
};
|
|
||||||
let harness = Harness { instance: instance.0.clone(), persona: persona.as_ref().map(|persona| persona as &dyn PersonaSource), model: model.as_ref().map(|model| model as &dyn Model), tuning };
|
|
||||||
if let Some(out) = out {
|
|
||||||
let report = match (&batch_plan, &simulate_plan) {
|
|
||||||
(Some(plan), _) => batch(&harness, plan)?,
|
|
||||||
(_, Some(plan)) => simulate(&harness, plan)?,
|
|
||||||
_ => unreachable!("a plan was given"),
|
|
||||||
};
|
|
||||||
std::fs::write(&out, &report).with_context(|| format!("the report {} could not be written", out.display()))?;
|
|
||||||
return Ok(format!("wrote {} ({} bytes)", out.display(), report.len()));
|
|
||||||
}
|
|
||||||
let state = state.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?;
|
|
||||||
let judge = judge.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?;
|
|
||||||
let told: Vec<serde_json::Value> = told.map(|path| rows_file(Path::new(&path))).transpose()?.unwrap_or_default();
|
|
||||||
let seed_now = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default();
|
|
||||||
if let Some(fixture) = &fixture {
|
|
||||||
// The fixture is the room, the clock and who is who: no mouth, no heartbeat table, no persona.env.
|
|
||||||
let organs = ProjectOrgans { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model, domain: fixture.domain(), reads: fixture.reads() };
|
|
||||||
let request = ProjectRequest { judge_against: judge, told: told.clone(), ..fixture_request(&harness, fixture, state, seed.unwrap_or(seed_now), renders, through) };
|
|
||||||
return Ok(serde_json::to_string_pretty(&project(&organs, &request, fixture.now)?)?);
|
|
||||||
}
|
|
||||||
let chat = chat(&instance)?;
|
|
||||||
let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new);
|
|
||||||
// Her domain: her mind through the endpoint given (her read door, for a Persona) and the forge, both read-only.
|
|
||||||
let domain = match (address, setting("MIND_PERSONA_FORGE_URL")) {
|
|
||||||
(Some(address), Some(forge)) => Some(MindDomain::new(HuginnClient::new(address, instance.clone(), TIMEOUT), HttpForge::new(&forge))),
|
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
// Her own rooms, as the heartbeat reads them: the rooms the mouth names for a repo she stewards. An unread mind or mouth is
|
let renders = if select_only { None } else { Some(renders.unwrap_or(1)) };
|
||||||
// said in the report, not read as no rooms.
|
let model = match renders {
|
||||||
let (own, own_unread) = match (address, &chat) {
|
Some(_) => {
|
||||||
(Some(address), Some(chat)) => match chat.pending() {
|
let endpoint: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
|
||||||
Ok(pending) => match own_rooms_among(&HuginnMind::new(HuginnClient::new(address, instance.clone(), TIMEOUT)), pending.deliveries.iter().map(|delivery| delivery.room_alias.as_str())) {
|
Some(KitModel::open(endpoint, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?)
|
||||||
Ok(rooms) => (rooms, None),
|
}
|
||||||
Err(error) => (vec![], Some(format!("her stewardships unread: {error}"))),
|
None => None,
|
||||||
},
|
|
||||||
Err(error) => (vec![], Some(format!("the mouth's pending unread: {error}"))),
|
|
||||||
},
|
|
||||||
_ => (vec![], None),
|
|
||||||
};
|
};
|
||||||
// The lines the heartbeat woke her for, from its handled keys; an unread state is said in the report, not read as none.
|
let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new);
|
||||||
let (woken, woken_unread) = match heartbeat.as_ref().map(Store::load) {
|
|
||||||
Some(Ok(state)) => (state.map(|state| woken_for(&state, &instance.0)).unwrap_or_default(), None),
|
|
||||||
Some(Err(error)) => (vec![], Some(format!("the heartbeat state unread: {error}"))),
|
|
||||||
None => (vec![], None),
|
|
||||||
};
|
|
||||||
// Her reads by intent (map 16.22.3): her mind through the same endpoint, the forge when it is named, the web.
|
|
||||||
let reads = address.map(|address| LiveReads::new(HuginnClient::new(address, instance.clone(), TIMEOUT), setting("MIND_PERSONA_FORGE_URL").map(|forge| HttpForge::new(&forge))));
|
|
||||||
let organs = ProjectOrgans {
|
let organs = ProjectOrgans {
|
||||||
persona: harness.persona,
|
persona: Some(&persona),
|
||||||
chat: chat.as_ref().map(|chat| chat as &dyn MouthReader),
|
chat: chat.as_ref().map(|chat| chat as &dyn MouthReader),
|
||||||
addressing: heartbeat.as_ref().map(|store| store as &dyn HeartbeatView),
|
addressing: heartbeat.as_ref().map(|store| store as &dyn HeartbeatView),
|
||||||
model: harness.model,
|
model: model.as_ref().map(|model| model as &dyn Model),
|
||||||
domain: domain.as_ref().map(|domain| domain as &dyn DomainSource),
|
|
||||||
reads: reads.as_ref().map(|reads| reads as &dyn ReadSource),
|
|
||||||
};
|
};
|
||||||
let request = ProjectRequest {
|
let request = ProjectRequest {
|
||||||
instance: instance.0.clone(),
|
instance: instance.0.clone(),
|
||||||
kind: kind.unwrap_or(TurnKind::Beat),
|
kind,
|
||||||
state,
|
state,
|
||||||
rooms: here.into_iter().collect(),
|
room,
|
||||||
seed: seed.unwrap_or(seed_now),
|
seed: seed.unwrap_or_else(|| u64::try_from(now.timestamp_millis()).unwrap_or_default()),
|
||||||
renders,
|
renders,
|
||||||
judge_against: judge,
|
judge_against: judge,
|
||||||
operators: setting("MIND_PERSONA_OPERATOR").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(),
|
operators: setting("MIND_PERSONA_OPERATOR").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(),
|
||||||
minds: setting("MIND_PERSONA_MINDS").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(),
|
minds: setting("MIND_PERSONA_MINDS").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(),
|
||||||
own_sender: required("MIND_PERSONA_SELF_SENDER")?,
|
own_sender: required("MIND_PERSONA_SELF_SENDER")?,
|
||||||
tuning: harness.tuning.clone(),
|
tuning,
|
||||||
through,
|
|
||||||
last_heard: vec![],
|
|
||||||
recent: vec![],
|
|
||||||
own_rooms: own,
|
|
||||||
woken_for: woken,
|
|
||||||
told,
|
|
||||||
tools: vec![],
|
|
||||||
last_wake: None,
|
|
||||||
records: vec![],
|
|
||||||
};
|
};
|
||||||
let mut report = project(&organs, &request, chrono::Utc::now())?;
|
let report = project(&organs, &request, now)?;
|
||||||
if let Some(unread) = own_unread {
|
|
||||||
report["own_rooms_unread"] = unread.into();
|
|
||||||
}
|
|
||||||
if let Some(unread) = woken_unread {
|
|
||||||
report["woken_for_unread"] = unread.into();
|
|
||||||
}
|
|
||||||
let addressing = &report["addressing"];
|
let addressing = &report["addressing"];
|
||||||
// The addressing source is what decides "said to her": said first, where a person running this by hand sees it.
|
// The addressing source is what decides "said to her": said first, where a person running this by hand sees it.
|
||||||
eprintln!(
|
eprintln!(
|
||||||
|
|
@ -372,30 +177,8 @@ fn main() {
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if args.first().map(String::as_str) == Some("box-exec") {
|
|
||||||
if let Err(error) = run_box_exec(&args[1..]) {
|
|
||||||
eprintln!("mind-persona box-exec: {error:#}");
|
|
||||||
std::process::exit(2);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if args.first().map(String::as_str) == Some("trace") {
|
|
||||||
match run_trace(&args[1..]) {
|
|
||||||
Ok(lines) => println!("{lines}"),
|
|
||||||
Err(error) => {
|
|
||||||
eprintln!("mind-persona trace: {error:#}");
|
|
||||||
std::process::exit(2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
match run() {
|
match run() {
|
||||||
Ok(outcome) => {
|
Ok(outcome) => println!("{outcome}"),
|
||||||
println!("{outcome}");
|
|
||||||
if matches!(outcome, Outcome::Failed(_)) {
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
eprintln!("mind-persona: {error:#}");
|
eprintln!("mind-persona: {error:#}");
|
||||||
std::process::exit(2);
|
std::process::exit(2);
|
||||||
|
|
|
||||||
|
|
@ -36,8 +36,6 @@ pub const ACK: &str = "gamecult.persona.chat_ack.v1";
|
||||||
pub const READ: &str = "gamecult.persona.chat_read.v1";
|
pub const READ: &str = "gamecult.persona.chat_read.v1";
|
||||||
pub const SEND_REQUEST: &str = "gamecult.persona.chat_send_request.v2";
|
pub const SEND_REQUEST: &str = "gamecult.persona.chat_send_request.v2";
|
||||||
pub const SEND_RECEIPT: &str = "gamecult.persona.chat_send_receipt.v2";
|
pub const SEND_RECEIPT: &str = "gamecult.persona.chat_send_receipt.v2";
|
||||||
/// A send that repeats an earlier one: the v2 tuple plus `resend`, answered with the v2 receipt.
|
|
||||||
pub const SEND_REQUEST_V3: &str = "gamecult.persona.chat_send_request.v3";
|
|
||||||
/// Her request that the mouth open a DM with a person, and its answer.
|
/// Her request that the mouth open a DM with a person, and its answer.
|
||||||
pub const OPEN_DIRECT_REQUEST: &str = "gamecult.persona.chat_open_direct_request.v1";
|
pub const OPEN_DIRECT_REQUEST: &str = "gamecult.persona.chat_open_direct_request.v1";
|
||||||
pub const OPEN_DIRECT_RECEIPT: &str = "gamecult.persona.chat_open_direct_receipt.v1";
|
pub const OPEN_DIRECT_RECEIPT: &str = "gamecult.persona.chat_open_direct_receipt.v1";
|
||||||
|
|
@ -96,11 +94,6 @@ pub struct ReplyTo {
|
||||||
pub event_id: String,
|
pub event_id: String,
|
||||||
pub sender: String,
|
pub sender: String,
|
||||||
pub excerpt: Option<String>,
|
pub excerpt: Option<String>,
|
||||||
/// Whether the excerpt as sent reached `REPLY_EXCERPT_CHARS`, the mouth's cap: the line may run on past it, cut wherever the
|
|
||||||
/// cap fell. A line of exactly the cap reads as cut too; the mouth says nothing that tells the two apart. Read off the decode,
|
|
||||||
/// never sent.
|
|
||||||
#[serde(skip)]
|
|
||||||
pub at_cap: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How a reply link out of the mouth's contract fails it, first by tuple order. A class and nothing the mouth sent, so no path can echo
|
/// How a reply link out of the mouth's contract fails it, first by tuple order. A class and nothing the mouth sent, so no path can echo
|
||||||
|
|
@ -318,11 +311,11 @@ impl<'de> Deserialize<'de> for ReplyLink {
|
||||||
(Some(Element::Text(event_id)), _, _) if !event_id_shape(&event_id) => Self::Dropped(ReplyViolation::BadEventId),
|
(Some(Element::Text(event_id)), _, _) if !event_id_shape(&event_id) => Self::Dropped(ReplyViolation::BadEventId),
|
||||||
(Some(Element::Text(_)), Some(Element::Text(sender)), _) if !matrix_user_id(&sender) => Self::Dropped(ReplyViolation::BadSenderId),
|
(Some(Element::Text(_)), Some(Element::Text(sender)), _) if !matrix_user_id(&sender) => Self::Dropped(ReplyViolation::BadSenderId),
|
||||||
(Some(Element::Text(event_id)), Some(Element::Text(sender)), Some(excerpt)) => match excerpt {
|
(Some(Element::Text(event_id)), Some(Element::Text(sender)), Some(excerpt)) => match excerpt {
|
||||||
Element::Nil => Self::Quote(ReplyTo { event_id, sender, excerpt: None, at_cap: false }),
|
Element::Nil => Self::Quote(ReplyTo { event_id, sender, excerpt: None }),
|
||||||
Element::Text(text) if text.chars().take(REPLY_EXCERPT_CHARS + 1).count() > REPLY_EXCERPT_CHARS => Self::Dropped(ReplyViolation::ExcerptTooLong),
|
Element::Text(text) if text.chars().take(REPLY_EXCERPT_CHARS + 1).count() > REPLY_EXCERPT_CHARS => Self::Dropped(ReplyViolation::ExcerptTooLong),
|
||||||
Element::Text(text) => {
|
Element::Text(text) => {
|
||||||
let (shown, at_cap) = (without_invisible(&text), text.chars().count() == REPLY_EXCERPT_CHARS);
|
let shown = without_invisible(&text);
|
||||||
Self::Quote(ReplyTo { event_id, sender, excerpt: if shown.is_empty() { None } else { Some(shown) }, at_cap })
|
Self::Quote(ReplyTo { event_id, sender, excerpt: if shown.is_empty() { None } else { Some(shown) } })
|
||||||
}
|
}
|
||||||
_ => Self::Dropped(ReplyViolation::ExcerptNotText),
|
_ => Self::Dropped(ReplyViolation::ExcerptNotText),
|
||||||
},
|
},
|
||||||
|
|
@ -462,10 +455,8 @@ pub struct ChatPending {
|
||||||
pub tail_gaps: Vec<String>,
|
pub tail_gaps: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One line of the room tail: `[room, event_id, at_unix_ms, sender, form, basis, body, reply_to]`. `room` is the configured alias (the
|
/// One line of the room tail: `[room, event_id, at_unix_ms, sender, form, basis, body]`. `room` is the configured alias (the room id
|
||||||
/// room id for a DM); `basis` is what Matrix says on the event itself, none being unproven; `body` is untrusted text clipped by the
|
/// for a DM); `basis` is what Matrix says on the event itself, none being unproven; `body` is untrusted text clipped by the mouth.
|
||||||
/// mouth; `reply_to` is the event the line replies to, quoted as a delivery's is (Bifrost B3, map 16.20.10 K20). A mouth that sends
|
|
||||||
/// seven fields sends no reply links, and every line reads as replying to nothing.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct TailLine {
|
pub struct TailLine {
|
||||||
pub room: String,
|
pub room: String,
|
||||||
|
|
@ -475,8 +466,6 @@ pub struct TailLine {
|
||||||
pub form: Form,
|
pub form: Form,
|
||||||
pub basis: Option<Basis>,
|
pub basis: Option<Basis>,
|
||||||
pub body: String,
|
pub body: String,
|
||||||
#[serde(default, skip_serializing_if = "ReplyLink::sends_nothing")]
|
|
||||||
pub reply_to: ReplyLink,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
|
@ -507,24 +496,15 @@ pub enum Refusal {
|
||||||
PersonaMismatch,
|
PersonaMismatch,
|
||||||
UnknownRoom,
|
UnknownRoom,
|
||||||
EmptyText,
|
EmptyText,
|
||||||
/// The PUT was attempted and not answered (timed out, 5xx, 429): the event may exist.
|
|
||||||
SendFailed,
|
SendFailed,
|
||||||
/// The mouth attempted no PUT (its start, a room join or a head read failed first): the send is certainly not posted.
|
|
||||||
NotSent,
|
|
||||||
UnknownPersona,
|
UnknownPersona,
|
||||||
/// A send with a basis found the room had moved past it: the receipt names what moved it.
|
/// A send with a basis found the room had moved past it: the receipt names what moved it.
|
||||||
RoomMoved,
|
RoomMoved,
|
||||||
/// A resend the mouth cannot vouch for: it did not attempt that request id for this Persona and room within its resend window (forgotten,
|
|
||||||
/// too old, lost in a restart). It posted nothing now, and whether the first try posted is unknown.
|
|
||||||
ResendUnknown,
|
|
||||||
/// The mouth does not serve this document kind. Answers an open-direct request only: a send receipt never carries it.
|
/// The mouth does not serve this document kind. Answers an open-direct request only: a send receipt never carries it.
|
||||||
UnknownKind,
|
UnknownKind,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Refusal {
|
impl Refusal {
|
||||||
/// Every kind the mouth names.
|
|
||||||
pub const ALL: [Self; 10] = [Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::NotSent, Self::UnknownPersona, Self::RoomMoved, Self::ResendUnknown, Self::UnknownKind];
|
|
||||||
|
|
||||||
/// The mouth's spelling: a MessagePack string, whatever the codec does with unit variants.
|
/// The mouth's spelling: a MessagePack string, whatever the codec does with unit variants.
|
||||||
pub fn name(self) -> &'static str {
|
pub fn name(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
|
|
@ -533,44 +513,13 @@ impl Refusal {
|
||||||
Self::UnknownRoom => "UnknownRoom",
|
Self::UnknownRoom => "UnknownRoom",
|
||||||
Self::EmptyText => "EmptyText",
|
Self::EmptyText => "EmptyText",
|
||||||
Self::SendFailed => "SendFailed",
|
Self::SendFailed => "SendFailed",
|
||||||
Self::NotSent => "NotSent",
|
|
||||||
Self::UnknownPersona => "UnknownPersona",
|
Self::UnknownPersona => "UnknownPersona",
|
||||||
Self::RoomMoved => "RoomMoved",
|
Self::RoomMoved => "RoomMoved",
|
||||||
Self::ResendUnknown => "ResendUnknown",
|
|
||||||
Self::UnknownKind => "UnknownKind",
|
Self::UnknownKind => "UnknownKind",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Refusal {
|
|
||||||
/// What the mouth's refusal says of a send, by whether the send repeats one already handed to the mouth (`resend`): the homeserver was
|
|
||||||
/// not heard, so the event may exist and the send stays handed (`NoAnswer`); the mouth attempted no PUT (`NotSent`); an earlier try's
|
|
||||||
/// outcome cannot be told, so the send is never repeated (`Unknown`); or the mouth declined before it put anything (`Declined`), which
|
|
||||||
/// for a repeat says nothing of the earlier try, whose outcome stays unknown. The match names every kind, so a new one has to be placed.
|
|
||||||
pub(crate) fn reading(self, resend: bool) -> Reading {
|
|
||||||
match self {
|
|
||||||
// The mouth's PUT timed out or the homeserver answered 5xx or 429: the event may have been persisted, and the same id is safe to repeat.
|
|
||||||
Self::SendFailed => Reading::NoAnswer,
|
|
||||||
// The mouth made no PUT this time.
|
|
||||||
Self::NotSent => Reading::NotSent,
|
|
||||||
// A resend the mouth does not remember attempting: the first try may have posted, and the id can no longer be told from a new line.
|
|
||||||
Self::ResendUnknown => Reading::Unknown,
|
|
||||||
// The mouth's checks that come before its vouch for a resend, and `RoomMoved`, which a resend skips.
|
|
||||||
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind if resend => Reading::Unknown,
|
|
||||||
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind => Reading::Declined,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How a send's settlement reads a refusal.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) enum Reading {
|
|
||||||
Declined,
|
|
||||||
NoAnswer,
|
|
||||||
NotSent,
|
|
||||||
Unknown,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Serialize for Refusal {
|
impl Serialize for Refusal {
|
||||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||||
serializer.serialize_str(self.name())
|
serializer.serialize_str(self.name())
|
||||||
|
|
@ -580,7 +529,7 @@ impl Serialize for Refusal {
|
||||||
impl<'de> Deserialize<'de> for Refusal {
|
impl<'de> Deserialize<'de> for Refusal {
|
||||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||||
let name = String::deserialize(deserializer)?;
|
let name = String::deserialize(deserializer)?;
|
||||||
Self::ALL
|
[Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::UnknownPersona, Self::RoomMoved, Self::UnknownKind]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|refusal| refusal.name() == name)
|
.find(|refusal| refusal.name() == name)
|
||||||
.ok_or_else(|| serde::de::Error::custom("the mouth named a refusal this side does not know"))
|
.ok_or_else(|| serde::de::Error::custom("the mouth named a refusal this side does not know"))
|
||||||
|
|
@ -618,9 +567,7 @@ pub struct SendBasis {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A send. `request_id` is the mouth's transaction id, so a repeat of the same
|
/// A send. `request_id` is the mouth's transaction id, so a repeat of the same
|
||||||
/// id is the same send. No `basis` is her choice standing: the mouth checks nothing. `resend` says this repeats an earlier send
|
/// id is the same send. No `basis` is her choice standing: the mouth checks nothing.
|
||||||
/// under the same id: the mouth does not check its basis (the decision was made against the first try's), and the homeserver answers
|
|
||||||
/// with the first try's event if it was made. It is on the wire only when true, as the sixth field of the v3 request.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct ChatSendRequest {
|
pub struct ChatSendRequest {
|
||||||
pub request_id: String,
|
pub request_id: String,
|
||||||
|
|
@ -628,8 +575,6 @@ pub struct ChatSendRequest {
|
||||||
pub room_alias: String,
|
pub room_alias: String,
|
||||||
pub text: String,
|
pub text: String,
|
||||||
pub basis: Option<SendBasis>,
|
pub basis: Option<SendBasis>,
|
||||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
|
||||||
pub resend: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The mouth's answer to a send: the event it made, or why it did not. `newer` names the events that moved the
|
/// The mouth's answer to a send: the event it made, or why it did not. `newer` names the events that moved the
|
||||||
|
|
|
||||||
|
|
@ -129,28 +129,12 @@ fn the_pending_answer_decodes_with_the_tail_field_and_without_it() {
|
||||||
golden(PENDING_UNPROVEN_NOTICE_TAILED_BYTES, &one(false, &[], None, Form::Notice, Some(vec![])));
|
golden(PENDING_UNPROVEN_NOTICE_TAILED_BYTES, &one(false, &[], None, Form::Notice, Some(vec![])));
|
||||||
let tailed: ChatPending = decode(PENDING_TAIL_BYTES).unwrap();
|
let tailed: ChatPending = decode(PENDING_TAIL_BYTES).unwrap();
|
||||||
assert!(tailed.deliveries.is_empty());
|
assert!(tailed.deliveries.is_empty());
|
||||||
let line = |event: &str, at, form, basis, body: &str| TailLine { room: "#operator:gamecult.org".into(), event_id: event.into(), at_unix_ms: at, sender: "@meta:gamecult.org".into(), form, basis, body: body.into(), reply_to: ReplyLink::Absent };
|
let line = |event: &str, at, form, basis, body: &str| TailLine { room: "#operator:gamecult.org".into(), event_id: event.into(), at_unix_ms: at, sender: "@meta:gamecult.org".into(), form, basis, body: body.into() };
|
||||||
assert_eq!(tailed.tail, Some(vec![line("$e0", 1_700_000_000_000, Form::Message, None, "earlier"), line("$e1", 1_700_000_001_000, Form::Notice, Some(Basis::Tag), "hello eureka")]));
|
assert_eq!(tailed.tail, Some(vec![line("$e0", 1_700_000_000_000, Form::Message, None, "earlier"), line("$e1", 1_700_000_001_000, Form::Notice, Some(Basis::Tag), "hello eureka")]));
|
||||||
golden(PENDING_TAIL_BYTES, &tailed);
|
golden(PENDING_TAIL_BYTES, &tailed);
|
||||||
assert_eq!(rmp_serde::from_slice::<serde_json::Value>(PENDING_TAIL_BYTES).unwrap()[2][0].as_array().unwrap().len(), 7, "a tail line is seven fields");
|
assert_eq!(rmp_serde::from_slice::<serde_json::Value>(PENDING_TAIL_BYTES).unwrap()[2][0].as_array().unwrap().len(), 7, "a tail line is seven fields");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A tail line may carry the event it replies to at index 7, quoted as a delivery's is (Bifrost B3, map 16.20.10 K20): a quote decodes,
|
|
||||||
/// a defective one is dropped without failing the poll, and a line without it replies to nothing and encodes as seven fields again.
|
|
||||||
#[test]
|
|
||||||
fn a_tail_line_carries_the_event_it_replies_to() {
|
|
||||||
let mut value: serde_json::Value = rmp_serde::from_slice(PENDING_TAIL_BYTES).unwrap();
|
|
||||||
value[2][1].as_array_mut().unwrap().push(serde_json::json!(["$e0", "@meta:gamecult.org", "earlier"]));
|
|
||||||
value[2][0].as_array_mut().unwrap().push(serde_json::json!(["$q", "@a:b", 5]));
|
|
||||||
let tail = decode::<ChatPending>(&rmp_serde::to_vec(&value).unwrap()).unwrap().tail.unwrap();
|
|
||||||
assert_eq!(tail[1].reply_to, ReplyLink::Quote(ReplyTo { event_id: "$e0".into(), sender: "@meta:gamecult.org".into(), excerpt: Some("earlier".into()), at_cap: false }));
|
|
||||||
assert_eq!(tail[0].reply_to, ReplyLink::Dropped(ReplyViolation::ExcerptNotText), "a defective link drops that quote only");
|
|
||||||
let plain: ChatPending = decode(PENDING_TAIL_BYTES).unwrap();
|
|
||||||
assert!(plain.tail.unwrap().iter().all(|line| line.reply_to == ReplyLink::Absent), "seven fields reply to nothing");
|
|
||||||
let reencoded: serde_json::Value = rmp_serde::from_slice(&encode(&decode::<ChatPending>(&rmp_serde::to_vec(&value).unwrap()).unwrap()).unwrap()).unwrap();
|
|
||||||
assert_eq!((reencoded[2][0].as_array().unwrap().len(), reencoded[2][1].as_array().unwrap().len()), (7, 8), "only a quote is sent");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_basis_or_form_this_side_does_not_know_does_not_decode() {
|
fn a_basis_or_form_this_side_does_not_know_does_not_decode() {
|
||||||
let mut value: serde_json::Value = rmp_serde::from_slice(PENDING_TAG_BYTES).unwrap();
|
let mut value: serde_json::Value = rmp_serde::from_slice(PENDING_TAG_BYTES).unwrap();
|
||||||
|
|
@ -200,7 +184,7 @@ fn a_refusal_is_the_mouths_bytes_and_a_typed_name() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_send_and_its_receipt_are_the_mouths_bytes() {
|
fn a_send_and_its_receipt_are_the_mouths_bytes() {
|
||||||
let request = |basis: Option<SendBasis>| ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#swarm:gamecult.org".into(), text: "hi".into(), basis, resend: false };
|
let request = |basis: Option<SendBasis>| ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#swarm:gamecult.org".into(), text: "hi".into(), basis };
|
||||||
golden(NIL_BASIS_BYTES, &request(None));
|
golden(NIL_BASIS_BYTES, &request(None));
|
||||||
golden(SEEN_AND_SINCE_BYTES, &request(Some(SendBasis { seen_event_id: Some("$seen".into()), since_unix_ms: 1_793_698_425_998 })));
|
golden(SEEN_AND_SINCE_BYTES, &request(Some(SendBasis { seen_event_id: Some("$seen".into()), since_unix_ms: 1_793_698_425_998 })));
|
||||||
golden(SINCE_ONLY_BYTES, &request(Some(SendBasis { seen_event_id: None, since_unix_ms: 1_793_698_425_998 })));
|
golden(SINCE_ONLY_BYTES, &request(Some(SendBasis { seen_event_id: None, since_unix_ms: 1_793_698_425_998 })));
|
||||||
|
|
@ -349,7 +333,7 @@ fn the_pending_answer_decodes_tail_gaps_and_defaults_them_to_none() {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn quote(sender: &str, excerpt: Option<&str>) -> ReplyLink {
|
fn quote(sender: &str, excerpt: Option<&str>) -> ReplyLink {
|
||||||
ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: sender.into(), excerpt: excerpt.map(Into::into), at_cap: false })
|
ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: sender.into(), excerpt: excerpt.map(Into::into) })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The v4 answers carry `reply_to` at delivery index 14. The mouth always sends the fourth, empty `tail_gaps` element on a v4 answer,
|
/// The v4 answers carry `reply_to` at delivery index 14. The mouth always sends the fourth, empty `tail_gaps` element on a v4 answer,
|
||||||
|
|
@ -578,7 +562,7 @@ fn format_and_private_use_characters_are_stripped_from_the_excerpt() {
|
||||||
fn an_excerpt_emptied_by_stripping_is_none_and_the_quote_stays() {
|
fn an_excerpt_emptied_by_stripping_is_none_and_the_quote_stays() {
|
||||||
for sent in ["\u{FE0F}", "\u{200B}\u{E0049}", &"\u{FE0F}\u{200D}".repeat(5), ""] {
|
for sent in ["\u{FE0F}", "\u{200B}\u{E0049}", &"\u{FE0F}\u{200D}".repeat(5), ""] {
|
||||||
let link = link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", sent])));
|
let link = link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", sent])));
|
||||||
assert_eq!(link, ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: "@alice:gamecult.org".into(), excerpt: None, at_cap: false }), "{sent:?}");
|
assert_eq!(link, ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: "@alice:gamecult.org".into(), excerpt: None }), "{sent:?}");
|
||||||
}
|
}
|
||||||
assert_eq!(excerpt_of(" ").as_deref(), Some(" "));
|
assert_eq!(excerpt_of(" ").as_deref(), Some(" "));
|
||||||
assert_eq!(link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", null]))), quote("@alice:gamecult.org", None));
|
assert_eq!(link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", null]))), quote("@alice:gamecult.org", None));
|
||||||
|
|
@ -592,11 +576,6 @@ fn the_excerpt_bound_is_checked_before_the_strip_and_never_clips() {
|
||||||
assert_eq!(dropped_as(long(240, "\u{FE0F}")), Some(ReplyViolation::ExcerptTooLong));
|
assert_eq!(dropped_as(long(240, "\u{FE0F}")), Some(ReplyViolation::ExcerptTooLong));
|
||||||
assert_eq!(excerpt_of(&format!("{}\u{FE0F}", "x".repeat(239))).map(|t| t.chars().count()), Some(239));
|
assert_eq!(excerpt_of(&format!("{}\u{FE0F}", "x".repeat(239))).map(|t| t.chars().count()), Some(239));
|
||||||
assert_eq!(dropped_as(serde_json::json!(["$q1", "@a:b", "\u{FE0F}".repeat(1_000_000)])), Some(ReplyViolation::ExcerptTooLong));
|
assert_eq!(dropped_as(serde_json::json!(["$q1", "@a:b", "\u{FE0F}".repeat(1_000_000)])), Some(ReplyViolation::ExcerptTooLong));
|
||||||
// An excerpt that reached the cap as sent may be cut, whatever the strip left of it; one short of it is whole.
|
|
||||||
let at_cap = |sent: serde_json::Value| link_of(&answer_with(sent)).quote().map(|quote| quote.at_cap);
|
|
||||||
assert_eq!(at_cap(long(240, "")), Some(true));
|
|
||||||
assert_eq!(at_cap(long(239, "\u{FE0F}")), Some(true));
|
|
||||||
assert_eq!(at_cap(long(239, "")), Some(false));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Invalid UTF-8 in the excerpt's bytes is a defect of that quote, never of the document.
|
/// Invalid UTF-8 in the excerpt's bytes is a defect of that quote, never of the document.
|
||||||
|
|
@ -668,16 +647,3 @@ fn invisible_cells_that_render_as_nothing_are_stripped_from_the_excerpt() {
|
||||||
assert_eq!(excerpt_of("\u{2800}\u{3164}"), None);
|
assert_eq!(excerpt_of("\u{2800}\u{3164}"), None);
|
||||||
assert_eq!(excerpt_of("a\u{00A0}b").as_deref(), Some("a\u{00A0}b"), "NBSP stays");
|
assert_eq!(excerpt_of("a\u{00A0}b").as_deref(), Some("a\u{00A0}b"), "NBSP stays");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The v3 send is the v2 tuple plus `resend` (Bifrost `sendRequestV3Tuple`), and a first try stays the v2 tuple the mouth has always read.
|
|
||||||
#[test]
|
|
||||||
fn a_resend_is_the_v2_tuple_plus_one_boolean_and_a_first_send_is_the_v2_tuple() {
|
|
||||||
let first = ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#swarm:gamecult.org".into(), text: "hi".into(), basis: None, resend: false };
|
|
||||||
let again = ChatSendRequest { resend: true, ..first.clone() };
|
|
||||||
let fields = |request: &ChatSendRequest| decode::<Vec<serde_json::Value>>(&encode(request).unwrap()).unwrap();
|
|
||||||
assert_eq!(fields(&first).len(), 5);
|
|
||||||
let sent = fields(&again);
|
|
||||||
assert_eq!((sent.len(), &sent[5]), (6, &serde_json::Value::Bool(true)));
|
|
||||||
assert_eq!(decode::<ChatSendRequest>(&encode(&again).unwrap()).unwrap(), again);
|
|
||||||
assert_eq!(decode::<ChatSendRequest>(&encode(&first).unwrap()).unwrap(), first, "a v2 tuple reads as a first send");
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@ use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::chat_client::{
|
use crate::chat_client::{
|
||||||
ACK, Chat, ChatAck, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatPendingRequest, ChatRead, ChatRefusal, MouthRefused, Refusal, reply_warnings, ChatSendReceipt, ChatSendRequest, PENDING, PENDING_REQUEST, PENDING_REQUEST_V1, PENDING_REQUEST_V4, PENDING_V2, PENDING_V4, OPEN_DIRECT_RECEIPT, OPEN_DIRECT_REQUEST, FETCH_RECEIPT, FETCH_REQUEST, PENDING_V1, READ, REFUSAL, SEND_RECEIPT,
|
ACK, Chat, ChatAck, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatPendingRequest, ChatRead, ChatRefusal, MouthRefused, Refusal, reply_warnings, ChatSendReceipt, ChatSendRequest, PENDING, PENDING_REQUEST, PENDING_REQUEST_V1, PENDING_REQUEST_V4, PENDING_V2, PENDING_V4, OPEN_DIRECT_RECEIPT, OPEN_DIRECT_REQUEST, FETCH_RECEIPT, FETCH_REQUEST, PENDING_V1, READ, REFUSAL, SEND_RECEIPT,
|
||||||
SEND_REQUEST, SEND_REQUEST_V3, decode, encode,
|
SEND_REQUEST, decode, encode,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The tag every chat document carries; the mouth refuses any other.
|
/// The tag every chat document carries; the mouth refuses any other.
|
||||||
|
|
@ -202,17 +202,7 @@ impl Chat for RudpChat {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
|
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
|
||||||
let receipt: ChatSendReceipt = if request.resend {
|
let receipt: ChatSendReceipt = self.call(SEND_REQUEST, &request.request_id, request, (SEND_RECEIPT, &request.request_id))?;
|
||||||
// A mouth that does not serve v3 answers `UnknownKind` keyed by the persona: heard here, the resend is known not made.
|
|
||||||
let answers = [(SEND_RECEIPT, request.request_id.as_str()), (REFUSAL, self.persona.as_str())];
|
|
||||||
let (kind, payload) = self.exchange(SEND_REQUEST_V3, &request.request_id, request, Some(&answers))?.ok_or_else(|| anyhow!("no answer payload"))?;
|
|
||||||
if kind == REFUSAL {
|
|
||||||
bail!("the mouth refused the resend: {}", decode::<ChatRefusal>(&payload)?.refusal.name());
|
|
||||||
}
|
|
||||||
decode(&payload)?
|
|
||||||
} else {
|
|
||||||
self.call(SEND_REQUEST, &request.request_id, request, (SEND_RECEIPT, &request.request_id))?
|
|
||||||
};
|
|
||||||
if receipt.request_id != request.request_id {
|
if receipt.request_id != request.request_id {
|
||||||
bail!("the mouth answered another send");
|
bail!("the mouth answered another send");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -45,13 +45,6 @@ const USAGE: &str =
|
||||||
/// `rudp://<ip>:<port>` is refused with `usage` or a fixed message, and no
|
/// `rudp://<ip>:<port>` is refused with `usage` or a fixed message, and no
|
||||||
/// value is echoed.
|
/// value is echoed.
|
||||||
pub fn instance_and_endpoint(args: &[String], env_endpoint: Option<String>, usage: &str) -> Result<(Slug, SocketAddr)> {
|
pub fn instance_and_endpoint(args: &[String], env_endpoint: Option<String>, usage: &str) -> Result<(Slug, SocketAddr)> {
|
||||||
let (instance, endpoint) = instance_and_maybe_endpoint(args, env_endpoint, usage)?;
|
|
||||||
Ok((instance, endpoint.ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `instance_and_endpoint` for a binary that may run without a daemon (`mind-persona project` over a state file): no
|
|
||||||
/// endpoint given is none, and one given is still checked.
|
|
||||||
pub fn instance_and_maybe_endpoint(args: &[String], env_endpoint: Option<String>, usage: &str) -> Result<(Slug, Option<SocketAddr>)> {
|
|
||||||
let (mut instance, mut endpoint) = (None, None);
|
let (mut instance, mut endpoint) = (None, None);
|
||||||
let mut rest = args.iter();
|
let mut rest = args.iter();
|
||||||
while let Some(flag) = rest.next() {
|
while let Some(flag) = rest.next() {
|
||||||
|
|
@ -67,12 +60,12 @@ pub fn instance_and_maybe_endpoint(args: &[String], env_endpoint: Option<String>
|
||||||
}
|
}
|
||||||
let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?);
|
let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?);
|
||||||
instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?;
|
instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?;
|
||||||
let Some(endpoint) = endpoint.or(env_endpoint) else { return Ok((instance, None)) };
|
let endpoint = endpoint.or(env_endpoint).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?;
|
||||||
let address = endpoint
|
let address = endpoint
|
||||||
.strip_prefix("rudp://")
|
.strip_prefix("rudp://")
|
||||||
.and_then(|address| address.parse::<SocketAddr>().ok())
|
.and_then(|address| address.parse::<SocketAddr>().ok())
|
||||||
.ok_or_else(|| anyhow!("the endpoint is not rudp://<ip>:<port>"))?;
|
.ok_or_else(|| anyhow!("the endpoint is not rudp://<ip>:<port>"))?;
|
||||||
Ok((instance, Some(address)))
|
Ok((instance, address))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty
|
/// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@
|
||||||
//!
|
//!
|
||||||
//! A held swarm brake ends the poll before the mind or the mouth is touched.
|
//! A held swarm brake ends the poll before the mind or the mouth is touched.
|
||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::BTreeMap;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
@ -32,11 +32,9 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug};
|
||||||
use huginn_mind::PipelineFacts;
|
use huginn_mind::PipelineFacts;
|
||||||
|
|
||||||
use crate::address::{Addressee, Name, is_for, project_names};
|
use crate::address::{Addressee, Name, is_for, project_names};
|
||||||
use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending, Form};
|
use crate::chat_client::{Chat, ChatDelivery};
|
||||||
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
|
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
|
||||||
use crate::launch::{Clock, Launcher};
|
use crate::launch::{Clock, Launcher};
|
||||||
use crate::persona::TraceView;
|
|
||||||
use crate::projection::{decided, failed_run};
|
|
||||||
use crate::queue::{MindPort, headers, in_force, of_kind};
|
use crate::queue::{MindPort, headers, in_force, of_kind};
|
||||||
use crate::tempo::{self, Standing};
|
use crate::tempo::{self, Standing};
|
||||||
|
|
||||||
|
|
@ -44,8 +42,6 @@ use crate::tempo::{self, Standing};
|
||||||
const MENTIONS_KEPT: usize = 64;
|
const MENTIONS_KEPT: usize = 64;
|
||||||
/// The most pages of pending chat one poll reads for one Persona.
|
/// The most pages of pending chat one poll reads for one Persona.
|
||||||
const PENDING_PAGES: usize = 16;
|
const PENDING_PAGES: usize = 16;
|
||||||
/// How long after one failed wake the next may come, in seconds; each failure in a row doubles it, up to the beat.
|
|
||||||
const BACKOFF_BASE_S: i64 = 20;
|
|
||||||
/// The beat, in seconds, when `HEARTBEAT_BEAT_S` is not set.
|
/// The beat, in seconds, when `HEARTBEAT_BEAT_S` is not set.
|
||||||
pub const DEFAULT_BEAT_S: u32 = 1800;
|
pub const DEFAULT_BEAT_S: u32 = 1800;
|
||||||
|
|
||||||
|
|
@ -102,15 +98,11 @@ pub struct Config {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
/// Refuses no Persona, a Persona twice, a beat of zero seconds, or an operator id that is also a Persona's: one
|
/// Refuses no Persona, a Persona twice, or a beat of zero seconds.
|
||||||
/// sender is either the operator or a Mind, never both, or the wake rule could not tell which it heard.
|
|
||||||
pub fn new(personas: Vec<PersonaId>, operators: Vec<String>, beat_s: u32) -> Result<Self> {
|
pub fn new(personas: Vec<PersonaId>, operators: Vec<String>, beat_s: u32) -> Result<Self> {
|
||||||
if personas.is_empty() {
|
if personas.is_empty() {
|
||||||
bail!("no persona is configured");
|
bail!("no persona is configured");
|
||||||
}
|
}
|
||||||
if operators.iter().any(|operator| personas.iter().any(|persona| persona.matrix_id == *operator)) {
|
|
||||||
bail!("an operator id is also a persona's matrix id");
|
|
||||||
}
|
|
||||||
if beat_s == 0 {
|
if beat_s == 0 {
|
||||||
bail!("the beat is zero seconds");
|
bail!("the beat is zero seconds");
|
||||||
}
|
}
|
||||||
|
|
@ -145,10 +137,6 @@ pub struct HeartbeatState {
|
||||||
/// When the heartbeat last started each Persona's turn, by instance slug.
|
/// When the heartbeat last started each Persona's turn, by instance slug.
|
||||||
#[cultcache(key = 2, default)]
|
#[cultcache(key = 2, default)]
|
||||||
pub last_turn_at: BTreeMap<String, DateTime<Utc>>,
|
pub last_turn_at: BTreeMap<String, DateTime<Utc>>,
|
||||||
/// Retired slot 3, once the owed waker's count of starts. Nothing reads or writes it beyond the default; it stays declared because deployed state
|
|
||||||
/// files hold four slots and the store refuses to save over a record with a slot its type does not declare (read-only), so the heartbeat could not save.
|
|
||||||
#[cultcache(key = 3, default)]
|
|
||||||
pub retired_slot_3: BTreeMap<String, u32>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATE_KEY: &str = "state";
|
const STATE_KEY: &str = "state";
|
||||||
|
|
@ -229,25 +217,6 @@ pub trait Store {
|
||||||
fn save_addressing(&self, addressing: &Addressing) -> Result<()>;
|
fn save_addressing(&self, addressing: &Addressing) -> Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The lines a wake of one Mind is for: the line that woke her (none for the beat's) and the open-floor lines she took. The
|
|
||||||
/// one derivation: the poll records them as her handled keys, `woken_for` reads them back for her packet, and the simulator
|
|
||||||
/// hands her packet the same, so the simulator measures what live does.
|
|
||||||
pub(crate) fn claimed(waking: Option<&str>, floor: &[String]) -> Vec<String> {
|
|
||||||
let mut events: Vec<String> = Vec::new();
|
|
||||||
for event in waking.into_iter().chain(floor.iter().map(String::as_str)) {
|
|
||||||
if !events.iter().any(|held| held == event) {
|
|
||||||
events.push(event.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
events
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The lines the heartbeat woke `slug` for, as her handled keys name them (`slug:event`): what her packet reads as said to
|
|
||||||
/// her, so the wake and the packet cannot disagree about whose line it was.
|
|
||||||
pub fn woken_for(state: &HeartbeatState, slug: &str) -> Vec<String> {
|
|
||||||
state.handled_mentions.iter().filter_map(|key| key.split_once(':').filter(|(who, _)| *who == slug).map(|(_, event)| event.to_owned())).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a Persona unit may read of `heartbeat.cc`: the swarm's addressing. Read-only.
|
/// What a Persona unit may read of `heartbeat.cc`: the swarm's addressing. Read-only.
|
||||||
pub trait HeartbeatView {
|
pub trait HeartbeatView {
|
||||||
fn addressing(&self) -> Result<Option<Addressing>>;
|
fn addressing(&self) -> Result<Option<Addressing>>;
|
||||||
|
|
@ -255,11 +224,6 @@ pub trait HeartbeatView {
|
||||||
fn written_at(&self) -> Option<DateTime<Utc>> {
|
fn written_at(&self) -> Option<DateTime<Utc>> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
/// The lines the heartbeat woke `slug` for (`woken_for`): the poll records them before it starts her unit, so a start finds
|
|
||||||
/// them. A view with no heartbeat behind it names none.
|
|
||||||
fn woken_for(&self, _slug: &str) -> Result<Vec<String>> {
|
|
||||||
Ok(Vec::new())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The store as a CultCache single-file store under the unit's state directory.
|
/// The store as a CultCache single-file store under the unit's state directory.
|
||||||
|
|
@ -359,10 +323,6 @@ impl HeartbeatView for FileStore {
|
||||||
fn written_at(&self) -> Option<DateTime<Utc>> {
|
fn written_at(&self) -> Option<DateTime<Utc>> {
|
||||||
std::fs::metadata(&self.path).and_then(|meta| meta.modified()).ok().map(DateTime::<Utc>::from)
|
std::fs::metadata(&self.path).and_then(|meta| meta.modified()).ok().map(DateTime::<Utc>::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn woken_for(&self, slug: &str) -> Result<Vec<String>> {
|
|
||||||
Ok(self.load()?.map(|state| woken_for(&state, slug)).unwrap_or_default())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the operator stores allow: the swarm brake, and each instance's own
|
/// What the operator stores allow: the swarm brake, and each instance's own
|
||||||
|
|
@ -390,8 +350,6 @@ pub struct Seat<'a> {
|
||||||
pub who: PersonaId,
|
pub who: PersonaId,
|
||||||
pub mind: &'a dyn MindPort,
|
pub mind: &'a dyn MindPort,
|
||||||
pub chat: &'a dyn Chat,
|
pub chat: &'a dyn Chat,
|
||||||
/// Her trace, read-only: the one record of which lines she has decided.
|
|
||||||
pub trace: &'a dyn TraceView,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Organs<'a> {
|
pub struct Organs<'a> {
|
||||||
|
|
@ -435,354 +393,34 @@ pub(crate) fn stewardships_of(mind: &dyn MindPort) -> Result<(Vec<Name>, Vec<Org
|
||||||
Ok((names, repos))
|
Ok((names, repos))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A member (anyone not the operator) has a pending delivery that addresses her: the beat's urgency. The one owner of
|
/// Whether a delivery wakes `who` off the beat: the operator or another Mind of
|
||||||
/// that reading: the poll's rows and the simulator's beat both ask it, over the deliveries the mouth would give her.
|
/// the roster addresses her. A Mind naming herself does not; a member does not.
|
||||||
pub(crate) fn addressed_by_member(operators: &[String], who: &Addressee, pending: &[ChatDelivery]) -> bool {
|
fn wakes(config: &Config, who: &Addressee, delivery: &ChatDelivery) -> bool {
|
||||||
pending.iter().any(|delivery| !operators.contains(&delivery.sender) && is_for(who, delivery))
|
let from_operator = config.operators.contains(&delivery.sender);
|
||||||
}
|
let from_other_mind = delivery.sender != who.matrix_id() && config.personas.iter().any(|mind| mind.matrix_id == delivery.sender);
|
||||||
|
(from_operator || from_other_mind) && is_for(who, delivery)
|
||||||
/// Who sent a line, as the wake rule sees them.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) enum Speaker {
|
|
||||||
Operator,
|
|
||||||
/// Another Mind of the roster.
|
|
||||||
Mind,
|
|
||||||
/// A human who is not the operator: a member.
|
|
||||||
Member,
|
|
||||||
/// The Persona herself.
|
|
||||||
Her,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Speaker {
|
|
||||||
fn human(self) -> bool {
|
|
||||||
matches!(self, Self::Operator | Self::Member)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The backstop of the wake rule: a Mind's explicit mention wakes her only while fewer than this many Mind lines in a row
|
|
||||||
/// came before it across her rooms (`LineFacts::mind_run`).
|
|
||||||
pub(crate) const MIND_RUN_BACKSTOP: usize = 4;
|
|
||||||
|
|
||||||
/// She is in a room's exchange when she has spoken there within this many minutes before the line: others talking on does
|
|
||||||
/// not keep her in it. A simulation plan may set another window; the live poll uses this one.
|
|
||||||
pub(crate) const EXCHANGE_MINUTES: i64 = 30;
|
|
||||||
|
|
||||||
/// Why a line wakes her, strongest first.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub(crate) enum WakeCause {
|
|
||||||
AddressedByHuman,
|
|
||||||
Human,
|
|
||||||
AddressedByMind,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the room says about a line, beside the line: the facts `wakes` weighs, from `line_facts`.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct LineFacts {
|
|
||||||
/// How many lines her current Mind-only run held before this one: one run across every line the caller gives, so a
|
|
||||||
/// loop cannot dodge the backstop by changing rooms. A human's line in a room the run has lines in ends it, and so
|
|
||||||
/// does a silence of the exchange window: no line within it, and the next Mind's tag starts afresh.
|
|
||||||
pub mind_run: usize,
|
|
||||||
/// The line is in a room named for a repo she stewards (`own_rooms`). A direct message is hers by `address::is_for`.
|
|
||||||
pub own_room: bool,
|
|
||||||
/// She has spoken in the room's current exchange: the lines before this one that follow each other without a long gap.
|
|
||||||
pub in_exchange: bool,
|
|
||||||
/// No Mind of the roster has spoken in the line's room within the exchange window before it. `line_facts` sets it from
|
|
||||||
/// the lines; the caller leaves it set only for the Mind the floor falls to (`floor_to`), and `wakes` reads it as hers.
|
|
||||||
pub open_floor: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fail-safe: a caller that has not counted the Mind run is at the cap, so a Mind's line wakes no one; the room facts
|
|
||||||
/// are unknown, so none opens a wake.
|
|
||||||
impl Default for LineFacts {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { mind_run: usize::MAX, own_room: false, in_exchange: false, open_floor: false }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One line of the rooms she sees, as `line_facts` weighs it: who said it, where, and when.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct FactLine<'a> {
|
|
||||||
pub sender: &'a str,
|
|
||||||
pub room: &'a str,
|
|
||||||
pub at_ms: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The facts of every line of an ordered list of the lines she sees, hers included: the one owner of the Mind run, her
|
|
||||||
/// rooms and her exchange, for the live poll and the simulator alike. `minds` is every Mind of the roster, her too.
|
|
||||||
/// Both count over the lines they are given and no others: the simulator gives every line of every room she is in; the poll
|
|
||||||
/// gives the pending deliveries and the mouth's context of each (at most 20 earlier lines of its room), because the mouth
|
|
||||||
/// shows her no room that has nothing pending. So live, a run that alternates rooms is counted per room that has
|
|
||||||
/// something pending, and an exchange 20 lines back is not seen; the simulator overstates the bound by that much.
|
|
||||||
pub(crate) fn line_facts(lines: &[FactLine], her: &str, minds: &[String], own_rooms: &[String], window_ms: u64) -> Vec<LineFacts> {
|
|
||||||
let mut run = 0usize;
|
|
||||||
let mut run_rooms: Vec<&str> = Vec::new();
|
|
||||||
let mut last_at: Option<u64> = None;
|
|
||||||
lines
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(at, line)| {
|
|
||||||
// The run lapses with time: no line within the window before this one, and no run is left to count.
|
|
||||||
if last_at.is_some_and(|last| line.at_ms.saturating_sub(last) > window_ms) {
|
|
||||||
run = 0;
|
|
||||||
run_rooms.clear();
|
|
||||||
}
|
|
||||||
last_at = Some(line.at_ms);
|
|
||||||
let mind_run = run;
|
|
||||||
if minds.iter().any(|mind| mind == line.sender) {
|
|
||||||
run += 1;
|
|
||||||
run_rooms.push(line.room);
|
|
||||||
} else if run_rooms.contains(&line.room) {
|
|
||||||
run = 0;
|
|
||||||
run_rooms.clear();
|
|
||||||
}
|
|
||||||
let since = line.at_ms.saturating_sub(window_ms);
|
|
||||||
LineFacts {
|
|
||||||
mind_run,
|
|
||||||
own_room: own_rooms.iter().any(|room| room == line.room),
|
|
||||||
in_exchange: lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.sender == her && earlier.at_ms >= since),
|
|
||||||
open_floor: !lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.at_ms >= since && minds.iter().any(|mind| *mind == earlier.sender)),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her own rooms among `aliases`, read from her mind the way the poll reads her stewardships (`stewardships_of`): the drain's
|
|
||||||
/// input. An unreadable mind is an error for the caller to report, never an empty answer.
|
|
||||||
pub fn own_rooms_among<'a>(mind: &dyn MindPort, aliases: impl IntoIterator<Item = &'a str>) -> Result<Vec<String>> {
|
|
||||||
let (_, repos) = stewardships_of(mind)?;
|
|
||||||
Ok(own_rooms(repos.iter().map(|repo| repo.0.as_str()), aliases))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Which of `aliases` are her own rooms: those named for a repo she stewards (`#huginn:gamecult.org` for `GameCult/Huginn`),
|
|
||||||
/// case-blind. A direct message is hers by `address::is_for`, not by name.
|
|
||||||
pub(crate) fn own_rooms<'r, 'a>(repos: impl IntoIterator<Item = &'r str>, aliases: impl IntoIterator<Item = &'a str>) -> Vec<String> {
|
|
||||||
let names: Vec<&str> = repos.into_iter().map(|repo| repo.rsplit_once('/').map_or(repo, |(_, name)| name)).collect();
|
|
||||||
let mut found: Vec<String> = Vec::new();
|
|
||||||
for alias in aliases {
|
|
||||||
let local = alias.strip_prefix('#').map(|rest| rest.split_once(':').map_or(rest, |(local, _)| local));
|
|
||||||
if local.is_some_and(|local| names.iter().any(|name| name.eq_ignore_ascii_case(local))) && !found.iter().any(|held| held == alias) {
|
|
||||||
found.push(alias.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a line in her rooms wakes `who` off the beat, and why: the one owner of the wake rule, asked by the heartbeat's
|
|
||||||
/// poll and by the simulator. A human's line wakes her in her own room (a direct message, or a room named for a repo she
|
|
||||||
/// stewards), and in a public room only when it addresses her or continues an exchange she is in. A Mind's line wakes
|
|
||||||
/// her only by an explicit mention (a Matrix mention of her or a reply to her, never a name in prose), in any room, and
|
|
||||||
/// only while fewer than `MIND_RUN_BACKSTOP` Mind lines in a row came before it across her rooms.
|
|
||||||
pub(crate) fn wakes(who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, facts: LineFacts) -> Option<WakeCause> {
|
|
||||||
// Only a new message wakes her: an edit of a line, or a notice, never does, whoever sent it.
|
|
||||||
if speaker == Speaker::Her || delivery.form != Form::Message {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let addressed = is_for(who, delivery);
|
|
||||||
if speaker.human() {
|
|
||||||
let wakes = addressed || facts.own_room || facts.in_exchange || facts.open_floor;
|
|
||||||
return wakes.then_some(if addressed { WakeCause::AddressedByHuman } else { WakeCause::Human });
|
|
||||||
}
|
|
||||||
let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply));
|
|
||||||
(explicit && facts.mind_run < MIND_RUN_BACKSTOP).then_some(WakeCause::AddressedByMind)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One Mind that has a line pending, as the open floor sees her: the line as her mouth gave it, whether its room's floor is open
|
|
||||||
/// to her (`LineFacts::open_floor`), and her standing in the beat's pick.
|
|
||||||
pub(crate) struct Hearer<'a> {
|
|
||||||
pub addressee: &'a Addressee,
|
|
||||||
pub delivery: ChatDelivery,
|
|
||||||
pub open: bool,
|
|
||||||
pub standing: Standing,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one Mind an open line falls to, as an index into `hearers`: a member's untagged new message in a public room that
|
|
||||||
/// names no Mind of the roster, when no Mind has spoken there within the exchange window. She is the beat's pick
|
|
||||||
/// (`tempo::pick`) among the hearers whose floor is open, so the poll and the simulator choose the same one. None when the
|
|
||||||
/// line is not open or no hearer is eligible.
|
|
||||||
pub(crate) fn floor_to(hearers: &[Hearer], speaker: Speaker, beat_s: u32) -> Option<usize> {
|
|
||||||
if !open_line(hearers, speaker) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let candidates: Vec<usize> = (0..hearers.len()).filter(|at| hearers[*at].open).collect();
|
|
||||||
let standings: Vec<Standing> = candidates.iter().map(|at| hearers[*at].standing.clone()).collect();
|
|
||||||
tempo::pick(&standings, beat_s).map(|at| candidates[at])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a line is the floor's at all: a member's untagged message, not direct, naming no Mind of the roster to any hearer of
|
|
||||||
/// it. Whether anyone is eligible to take it is `floor_to`'s.
|
|
||||||
pub(crate) fn open_line(hearers: &[Hearer], speaker: Speaker) -> bool {
|
|
||||||
!hearers.is_empty() && speaker == Speaker::Member && !hearers.iter().any(|hearer| hearer.delivery.is_direct || !hearer.delivery.mentions.is_empty() || is_for(hearer.addressee, &hearer.delivery))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every Mind's standing in the pick, from the heartbeat's state: eligible when idle and released.
|
|
||||||
fn standings_of(rows: &[Row], state: &HeartbeatState, now: DateTime<Utc>, config: &Config) -> Vec<Standing> {
|
|
||||||
rows.iter()
|
|
||||||
.map(|row| {
|
|
||||||
let last = state.last_turn_at.get(&row.slug().0).copied();
|
|
||||||
Standing {
|
|
||||||
slug: row.slug().0.clone(),
|
|
||||||
eligible: row.idle() && !row.cooling(now, config.beat_s),
|
|
||||||
waited_s: last.map(|turn| u64::try_from((now - turn).num_seconds()).unwrap_or(0)),
|
|
||||||
last_turn_ms: last.map(|turn| turn.timestamp_millis()),
|
|
||||||
// The seam for topic subscriptions (a later cut): a Mind's nearest subscription scores her deliveries here.
|
|
||||||
topic_permille: 0,
|
|
||||||
addressed_by_member: row.addressed_by_member(config),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Config {
|
|
||||||
/// Who sent a delivery, as `wakes` sees them.
|
|
||||||
fn speaker(&self, who: &Addressee, delivery: &ChatDelivery) -> Speaker {
|
|
||||||
if delivery.sender == who.matrix_id() {
|
|
||||||
Speaker::Her
|
|
||||||
} else if self.operators.contains(&delivery.sender) {
|
|
||||||
Speaker::Operator
|
|
||||||
} else if self.personas.iter().any(|mind| mind.matrix_id == delivery.sender) {
|
|
||||||
Speaker::Mind
|
|
||||||
} else {
|
|
||||||
Speaker::Member
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The facts of each of `pending` (in seq order), over the lines she can see: every delivery's context lines before it,
|
|
||||||
/// then the delivery, merged in time order and each line once. The mouth's context is the room's own earlier lines, hers
|
|
||||||
/// among them, so the Mind run and her exchange read as the simulator's room gives them.
|
|
||||||
pub(crate) fn pending_facts(pending: &[&ChatDelivery], her: &str, minds: &[String], own_rooms: &[String]) -> Vec<LineFacts> {
|
|
||||||
let mut lines: Vec<(FactLine, Option<usize>)> = Vec::new();
|
|
||||||
for (index, delivery) in pending.iter().enumerate() {
|
|
||||||
let room = delivery.room_alias.as_str();
|
|
||||||
for context in &delivery.context {
|
|
||||||
if !lines.iter().any(|(held, _)| held.room == room && held.sender == context.sender && held.at_ms == context.at_unix_ms) {
|
|
||||||
lines.push((FactLine { sender: &context.sender, room, at_ms: context.at_unix_ms }, None));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
match lines.iter_mut().find(|(held, _)| held.room == room && held.sender == delivery.sender && held.at_ms == delivery.at_unix_ms) {
|
|
||||||
Some((_, slot)) => *slot = Some(index),
|
|
||||||
None => lines.push((FactLine { sender: &delivery.sender, room, at_ms: delivery.at_unix_ms }, Some(index))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lines.sort_by_key(|(line, _)| line.at_ms);
|
|
||||||
let facts = line_facts(&lines.iter().map(|(line, _)| *line).collect::<Vec<_>>(), her, minds, own_rooms, u64::try_from(EXCHANGE_MINUTES * 60_000).unwrap_or_default());
|
|
||||||
let mut of = vec![LineFacts::default(); pending.len()];
|
|
||||||
for ((_, slot), facts) in lines.iter().zip(facts) {
|
|
||||||
if let Some(index) = slot {
|
|
||||||
of[*index] = facts;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
of
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The mouth pages a pending answer, so fewer deliveries may come than wait.
|
/// The mouth pages a pending answer, so fewer deliveries may come than wait.
|
||||||
/// The heartbeat acks nothing: it asks again after the highest seq it has until
|
/// The heartbeat acks nothing: it asks again after the highest seq it has until
|
||||||
/// the answer is empty. A mouth that never empties is cut off at `PENDING_PAGES`.
|
/// the answer is empty. A mouth that never empties is cut off at `PENDING_PAGES`.
|
||||||
/// The answer's first page is the one that carries the room tail, and every later page adds its deliveries to it.
|
fn read_pending(chat: &dyn Chat) -> Result<Vec<ChatDelivery>> {
|
||||||
pub(crate) fn read_pending(chat: &dyn Chat) -> Result<ChatPending> {
|
let mut all: Vec<ChatDelivery> = Vec::new();
|
||||||
let mut all = chat.pending(0)?;
|
let mut after = 0;
|
||||||
let mut after = all.deliveries.iter().map(|delivery| delivery.seq).max().unwrap_or(0);
|
for _ in 0..PENDING_PAGES {
|
||||||
for _ in 1..PENDING_PAGES {
|
let page = chat.pending(after)?.deliveries;
|
||||||
if after == 0 {
|
let Some(top) = page.iter().map(|delivery| delivery.seq).max() else {
|
||||||
break;
|
|
||||||
}
|
|
||||||
let mut page = chat.pending(after)?;
|
|
||||||
let Some(top) = page.deliveries.iter().map(|delivery| delivery.seq).max() else {
|
|
||||||
break;
|
break;
|
||||||
};
|
};
|
||||||
if top <= after {
|
if top <= after {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
after = top;
|
after = top;
|
||||||
all.deliveries.append(&mut page.deliveries);
|
all.extend(page);
|
||||||
}
|
}
|
||||||
Ok(all)
|
Ok(all)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The facts of each of a row's pending lines (in seq order, as `pending`), the open floor narrowed to the events in `taken`.
|
|
||||||
fn row_facts(row: &Row, pending: &[&ChatDelivery], minds: &[String], taken: &[String]) -> Vec<LineFacts> {
|
|
||||||
let mut facts = pending_facts(pending, row.addressee.matrix_id(), minds, &row.own_rooms);
|
|
||||||
for (delivery, facts) in pending.iter().zip(&mut facts) {
|
|
||||||
facts.open_floor &= taken.contains(&delivery.event_id);
|
|
||||||
}
|
|
||||||
facts
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a Mind's claim on a line stands: her turn on it is running, or her trace holds it decided. The claim of a Mind whose
|
|
||||||
/// unit is idle and whose trace does not hold the line (her turn failed, died or never started) has lapsed; one whose trace could
|
|
||||||
/// not be read is kept.
|
|
||||||
fn claim_stands(rows: &[Row], who: &str, event: &str) -> bool {
|
|
||||||
rows.iter().find(|row| row.slug().0 == who).is_none_or(|row| !row.idle() || row.done.as_ref().is_none_or(|done| done.contains(event)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the open floor decides over the pending lines: per row, the events that fall to her, and whether she holds a hello
|
|
||||||
/// another Mind has taken.
|
|
||||||
struct Floor {
|
|
||||||
won: Vec<Vec<String>>,
|
|
||||||
/// She holds an open hello that another Mind took and that is still within the exchange window: it is spoken for, and the
|
|
||||||
/// beat does not hand it to her too.
|
|
||||||
spoken_for: Vec<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a line is still the floor's to give: said within the exchange window before `now`. A taken line's handled key is
|
|
||||||
/// forgotten at `MENTIONS_KEPT`; an old line is no one's to take whatever the keys remember.
|
|
||||||
fn fresh(delivery: &ChatDelivery, now: DateTime<Utc>) -> bool {
|
|
||||||
let window_ms = u64::try_from(EXCHANGE_MINUTES * 60_000).unwrap_or_default();
|
|
||||||
u64::try_from(now.timestamp_millis()).unwrap_or_default().saturating_sub(delivery.at_unix_ms) <= window_ms
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each pending open line is judged once, over every row that holds it. A line some Mind already took (a handled key for its
|
|
||||||
/// event) is not judged again, and is spoken for to every other Mind that holds it. A Mind in `passed_over` (her start failed
|
|
||||||
/// this poll) is not eligible: the line falls to the next of the pick, as the beat's does.
|
|
||||||
fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime<Utc>, config: &Config, minds: &[String], passed_over: &[String]) -> Floor {
|
|
||||||
let mut standings = standings_of(rows, state, now, config);
|
|
||||||
for standing in &mut standings {
|
|
||||||
standing.eligible &= !passed_over.contains(&standing.slug);
|
|
||||||
}
|
|
||||||
let sorted: Vec<Vec<&ChatDelivery>> = rows
|
|
||||||
.iter()
|
|
||||||
.map(|row| {
|
|
||||||
let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect();
|
|
||||||
pending.sort_by_key(|delivery| delivery.seq);
|
|
||||||
pending
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let raw: Vec<Vec<LineFacts>> = rows.iter().zip(&sorted).map(|(row, pending)| pending_facts(pending, row.addressee.matrix_id(), minds, &row.own_rooms)).collect();
|
|
||||||
let mut floor = Floor { won: vec![Vec::new(); rows.len()], spoken_for: vec![false; rows.len()] };
|
|
||||||
for (index, row) in rows.iter().enumerate() {
|
|
||||||
for delivery in &sorted[index] {
|
|
||||||
let event = delivery.event_id.as_str();
|
|
||||||
let held: Vec<(usize, usize)> = (0..rows.len()).filter_map(|at| Some((at, sorted[at].iter().position(|held| held.event_id == event)?))).collect();
|
|
||||||
// Judged once, by the first row that holds it.
|
|
||||||
if held.first().map(|(at, _)| *at) != Some(index) || !fresh(delivery, now) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let hearers: Vec<Hearer> = held.iter().map(|(at, place)| Hearer { addressee: &rows[*at].addressee, delivery: sorted[*at][*place].clone(), open: raw[*at][*place].open_floor, standing: standings[*at].clone() }).collect();
|
|
||||||
let speaker = config.speaker(&row.addressee, delivery);
|
|
||||||
if !open_line(&hearers, speaker) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let takers: Vec<&str> = state.handled_mentions.iter().filter_map(|key| key.split_once(':').filter(|(who, held)| *held == event && claim_stands(rows, who, held)).map(|(who, _)| who)).collect();
|
|
||||||
if !takers.is_empty() {
|
|
||||||
for (at, place) in &held {
|
|
||||||
floor.spoken_for[*at] |= raw[*at][*place].open_floor && takers.iter().any(|who| *who != rows[*at].slug().0);
|
|
||||||
}
|
|
||||||
} else if let Some(winner) = floor_to(&hearers, speaker, config.beat_s)
|
|
||||||
&& let Some(at) = rows.iter().position(|other| other.slug().0 == hearers[winner].standing.slug)
|
|
||||||
{
|
|
||||||
floor.won[at].push(event.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
floor
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How long after the last of `run` failed or unpaid starts in a row the next may come, in seconds: `BACKOFF_BASE_S`, doubled by each, up to the beat.
|
|
||||||
fn backoff(run: u32, beat_s: u32) -> i64 {
|
|
||||||
BACKOFF_BASE_S.saturating_mul(1i64 << run.saturating_sub(1).min(30)).min(i64::from(beat_s))
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Row<'a> {
|
struct Row<'a> {
|
||||||
seat: &'a Seat<'a>,
|
seat: &'a Seat<'a>,
|
||||||
released: bool,
|
released: bool,
|
||||||
|
|
@ -791,12 +429,6 @@ struct Row<'a> {
|
||||||
pending: Vec<ChatDelivery>,
|
pending: Vec<ChatDelivery>,
|
||||||
/// Whom a delivery may address in her: her roster names and her projects' names as the last poll that read her pending chat left them.
|
/// Whom a delivery may address in her: her roster names and her projects' names as the last poll that read her pending chat left them.
|
||||||
addressee: Addressee,
|
addressee: Addressee,
|
||||||
/// Her rooms among the pending deliveries': those named for a repo she stewards, as the last poll read her stewardships.
|
|
||||||
own_rooms: Vec<String>,
|
|
||||||
/// The lines her trace holds decided (`projection::decided`), as the drain reads them; none when it could not be read, and then no line is judged.
|
|
||||||
done: Option<BTreeSet<String>>,
|
|
||||||
/// How many of her last records are failures in a row, and when the last was made.
|
|
||||||
failures: (u32, Option<DateTime<Utc>>),
|
|
||||||
note: String,
|
note: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -809,16 +441,9 @@ impl Row<'_> {
|
||||||
self.released && !self.busy
|
self.released && !self.busy
|
||||||
}
|
}
|
||||||
|
|
||||||
/// No start is made for her: a failed wake, or a start the day cap held, is waited out before the next (`BACKOFF_BASE_S`, doubled by
|
|
||||||
/// each such start in a row her trace holds, to the beat). Whether she is held is the drain's to say, at each start.
|
|
||||||
fn cooling(&self, now: DateTime<Utc>, beat_s: u32) -> bool {
|
|
||||||
let (run, at) = self.failures;
|
|
||||||
run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A member (not the operator) has a pending message that names or tags her.
|
/// A member (not the operator) has a pending message that names or tags her.
|
||||||
fn addressed_by_member(&self, config: &Config) -> bool {
|
fn addressed_by_member(&self, config: &Config) -> bool {
|
||||||
addressed_by_member(&config.operators, &self.addressee, &self.pending)
|
self.pending.iter().any(|delivery| !config.operators.contains(&delivery.sender) && is_for(&self.addressee, delivery))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -851,7 +476,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
||||||
}
|
}
|
||||||
let now = organs.clock.now();
|
let now = organs.clock.now();
|
||||||
let stored = organs.store.load()?;
|
let stored = organs.store.load()?;
|
||||||
let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() });
|
let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new() });
|
||||||
let mut eventful = false;
|
let mut eventful = false;
|
||||||
// The table as the last poll left it; unreadable counts as none, is noted in the trace, and is not overwritten.
|
// The table as the last poll left it; unreadable counts as none, is noted in the trace, and is not overwritten.
|
||||||
let (stored_addressing, addressing_unread) = match organs.store.load_addressing() {
|
let (stored_addressing, addressing_unread) = match organs.store.load_addressing() {
|
||||||
|
|
@ -866,21 +491,11 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
||||||
// Her last-read names when the table holds her, else her roster names alone.
|
// Her last-read names when the table holds her, else her roster names alone.
|
||||||
let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]);
|
let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]);
|
||||||
let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone());
|
let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone());
|
||||||
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), note: String::new() };
|
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, note: String::new() };
|
||||||
// Pending chat, read-only, for a released Mind.
|
// Pending chat, read-only, for a released Mind.
|
||||||
if row.released {
|
if row.released {
|
||||||
match seat.trace.records() {
|
|
||||||
Ok(records) => {
|
|
||||||
row.done = Some(decided(&records).into_iter().map(str::to_owned).collect());
|
|
||||||
row.failures = failed_run(&records, now);
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
eventful = true;
|
|
||||||
row.note = format!("trace unread: {error:#}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
match read_pending(seat.chat) {
|
match read_pending(seat.chat) {
|
||||||
Ok(pending) => row.pending = pending.deliveries,
|
Ok(deliveries) => row.pending = deliveries,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
eventful = true;
|
eventful = true;
|
||||||
row.note = "chat: pending failed".into();
|
row.note = "chat: pending failed".into();
|
||||||
|
|
@ -889,10 +504,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
||||||
// Her projects' names address her too; read only when something is pending. A failed read keeps her last-read row.
|
// Her projects' names address her too; read only when something is pending. A failed read keeps her last-read row.
|
||||||
if !row.pending.is_empty() {
|
if !row.pending.is_empty() {
|
||||||
match stewardships_of(seat.mind) {
|
match stewardships_of(seat.mind) {
|
||||||
Ok((names, repos)) => {
|
Ok((names, repos)) => row.addressee = roster.with_stewardships(names, repos),
|
||||||
row.own_rooms = own_rooms(repos.iter().map(|repo| repo.0.as_str()), row.pending.iter().map(|delivery| delivery.room_alias.as_str()));
|
|
||||||
row.addressee = roster.with_stewardships(names, repos);
|
|
||||||
}
|
|
||||||
Err(error) => row.note = format!("{} stewardship names unread: {error}", row.note).trim().to_string(),
|
Err(error) => row.note = format!("{} stewardship names unread: {error}", row.note).trim().to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -900,85 +512,62 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
||||||
rows.push(row);
|
rows.push(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A claim whose turn did not decide its line has lapsed, and is dropped. Her trace is the one record of what she decided: a Mind
|
|
||||||
// whose unit is not running and whose trace does not hold the line decided did not take it, and the open floor judges it afresh.
|
|
||||||
state.handled_mentions.retain(|key| key.split_once(':').is_none_or(|(who, event)| claim_stands(&rows, who, event)));
|
|
||||||
|
|
||||||
let beat_s = config.beat_s;
|
let beat_s = config.beat_s;
|
||||||
let mut launches: Vec<String> = Vec::new();
|
let mut launches: Vec<String> = Vec::new();
|
||||||
let mut launched: Vec<Slug> = Vec::new();
|
let mut launched: Vec<Slug> = Vec::new();
|
||||||
|
|
||||||
// Off the beat: a line that wakes her by `wakes`, once per message. It does not wait for the beat; it needs her idle and
|
// Off the beat: the operator or another Mind of the roster naming her, once per message. It does not wait for the beat;
|
||||||
// released. The open floor is decided first, over every Mind's pending lines, so one Mind of the roster takes each.
|
// it needs her idle and released.
|
||||||
let minds: Vec<String> = config.personas.iter().map(|mind| mind.matrix_id.clone()).collect();
|
for row in &mut rows {
|
||||||
// A Mind whose start failed on a line the floor gave her passes it on: the next of the pick takes it in the same poll. One whose
|
if !row.idle() {
|
||||||
// last wakes failed is waited out (`cooling`) and passes the floor on likewise.
|
continue;
|
||||||
let mut passed_over: Vec<String> = Vec::new();
|
}
|
||||||
let mut tried: Vec<usize> = Vec::new();
|
let slug = row.slug().clone();
|
||||||
'floor: loop {
|
let mentioned = {
|
||||||
let floor = floors(&rows, &state, now, config, &minds, &passed_over).won;
|
let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect();
|
||||||
for (index, row) in rows.iter_mut().enumerate() {
|
pending.sort_by_key(|delivery| delivery.seq);
|
||||||
if !row.idle() || tried.contains(&index) || row.cooling(now, beat_s) {
|
pending
|
||||||
continue;
|
.into_iter()
|
||||||
}
|
.filter(|delivery| wakes(config, &row.addressee, delivery))
|
||||||
let slug = row.slug().clone();
|
.map(|delivery| format!("{}:{}", slug.0, delivery.event_id))
|
||||||
// The first line that wakes her and her trace does not hold decided: that, and only that, decides whether she is woken.
|
.find(|key| !state.handled_mentions.contains(key))
|
||||||
let mentioned = {
|
};
|
||||||
let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect();
|
let Some(key) = mentioned else { continue };
|
||||||
pending.sort_by_key(|delivery| delivery.seq);
|
match wake(organs, row) {
|
||||||
let facts = row_facts(row, &pending, &minds, &floor[index]);
|
Woke::Started => {
|
||||||
pending
|
state.handled_mentions.push(key);
|
||||||
.into_iter()
|
let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT);
|
||||||
.zip(facts)
|
state.handled_mentions.drain(..excess);
|
||||||
.filter(|(delivery, facts)| wakes(&row.addressee, delivery, config.speaker(&row.addressee, delivery), *facts).is_some())
|
state.last_turn_at.insert(slug.0.clone(), now);
|
||||||
.map(|(delivery, _)| delivery.event_id.clone())
|
row.busy = true;
|
||||||
.find(|event| row.done.as_ref().is_some_and(|done| !done.contains(event)))
|
launches.push(slug.0.clone());
|
||||||
};
|
launched.push(slug);
|
||||||
let Some(event) = mentioned else { continue };
|
}
|
||||||
tried.push(index);
|
Woke::Busy => row.busy = true,
|
||||||
// The wake's lines are recorded before her unit starts, so the start reads them. A start that does not happen leaves the
|
Woke::Refused(why) => row.note = why,
|
||||||
// claim to lapse (`claim_stands`): she is neither running nor has she decided the line.
|
|
||||||
for event in claimed(Some(&event), &floor[index]) {
|
|
||||||
let key = format!("{}:{event}", slug.0);
|
|
||||||
if !state.handled_mentions.contains(&key) {
|
|
||||||
state.handled_mentions.push(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT);
|
|
||||||
state.handled_mentions.drain(..excess);
|
|
||||||
organs.store.save(&state)?;
|
|
||||||
match wake(organs, row) {
|
|
||||||
Woke::Started => {
|
|
||||||
state.last_turn_at.insert(slug.0.clone(), now);
|
|
||||||
row.busy = true;
|
|
||||||
launches.push(slug.0.clone());
|
|
||||||
launched.push(slug);
|
|
||||||
}
|
|
||||||
refused => {
|
|
||||||
match refused {
|
|
||||||
Woke::Refused(why) => row.note = why,
|
|
||||||
_ => row.busy = true,
|
|
||||||
}
|
|
||||||
if !floor[index].is_empty() {
|
|
||||||
passed_over.push(slug.0);
|
|
||||||
continue 'floor;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// On the beat: when the beat has passed, one wake for the winner of the pick.
|
// On the beat: when the beat has passed, one wake for the winner of the pick.
|
||||||
let due = (now - state.last_beat_at).num_seconds() >= i64::from(beat_s);
|
let due = (now - state.last_beat_at).num_seconds() >= i64::from(beat_s);
|
||||||
let standings = standings_of(&rows, &state, now, config);
|
let standings: Vec<Standing> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| {
|
||||||
|
let last = state.last_turn_at.get(&row.slug().0).copied();
|
||||||
|
Standing {
|
||||||
|
slug: row.slug().0.clone(),
|
||||||
|
eligible: row.idle(),
|
||||||
|
waited_s: last.map(|turn| u64::try_from((now - turn).num_seconds()).unwrap_or(0)),
|
||||||
|
last_turn_ms: last.map(|turn| turn.timestamp_millis()),
|
||||||
|
// The seam for topic subscriptions (a later cut): a Mind's nearest subscription scores her deliveries here.
|
||||||
|
topic_permille: 0,
|
||||||
|
addressed_by_member: row.addressed_by_member(config),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
// A winner whose unit cannot start loses the beat to the next of the pick, so
|
// A winner whose unit cannot start loses the beat to the next of the pick, so
|
||||||
// one failing Mind never starves the others; a wake ends the beat.
|
// one failing Mind never starves the others; a wake ends the beat.
|
||||||
let mut passed: Vec<Standing> = standings.clone();
|
let mut passed: Vec<Standing> = standings.clone();
|
||||||
// A hello another Mind took is spoken for: the beat does not give it to a second Mind.
|
|
||||||
for (at, spoken) in floors(&rows, &state, now, config, &minds, &[]).spoken_for.into_iter().enumerate() {
|
|
||||||
passed[at].eligible &= !spoken;
|
|
||||||
}
|
|
||||||
while due && let Some(winner) = tempo::pick(&passed, beat_s) {
|
while due && let Some(winner) = tempo::pick(&passed, beat_s) {
|
||||||
match wake(organs, &rows[winner]) {
|
match wake(organs, &rows[winner]) {
|
||||||
Woke::Started => {
|
Woke::Started => {
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,6 @@ use huginn_mind::PipelineSelectionPage;
|
||||||
use tempfile::TempDir;
|
use tempfile::TempDir;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::persona::Trace;
|
|
||||||
use crate::address::addresses;
|
use crate::address::addresses;
|
||||||
use crate::control::{Brake, ControlState, SwarmState};
|
use crate::control::{Brake, ControlState, SwarmState};
|
||||||
use crate::testkit::{Fixed, Recording, TestMind, at, reference};
|
use crate::testkit::{Fixed, Recording, TestMind, at, reference};
|
||||||
|
|
@ -118,8 +117,6 @@ struct MemStore {
|
||||||
traces: RefCell<Vec<PollTrace>>,
|
traces: RefCell<Vec<PollTrace>>,
|
||||||
addressing: RefCell<Option<Addressing>>,
|
addressing: RefCell<Option<Addressing>>,
|
||||||
addressing_saves: Cell<u32>,
|
addressing_saves: Cell<u32>,
|
||||||
/// `save` into the order a launcher's `start` logs into.
|
|
||||||
log: std::rc::Rc<RefCell<Vec<&'static str>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Store for MemStore {
|
impl Store for MemStore {
|
||||||
|
|
@ -128,7 +125,6 @@ impl Store for MemStore {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save(&self, state: &HeartbeatState) -> Result<()> {
|
fn save(&self, state: &HeartbeatState) -> Result<()> {
|
||||||
self.log.borrow_mut().push("save");
|
|
||||||
*self.state.borrow_mut() = Some(state.clone());
|
*self.state.borrow_mut() = Some(state.clone());
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -173,40 +169,11 @@ fn delivery(seq: u64, sender: &str, text: &str, mentions: &[&str]) -> ChatDelive
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A line in a room where a Mind spoke just before it: the floor is not open to anyone.
|
|
||||||
fn quiet(line: ChatDelivery) -> ChatDelivery {
|
|
||||||
ChatDelivery { context: vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "x".into(), at_unix_ms: 0 }], ..line }
|
|
||||||
}
|
|
||||||
|
|
||||||
const ANN: usize = 0;
|
const ANN: usize = 0;
|
||||||
const BOB: usize = 1;
|
const BOB: usize = 1;
|
||||||
const NAMES: [&str; 2] = ["ann", "bob"];
|
const NAMES: [&str; 2] = ["ann", "bob"];
|
||||||
|
|
||||||
/// A Persona's trace as the poll reads it: the records her drain wrote, or none readable.
|
|
||||||
#[derive(Default)]
|
|
||||||
struct FakeTrace {
|
|
||||||
rows: RefCell<Vec<serde_json::Value>>,
|
|
||||||
unreadable: Cell<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Trace for FakeTrace {
|
|
||||||
fn record(&self, _: &str, record: &serde_json::Value) -> Result<()> {
|
|
||||||
self.rows.borrow_mut().push(record.clone());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TraceView for FakeTrace {
|
|
||||||
fn records(&self) -> Result<Vec<serde_json::Value>> {
|
|
||||||
if self.unreadable.get() {
|
|
||||||
bail!("her trace is unreadable");
|
|
||||||
}
|
|
||||||
Ok(self.rows.borrow().clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Rig {
|
struct Rig {
|
||||||
traces: Vec<FakeTrace>,
|
|
||||||
minds: Vec<TestMind>,
|
minds: Vec<TestMind>,
|
||||||
calls: Vec<Cell<u32>>,
|
calls: Vec<Cell<u32>>,
|
||||||
admits: Cell<u32>,
|
admits: Cell<u32>,
|
||||||
|
|
@ -223,7 +190,6 @@ struct Rig {
|
||||||
impl Rig {
|
impl Rig {
|
||||||
fn new() -> Box<Self> {
|
fn new() -> Box<Self> {
|
||||||
Box::new(Self {
|
Box::new(Self {
|
||||||
traces: vec![FakeTrace::default(), FakeTrace::default()],
|
|
||||||
minds: vec![TestMind::seeded_as("ann"), TestMind::seeded_as("bob")],
|
minds: vec![TestMind::seeded_as("ann"), TestMind::seeded_as("bob")],
|
||||||
calls: vec![Cell::new(0), Cell::new(0)],
|
calls: vec![Cell::new(0), Cell::new(0)],
|
||||||
admits: Cell::new(0),
|
admits: Cell::new(0),
|
||||||
|
|
@ -257,14 +223,14 @@ impl Rig {
|
||||||
.zip(&self.calls)
|
.zip(&self.calls)
|
||||||
.map(|(inner, calls)| Counting { inner, calls, admits: &self.admits, stewardship_reads: &self.stewardship_reads, stewardship_down: &self.stewardship_down })
|
.map(|(inner, calls)| Counting { inner, calls, admits: &self.admits, stewardship_reads: &self.stewardship_reads, stewardship_down: &self.stewardship_down })
|
||||||
.collect();
|
.collect();
|
||||||
let seats: Vec<Seat> = self.config.personas.iter().enumerate().map(|(index, who)| Seat { who: who.clone(), mind: &ports[index], chat: &self.chats[index], trace: &self.traces[index] }).collect();
|
let seats: Vec<Seat> = self.config.personas.iter().enumerate().map(|(index, who)| Seat { who: who.clone(), mind: &ports[index], chat: &self.chats[index] }).collect();
|
||||||
let organs = Organs { seats: &seats, control: &self.control, launcher: &self.launcher, clock: &self.clock, store: &self.store };
|
let organs = Organs { seats: &seats, control: &self.control, launcher: &self.launcher, clock: &self.clock, store: &self.store };
|
||||||
poll(&organs, &self.config).unwrap()
|
poll(&organs, &self.config).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The stored state, made if there is none, changed by `change`.
|
/// The stored state, made if there is none, changed by `change`.
|
||||||
fn with_state(&self, change: impl FnOnce(&mut HeartbeatState)) {
|
fn with_state(&self, change: impl FnOnce(&mut HeartbeatState)) {
|
||||||
let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() });
|
let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new() });
|
||||||
change(&mut state);
|
change(&mut state);
|
||||||
*self.store.state.borrow_mut() = Some(state);
|
*self.store.state.borrow_mut() = Some(state);
|
||||||
}
|
}
|
||||||
|
|
@ -296,20 +262,6 @@ impl Rig {
|
||||||
self.launcher.kill_as(&Slug(NAMES[who].into()), RunTurn::PersonaTurn);
|
self.launcher.kill_as(&Slug(NAMES[who].into()), RunTurn::PersonaTurn);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Her turn finished: her unit ends, her trace holds the pending lines decided and her drain acked them, so her chat holds none of it.
|
|
||||||
fn finish_turn(&self, who: usize) {
|
|
||||||
self.end_unit(who);
|
|
||||||
let held: Vec<String> = self.chats[who].deliveries.borrow().iter().map(|line| line.event_id.clone()).collect();
|
|
||||||
self.traces[who].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": held, "at": self.now().to_rfc3339() }));
|
|
||||||
self.chats[who].deliveries.borrow_mut().clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her turn failed: her unit ends, her trace holds a failed record, and her chat still holds the lines.
|
|
||||||
fn fail_turn(&self, who: usize) {
|
|
||||||
self.end_unit(who);
|
|
||||||
self.traces[who].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": [], "failed": "the connector did not answer: unavailable", "outage": true, "at": self.now().to_rfc3339() }));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her unit is active.
|
/// Her unit is active.
|
||||||
fn in_a_turn(&self, who: usize) {
|
fn in_a_turn(&self, who: usize) {
|
||||||
self.launcher.revive_as(&Slug(NAMES[who].into()), RunTurn::PersonaTurn);
|
self.launcher.revive_as(&Slug(NAMES[who].into()), RunTurn::PersonaTurn);
|
||||||
|
|
@ -341,9 +293,7 @@ fn each_persona_carries_her_own_huginn_and_a_missing_or_malformed_one_refuses_th
|
||||||
for bad in ["ann,ann,Ann,@ann:chat", "ann,ann,Ann,@ann:chat,", "ann,ann,Ann,@ann:chat,127.0.0.1:4101", "ann,ann,Ann,@ann:chat,rudp://localhost:4101"] {
|
for bad in ["ann,ann,Ann,@ann:chat", "ann,ann,Ann,@ann:chat,", "ann,ann,Ann,@ann:chat,127.0.0.1:4101", "ann,ann,Ann,@ann:chat,rudp://localhost:4101"] {
|
||||||
assert!(PersonaId::parse(bad).is_err(), "{bad}");
|
assert!(PersonaId::parse(bad).is_err(), "{bad}");
|
||||||
}
|
}
|
||||||
assert!(Config::new(personas.clone(), vec![], 0).is_err(), "a beat of zero seconds is refused");
|
assert!(Config::new(personas, vec![], 0).is_err(), "a beat of zero seconds is refused");
|
||||||
let refused = Config::new(personas, vec!["@bob:chat".into()], 60).map(|_| ()).unwrap_err();
|
|
||||||
assert!(format!("{refused:#}").contains("operator id is also a persona"), "a sender is the operator or a Mind, never both");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -430,7 +380,7 @@ fn the_operator_naming_a_persona_wakes_her_at_once_off_the_beat_and_once_per_mes
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the beat has just fallen, and the operator does not wait for the next");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the beat has just fallen, and the operator does not wait for the next");
|
||||||
assert_eq!(rig.store.state.borrow().as_ref().unwrap().last_beat_at, rig.now(), "an off-beat wake does not move the beat");
|
assert_eq!(rig.store.state.borrow().as_ref().unwrap().last_beat_at, rig.now(), "an off-beat wake does not move the beat");
|
||||||
// Her turn ends without acking; the same message does not wake her again.
|
// Her turn ends without acking; the same message does not wake her again.
|
||||||
rig.finish_turn(BOB);
|
rig.end_unit(BOB);
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
||||||
assert_eq!(rig.launched(), vec![Slug("bob".into())]);
|
assert_eq!(rig.launched(), vec![Slug("bob".into())]);
|
||||||
// A tag in m.mentions counts as naming.
|
// A tag in m.mentions counts as naming.
|
||||||
|
|
@ -439,13 +389,11 @@ fn the_operator_naming_a_persona_wakes_her_at_once_off_the_beat_and_once_per_mes
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn another_mind_tagging_a_persona_wakes_her_once_off_the_beat_and_a_name_in_prose_does_not() {
|
fn another_mind_naming_a_persona_wakes_her_once_off_the_beat() {
|
||||||
let rig = quiet_rig();
|
let rig = quiet_rig();
|
||||||
rig.say(BOB, delivery(1, "@ann:chat", "Bob, a word", &[]));
|
rig.say(BOB, delivery(1, "@ann:chat", "Bob, a word", &[]));
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a name in a Mind's prose wakes no one");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a Mind of the roster wakes her at once");
|
||||||
rig.say(BOB, delivery(2, "@ann:chat", "a word", &["@bob:chat"]));
|
rig.end_unit(BOB);
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a Mind of the roster tagging her wakes her at once");
|
|
||||||
rig.finish_turn(BOB);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the same message polled again wakes nobody");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the same message polled again wakes nobody");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -458,13 +406,16 @@ fn a_mind_naming_no_one_or_herself_wakes_nobody() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_member_naming_a_persona_wakes_her_at_once() {
|
fn a_member_naming_a_persona_wakes_nobody_off_the_beat_but_counts_as_full_urgency_on_it() {
|
||||||
let rig = Rig::new();
|
let rig = Rig::new();
|
||||||
rig.turn(ANN, 1000);
|
rig.turn(ANN, 1000);
|
||||||
rig.turn(BOB, 90);
|
rig.turn(BOB, 90);
|
||||||
rig.beat_fell();
|
rig.beat_fell();
|
||||||
rig.say(BOB, delivery(1, "@member:chat", "Bob, are you there?", &[]));
|
rig.say(BOB, delivery(1, "@member:chat", "Bob, are you there?", &[]));
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a member addressing her wakes her off the beat");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a member does not start a turn");
|
||||||
|
rig.advance(900);
|
||||||
|
// Bob waited 990 s x ten for the member addressing him; Ann waited 1900 s x one: Bob wins the beat.
|
||||||
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] });
|
||||||
assert_eq!(rig.store.traces.borrow().last().unwrap().instances[BOB].urgency_permille, 1000);
|
assert_eq!(rig.store.traces.borrow().last().unwrap().instances[BOB].urgency_permille, 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -474,8 +425,8 @@ fn a_member_message_naming_nobody_of_hers_scores_nobody() {
|
||||||
rig.turn(ANN, 1000);
|
rig.turn(ANN, 1000);
|
||||||
rig.turn(BOB, 90);
|
rig.turn(BOB, 90);
|
||||||
rig.beat_fell();
|
rig.beat_fell();
|
||||||
rig.say(BOB, quiet(delivery(1, "@member:chat", "good morning, swarm", &[])));
|
rig.say(BOB, delivery(1, "@member:chat", "good morning, swarm", &[]));
|
||||||
rig.say(BOB, quiet(delivery(2, "@member:chat", "is BDS green?", &[])));
|
rig.say(BOB, delivery(2, "@member:chat", "is BDS green?", &[]));
|
||||||
rig.advance(900);
|
rig.advance(900);
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "BDS is nobody's here: no one stewards it");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "BDS is nobody's here: no one stewards it");
|
||||||
}
|
}
|
||||||
|
|
@ -498,7 +449,7 @@ fn the_operator_naming_a_project_untagged_wakes_its_idle_steward_once_off_the_be
|
||||||
steward(&rig, ANN, "GameCult/BadDaySimulator", &["BDS"]);
|
steward(&rig, ANN, "GameCult/BadDaySimulator", &["BDS"]);
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "BDS is down", &[]));
|
rig.say(ANN, delivery(1, "@op:chat", "BDS is down", &[]));
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
||||||
rig.finish_turn(ANN);
|
rig.end_unit(ANN);
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the same message polled again wakes nobody");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the same message polled again wakes nobody");
|
||||||
rig.say(ANN, delivery(2, "@op:chat", "BDSX is down", &[]));
|
rig.say(ANN, delivery(2, "@op:chat", "BDSX is down", &[]));
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a substring of a name is not the name");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a substring of a name is not the name");
|
||||||
|
|
@ -520,18 +471,20 @@ fn a_listed_name_wakes_on_its_exact_spelling_only_and_a_derived_name_in_any_case
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_member_naming_a_project_wakes_its_steward_and_a_mind_naming_it_in_prose_does_not() {
|
fn another_mind_naming_a_project_wakes_its_steward_and_a_member_scores_her_without_waking_her() {
|
||||||
let rig = quiet_rig();
|
let rig = quiet_rig();
|
||||||
steward(&rig, BOB, "GameCult/BadDaySimulator", &["BDS"]);
|
steward(&rig, BOB, "GameCult/BadDaySimulator", &["BDS"]);
|
||||||
rig.say(BOB, delivery(1, "@ann:chat", "BDS needs a look", &[]));
|
rig.say(BOB, delivery(1, "@ann:chat", "BDS needs a look", &[]));
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a Mind's prose naming her project wakes no one");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a Mind of the roster naming her project wakes her");
|
||||||
let rig = Rig::new();
|
let rig = Rig::new();
|
||||||
rig.turn(ANN, 1000);
|
rig.turn(ANN, 1000);
|
||||||
rig.turn(BOB, 90);
|
rig.turn(BOB, 90);
|
||||||
steward(&rig, BOB, "GameCult/BadDaySimulator", &["BDS"]);
|
steward(&rig, BOB, "GameCult/BadDaySimulator", &["BDS"]);
|
||||||
rig.beat_fell();
|
rig.beat_fell();
|
||||||
rig.say(BOB, delivery(1, "@member:chat", "is BDS green?", &[]));
|
rig.say(BOB, delivery(1, "@member:chat", "is BDS green?", &[]));
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a member naming her project wakes her");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a member does not start a turn");
|
||||||
|
rig.advance(900);
|
||||||
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the member's naming scores her at full urgency");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -557,7 +510,7 @@ fn the_heartbeat_writes_the_table_it_read_and_only_when_it_changed() {
|
||||||
rig.poll();
|
rig.poll();
|
||||||
assert_eq!(rig.store.addressing_saves.get(), 1, "the roster is written at the first poll");
|
assert_eq!(rig.store.addressing_saves.get(), 1, "the roster is written at the first poll");
|
||||||
assert!(!addresses(&table_row(&rig, "@bob:chat"), &delivery(9, "@op:chat", "BDS is down", &[])), "nothing pending, nothing read: no project name yet");
|
assert!(!addresses(&table_row(&rig, "@bob:chat"), &delivery(9, "@op:chat", "BDS is down", &[])), "nothing pending, nothing read: no project name yet");
|
||||||
rig.say(BOB, quiet(delivery(1, "@member:chat", "hello", &[])));
|
rig.say(BOB, delivery(1, "@member:chat", "hello", &[]));
|
||||||
rig.poll();
|
rig.poll();
|
||||||
assert_eq!(rig.store.addressing_saves.get(), 2);
|
assert_eq!(rig.store.addressing_saves.get(), 2);
|
||||||
assert!(addresses(&table_row(&rig, "@bob:chat"), &delivery(9, "@op:chat", "BDS is down", &[])));
|
assert!(addresses(&table_row(&rig, "@bob:chat"), &delivery(9, "@op:chat", "BDS is down", &[])));
|
||||||
|
|
@ -570,7 +523,7 @@ fn the_heartbeat_writes_the_table_it_read_and_only_when_it_changed() {
|
||||||
fn a_failed_stewardship_read_keeps_her_last_read_names_and_roster_names_when_none_are_stored() {
|
fn a_failed_stewardship_read_keeps_her_last_read_names_and_roster_names_when_none_are_stored() {
|
||||||
let rig = quiet_rig();
|
let rig = quiet_rig();
|
||||||
steward(&rig, BOB, "GameCult/BadDaySimulator", &["BDS"]);
|
steward(&rig, BOB, "GameCult/BadDaySimulator", &["BDS"]);
|
||||||
rig.say(BOB, quiet(delivery(1, "@member:chat", "hello", &[])));
|
rig.say(BOB, delivery(1, "@member:chat", "hello", &[]));
|
||||||
rig.poll();
|
rig.poll();
|
||||||
rig.stewardship_down.set(true);
|
rig.stewardship_down.set(true);
|
||||||
rig.say(BOB, delivery(2, "@op:chat", "BDS is down", &[]));
|
rig.say(BOB, delivery(2, "@op:chat", "BDS is down", &[]));
|
||||||
|
|
@ -670,7 +623,7 @@ fn trace_at(seconds: i64, tempo_s: u32) -> PollTrace {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn state_at(milliseconds: i64) -> HeartbeatState {
|
fn state_at(milliseconds: i64) -> HeartbeatState {
|
||||||
HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]), retired_slot_3: BTreeMap::new() }
|
HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]) }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -713,42 +666,9 @@ fn a_state_written_before_the_cut_reads_with_no_turns() {
|
||||||
cache.pull_all_backing_stores().unwrap();
|
cache.pull_all_backing_stores().unwrap();
|
||||||
cache.put(STATE_KEY, &StateBeforeTheCut { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()] }).unwrap();
|
cache.put(STATE_KEY, &StateBeforeTheCut { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()] }).unwrap();
|
||||||
let state = FileStore::new(&path).load().unwrap().expect("the old state reads");
|
let state = FileStore::new(&path).load().unwrap().expect("the old state reads");
|
||||||
assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() });
|
assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new() });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// The state as the e951555 build wrote it, and as deployed files still hold it: four slots, the last the owed waker's count.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "eureka.heartbeat.state.v1", schema = "HeartbeatState")]
|
|
||||||
struct StateWithOwedStarts {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
last_beat_at: DateTime<Utc>,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
handled_mentions: Vec<String>,
|
|
||||||
#[cultcache(key = 2, default)]
|
|
||||||
last_turn_at: BTreeMap<String, DateTime<Utc>>,
|
|
||||||
#[cultcache(key = 3, default)]
|
|
||||||
owed_starts: BTreeMap<String, u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul s2 state-slot3-readonly: a deployed four-slot file loads, and the poll's save over it succeeds instead of refusing it read-only.
|
|
||||||
#[test]
|
|
||||||
fn a_four_slot_state_from_the_deployed_build_loads_and_saves() {
|
|
||||||
let dir = TempDir::new().unwrap();
|
|
||||||
let path = dir.path().join("heartbeat.cc");
|
|
||||||
let mut cache = CultCache::new();
|
|
||||||
cache.register_entry_type::<StateWithOwedStarts>().unwrap();
|
|
||||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
|
||||||
cache.pull_all_backing_stores().unwrap();
|
|
||||||
cache.put(STATE_KEY, &StateWithOwedStarts { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::from([("ann".to_string(), 2)]) }).unwrap();
|
|
||||||
drop(cache);
|
|
||||||
let store = FileStore::new(&path);
|
|
||||||
let mut state = store.load().unwrap().expect("the four-slot state reads");
|
|
||||||
assert_eq!(state.handled_mentions, ["ann:e1"]);
|
|
||||||
state.last_beat_at = crate::testkit::at(9);
|
|
||||||
store.save(&state).expect("the save over a four-slot file is not refused");
|
|
||||||
assert_eq!(store.load().unwrap().unwrap().last_beat_at, crate::testkit::at(9));
|
|
||||||
}
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_old_heartbeat_store_fails_closed_naming_the_file_and_is_never_migrated() {
|
fn an_old_heartbeat_store_fails_closed_naming_the_file_and_is_never_migrated() {
|
||||||
let dir = TempDir::new().unwrap();
|
let dir = TempDir::new().unwrap();
|
||||||
|
|
@ -777,7 +697,7 @@ fn the_file_store_reads_back_the_addressing_it_wrote_to_the_view() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Matrix's word that a message is her DM, a tag or a reply wakes her off the beat from the operator; a notice or an edit never does,
|
/// Matrix's word that a message is her DM, a tag or a reply wakes her off the beat from the operator; a notice or an edit never does,
|
||||||
/// whatever its basis, and a member's direct message wakes her too.
|
/// whatever its basis, and a stranger's direct message is delivered but wakes no one.
|
||||||
#[test]
|
#[test]
|
||||||
fn matrixs_addressing_facts_wake_her_off_the_beat_only_on_a_message_from_the_roster() {
|
fn matrixs_addressing_facts_wake_her_off_the_beat_only_on_a_message_from_the_roster() {
|
||||||
use crate::chat_client::{Basis, Form};
|
use crate::chat_client::{Basis, Form};
|
||||||
|
|
@ -800,637 +720,5 @@ fn matrixs_addressing_facts_wake_her_off_the_beat_only_on_a_message_from_the_ros
|
||||||
}
|
}
|
||||||
let rig = quiet_rig();
|
let rig = quiet_rig();
|
||||||
rig.say(BOB, with(1, "@stranger:chat", Some(Basis::Direct), Form::Message));
|
rig.say(BOB, with(1, "@stranger:chat", Some(Basis::Direct), Form::Message));
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a member's direct message wakes her: no sender gate");
|
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the sender gate stays: a stranger's DM is delivered and wakes no one off the beat");
|
||||||
}
|
|
||||||
|
|
||||||
/// The fact the live poll lacked: a member's unaddressed line in a room named for a repo she stewards wakes her, and the same line
|
|
||||||
/// in a room named for nothing of hers does not.
|
|
||||||
#[test]
|
|
||||||
fn a_member_line_in_a_room_named_for_her_repo_wakes_her_off_the_beat() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
steward(&rig, BOB, "GameCult/Swarm", &["Zed"]);
|
|
||||||
rig.say(BOB, quiet(ChatDelivery { room_alias: "#elsewhere:chat".into(), ..delivery(1, "@member:chat", "what a day", &[]) }));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a public room that is not hers wakes her only by address");
|
|
||||||
rig.say(BOB, delivery(2, "@member:chat", "what a day", &[]));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "#swarm is named for her repo");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The wake rule over the facts the poll builds: the pending deliveries and their context, as Bob (`@bob:chat`) reads them.
|
|
||||||
mod wake_rule {
|
|
||||||
use super::*;
|
|
||||||
use crate::chat_client::ContextLine;
|
|
||||||
|
|
||||||
const DAY: u64 = 86_400_000;
|
|
||||||
const MINUTE: u64 = 60_000;
|
|
||||||
|
|
||||||
fn bob() -> Addressee {
|
|
||||||
Addressee::new("@bob:chat", ["Bob"])
|
|
||||||
}
|
|
||||||
|
|
||||||
fn minds() -> Vec<String> {
|
|
||||||
vec!["@ann:chat".into(), "@bob:chat".into()]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn said(sender: &str, at: u64) -> ContextLine {
|
|
||||||
ContextLine { sender: sender.into(), text: "x".into(), at_unix_ms: at }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the poll concludes for one delivery (its context is its own); `own` are her rooms.
|
|
||||||
fn woken(line: &ChatDelivery, speaker: Speaker, own: &[&str]) -> Option<WakeCause> {
|
|
||||||
let own: Vec<String> = own.iter().map(|room| (*room).to_owned()).collect();
|
|
||||||
// The open floor is the caller's, narrowed to the pick (`floor_to`): these lines are judged without it.
|
|
||||||
let facts = LineFacts { open_floor: false, ..pending_facts(&[line], "@bob:chat", &minds(), &own)[0] };
|
|
||||||
wakes(&bob(), line, speaker, facts)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Four alternating Mind lines, the last of them `ago` before `at`, a minute apart.
|
|
||||||
fn four_minds(at: u64, ago: u64) -> Vec<ContextLine> {
|
|
||||||
(0..4).map(|index| said(if index % 2 == 0 { "@ann:chat" } else { "@bob:chat" }, at - ago - (4 - index) * MINUTE)).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tag(room: &str, at: u64, context: Vec<ContextLine>) -> ChatDelivery {
|
|
||||||
ChatDelivery { room_alias: room.into(), at_unix_ms: at, context, ..delivery(1, "@ann:chat", "a word", &["@bob:chat"]) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_minds_tag_wakes_her_after_a_silence_in_a_room_no_human_speaks_in() {
|
|
||||||
let now = 2 * DAY;
|
|
||||||
let old = four_minds(now, now - 10 * MINUTE);
|
|
||||||
assert_eq!(woken(&tag("#minds:chat", now, old.clone()), Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "four Mind lines two days ago are no run now");
|
|
||||||
let reply = ChatDelivery { basis: Some(Basis::Reply), is_direct: true, room_alias: "!dm:chat".into(), context: old, at_unix_ms: now, ..delivery(2, "@ann:chat", "a word", &[]) };
|
|
||||||
assert_eq!(woken(&reply, Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "a Mind-to-Mind DM reply the same");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_backstop_is_four_mind_lines_in_a_row_within_the_exchange_window() {
|
|
||||||
let now = 3 * DAY;
|
|
||||||
let three = four_minds(now, MINUTE)[1..].to_vec();
|
|
||||||
assert_eq!(woken(&tag("#minds:chat", now, three), Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "three before it still wake");
|
|
||||||
assert_eq!(woken(&tag("#minds:chat", now, four_minds(now, MINUTE)), Speaker::Mind, &[]), None, "four in a row wake no one");
|
|
||||||
let after = |ago: u64| woken(&tag("#minds:chat", now, four_minds(now, ago)), Speaker::Mind, &[]);
|
|
||||||
assert_eq!(after(29 * MINUTE), None, "the last of the four came exactly a window before: the run stands");
|
|
||||||
assert_eq!(after(29 * MINUTE + 1), Some(WakeCause::AddressedByMind), "a moment longer and it is over");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_minds_reply_or_tag_wakes_her_with_no_matrix_mention() {
|
|
||||||
for basis in [Basis::Reply, Basis::Tag] {
|
|
||||||
let line = ChatDelivery { basis: Some(basis), ..delivery(1, "@ann:chat", "a word", &[]) };
|
|
||||||
assert_eq!(woken(&line, Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "{basis:?}");
|
|
||||||
}
|
|
||||||
assert_eq!(woken(&delivery(1, "@ann:chat", "a word", &[]), Speaker::Mind, &[]), None, "no mention, no basis");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_a_new_message_wakes_her_on_every_path() {
|
|
||||||
let own = ["#swarm:chat"];
|
|
||||||
let exchange = ChatDelivery { room_alias: "#general:chat".into(), at_unix_ms: 10 * MINUTE, context: vec![said("@bob:chat", 5 * MINUTE)], ..delivery(3, "@member:chat", "fixed", &[]) };
|
|
||||||
assert_eq!(woken(&exchange, Speaker::Member, &[]), Some(WakeCause::Human), "as a message, the line is in her exchange");
|
|
||||||
assert_eq!(woken(&delivery(2, "@ci-bot:chat", "build green", &[]), Speaker::Member, &own), Some(WakeCause::Human), "and in her project room");
|
|
||||||
for form in [Form::Edit, Form::Notice] {
|
|
||||||
let formed = |line: ChatDelivery| ChatDelivery { form, ..line };
|
|
||||||
assert_eq!(woken(&formed(ChatDelivery { is_direct: true, room_alias: "!dm:chat".into(), ..delivery(1, "@member:chat", "fixed", &[]) }), Speaker::Member, &[]), None, "{form:?} in a DM");
|
|
||||||
assert_eq!(woken(&formed(delivery(2, "@ci-bot:chat", "build green", &[])), Speaker::Member, &own), None, "{form:?} in her project room");
|
|
||||||
assert_eq!(woken(&formed(exchange.clone()), Speaker::Member, &[]), None, "{form:?} in her exchange");
|
|
||||||
assert_eq!(woken(&formed(delivery(4, "@member:chat", "Bob?", &["@bob:chat"])), Speaker::Member, &[]), None, "{form:?} naming her");
|
|
||||||
assert_eq!(woken(&formed(delivery(5, "@ann:chat", "a word", &["@bob:chat"])), Speaker::Mind, &[]), None, "{form:?} from a Mind carrying her mention");
|
|
||||||
}
|
|
||||||
let rig = quiet_rig();
|
|
||||||
steward(&rig, BOB, "GameCult/Swarm", &[]);
|
|
||||||
rig.say(BOB, ChatDelivery { form: Form::Notice, ..delivery(1, "@ci-bot:chat", "build green", &[]) });
|
|
||||||
rig.say(BOB, ChatDelivery { form: Form::Edit, is_direct: true, room_alias: "!dm:chat".into(), ..delivery(2, "@member:chat", "fixed", &[]) });
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "off the beat, a notice and an edit start no turn");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_direct_message_wakes_her_as_addressed_by_the_one_check_in_is_for() {
|
|
||||||
let dm = ChatDelivery { is_direct: true, room_alias: "!dm:chat".into(), ..delivery(1, "@member:chat", "psst", &[]) };
|
|
||||||
assert_eq!(woken(&dm, Speaker::Member, &[]), Some(WakeCause::AddressedByHuman));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn general(seq: u64, sender: &str, text: &str) -> ChatDelivery {
|
|
||||||
ChatDelivery { room_alias: "#general:chat".into(), at_unix_ms: now_ms() + 1000 * seq, ..delivery(seq, sender, text, &[]) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The rig's clock, in the unit the lines carry: a line said just now is within the exchange window of it.
|
|
||||||
pub(super) fn now_ms() -> u64 {
|
|
||||||
u64::try_from(at(1_000_000).timestamp_millis()).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
pub(super) fn said_in_general(rig: &Rig, line: ChatDelivery) {
|
|
||||||
for who in [ANN, BOB] {
|
|
||||||
rig.say(who, line.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_member_naming_her_untagged_in_a_public_room_wakes_her() {
|
|
||||||
assert_eq!(woken(&general(1, "@member:chat", "Bob, can you look at this?"), Speaker::Member, &[]), Some(WakeCause::AddressedByHuman));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_newcomers_open_hello_wakes_exactly_one_mind_the_one_the_pick_names() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "never-tied waits break to the lowest slug, as the beat's pick does");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.turn(ANN, 5);
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the longer waiter takes it");
|
|
||||||
rig.finish_turn(BOB);
|
|
||||||
rig.advance(1);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "once per line: the Mind who took it is not woken again and no other is picked for it");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_lines_a_wake_is_for_are_recorded_before_her_unit_starts_and_lapse_when_it_does_not_start() {
|
|
||||||
let mut rig = quiet_rig();
|
|
||||||
rig.launcher.log = rig.store.log.clone();
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
rig.store.log.borrow_mut().clear();
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
let log = rig.store.log.borrow().clone();
|
|
||||||
assert_eq!(log.iter().position(|step| *step == "start").and_then(|start| log[..start].iter().position(|step| *step == "save")), Some(0), "her state held the claim when her unit started: {log:?}");
|
|
||||||
let state = rig.store.state.borrow().clone().unwrap();
|
|
||||||
assert_eq!(woken_for(&state, "ann"), vec![state.handled_mentions[0].split_once(':').unwrap().1.to_owned()], "the line is hers");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.launcher.fail.set(true);
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
|
||||||
rig.launcher.fail.set(false);
|
|
||||||
rig.advance(1);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "nothing was taken: the claim of a start that did not happen lapsed, and the hello is judged afresh");
|
|
||||||
let state = rig.store.state.borrow().clone().unwrap();
|
|
||||||
assert!(woken_for(&state, "bob").is_empty() && woken_for(&state, "ann").len() == 1, "one claim, hers: {:?}", state.handled_mentions);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wake_is_for_the_line_that_woke_her_and_the_floor_lines_she_took_and_for_nothing_twice() {
|
|
||||||
assert_eq!(claimed(Some("$a"), &["$b".into(), "$a".into()]), vec!["$a".to_owned(), "$b".to_owned()]);
|
|
||||||
assert_eq!(claimed(None, &["$b".into()]), vec!["$b".to_owned()], "the beat's wake names no line of its own");
|
|
||||||
assert!(claimed(None, &[]).is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_second_hello_after_that_mind_answered_wakes_no_extra_mind() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
rig.finish_turn(ANN);
|
|
||||||
rig.advance(60);
|
|
||||||
let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: now_ms() + 1500 }];
|
|
||||||
said_in_general(&rig, ChatDelivery { context: answered, ..general(2, "@other:chat", "me too, hello") });
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "she is in the exchange she opened; Bob is not picked for a line a Mind has answered the room on");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: now_ms() + 1500 }];
|
|
||||||
rig.say(BOB, ChatDelivery { context: answered, ..general(2, "@other:chat", "me too, hello") });
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a Mind who was not in the exchange is not woken by it");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(BOB, ChatDelivery { context: vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: now_ms() + 1500 }], ..general(3, "@other:chat", "Bob, you too?") });
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "unless the line addresses her");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_open_line_a_mind_took_in_one_wake_is_taken_and_a_line_tagging_anyone_is_not_open() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
said_in_general(&rig, general(2, "@other:chat", "hello, I am new too"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
rig.finish_turn(ANN);
|
|
||||||
rig.advance(1);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her one turn took both lines: Bob is not picked for the second");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
said_in_general(&rig, ChatDelivery { mentions: vec!["@alice:chat".into()], ..general(3, "@newcomer:chat", "hello alice") });
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a line that tags a person is not the floor's");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_start_that_fails_passes_the_hello_to_the_next_of_the_pick_in_the_same_poll() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
*rig.launcher.fail_for.borrow_mut() = Some(Slug("ann".into()));
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "Ann wins the pick, her unit will not start, and Bob takes the line in the same poll");
|
|
||||||
assert!(rig.notes().iter().any(|note| note.contains("start failed")), "the refusal is still said");
|
|
||||||
rig.finish_turn(BOB);
|
|
||||||
for poll in 0..10 {
|
|
||||||
rig.advance(1);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "poll {poll}: Bob took it; Ann's broken unit is not tried for it again");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn when_every_start_fails_the_line_is_tried_once_per_mind_and_then_waits() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.launcher.fail.set(true);
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
|
||||||
rig.launcher.fail.set(false);
|
|
||||||
rig.advance(1);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "nothing was taken, so the next poll picks again from the top");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_beat_does_not_give_a_hello_one_mind_took_to_a_second_mind() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.turn(ANN, 5000);
|
|
||||||
rig.turn(BOB, 4000);
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "the beat is due: Ann takes the floor and the beat does not wake Bob on the same line");
|
|
||||||
rig.advance(1);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "nor a poll later, Ann still in her turn, while the line is within the exchange window");
|
|
||||||
rig.advance(31 * 60);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a Mind that holds only an old taken line is woken by the beat like any other");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_old_hello_whose_taken_key_was_forgotten_wakes_no_one_and_the_keys_are_bounded() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
let old: Vec<String> = (0..70).map(|at| format!("$old{at}")).collect();
|
|
||||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": old, "at": rig.now().to_rfc3339() }));
|
|
||||||
rig.with_state(|state| state.handled_mentions = (0..70).map(|at| format!("ann:$old{at}")).collect());
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
assert_eq!(rig.store.state.borrow().as_ref().unwrap().handled_mentions.len(), MENTIONS_KEPT, "the handled keys keep their bound");
|
|
||||||
rig.finish_turn(ANN);
|
|
||||||
rig.with_state(|state| state.handled_mentions.clear());
|
|
||||||
rig.advance(31 * 60);
|
|
||||||
rig.beat_fell();
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the line is older than the window: no key to remember it, and it is no one's to take");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_minds_line_in_another_room_does_not_close_this_rooms_floor() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
let elsewhere = ChatDelivery { room_alias: "#random:chat".into(), at_unix_ms: now_ms() - 1000, ..delivery(9, "@ann:chat", "something", &[]) };
|
|
||||||
rig.say(ANN, elsewhere);
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "Ann spoke in #random, not in #general: she is still a candidate for the hello");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_busy_or_braked_mind_is_never_picked_for_the_floor_and_a_line_to_a_busy_mind_is_not_the_floor() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.in_a_turn(ANN);
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "Ann is in a turn: Bob takes it");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.control.braked.borrow_mut().push("ann".into());
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "Ann is braked: Bob takes it");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.in_a_turn(BOB);
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "Bob, hello?"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a line that names Bob is Bob's, even while he is busy: Ann is not picked for it");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_lines_the_heartbeat_woke_her_for_are_read_from_her_own_handled_keys() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
let state = rig.store.state.borrow().clone().unwrap();
|
|
||||||
assert_eq!(woken_for(&state, "ann"), vec!["$e1".to_owned()], "the hello that woke her");
|
|
||||||
assert!(woken_for(&state, "bob").is_empty(), "not the Mind who was not woken for it");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_minds_own_line_a_notice_an_edit_a_tag_or_an_operator_opens_no_floor() {
|
|
||||||
for (line, why) in [
|
|
||||||
(general(1, "@ann:chat", "hello everyone!"), "a Mind's line"),
|
|
||||||
(ChatDelivery { form: Form::Notice, ..general(2, "@newcomer:chat", "hello everyone!") }, "a notice"),
|
|
||||||
(ChatDelivery { form: Form::Edit, ..general(3, "@newcomer:chat", "hello everyone!") }, "an edit"),
|
|
||||||
(general(4, "@op:chat", "hello everyone!"), "the operator's line (a member's alone opens it)"),
|
|
||||||
] {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
said_in_general(&rig, line);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "{why}");
|
|
||||||
}
|
|
||||||
let rig = quiet_rig();
|
|
||||||
said_in_general(&rig, ChatDelivery { mentions: vec!["@bob:chat".into()], ..general(5, "@newcomer:chat", "hello") });
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a line that tags one Mind is hers alone, not the floor's");
|
|
||||||
let rig = quiet_rig();
|
|
||||||
steward(&rig, BOB, "GameCult/Swarm", &["Zed"]);
|
|
||||||
said_in_general(&rig, general(6, "@newcomer:chat", "is Zed down?"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a line that names a project belongs to its steward, not the floor");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_open_floor_is_judged_the_same_from_the_pending_lines_and_from_the_simulators_room() {
|
|
||||||
// Never-acted Minds of the roster, eligible: the pick breaks to the lowest slug, in both.
|
|
||||||
let who = |slug: &str, eligible: bool| (Addressee::new(&format!("@{slug}:chat"), [slug]), tempo::Standing { slug: slug.into(), eligible, waited_s: None, last_turn_ms: None, topic_permille: 0, addressed_by_member: false });
|
|
||||||
let (zed, ann) = (who("zed", true), who("ann", true));
|
|
||||||
let line = general(1, "@newcomer:chat", "hello everyone!");
|
|
||||||
fn hear<'a>(minds: &[&'a (Addressee, tempo::Standing)], open: &[bool], line: &ChatDelivery) -> Vec<Hearer<'a>> {
|
|
||||||
minds.iter().zip(open).map(|(mind, open)| Hearer { addressee: &mind.0, delivery: line.clone(), open: *open, standing: mind.1.clone() }).collect()
|
|
||||||
}
|
|
||||||
assert_eq!(floor_to(&hear(&[&zed, &ann], &[true, true], &line), Speaker::Member, BEAT_S), Some(1), "ann sorts before zed");
|
|
||||||
assert_eq!(floor_to(&hear(&[&zed, &ann], &[true, false], &line), Speaker::Member, BEAT_S), Some(0), "a Mind for whom a Mind has spoken in the room is not a candidate");
|
|
||||||
let busy = who("ann", false);
|
|
||||||
assert_eq!(floor_to(&hear(&[&zed, &busy], &[true, true], &line), Speaker::Member, BEAT_S), Some(0), "a busy Mind is not picked");
|
|
||||||
assert_eq!(floor_to(&hear(&[&zed, &ann], &[true, true], &line), Speaker::Mind, BEAT_S), None);
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn the_exchange_holds_to_the_millisecond_of_the_window() {
|
|
||||||
let window = 30 * MINUTE;
|
|
||||||
let line = |sender, at_ms| FactLine { sender, room: "#general:chat", at_ms };
|
|
||||||
let in_exchange = |gap: u64| line_facts(&[line("@bob:chat", 0), line("@member:chat", gap)], "@bob:chat", &minds(), &[], window)[1].in_exchange;
|
|
||||||
assert!(in_exchange(window), "a line exactly one window after hers is in her exchange");
|
|
||||||
assert!(!in_exchange(window + 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_mind_run_lapses_after_a_silence_longer_than_the_window_and_not_before() {
|
|
||||||
let window = 30 * MINUTE;
|
|
||||||
let line = |sender, at_ms| FactLine { sender, room: "#minds:chat", at_ms };
|
|
||||||
let run = |gap: u64| {
|
|
||||||
let lines = [line("@ann:chat", 0), line("@bob:chat", MINUTE), line("@ann:chat", 2 * MINUTE), line("@bob:chat", 3 * MINUTE), line("@ann:chat", 3 * MINUTE + gap)];
|
|
||||||
line_facts(&lines, "@bob:chat", &minds(), &[], window)[4].mind_run
|
|
||||||
};
|
|
||||||
assert_eq!(run(window), 4, "a silence of exactly the window keeps the run");
|
|
||||||
assert_eq!(run(window + 1), 0, "a longer one ends it, in a room no human speaks in");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn her_own_rooms_are_read_from_her_mind_as_the_poll_reads_them_and_an_unreadable_mind_is_an_error() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
steward(&rig, BOB, "GameCult/Swarm", &[]);
|
|
||||||
// Her mind refuses another instance's stewardship (ForeignInstance), so the poll's and the drain's readers cannot disagree on instance.
|
|
||||||
let aliases = ["#SWARM:chat", "#general:chat", "!dm:chat"];
|
|
||||||
let rooms = |down: bool| {
|
|
||||||
let (calls, admits, reads, stewardship_down) = (Cell::new(0), Cell::new(0), Cell::new(0), Cell::new(down));
|
|
||||||
own_rooms_among(&Counting { inner: &rig.minds[BOB], calls: &calls, admits: &admits, stewardship_reads: &reads, stewardship_down: &stewardship_down }, aliases)
|
|
||||||
};
|
|
||||||
assert_eq!(rooms(false).unwrap(), vec!["#SWARM:chat".to_owned()]);
|
|
||||||
assert!(rooms(true).is_err(), "unread is an error the caller reports, not no rooms");
|
|
||||||
rig.say(BOB, ChatDelivery { ..delivery(1, "@member:chat", "what a day", &[]) });
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the poll reads the same room as hers");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul R21 p1, pinned: a line the poll woke her for whose turn then failed stays pending, and the next poll wakes her for it again; it
|
|
||||||
/// does not wait for an unrelated start. Once her turn finishes the line (the drain acked it) she is not woken for it again.
|
|
||||||
#[test]
|
|
||||||
fn a_line_whose_turn_failed_wakes_her_again_on_the_next_poll_and_a_finished_one_does_not() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
rig.in_a_turn(ANN);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her unit is running: the claim stands");
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.advance(120);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "her turn left the line pending: she is woken for it again");
|
|
||||||
rig.finish_turn(ANN);
|
|
||||||
rig.advance(120);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the drain acked it: once per message holds");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A crash between the save of the claim and the start of her unit leaves a key and no turn.
|
|
||||||
#[test]
|
|
||||||
fn a_claim_saved_before_a_start_that_never_happened_does_not_strand_the_line() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
rig.with_state(|state| state.handled_mentions.push("ann:$e1".into()));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_hello_whose_takers_turn_failed_is_not_barred_from_the_other_minds() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.advance(60);
|
|
||||||
*rig.launcher.fail_for.borrow_mut() = Some(Slug("ann".into()));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "Ann's turn failed and her unit will not start: Bob takes the hello");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The binding the live unit reads: the file store gives back the lines the poll recorded for her, and only hers.
|
|
||||||
#[test]
|
|
||||||
fn the_file_store_view_reads_the_lines_the_poll_recorded_for_her() {
|
|
||||||
let dir = TempDir::new().unwrap();
|
|
||||||
let store = FileStore::new(dir.path().join("heartbeat.cc"));
|
|
||||||
assert!(HeartbeatView::woken_for(&store, "ann").unwrap().is_empty(), "no state yet: no claims");
|
|
||||||
store.save(&HeartbeatState { last_beat_at: at(0), handled_mentions: vec!["ann:$e1".into(), "bob:$e2".into(), "ann:$e3".into()], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() }).unwrap();
|
|
||||||
assert_eq!(HeartbeatView::woken_for(&store, "ann").unwrap(), ["$e1", "$e3"]);
|
|
||||||
assert_eq!(HeartbeatView::woken_for(&store, "bob").unwrap(), ["$e2"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An unreadable state is an error to the drain, never no claims.
|
|
||||||
#[test]
|
|
||||||
fn the_file_store_view_fails_on_an_unreadable_state() {
|
|
||||||
let dir = TempDir::new().unwrap();
|
|
||||||
let path = dir.path().join("heartbeat.cc");
|
|
||||||
std::fs::write(&path, b"not a cultcache file").unwrap();
|
|
||||||
assert!(HeartbeatView::woken_for(&FileStore::new(path), "ann").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul s4 release-regives-answered-hello: she decided the hello, but an older room's failed turn holds the ack below it, so it is
|
|
||||||
/// still pending in her queue. Her trace says it is hers and done; the poll does not read "still pending" as "her turn left it".
|
|
||||||
#[test]
|
|
||||||
fn a_hello_she_decided_whose_ack_is_held_is_not_given_to_a_second_mind() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "at": rig.now().to_rfc3339() }));
|
|
||||||
assert!(!rig.chats[ANN].deliveries.borrow().is_empty(), "the ack is held: the hello is still in her queue");
|
|
||||||
for _ in 0..5 {
|
|
||||||
rig.advance(60);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided by her trace: not hers again, not Bob's");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line her trace holds decided is not woken for again however long the mouth keeps it; one it does not hold is.
|
|
||||||
#[test]
|
|
||||||
fn only_her_trace_decides_whether_a_line_is_woken_for() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "at": rig.now().to_rfc3339() }));
|
|
||||||
rig.advance(120);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided");
|
|
||||||
rig.say(ANN, delivery(2, "@op:chat", "Ann, again", &[]));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "a new line is not");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A trace the poll cannot read decides nothing: she is not woken on a guess, and the poll says so.
|
|
||||||
#[test]
|
|
||||||
fn an_unreadable_trace_wakes_no_one_and_is_noted() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.traces[ANN].unreadable.set(true);
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
|
||||||
assert!(rig.notes().iter().any(|note| note.contains("trace unread")), "{:?}", rig.notes());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul s4 outage-rewake-floods-records: a wake whose turn failed is waited out, 20 s doubling with each failure in a row her trace
|
|
||||||
/// holds, up to the beat, instead of failing every poll.
|
|
||||||
#[test]
|
|
||||||
fn a_wake_that_failed_is_waited_out_by_the_failures_in_a_row_up_to_the_beat() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
for run in 1..=9u32 {
|
|
||||||
rig.fail_turn(ANN);
|
|
||||||
let wait = (20i64 << (run - 1)).min(i64::from(BEAT_S));
|
|
||||||
rig.advance(wait - 1);
|
|
||||||
rig.beat_fell();
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "failure {run}: still waiting out {wait} s");
|
|
||||||
rig.advance(1);
|
|
||||||
rig.beat_fell();
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "failure {run}: {wait} s passed");
|
|
||||||
}
|
|
||||||
assert_eq!(rig.launched().len(), 10);
|
|
||||||
rig.finish_turn(ANN);
|
|
||||||
rig.advance(1);
|
|
||||||
rig.beat_fell();
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided: the run ends");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Mind that is waiting out failures passes the open floor on, as one whose start failed does.
|
|
||||||
#[test]
|
|
||||||
fn a_mind_waiting_out_failures_passes_the_hello_to_the_other() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.fail_turn(ANN);
|
|
||||||
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's p5: a hello she decided is decided, whatever her record also holds: her claim stands when her unit ends, no second Mind is given it, and
|
|
||||||
/// nothing starts her again for it. A record's `owed` list is read by no one.
|
|
||||||
#[test]
|
|
||||||
fn a_hello_she_decided_is_not_given_to_a_second_mind_and_starts_no_one() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
rig.poll();
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "#general:chat", "text": "hi" }], "at": rig.now().to_rfc3339() }));
|
|
||||||
rig.advance(60);
|
|
||||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
|
||||||
assert_eq!(launched, vec![], "no one is started, and no one is given the hello");
|
|
||||||
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "her claim stands");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's S12: a claim survives a trace that cannot be read, so the line is not given on a guess.
|
|
||||||
#[test]
|
|
||||||
fn a_claim_survives_a_trace_that_cannot_be_read() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
|
|
||||||
rig.poll();
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.traces[ANN].unreadable.set(true);
|
|
||||||
rig.advance(60);
|
|
||||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
|
||||||
assert_eq!(launched, vec![]);
|
|
||||||
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's p7: the beat waits out a Mind's failed wakes as the poll does.
|
|
||||||
#[test]
|
|
||||||
fn the_beat_does_not_start_a_mind_that_is_cooling() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
rig.poll();
|
|
||||||
rig.fail_turn(ANN);
|
|
||||||
rig.advance(5);
|
|
||||||
let now = rig.now();
|
|
||||||
rig.with_state(|state| {
|
|
||||||
state.last_beat_at = now - Duration::seconds(i64::from(BEAT_S) + 1);
|
|
||||||
state.last_turn_at.insert("bob".into(), now);
|
|
||||||
});
|
|
||||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
|
||||||
assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A record that holds a send in `owed` wakes no one: nothing settles such a list now, so a poll that started her for it would start her forever.
|
|
||||||
/// Every poll over half an hour, with nothing new arriving, starts her never (the beat's turn for the others aside).
|
|
||||||
#[test]
|
|
||||||
fn t_l3_an_owed_list_in_her_trace_starts_no_one() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
rig.poll();
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
|
|
||||||
for minute in 1..=29 {
|
|
||||||
rig.advance(60);
|
|
||||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
|
||||||
assert!(!launched.iter().any(|slug| slug.0 == "ann"), "minute {minute}: {launched:?}");
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A send settled starts no one.
|
|
||||||
#[test]
|
|
||||||
fn t_l3_a_send_settled_starts_no_one() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "posted": [{ "event": "$sent-1", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
|
|
||||||
rig.advance(60);
|
|
||||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
|
||||||
assert!(launched.is_empty(), "{launched:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul s7 pins-on-new-lines. A line that wakes her and her trace does not hold decided starts her by the wake rule, which writes the claim for
|
|
||||||
/// the line, whatever an older record of hers holds in `owed`.
|
|
||||||
#[test]
|
|
||||||
fn t_l3_a_new_waking_line_is_woken_for_by_the_wake_rule_with_an_owed_list_in_her_trace() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
rig.poll();
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
|
|
||||||
rig.say(ANN, delivery(2, "@op:chat", "Ann, again", &[]));
|
|
||||||
rig.advance(60);
|
|
||||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
|
||||||
assert_eq!(launched, vec![Slug("ann".into())]);
|
|
||||||
assert!(rig.store.state.borrow().clone().unwrap().handled_mentions.contains(&"ann:$e2".to_owned()), "the new line's claim is written: the wake rule started her");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A start the day cap held writes no wake record and decides no line, so the poll would start her unit for the same undecided line at
|
|
||||||
/// every poll. The drain alone says whether she is held; the poll only backs off by her held starts as by failed wakes (20 s, doubling to
|
|
||||||
/// the beat). A row's `until` is no authority: a far-future one, written by anyone, holds her no longer than the backoff. A start after
|
|
||||||
/// the backoff is made, so a raised cap releases her within a beat.
|
|
||||||
#[test]
|
|
||||||
fn t_h4_held_starts_back_off_like_failures_and_never_hold_her_for_a_day() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
let t0 = rig.now();
|
|
||||||
let far = (t0 + Duration::days(300)).to_rfc3339();
|
|
||||||
let mut launches: Vec<i64> = vec![];
|
|
||||||
for _ in 0..360 {
|
|
||||||
rig.advance(10);
|
|
||||||
let Outcome::Polled { launched } = rig.poll() else { panic!("polled") };
|
|
||||||
if launched.iter().any(|slug| slug.0 == "ann") {
|
|
||||||
launches.push((rig.now() - t0).num_seconds());
|
|
||||||
rig.end_unit(ANN);
|
|
||||||
// What the drain does at a start it holds: appends a row of its own, at the place the trace has reached.
|
|
||||||
let mut rows = rig.traces[ANN].rows.borrow_mut();
|
|
||||||
let seq = rows.len();
|
|
||||||
rows.push(serde_json::json!({ "held_by": "day_cap", "spent": 3.2, "cap": 3.0, "until": far, "at": rig.now().to_rfc3339(), "seq": seq }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let gaps: Vec<i64> = launches.windows(2).map(|pair| pair[1] - pair[0]).collect();
|
|
||||||
assert_eq!(gaps, [20, 40, 80, 160, 320, 640, 900, 900].map(i64::from), "{launches:?}: each held start waits the failure backoff, to the beat");
|
|
||||||
assert_eq!(launches.len(), 9, "an hour of held starts costs nine unit starts, not 360: {launches:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W2: lines that reach a Mind whose wake is open are the wake's, read from the mouth by the wake itself. The heartbeat starts no second unit for
|
|
||||||
/// them, writes no claim for them, and does not wake her for them once her unit has ended with her trace holding them decided.
|
|
||||||
#[test]
|
|
||||||
fn lines_that_reach_a_mind_with_a_wake_open_start_no_second_unit_and_claim_nothing() {
|
|
||||||
let rig = quiet_rig();
|
|
||||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
|
||||||
rig.in_a_turn(ANN);
|
|
||||||
for seq in 2..=4 {
|
|
||||||
rig.say(ANN, delivery(seq, "@op:chat", "Ann, and again", &[]));
|
|
||||||
rig.advance(60);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her unit is active: line {seq} is her wake's, and starts nothing");
|
|
||||||
}
|
|
||||||
assert_eq!(rig.launched(), vec![Slug("ann".into())], "one start, one unit");
|
|
||||||
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "no claim was written for the lines her wake took");
|
|
||||||
rig.finish_turn(ANN);
|
|
||||||
rig.advance(120);
|
|
||||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her wake decided them all: nothing wakes her again");
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
//!
|
//!
|
||||||
//! Today that is `control`, the operator's brakes, and `cli`, the operator's
|
//! Today that is `control`, the operator's brakes, and `cli`, the operator's
|
||||||
//! hand on them. The brakes are the operator's consent, not her body: the store
|
//! hand on them. The brakes are the operator's consent, not her body: the store
|
||||||
//! is root-owned and nothing of hers writes it.
|
//! is root-owned and no organ of hers writes it.
|
||||||
//!
|
//!
|
||||||
//! `launch` holds her units under systemd and the reads of the runs a Self run
|
//! `launch` holds her units under systemd and the reads of the runs a Self run
|
||||||
//! holds; `queue` is her port to her mind and what an open question holds.
|
//! holds; `queue` is her port to her mind and what an open question holds.
|
||||||
|
|
@ -16,9 +16,8 @@
|
||||||
//! (`chat_client` is the chat wire and port and `chat_rudp` its RUDP transport to Bifrost's mouth).
|
//! (`chat_client` is the chat wire and port and `chat_rudp` its RUDP transport to Bifrost's mouth).
|
||||||
//!
|
//!
|
||||||
//! `projection` is the Projector of the Persona-only turn: the Select stage chooses what she can feel and the
|
//! `projection` is the Projector of the Persona-only turn: the Select stage chooses what she can feel and the
|
||||||
//! Projector narrates it as her lived stream, under `persona-tuning.toml`; the Persona stage continues it in her prose.
|
//! Projector narrates it as her lived stream, under `persona-tuning.toml`; `mind-persona project` runs both and writes
|
||||||
//! `mind-persona project` runs them and writes nothing; `projection::harness` runs it over mocked rooms, batches of
|
//! nothing.
|
||||||
//! candidate states and a simulated swarm.
|
|
||||||
//!
|
//!
|
||||||
//! `lease_client` asks the Claude connector for a session's credential and the
|
//! `lease_client` asks the Claude connector for a session's credential and the
|
||||||
//! plan's usage windows. `self_run` carries one Self run inside `mind-self@<instance>`: the
|
//! plan's usage windows. `self_run` carries one Self run inside `mind-self@<instance>`: the
|
||||||
|
|
@ -47,7 +46,6 @@ pub mod lease_client;
|
||||||
pub mod persona;
|
pub mod persona;
|
||||||
pub mod projection;
|
pub mod projection;
|
||||||
pub mod queue;
|
pub mod queue;
|
||||||
pub mod sandbox;
|
|
||||||
pub mod self_run;
|
pub mod self_run;
|
||||||
pub mod tempo;
|
pub mod tempo;
|
||||||
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,467 +0,0 @@
|
||||||
//! A wake that stays open (cut W2): its second and later turns, the end it comes to, and its close. One start, the fake clock, the scripted agent.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
const EUREKA: &str = "@eureka:gamecult.org";
|
|
||||||
const MINDS: &str = "#minds:gamecult.org";
|
|
||||||
|
|
||||||
/// Her agent ends its turn at once.
|
|
||||||
fn done() -> std::result::Result<Stepped, Failed> {
|
|
||||||
Ok(Stepped { items: vec![InputItem::AssistantText { text: "Done.".into() }], text: "Done.".into(), calls: vec![], stop: StopReason::EndTurn, usage: spent() })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her agent runs `command` in her shell.
|
|
||||||
fn shells(id: &str, command: &str) -> std::result::Result<Stepped, Failed> {
|
|
||||||
let call = ToolCall { call_id: id.into(), name: "shell".into(), arguments: json!({ "command": command }).to_string() };
|
|
||||||
Ok(Stepped { items: vec![InputItem::ToolCall { call_id: call.call_id.clone(), name: call.name.clone(), arguments: call.arguments.clone() }], text: String::new(), calls: vec![call], stop: StopReason::ToolUse, usage: spent() })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line that reaches the mouth by the time the fake clock reads `tick`.
|
|
||||||
fn arrives(rig: &Rig, tick: i64, line: ChatDelivery) {
|
|
||||||
rig.arrivals.borrow_mut().push((tick, line));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line of the operator's, `tick` seconds into the wake.
|
|
||||||
fn later(seq: u64, room: &str, tick: i64, text: &str) -> ChatDelivery {
|
|
||||||
line_at(seq, room, META, text, BASE_MS + u64::try_from(tick).unwrap() * 1000)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn answers(rig: &Rig, list: impl IntoIterator<Item = std::result::Result<Stepped, Failed>>) {
|
|
||||||
rig.agent.answers.borrow_mut().extend(list);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tune(rig: &Rig, body: &str) {
|
|
||||||
std::fs::write(rig.dir.path().join("persona-tuning.toml"), body).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn calls(rig: &Rig, stage: &str) -> usize {
|
|
||||||
rig.log.all().iter().filter(|what| *what == stage).count()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn at_of(row: &Value) -> DateTime<Utc> {
|
|
||||||
row["at"].as_str().unwrap().parse().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn user_text(items: &[InputItem]) -> String {
|
|
||||||
match items.last() {
|
|
||||||
Some(InputItem::UserText { text }) => text.clone(),
|
|
||||||
other => panic!("a turn's last item is its lines: {other:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W2-I6, I7 and the turn itself: a second line a minute after the first is a second turn of the same wake, in the same agent conversation, with only the new
|
|
||||||
/// line as its input. The Projector and the Persona ran once, the Interpreter once over both turns' receipts, and each turn's lines were acked behind its own row.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_second_line_is_a_second_turn_of_one_wake() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first line, are you there")]);
|
|
||||||
answers(&rig, [shells("one", "ls /srv/one"), done(), shells("two", "ls /srv/two"), done()]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "and a second line"));
|
|
||||||
let model = Tally::default();
|
|
||||||
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) });
|
|
||||||
assert_eq!((calls(&rig, "projector"), calls(&rig, "persona"), calls(&rig, "interpreter")), (1, 1, 2), "one Projector, one Persona, and the Interpreter's two halves once, over both turns");
|
|
||||||
// The second turn's request carries the first turn's items as its prefix: one conversation.
|
|
||||||
let seen = rig.agent.seen.borrow();
|
|
||||||
assert_eq!(seen.len(), 4);
|
|
||||||
let (first_end, second) = (&seen[1], &seen[2]);
|
|
||||||
assert_eq!(second.len(), first_end.len() + 2, "the first turn's items, her closing words, then the new lines");
|
|
||||||
assert!(first_end.iter().zip(second).all(|(before, now)| format!("{before:?}") == format!("{now:?}")), "{second:?}");
|
|
||||||
let (opening, input) = (user_text(&seen[0]), user_text(second));
|
|
||||||
assert!(opening.contains("What she lives now") && opening.contains("first line, are you there"), "{opening}");
|
|
||||||
assert!(input.contains("and a second line") && !input.contains("first line") && !input.contains("What she lives now") && !input.contains("Her own inner voice"), "the second turn is the new lines alone: {input}");
|
|
||||||
drop(seen);
|
|
||||||
// Both turns' acts reach the one Interpreter pass.
|
|
||||||
for prompt in model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)) {
|
|
||||||
let acts = prompt.split("\nACTS\n").nth(1).unwrap_or_else(|| panic!("no ACTS section: {prompt}")).split("NARRATION").next().unwrap();
|
|
||||||
assert!(acts.contains("\"ls /srv/one\"") && acts.contains("\"ls /srv/two\""), "{acts}");
|
|
||||||
}
|
|
||||||
let turns = rig.turns();
|
|
||||||
assert_eq!(turns.iter().map(|turn| (turn["turn"].clone(), turn["held"].clone())).collect::<Vec<_>>(), [(json!(1), json!(["$e1"])), (json!(2), json!(["$e2"]))]);
|
|
||||||
let records = rig.records();
|
|
||||||
assert_eq!((records.len(), records[0]["turns"].clone(), records[0]["ended"].clone(), records[0]["status"].clone(), records[0]["held"].clone()), (1, json!(2), json!("idle"), json!("completed"), json!([])));
|
|
||||||
assert_eq!(rig.acks(), [1, 2], "each turn's lines are acked behind its own row");
|
|
||||||
let ids: Vec<String> = rig.all_records().iter().filter(|row| row["agent"] == "call").map(|row| row["call"].as_str().unwrap().to_owned()).collect();
|
|
||||||
assert!(ids.iter().any(|id| id.contains("-t2-m")) && ids.iter().collect::<std::collections::BTreeSet<_>>().len() == ids.len(), "no two model calls of the wake share a request id: {ids:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W2-I7: the Interpreter runs once at the close, not once per turn: three turns still make its two halves, and its receipt and the put are one each.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_the_interpreter_runs_once_at_close_over_all_turns() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
arrives(&rig, 100, later(2, &room(1), 100, "second"));
|
|
||||||
arrives(&rig, 250, later(3, &room(1), 250, "third"));
|
|
||||||
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, turns: 3, ended: Some(End::Idle), acked_through: Some(3) });
|
|
||||||
assert_eq!(calls(&rig, "interpreter"), 2, "two halves, once");
|
|
||||||
assert_eq!((rig.store.puts.borrow().len(), rows(&rig.all_records(), "interpreter").len()), (1, 1));
|
|
||||||
let log = rig.log.all();
|
|
||||||
let last_turn = log.iter().rposition(|what| what == "row:turn").unwrap();
|
|
||||||
assert!(log.iter().position(|what| what == "interpreter").unwrap() > last_turn, "after the last turn, not between turns: {log:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W2-I6: no Projector and no Persona call for a line that arrives in an open wake, however many turns follow.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_the_projector_and_the_persona_do_not_rerun_for_a_line_in_an_open_wake() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
for (n, tick) in [(2, 80), (3, 160), (4, 240)] {
|
|
||||||
arrives(&rig, tick, later(n, &room(1), tick, &format!("line {n}")));
|
|
||||||
}
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 4, ended: Some(End::Idle), acked_through: Some(4) });
|
|
||||||
assert_eq!((calls(&rig, "projector"), calls(&rig, "persona"), calls(&rig, "agent")), (1, 1, 4));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The idle window: no line after her turn, so the wake waits idle_s, polling every 5 s, and closes `ended: idle`.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_wake_with_no_new_line_closes_idle_after_idle_s_of_five_second_polls() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
|
|
||||||
let (turn, wake) = (at_of(&rig.turns()[0]), at_of(&rig.records()[0]));
|
|
||||||
let waited = (wake - turn).num_seconds();
|
|
||||||
assert!((300..330).contains(&waited), "the close came {waited} s after her turn");
|
|
||||||
let pauses = rig.pauses.borrow();
|
|
||||||
assert!(pauses.len() > 20 && pauses.iter().all(|wait| wait.as_secs() == 5), "{pauses:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The span: a line every minute keeps the wake open until span_s, and no longer.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_wake_open_span_s_closes_though_lines_keep_coming() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
tune(&rig, "[agent]\nspan_s = 300\nidle_s = 120\n");
|
|
||||||
for n in 0..40 {
|
|
||||||
arrives(&rig, 40 + 40 * n, later(2 + n as u64, &room(1), 40 + 40 * n, &format!("line {n}")));
|
|
||||||
}
|
|
||||||
let Outcome::Drained { turns, ended, .. } = rig.run(Tally::default()) else { panic!("drained") };
|
|
||||||
assert_eq!(ended, Some(End::Span));
|
|
||||||
assert!((4..=9).contains(&turns), "{turns} turns");
|
|
||||||
let (first, wake) = (at_of(&rig.turns()[0]), at_of(&rig.records()[0]));
|
|
||||||
let open = (wake - first).num_seconds();
|
|
||||||
assert!((250..330).contains(&open), "the wake closed {open} s after its first turn");
|
|
||||||
assert!(!rig.arrivals.borrow().is_empty(), "lines that came after the span were never read by this wake");
|
|
||||||
assert_eq!(rig.records()[0]["ended"], "span");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line that wakes her nothing: another room's member line starts no turn, and a notice in the wake's room is held by the wake record, which
|
|
||||||
/// decides it, and acked behind it.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_line_that_wakes_nothing_starts_no_turn_and_the_wake_record_holds_it_if_it_is_in_the_wakes_rooms() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
|
|
||||||
arrives(&rig, 40, line_at(2, MINDS, ANN, "status: green", BASE_MS + 40_000));
|
|
||||||
let mut notice = later(3, &room(1), 80, "a notice");
|
|
||||||
notice.form = Form::Notice;
|
|
||||||
arrives(&rig, 80, notice);
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(3) });
|
|
||||||
assert_eq!(rig.agent.seen.borrow().len(), 1, "her agent took the one turn");
|
|
||||||
let records = rig.records();
|
|
||||||
assert_eq!(records[0]["held"], json!(["$e3"]), "the notice, in the wake's room, and no other room's line");
|
|
||||||
assert!(decided(&rig.trace.records().unwrap()).contains("$e3"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The backstop: Minds tagging her in a row wake her only while fewer than MIND_RUN_BACKSTOP lines of the run came before; the pool of lines the wake
|
|
||||||
/// has seen is what the run is counted over, whatever was acked, so a chain does not restart at each ack.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_minds_tagging_her_in_a_row_stop_waking_her_at_the_backstop() {
|
|
||||||
let tagged = |seq: u64, tick: i64| ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(seq, MINDS, LIBBY, &format!("libby says {seq}"), BASE_MS + u64::try_from(tick).unwrap() * 1000) };
|
|
||||||
let rig = Rig::new(vec![tagged(1, 0)]);
|
|
||||||
for seq in 2..=6 {
|
|
||||||
arrives(&rig, 100 * (seq as i64 - 1), tagged(seq, 100 * (seq as i64 - 1)));
|
|
||||||
}
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 4, ended: Some(End::Idle), acked_through: Some(6) }, "four Mind lines wake her, the fifth and sixth do not");
|
|
||||||
let seen: String = rig.agent.seen.borrow().iter().flatten().map(|item| format!("{item:?}")).collect();
|
|
||||||
assert!(seen.contains("libby says 4") && !seen.contains("libby says 5") && !seen.contains("libby says 6"), "the lines past the backstop are not shown to her agent");
|
|
||||||
assert_eq!(rig.records()[0]["held"], json!(["$e5", "$e6"]), "they woke nothing, and are in the wake's room: the wake record holds them");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// (b) of W1: the mouth refuses a say whose basis is not the newest event of the room, so each line a turn shows must be shown to the mouth. A say after an
|
|
||||||
/// in-wake line is sent against that line.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_say_after_an_in_wake_line_is_sent_against_that_line() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
rig.mouth.strict.set(true);
|
|
||||||
answers(&rig, [says(&room(1), "first answer"), done(), says(&room(1), "second answer"), done()]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second"));
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) });
|
|
||||||
let sent = rig.mouth.sent.borrow();
|
|
||||||
assert_eq!(sent.iter().map(|request| request.text.as_str()).collect::<Vec<_>>(), ["first answer", "second answer"], "the second say was not refused RoomMoved");
|
|
||||||
assert_eq!(sent[1].basis.as_ref().and_then(|basis| basis.seen_event_id.as_deref()), Some("$e2"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W1 (a) and a turn 2 failure that is no outage: the strike is on turn 2's row, on turn 2's oldest waking line, once; the wake record is completed, the
|
|
||||||
/// Interpreter ran over turn 1, and the line is woken for again by the next start.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_failed_second_turn_strikes_its_line_on_its_own_row_and_the_wake_still_closes_completed() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
answers(&rig, [shells("one", "ls /srv/one"), done(), Err(Failed { reason: "the agent's turn ended early: Refusal".into(), outage: false, usage: None })]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "the line the model refuses"));
|
|
||||||
let model = Tally::default();
|
|
||||||
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Failed), acked_through: Some(1) });
|
|
||||||
let turns = rig.turns();
|
|
||||||
assert_eq!((turns[1]["status"].as_str(), turns[1]["strike"].clone()), (Some("failed"), json!("$e2")));
|
|
||||||
assert_eq!(rig.all_records().iter().filter(|row| row.get("strike").is_some()).count(), 1, "struck once, on the turn's row, not again on the wake record");
|
|
||||||
let wake = &rig.records()[0];
|
|
||||||
assert_eq!((wake["status"].as_str(), wake["ended"].as_str(), wake.get("failed").is_none(), wake["held"].clone()), (Some("completed"), Some("failed"), true, json!([])));
|
|
||||||
assert_eq!(calls(&rig, "interpreter"), 2, "the Interpreter ran, over turn 1");
|
|
||||||
assert!(model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).all(|prompt| prompt.contains("\"ls /srv/one\"")));
|
|
||||||
assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"), "a failed turn decides nothing");
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) }, "the next start answers the line");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An outage in turn 2 strikes nothing.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_an_outage_in_a_second_turn_strikes_nothing() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
answers(&rig, [done(), Err(Failed { reason: OUTAGE.into(), outage: true, usage: None })]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second"));
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Failed), acked_through: Some(1) });
|
|
||||||
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none()));
|
|
||||||
assert_eq!(rig.turns()[1]["outage"], true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The wake's own spend cap: the turns' spend is summed, and the wake closes `spend` when it reaches wake_usd.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_wake_closes_when_its_turns_have_spent_the_wake_cap() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
// One turn here is about $0.0003 a call.
|
|
||||||
tune(&rig, "[agent]\nwake_usd = 0.0005\n");
|
|
||||||
answers(&rig, [shells("one", "ls /srv/one")]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second"));
|
|
||||||
let Outcome::Drained { ended, .. } = rig.run(Tally::default()) else { panic!("drained") };
|
|
||||||
assert_eq!(ended, Some(End::Spend));
|
|
||||||
assert_eq!(rig.records()[0]["ended"], "spend");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The day cap, reached in a later turn, ends the wake, and the next start is held.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_the_day_cap_reached_mid_wake_ends_it_and_the_next_start_is_held() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
|
|
||||||
// The day has spent $0.9995 of its $1.00, and a call costs $0.0003: turn 1 fits, turn 2's second call does not.
|
|
||||||
let usage = json!(Spent { input_tokens: 499_750, output_tokens: 0, ..spent() });
|
|
||||||
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap().to_rfc3339();
|
|
||||||
rig.trace.rows.borrow_mut().push(("seed-g0".into(), json!({ "agent": "call", "at": at, "usage": usage, "seq": 0 })));
|
|
||||||
answers(&rig, [done(), says(&room(1), "second answer")]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second"));
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::DayCap), acked_through: Some(2) });
|
|
||||||
assert_eq!(rig.records()[0]["ended"], "day_cap");
|
|
||||||
rig.mouth.held.borrow_mut().push(line(3, &room(1), META, "third"));
|
|
||||||
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }), "the day is spent: the next start holds her");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A failed read of the mouth is a skipped poll; three in a row end the wake as an outage, which strikes nothing.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_failed_mouth_reads_skip_polls_and_three_in_a_row_end_the_wake() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
rig.mouth.pending_fails.set(2);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second"));
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) }, "two failed reads cost two polls, and nothing else");
|
|
||||||
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
rig.mouth.pending_fails.set(3);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second"));
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: Some(1) });
|
|
||||||
assert_eq!(rig.records()[0]["status"], "completed");
|
|
||||||
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none() && row.get("failed").is_none()));
|
|
||||||
assert!(calls(&rig, "interpreter") == 2, "the turn that ran still closes with its Interpreter");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first event whose hash ranks her `rank`th of the two Minds a line tags.
|
|
||||||
fn event_ranking_her(rank: u64) -> String {
|
|
||||||
let table: Vec<Addressee> = [EUREKA, LIBBY].iter().map(|id| Addressee::new(id, [crate::address::localpart(id)])).collect();
|
|
||||||
(0..2000)
|
|
||||||
.map(|n| format!("$tag{n}"))
|
|
||||||
.find(|event| crate::persona::live::stagger_ms(&table[0], &table, &ChatDelivery { event_id: event.clone(), mentions: vec![EUREKA.into(), LIBBY.into()], ..line(1, MINDS, META, "both of you") }) == rank * 8000)
|
|
||||||
.expect("among 2000 events one ranks her so")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line to both of two Minds, in a public room: the operator's, tagging both.
|
|
||||||
fn to_both(seq: u64, event: &str, tick: i64) -> ChatDelivery {
|
|
||||||
ChatDelivery { event_id: event.into(), mentions: vec![EUREKA.into(), LIBBY.into()], ..line_at(seq, MINDS, META, "both of you, a question", BASE_MS + u64::try_from(tick).unwrap() * 1000) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first experiment's stagger, in the span: a line that tags two Minds is taken by the one ranked second a step (8 s) after the one ranked first, and
|
|
||||||
/// a Mind ranked first takes it at once.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_a_line_to_several_awake_minds_is_taken_after_her_rank() {
|
|
||||||
let first_turn_two = |rank: u64| {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
|
|
||||||
arrives(&rig, 60, to_both(2, &event_ranking_her(rank), 60));
|
|
||||||
rig.run(Tally::default());
|
|
||||||
assert_eq!(rig.turns().len(), 2, "rank {rank}");
|
|
||||||
at_of(&rig.turns()[1])
|
|
||||||
};
|
|
||||||
let (at_once, after_a_step) = (first_turn_two(0), first_turn_two(1));
|
|
||||||
let delay = (after_a_step - at_once).num_seconds();
|
|
||||||
assert!((8..20).contains(&delay), "the second-ranked Mind took the line {delay} s after the first-ranked one would have");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first experiment's stagger, at the open: a start woken by a line tagging two Minds waits her rank, then reads the mouth afresh, so a line that
|
|
||||||
/// arrived while she waited is in her first turn.
|
|
||||||
#[test]
|
|
||||||
fn t_w2_the_open_waits_her_rank_and_reads_the_mouth_afresh() {
|
|
||||||
let ranked_second = event_ranking_her(1);
|
|
||||||
let rig = Rig::new(vec![to_both(1, &ranked_second, 0)]);
|
|
||||||
arrives(&rig, 4, later(2, MINDS, 4, "and one more thing while you wait"));
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) });
|
|
||||||
assert_eq!(rig.pauses.borrow().first().copied(), Some(std::time::Duration::from_secs(8)), "one step for rank one");
|
|
||||||
assert_eq!(rig.turns()[0]["held"], json!([ranked_second, "$e2"]), "the line that came in the wait is in the first turn");
|
|
||||||
assert_eq!(calls(&rig, "projector"), 1, "the wait reran no organ");
|
|
||||||
|
|
||||||
let rig = Rig::new(vec![to_both(1, &event_ranking_her(0), 0)]);
|
|
||||||
rig.run(Tally::default());
|
|
||||||
assert_eq!(rig.pauses.borrow().first().copied(), Some(std::time::Duration::from_secs(5)), "ranked first: no wait before the wake, only the span's polls");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// Soul's hold on 9187ee0.
|
|
||||||
|
|
||||||
/// H1, Soul's probe: a turn that completed and crossed the day's cap ends the wake. The line that arrived after it is never taken, so it is neither shown
|
|
||||||
/// to her agent nor decided nor acked, nor told to the Interpreter as heard, and the next start (held) leaves it for the day that follows.
|
|
||||||
#[test]
|
|
||||||
fn t_h1_a_day_cap_crossed_by_a_completed_turn_ends_the_wake_before_the_next_line_is_taken() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
|
|
||||||
// $0.9999 of the day is spent: turn 1's one call, $0.0003, crosses the cap, and the turn still completes.
|
|
||||||
let usage = json!(Spent { input_tokens: 499_950, output_tokens: 0, ..spent() });
|
|
||||||
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap().to_rfc3339();
|
|
||||||
rig.trace.rows.borrow_mut().push(("seed-g0".into(), json!({ "agent": "call", "at": at, "usage": usage, "seq": 0 })));
|
|
||||||
answers(&rig, [done(), done()]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second, never shown"));
|
|
||||||
let model = Tally::default();
|
|
||||||
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::DayCap), acked_through: Some(1) });
|
|
||||||
assert_eq!(rig.agent.seen.borrow().len(), 1, "her agent was called for turn 1 alone");
|
|
||||||
assert!(!rig.agent.seen.borrow().iter().any(|items| format!("{items:?}").contains("never shown")));
|
|
||||||
assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"), "the line was shown to no one, so nothing decided it");
|
|
||||||
assert!(model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).all(|prompt| !prompt.contains("never shown")));
|
|
||||||
assert_eq!(rig.turns().len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// H1's second half: a turn that made no model call (the cap crossed between the wake's judgement and the turn) holds no line and decides nothing: its
|
|
||||||
/// row holds none, its line is not acked, and the wake closes `day_cap` with the turns before it.
|
|
||||||
#[test]
|
|
||||||
fn t_h1_a_turn_that_made_no_model_call_holds_no_line_and_decides_nothing() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
|
|
||||||
rig.crossing.set(true);
|
|
||||||
answers(&rig, [done(), done()]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "second, never shown"));
|
|
||||||
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::DayCap), acked_through: Some(1) });
|
|
||||||
let turn = &rig.turns()[1];
|
|
||||||
assert_eq!((turn["model_calls"].clone(), turn["held"].clone(), turn["status"].as_str()), (json!(0), json!([]), Some("capped")), "{turn}");
|
|
||||||
assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"));
|
|
||||||
assert_eq!(rig.agent.seen.borrow().len(), 1, "no call reached her agent's model for it");
|
|
||||||
assert_eq!(rig.records()[0]["status"], "completed", "turn 1 completed, and the Interpreter ran over it");
|
|
||||||
assert_eq!(calls(&rig, "interpreter"), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The same race at her first turn: nothing was shown, so the wake fails as an outage, strikes nothing, and decides nothing.
|
|
||||||
#[test]
|
|
||||||
fn t_h1_a_first_turn_that_made_no_model_call_fails_the_wake_as_an_outage() {
|
|
||||||
struct Spends(Rc<MemTrace>, Tally);
|
|
||||||
impl Model for Spends {
|
|
||||||
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
|
||||||
if !prompt.starts_with("You are a private Projector.") && !prompt.starts_with(INTERPRETER) {
|
|
||||||
self.0.rows.borrow_mut().push(crossing_row());
|
|
||||||
}
|
|
||||||
self.1.ask(request_id, model, prompt, schema)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
|
|
||||||
assert_eq!(rig.run(Spends(rig.trace.clone(), Tally::default())), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::DayCap), acked_through: None });
|
|
||||||
assert_eq!(rig.turns()[0]["held"], json!([]));
|
|
||||||
assert!(!decided(&rig.trace.records().unwrap()).contains("$e1"));
|
|
||||||
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none()) && rig.records()[0]["outage"] == true);
|
|
||||||
assert_eq!(rig.agent.seen.borrow().len(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// M3, the ack's guard: a line that wakes her in a room the wake has not joined holds the ack behind it until a turn takes it, wherever the wake ended. The
|
|
||||||
/// line is held back by its stagger and the wake is made to end at every moment around it; whenever the wake ended with the line untaken, nothing past it
|
|
||||||
/// was acked and it is still in the mouth.
|
|
||||||
#[test]
|
|
||||||
fn t_m3_a_waking_line_no_turn_took_holds_the_ack_behind_it_wherever_the_wake_ends() {
|
|
||||||
let event = event_ranking_her(1);
|
|
||||||
let mut left_untaken = 0;
|
|
||||||
for tick in 8..90 {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
tune(&rig, "[agent]\nidle_s = 30\nspan_s = 60\n");
|
|
||||||
let side = ChatDelivery { room_alias: "#side:gamecult.org".into(), room_id: "#side:gamecult.org".into(), ..to_both(2, &event, tick) };
|
|
||||||
let mut notice = later(3, &room(1), tick, "a notice");
|
|
||||||
notice.form = Form::Notice;
|
|
||||||
arrives(&rig, tick, side);
|
|
||||||
arrives(&rig, tick, notice);
|
|
||||||
rig.run(Tally::default());
|
|
||||||
let taken = decided(&rig.trace.records().unwrap()).contains(event.as_str());
|
|
||||||
if !taken && rig.mouth.held.borrow().iter().any(|held| held.event_id == event) {
|
|
||||||
left_untaken += 1;
|
|
||||||
assert!(rig.acks().iter().all(|seq| *seq < 2), "tick {tick}: the ack passed a waking line no turn took: {:?}", rig.acks());
|
|
||||||
}
|
|
||||||
if !rig.mouth.held.borrow().iter().any(|held| held.event_id == event) && !taken {
|
|
||||||
assert!(rig.arrivals.borrow().iter().any(|(_, held)| held.event_id == event) || rig.acks().iter().all(|seq| *seq < 2), "tick {tick}: the line was acked undecided");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert!(left_untaken > 0, "the sweep never ended a wake with the line read and untaken: it proves nothing");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// M3, the trailing list's guard: the wake record holds the quiet lines of the wake's rooms and never a line that wakes her. A line that tags two Minds
|
|
||||||
/// and waits out its stagger is in a joined room; if the wake ends before it is taken, the record must not decide it unshown.
|
|
||||||
#[test]
|
|
||||||
fn t_m3_the_wake_record_never_decides_a_waking_line_it_did_not_show() {
|
|
||||||
let event = event_ranking_her(1);
|
|
||||||
let mut left_untaken = 0;
|
|
||||||
for tick in 8..90 {
|
|
||||||
let tagged_her = ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(1, MINDS, META, "hello Eureka", BASE_MS - 100_000) };
|
|
||||||
let rig = Rig::new(vec![tagged_her]);
|
|
||||||
tune(&rig, "[agent]\nidle_s = 30\nspan_s = 60\n");
|
|
||||||
arrives(&rig, tick, to_both(2, &event, tick));
|
|
||||||
rig.run(Tally::default());
|
|
||||||
let decided_it = decided(&rig.trace.records().unwrap()).contains(event.as_str());
|
|
||||||
let shown = rig.agent.seen.borrow().iter().any(|items| format!("{items:?}").contains("both of you"));
|
|
||||||
assert!(!decided_it || shown, "tick {tick}: the line was decided and never shown to her agent");
|
|
||||||
left_untaken += usize::from(!decided_it && rig.mouth.held.borrow().iter().any(|held| held.event_id == event));
|
|
||||||
}
|
|
||||||
assert!(left_untaken > 0, "the sweep never ended a wake with the line read and untaken: it proves nothing");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// M3, the open's guard: a quiet line the open had and no turn showed (the page had no room for it) is not the close's to decide. It stays undecided,
|
|
||||||
/// and the ack stops below it.
|
|
||||||
#[test]
|
|
||||||
fn t_m3_a_quiet_line_the_open_had_and_no_turn_showed_stays_undecided_at_close() {
|
|
||||||
let mut lines = vec![line(1, &room(1), META, "hello")];
|
|
||||||
lines.extend((2..=61).map(|seq| line_at(seq, MINDS, ANN, &format!("line {seq} of a long talk in the room, said at some length so that the page fills"), BASE_MS - 110_000 + seq * 100)));
|
|
||||||
lines.push(ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(62, MINDS, META, "Eureka, what do you make of it", BASE_MS - 40_000) });
|
|
||||||
let rig = Rig::new(lines);
|
|
||||||
assert!(matches!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, .. }));
|
|
||||||
let held: Vec<String> = rig.turns()[0]["held"].as_array().unwrap().iter().map(|event| event.as_str().unwrap().to_owned()).collect();
|
|
||||||
let unshown: Vec<u64> = (2..=61).filter(|seq| !held.contains(&format!("$e{seq}"))).collect();
|
|
||||||
assert!(!unshown.is_empty() && held.contains(&"$e62".to_owned()), "the page left some of the quiet lines out: {held:?}");
|
|
||||||
let done = decided(&rig.trace.records().unwrap()).into_iter().map(str::to_owned).collect::<Vec<_>>();
|
|
||||||
assert!(unshown.iter().all(|seq| !done.contains(&format!("$e{seq}"))), "a line no one was shown is not decided by the wake record: {done:?}");
|
|
||||||
assert!(rig.acks().iter().all(|seq| *seq < unshown[0]), "and the ack stops below the first of them: {:?}", rig.acks());
|
|
||||||
assert_eq!(rig.records()[0]["held"], json!([]));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// M1: a session that starts fresh at turn 2 is told what the wake already did, her own say among it, so she does not say it again. The session is
|
|
||||||
/// discarded as too long between the turns.
|
|
||||||
#[test]
|
|
||||||
fn t_m1_a_session_reseeded_at_turn_two_carries_turn_ones_say_and_acts() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
tune(&rig, "[agent]\nmax_session_tokens = 50\n");
|
|
||||||
answers(&rig, [says(&room(1), "I will be there at noon"), shells("one", "ls /srv/one"), done(), done()]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "and the second line"));
|
|
||||||
rig.run(Tally::default());
|
|
||||||
let seen = rig.agent.seen.borrow();
|
|
||||||
let turn_two = seen.iter().find(|items| items.len() == 1 && format!("{items:?}").contains("and the second line")).expect("turn 2 began a fresh session");
|
|
||||||
let text = user_text(turn_two);
|
|
||||||
assert!(text.contains("I will be there at noon") && text.contains("ls /srv/one"), "turn 1's say and acts are in the reseed: {text}");
|
|
||||||
assert!(text.contains("What she lives now") && text.contains("and the second line"), "with the wake's opening, and the new line: {text}");
|
|
||||||
assert!(text.find("I will be there at noon").unwrap() < text.find("and the second line").unwrap(), "what was done comes before the lines");
|
|
||||||
assert!(rig.all_records().iter().any(|row| row["agent"] == "session_discarded" && row["why"] == "too_long"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A kept session is not told what it already has.
|
|
||||||
#[test]
|
|
||||||
fn t_m1_a_kept_session_is_not_told_the_wake_again() {
|
|
||||||
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
|
|
||||||
answers(&rig, [says(&room(1), "I will be there at noon"), done(), done()]);
|
|
||||||
arrives(&rig, 60, later(2, &room(1), 60, "and the second line"));
|
|
||||||
rig.run(Tally::default());
|
|
||||||
let seen = rig.agent.seen.borrow();
|
|
||||||
assert!(!user_text(&seen[2]).contains("I will be there at noon") && !user_text(&seen[2]).contains("already done"));
|
|
||||||
}
|
|
||||||
|
|
@ -1,212 +0,0 @@
|
||||||
//! The live span of a wake (`docs/persona-wake-span-map.md`, cut W2): what the drain decides after her first turn, while the wake is open.
|
|
||||||
//!
|
|
||||||
//! A wake is one start of `mind-persona@<instance>`. After a turn the process polls the mouth every `POLL_S` seconds. A line that wakes her
|
|
||||||
//! by the heartbeat's own rule (`Hearing::waking`, which the open uses too) starts the next turn in the same agent conversation, with only the
|
|
||||||
//! new lines as its input. The wake ends by one pure function, `wake_end`, and by nothing else.
|
|
||||||
//!
|
|
||||||
//! What this gives up: a line after the first is answered on the inner voice the wake opened with, and her state moves only when the
|
|
||||||
//! wake closes.
|
|
||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
|
||||||
|
|
||||||
use chrono::{DateTime, Duration, Utc};
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use super::{Config, STRIKES, speaker, strikes};
|
|
||||||
use crate::address::{Addressee, addresses, is_for};
|
|
||||||
use crate::chat_client::ChatDelivery;
|
|
||||||
use crate::heartbeat::{pending_facts, wakes};
|
|
||||||
use crate::projection::AgentTuning;
|
|
||||||
use crate::projection::agent::{Cap, Ended};
|
|
||||||
|
|
||||||
/// How often an open wake reads the mouth, in seconds: the first experiment's `PERSONA_POLL_S`.
|
|
||||||
pub(crate) const POLL_S: u64 = 5;
|
|
||||||
/// How many mouth reads in a row may fail before the wake ends. One failed read is a skipped poll.
|
|
||||||
pub(crate) const MOUTH_FAILS_MAX: u32 = 3;
|
|
||||||
/// A line is taken this many seconds per rank after the first Mind addressed (`stagger_ms`), the first experiment's `STAGGER_STEP_S`: calibration,
|
|
||||||
/// about the time a Mind takes to answer (7 to 13 s observed on 2026-11-03).
|
|
||||||
pub(crate) const STAGGER_STEP_S: u64 = 8;
|
|
||||||
|
|
||||||
/// Why a wake ended: the first of these that holds, in this order.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum End {
|
|
||||||
/// A turn failed, or the wake could not read the mouth or her trace.
|
|
||||||
Failed,
|
|
||||||
/// The day's cap is reached: her trace holds the day's spend at it, or a turn stopped at it.
|
|
||||||
DayCap,
|
|
||||||
/// This wake's spend reached `agent.wake_usd`.
|
|
||||||
Spend,
|
|
||||||
/// The wake has been open `agent.span_s`.
|
|
||||||
Span,
|
|
||||||
/// No turn has started for `agent.idle_s` since her last ended.
|
|
||||||
Idle,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl End {
|
|
||||||
pub(crate) fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::Failed => "failed",
|
|
||||||
Self::DayCap => "day_cap",
|
|
||||||
Self::Spend => "spend",
|
|
||||||
Self::Span => "span",
|
|
||||||
Self::Idle => "idle",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for End {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.write_str(self.name())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a wake stands in time: when it opened and when her last turn ended.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub(crate) struct Span {
|
|
||||||
pub opened: DateTime<Utc>,
|
|
||||||
pub last_ended: DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the wake ends now, and why. `last` is how her last turn ended, `spent_usd` this wake's spend over all its turns and `day_spent_usd` the
|
|
||||||
/// UTC day's, both read from her trace before the next turn is judged: a turn that completed and crossed the day's cap ends the wake before another
|
|
||||||
/// turn is taken on lines it would never answer.
|
|
||||||
pub(crate) fn wake_end(span: &Span, last: &Ended, spent_usd: f64, day_spent_usd: f64, now: DateTime<Utc>, bounds: &AgentTuning) -> Option<End> {
|
|
||||||
let seconds = |secs: u64| Duration::seconds(i64::try_from(secs).unwrap_or(i64::MAX));
|
|
||||||
if matches!(last, Ended::Failed(_)) {
|
|
||||||
Some(End::Failed)
|
|
||||||
} else if day_spent_usd >= bounds.day_usd || matches!(last, Ended::Cap(Cap::DaySpend)) {
|
|
||||||
Some(End::DayCap)
|
|
||||||
} else if spent_usd >= bounds.wake_usd || matches!(last, Ended::Cap(Cap::WakeSpend)) {
|
|
||||||
Some(End::Spend)
|
|
||||||
} else if now - span.opened >= seconds(bounds.span_s) {
|
|
||||||
Some(End::Span)
|
|
||||||
} else if now - span.last_ended >= seconds(bounds.idle_s) {
|
|
||||||
Some(End::Idle)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How long after a poll first sees `delivery` a Mind takes it, in milliseconds. This is the first experiment's stagger, ported from
|
|
||||||
/// `crates/mind-body/src/persona.rs` at `0fd1232^` (`stagger_ms`, ruling `eureka-body:ruling:unaddressed-tell-stagger-ruled`): none in a direct
|
|
||||||
/// message, otherwise her rank times `STAGGER_STEP_S`. The Minds the message names (tagged, named, or named by a project, by `address::addresses`
|
|
||||||
/// over the swarm's addressing) rank first, by a hash of the Mind and the event, and the rest follow them, ranked the same way: the first addressed Mind
|
|
||||||
/// takes it at once, the others one step apart, so addressing several does not make a chorus, and the later ones read the earlier ones' answers before
|
|
||||||
/// they give theirs. A rank is the number of Minds in her set whose hash sorts before hers, from the message and the addressing table alone (the
|
|
||||||
/// sender, who will not take its own message, is not counted), so every process computes the same order with no word between them and nobody is
|
|
||||||
/// always last. The set is the addressed Minds when she is among them, else the others, after the addressed ones. Verbatim from the first
|
|
||||||
/// experiment, `own` standing for `config.own_sender`.
|
|
||||||
pub(crate) fn stagger_ms(own: &Addressee, addressing: &[Addressee], delivery: &ChatDelivery) -> u64 {
|
|
||||||
if delivery.is_direct {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
let mut minds: Vec<&Addressee> = addressing.iter().filter(|mind| mind.matrix_id() != delivery.sender).collect();
|
|
||||||
minds.sort_unstable_by_key(|mind| mind.matrix_id());
|
|
||||||
minds.dedup_by_key(|mind| mind.matrix_id());
|
|
||||||
let (addressed, others): (Vec<&Addressee>, Vec<&Addressee>) = minds.into_iter().partition(|mind| if mind.matrix_id() == own.matrix_id() { is_for(mind, delivery) } else { addresses(mind, delivery) });
|
|
||||||
let own_is_addressed = addressed.iter().any(|mind| mind.matrix_id() == own.matrix_id());
|
|
||||||
let (set, before) = if own_is_addressed { (&addressed, 0) } else { (&others, addressed.len()) };
|
|
||||||
let mine = (stagger_hash(own.matrix_id(), &delivery.event_id), own.matrix_id());
|
|
||||||
let rank = before + set.iter().filter(|mind| (stagger_hash(mind.matrix_id(), &delivery.event_id), mind.matrix_id()) < mine).count();
|
|
||||||
rank as u64 * STAGGER_STEP_S * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
/// FNV-1a over the Mind, a separator and the event, then murmur3's finalizer so a Mind's order against another changes from event to event
|
|
||||||
/// (FNV alone leaves it nearly fixed by the Minds' names): fixed by this definition, so every Mind's process computes the same order.
|
|
||||||
/// Verbatim from the first experiment's `stagger_hash`.
|
|
||||||
pub(crate) fn stagger_hash(mind: &str, event_id: &str) -> u64 {
|
|
||||||
let mut hash = mind.bytes().chain(std::iter::once(0xff)).chain(event_id.bytes()).fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
|
|
||||||
hash ^= hash >> 33;
|
|
||||||
hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
|
|
||||||
hash ^= hash >> 33;
|
|
||||||
hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
|
|
||||||
hash ^ (hash >> 33)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Who she is to the room, as the heartbeat reads it: the one derivation of "this line wakes her", for the open and for every poll of the span.
|
|
||||||
pub(crate) struct Hearing<'a> {
|
|
||||||
pub config: &'a Config,
|
|
||||||
pub her: &'a Addressee,
|
|
||||||
pub addressing: &'a [Addressee],
|
|
||||||
pub own_rooms: &'a [String],
|
|
||||||
/// The lines the heartbeat woke her for, read once at the open: the open floor is hers only on those. The heartbeat claims no floor line for a
|
|
||||||
/// Mind whose unit is active, so nothing new can appear in it mid-wake.
|
|
||||||
pub claimed: &'a [String],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Hearing<'_> {
|
|
||||||
/// For each of `deliveries` (oldest first), whether it wakes her: the heartbeat's `wakes`, or a claim the heartbeat made for her.
|
|
||||||
pub(crate) fn waking(&self, deliveries: &[&ChatDelivery]) -> Vec<bool> {
|
|
||||||
let mut facts = pending_facts(deliveries, &self.config.own_sender, &self.config.minds, self.own_rooms);
|
|
||||||
for (delivery, facts) in deliveries.iter().zip(&mut facts) {
|
|
||||||
facts.open_floor &= self.claimed.contains(&delivery.event_id);
|
|
||||||
}
|
|
||||||
deliveries.iter().zip(&facts).map(|(delivery, facts)| self.claimed.contains(&delivery.event_id) || wakes(self.her, delivery, speaker(self.config, delivery), *facts).is_some()).collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a poll finds in the mouth that this wake has not dealt with.
|
|
||||||
pub(crate) struct Found<'a> {
|
|
||||||
/// Every line her trace does not hold decided and no turn of this wake has taken, and that has not struck out, oldest first.
|
|
||||||
pub fresh: Vec<&'a ChatDelivery>,
|
|
||||||
/// Those of `fresh` that wake her.
|
|
||||||
pub waking: Vec<&'a ChatDelivery>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The lines of `pool` (oldest first) that are new to the wake: not decided by her trace (`done`), not in a turn this wake ran (`taken`), and
|
|
||||||
/// not a line two wakes failed on, which the next open sets aside.
|
|
||||||
pub(crate) fn find<'a>(hearing: &Hearing<'_>, pool: &'a [ChatDelivery], done: &BTreeSet<&str>, records: &[Value], taken: &BTreeSet<String>) -> Found<'a> {
|
|
||||||
let all: Vec<&ChatDelivery> = pool.iter().collect();
|
|
||||||
let flags = hearing.waking(&all);
|
|
||||||
let mut found = Found { fresh: vec![], waking: vec![] };
|
|
||||||
for (delivery, waking) in all.into_iter().zip(flags) {
|
|
||||||
if done.contains(delivery.event_id.as_str()) || taken.contains(&delivery.event_id) || strikes(records, &delivery.event_id) >= STRIKES {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
found.fresh.push(delivery);
|
|
||||||
if waking {
|
|
||||||
found.waking.push(delivery);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The next turn: the lines it holds, the rooms the wake now has, and the line its failure would strike.
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Taking {
|
|
||||||
pub hold: Vec<String>,
|
|
||||||
pub rooms: Vec<String>,
|
|
||||||
/// The oldest waking line, when the turn's waking lines are all in one room: a failure that is no outage strikes it and no other. A turn
|
|
||||||
/// over several rooms cannot say which one failed it, and strikes nothing.
|
|
||||||
pub strike: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the wake takes a turn now, and on what. A waking line is taken once it is due (`stagger_ms` from the poll that first saw it); the
|
|
||||||
/// turn then holds every waking line, due or not (she is never shown a line and kept from the ones before it), and every other new line of the
|
|
||||||
/// wake's rooms, her own and what is no message included, as the open's `held` does. The room of a waking line joins the wake. A wake that began
|
|
||||||
/// retreating (the start after one that failed for a reason that is no outage takes one room at a time, so a failure is found in one room alone
|
|
||||||
/// and strikes that room's oldest line and no innocent room's) takes one room a turn.
|
|
||||||
pub(crate) fn take(hearing: &Hearing<'_>, found: &Found<'_>, rooms: &[String], retreating: bool, first_seen: &mut BTreeMap<String, DateTime<Utc>>, now: DateTime<Utc>) -> Option<Taking> {
|
|
||||||
let oldest_room = found.waking.first().map(|delivery| delivery.room_alias.as_str());
|
|
||||||
let waking: Vec<&ChatDelivery> = found.waking.iter().copied().filter(|delivery| !retreating || Some(delivery.room_alias.as_str()) == oldest_room).collect();
|
|
||||||
for delivery in &waking {
|
|
||||||
first_seen.entry(delivery.event_id.clone()).or_insert(now);
|
|
||||||
}
|
|
||||||
let due = waking.iter().any(|delivery| now - first_seen[&delivery.event_id] >= Duration::milliseconds(i64::try_from(stagger_ms(hearing.her, hearing.addressing, delivery)).unwrap_or(i64::MAX)));
|
|
||||||
if !due {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let mut rooms = rooms.to_vec();
|
|
||||||
for delivery in &waking {
|
|
||||||
if !rooms.contains(&delivery.room_alias) {
|
|
||||||
rooms.push(delivery.room_alias.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let hold = found.fresh.iter().filter(|delivery| rooms.contains(&delivery.room_alias)).map(|delivery| delivery.event_id.clone()).collect();
|
|
||||||
let waking_rooms: BTreeSet<&str> = waking.iter().map(|delivery| delivery.room_alias.as_str()).collect();
|
|
||||||
let strike = (waking_rooms.len() == 1).then(|| waking.first().map(|delivery| delivery.event_id.clone())).flatten();
|
|
||||||
Some(Taking { hold, rooms, strike })
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,156 +0,0 @@
|
||||||
//! The pure parts of a wake's span: when it ends, and how long a line addressed to several Minds waits for her.
|
|
||||||
|
|
||||||
use chrono::TimeZone;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::chat_client::Form;
|
|
||||||
use crate::projection::Failed;
|
|
||||||
|
|
||||||
fn at(secs: i64) -> DateTime<Utc> {
|
|
||||||
Utc.timestamp_opt(1_800_000_000 + secs, 0).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A wake that opened at 0 and whose last turn ended at `last`, judged at `now`.
|
|
||||||
fn ends(last: Ended, spent: f64, ended_at: i64, now: i64) -> Option<End> {
|
|
||||||
wake_end(&Span { opened: at(0), last_ended: at(ended_at) }, &last, spent, 0.0, at(now), &AgentTuning::default())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn failed() -> Ended {
|
|
||||||
Ended::Failed(Failed { reason: "refused".into(), outage: false, usage: None })
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wake_waiting_for_a_line_ends_idle_at_idle_s_after_her_last_turn() {
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 100, 399), None);
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 100, 400), Some(End::Idle), "idle_s is 300");
|
|
||||||
// The window runs from her last turn's end, not from the wake's opening.
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 1000, 1299), None);
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 1000, 1300), Some(End::Idle));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wake_open_span_s_ends_though_lines_keep_coming() {
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 1799, 1799), None);
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 1799, 1800), Some(End::Span), "span_s is 1800");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wake_that_has_spent_its_cap_ends() {
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.99, 0, 10), None);
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 1.0, 0, 10), Some(End::Spend), "wake_usd is 1.00");
|
|
||||||
assert_eq!(ends(Ended::Cap(Cap::WakeSpend), 0.1, 0, 10), Some(End::Spend), "a turn the wake cap stopped");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_turn_that_hit_the_day_cap_or_failed_ends_the_wake() {
|
|
||||||
assert_eq!(ends(Ended::Cap(Cap::DaySpend), 0.1, 0, 10), Some(End::DayCap));
|
|
||||||
assert_eq!(ends(failed(), 0.1, 0, 10), Some(End::Failed));
|
|
||||||
// A turn a per-turn bound stopped is no reason to end the wake.
|
|
||||||
assert_eq!(ends(Ended::Cap(Cap::ToolCalls), 0.1, 0, 10), None);
|
|
||||||
assert_eq!(ends(Ended::Cap(Cap::ModelCalls), 0.1, 0, 10), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// H1: the day's spend is read from her trace before each turn is judged, so a turn that completed and crossed the cap ends the wake.
|
|
||||||
#[test]
|
|
||||||
fn a_day_spent_to_its_cap_ends_the_wake_though_her_last_turn_ended_well() {
|
|
||||||
let end = |day: f64| wake_end(&Span { opened: at(0), last_ended: at(0) }, &Ended::EndTurn, 0.1, day, at(10), &AgentTuning::default());
|
|
||||||
assert_eq!(end(2.99), None);
|
|
||||||
assert_eq!(end(3.0), Some(End::DayCap), "day_usd is 3.00");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_ends_are_judged_in_order() {
|
|
||||||
// Everything true at once: failed, then the day cap, then the wake's spend, then the span, then idle.
|
|
||||||
assert_eq!(ends(failed(), 5.0, 0, 5000), Some(End::Failed));
|
|
||||||
assert_eq!(ends(Ended::Cap(Cap::DaySpend), 5.0, 0, 5000), Some(End::DayCap));
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 5.0, 0, 5000), Some(End::Spend));
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 0, 5000), Some(End::Span));
|
|
||||||
assert_eq!(ends(Ended::EndTurn, 0.1, 0, 1000), Some(End::Idle));
|
|
||||||
}
|
|
||||||
|
|
||||||
const ALL: [&str; 3] = ["@eureka:gamecult.org", "@libby:gamecult.org", "@kiko:gamecult.org"];
|
|
||||||
|
|
||||||
fn table() -> Vec<Addressee> {
|
|
||||||
ALL.iter().map(|id| Addressee::new(id, [crate::address::localpart(id)])).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn said(event: &str, sender: &str, room: &str, direct: bool, mentions: &[&str], text: &str) -> ChatDelivery {
|
|
||||||
ChatDelivery {
|
|
||||||
seq: 1,
|
|
||||||
room_alias: room.into(),
|
|
||||||
room_id: room.into(),
|
|
||||||
event_id: event.into(),
|
|
||||||
sender: sender.into(),
|
|
||||||
sender_display: String::new(),
|
|
||||||
text: text.into(),
|
|
||||||
at_unix_ms: 0,
|
|
||||||
context: vec![],
|
|
||||||
mentions: mentions.iter().map(|id| (*id).to_owned()).collect(),
|
|
||||||
is_direct: direct,
|
|
||||||
image: None,
|
|
||||||
basis: None,
|
|
||||||
form: Form::Message,
|
|
||||||
reply_to: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each Mind's delay for one line from the operator tagging all three.
|
|
||||||
fn delays(event: &str) -> Vec<u64> {
|
|
||||||
let line = said(event, "@meta:gamecult.org", "#minds:gamecult.org", false, &ALL, "all of you, a question");
|
|
||||||
let table = table();
|
|
||||||
table.iter().map(|own| stagger_ms(own, &table, &line)).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first experiment's stagger (`persona.rs` at `0fd1232^`): a line addressed to several Minds is taken by them one step apart, each at her rank.
|
|
||||||
#[test]
|
|
||||||
fn a_line_to_three_minds_is_taken_one_step_apart() {
|
|
||||||
for event in ["$a", "$b", "$c", "$d", "$e"] {
|
|
||||||
let mut ranks = delays(event);
|
|
||||||
ranks.sort_unstable();
|
|
||||||
assert_eq!(ranks, [0, 8000, 16000], "{event}: the first Mind takes it at once and the others 8 s per rank");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_order_changes_from_event_to_event_so_nobody_is_always_last() {
|
|
||||||
let last: BTreeSet<usize> = (0..40).map(|n| delays(&format!("$ev{n}")).iter().position(|delay| *delay == 16000).unwrap()).collect();
|
|
||||||
assert_eq!(last.len(), 3, "each of the three is last for some event: {last:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_sender_is_not_counted_and_a_direct_message_waits_for_no_one() {
|
|
||||||
let table = table();
|
|
||||||
// Libby tags Eureka and Kiko: two Minds, not three.
|
|
||||||
let line = said("$x", ALL[1], "#minds:gamecult.org", false, &[ALL[0], ALL[2]], "you two");
|
|
||||||
let mut ranks: Vec<u64> = [&table[0], &table[2]].iter().map(|own| stagger_ms(own, &table, &line)).collect();
|
|
||||||
ranks.sort_unstable();
|
|
||||||
assert_eq!(ranks, [0, 8000]);
|
|
||||||
// A direct message is one Mind's alone.
|
|
||||||
assert_eq!(stagger_ms(&table[0], &table, &said("$z", "@meta:gamecult.org", "!dm:gamecult.org", true, &[], "hello")), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first experiment ranked the Minds a line did not address after the addressed ones, so a line to one Mind sends the others behind her: the
|
|
||||||
/// addressed Mind takes it at once, and the two it did not name one and two steps after.
|
|
||||||
#[test]
|
|
||||||
fn the_minds_a_line_did_not_address_rank_after_the_addressed_ones() {
|
|
||||||
let table = table();
|
|
||||||
for event in ["$a", "$b", "$c", "$d", "$e", "$f"] {
|
|
||||||
let line = said(event, "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0]], "just you, Eureka");
|
|
||||||
let delays: Vec<u64> = table.iter().map(|own| stagger_ms(own, &table, &line)).collect();
|
|
||||||
assert_eq!(delays[0], 0, "{event}: the Mind it names takes it at once");
|
|
||||||
let mut behind = vec![delays[1], delays[2]];
|
|
||||||
behind.sort_unstable();
|
|
||||||
assert_eq!(behind, [8000, 16000], "{event}: the others follow her, one step apart");
|
|
||||||
}
|
|
||||||
// Two named: the unnamed third is one step behind them.
|
|
||||||
let line = said("$g", "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0], ALL[1]], "you two");
|
|
||||||
assert_eq!(stagger_ms(&table[2], &table, &line), 16000, "two addressed ahead of her");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_hash_is_fixed_so_every_process_computes_the_same_order() {
|
|
||||||
assert_eq!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@eureka:gamecult.org", "$e1"));
|
|
||||||
assert_ne!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@libby:gamecult.org", "$e1"));
|
|
||||||
assert_ne!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@eureka:gamecult.org", "$e2"));
|
|
||||||
assert_eq!(STAGGER_STEP_S, 8, "the step is the calibration the ruling names");
|
|
||||||
}
|
|
||||||
|
|
@ -20,7 +20,6 @@ fn config() -> Config {
|
||||||
minds: vec!["@eureka:chat".into(), "@libby:chat".into()],
|
minds: vec!["@eureka:chat".into(), "@libby:chat".into()],
|
||||||
own_sender: "@eureka:chat".into(),
|
own_sender: "@eureka:chat".into(),
|
||||||
model: "claude-test-model".into(),
|
model: "claude-test-model".into(),
|
||||||
review_room: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -60,7 +59,7 @@ const LIBBY: &str = "@libby:chat";
|
||||||
|
|
||||||
/// A line of a room the mouth holds, the `n`th, stamped so lines order by `n`.
|
/// A line of a room the mouth holds, the `n`th, stamped so lines order by `n`.
|
||||||
fn tl(room: &str, n: u64, sender: &str, body: &str) -> TailLine {
|
fn tl(room: &str, n: u64, sender: &str, body: &str) -> TailLine {
|
||||||
TailLine { room: room.into(), event_id: format!("$t{room}{n}"), at_unix_ms: 1_700_000_000_000 + n, sender: sender.into(), form: crate::chat_client::Form::Message, basis: None, body: body.into(), reply_to: Default::default() }
|
TailLine { room: room.into(), event_id: format!("$t{room}{n}"), at_unix_ms: 1_700_000_000_000 + n, sender: sender.into(), form: crate::chat_client::Form::Message, basis: None, body: body.into() }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn no_one() -> Addressees {
|
fn no_one() -> Addressees {
|
||||||
|
|
@ -68,24 +67,17 @@ fn no_one() -> Addressees {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_held_brake_is_dead_and_a_released_one_builds_its_organs_only_then() {
|
fn a_held_brake_is_dead_and_a_released_one_has_no_organ() {
|
||||||
let dir = TempDir::new().unwrap();
|
let dir = TempDir::new().unwrap();
|
||||||
let (control, swarm) = (dir.path().join(INSTANCE).join("control.cc"), dir.path().join("swarm.cc"));
|
let (control, swarm) = (dir.path().join(INSTANCE).join("control.cc"), dir.path().join("swarm.cc"));
|
||||||
let instance = Slug(INSTANCE.into());
|
let instance = Slug(INSTANCE.into());
|
||||||
let built = std::cell::Cell::new(0);
|
|
||||||
let build = || -> Result<Start<crate::chat_rudp::RudpChat>> {
|
|
||||||
built.set(built.get() + 1);
|
|
||||||
bail!("nothing is built in this test")
|
|
||||||
};
|
|
||||||
ControlWriter::open(&control).unwrap().set_brake(true, at(0), "op").unwrap();
|
ControlWriter::open(&control).unwrap().set_brake(true, at(0), "op").unwrap();
|
||||||
SwarmWriter::open(&swarm).unwrap().set_brake(true, at(0), "op").unwrap();
|
SwarmWriter::open(&swarm).unwrap().set_brake(true, at(0), "op").unwrap();
|
||||||
assert_eq!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance, build), Outcome::Failed("nothing is built in this test".into()));
|
assert_eq!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance), Outcome::NoOrgan);
|
||||||
assert_eq!(built.get(), 1);
|
|
||||||
SwarmWriter::open(&swarm).unwrap().set_brake(false, at(1), "op").unwrap();
|
SwarmWriter::open(&swarm).unwrap().set_brake(false, at(1), "op").unwrap();
|
||||||
assert!(matches!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance, build), Outcome::Dead(_)), "the swarm brake held stops her");
|
assert!(matches!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance), Outcome::Dead(_)), "the swarm brake held stops her");
|
||||||
let missing = dir.path().join("absent.cc");
|
let missing = dir.path().join("absent.cc");
|
||||||
assert!(matches!(carry(&FileSource::new(&missing), &FileSource::new(&missing), &instance, build), Outcome::Dead(_)), "an unreadable brake is held");
|
assert!(matches!(carry(&FileSource::new(&missing), &FileSource::new(&missing), &instance), Outcome::Dead(_)), "an unreadable brake is held");
|
||||||
assert_eq!(built.get(), 1, "a held brake built nothing");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -179,16 +171,23 @@ fn her_own_row_is_in_the_addressing_exactly_once_whatever_the_table_holds() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_trace_store_keeps_each_record_under_its_key_and_lists_them_oldest_first() {
|
fn the_trace_store_keeps_each_turn_under_its_run_and_turn() {
|
||||||
let dir = TempDir::new().unwrap();
|
let dir = TempDir::new().unwrap();
|
||||||
let trace = FileTrace::new(dir.path().join("persona-trace.cc"));
|
let path = dir.path().join("persona-trace.cc");
|
||||||
let record = |turn: u32, minute: i64| serde_json::json!({ "at": at(minute).to_rfc3339(), "posted": [], "turn": turn });
|
let trace = TurnTrace {
|
||||||
trace.record("mind-1-t10", &record(10, 3)).unwrap();
|
run: "mind-1".into(),
|
||||||
trace.record("mind-1-t2", &record(2, 1)).unwrap();
|
turn: 2,
|
||||||
trace.record("mind-1-t3", &record(3, 2)).unwrap();
|
at: at(0),
|
||||||
let turns: Vec<u64> = trace.records().unwrap().iter().map(|record| record["turn"].as_u64().unwrap()).collect();
|
inputs: vec![TraceItem { provenance: "member".into(), room: "swarm".into(), text: "hi".into() }],
|
||||||
assert_eq!(turns, [2, 3, 10], "oldest first by when, not by key");
|
outputs: vec![],
|
||||||
assert_eq!(trace.records().unwrap()[0], record(2, 1), "the record is stored whole");
|
outcome: "answered".into(),
|
||||||
|
};
|
||||||
|
FileTrace::new(&path).record(&trace).unwrap();
|
||||||
|
let mut cache = CultCache::new();
|
||||||
|
cache.register_entry_type::<TurnTrace>().unwrap();
|
||||||
|
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
||||||
|
cache.pull_all_backing_stores().unwrap();
|
||||||
|
assert_eq!(cache.get::<TurnTrace>("mind-1-2").unwrap(), Some(trace));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -238,7 +237,7 @@ fn the_persona_flags_come_from_the_environment_when_the_command_line_lacks_them(
|
||||||
let (config, rest) = Config::from_args_and_env(&args("--instance eureka"), env, "usage").unwrap();
|
let (config, rest) = Config::from_args_and_env(&args("--instance eureka"), env, "usage").unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
config,
|
config,
|
||||||
Config { rooms: vec!["swarm".into(), "usage".into()], operators: vec!["@op:chat".into(), "@op2:chat".into()], minds: vec!["@libby:chat".into(), "@aqua:chat".into()], own_sender: "@eureka:chat".into(), model: "claude-test-model".into(), review_room: None }
|
Config { rooms: vec!["swarm".into(), "usage".into()], operators: vec!["@op:chat".into(), "@op2:chat".into()], minds: vec!["@libby:chat".into(), "@aqua:chat".into()], own_sender: "@eureka:chat".into(), model: "claude-test-model".into() }
|
||||||
);
|
);
|
||||||
assert_eq!(rest, ["--instance", "eureka"]);
|
assert_eq!(rest, ["--instance", "eureka"]);
|
||||||
// A flag wins over its variable, one at a time.
|
// A flag wins over its variable, one at a time.
|
||||||
|
|
@ -393,17 +392,3 @@ fn a_named_gap_with_no_lines_reads_unknown_and_never_empty() {
|
||||||
let none = render_tail(&config(), &[], Some(vec![]), &[], &rooms, &[], &[]);
|
let none = render_tail(&config(), &[], Some(vec![]), &[], &rooms, &[], &[]);
|
||||||
assert!(none.text.contains("Recent tail of your rooms: empty."), "{}", none.text);
|
assert!(none.text.contains("Recent tail of your rooms: empty."), "{}", none.text);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// M1: what a reseeded session is told of the wake so far is bounded, keeps the newest acts, says how many it left out, and is nothing when nothing was done.
|
|
||||||
#[test]
|
|
||||||
fn done_so_far_keeps_the_newest_acts_within_its_budget() {
|
|
||||||
use crate::projection::agent::Status;
|
|
||||||
assert_eq!(done_so_far(&[]), "");
|
|
||||||
let receipts: Vec<Receipt> = (0..300).map(|n| Receipt::new("say", Status::Ok, json!({ "room": "#minds:gamecult.org", "text": format!("act number {n:03} {}", "z".repeat(120)) }))).collect();
|
|
||||||
let told = done_so_far(&receipts);
|
|
||||||
assert!(told.len() < DONE_BYTES + 400, "{}", told.len());
|
|
||||||
assert!(told.contains("act number 299") && !told.contains("act number 000"), "the newest are kept");
|
|
||||||
assert!(told.contains("earlier act(s) are not shown"));
|
|
||||||
let few = done_so_far(&receipts[..2]);
|
|
||||||
assert!(few.contains("act number 000") && few.contains("act number 001") && !few.contains("not shown"));
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,38 +2,21 @@
|
||||||
//!
|
//!
|
||||||
//! Two stages. The Select stage (`select`) is code: it decides what she can feel this turn and renders it as a typed
|
//! Two stages. The Select stage (`select`) is code: it decides what she can feel this turn and renders it as a typed
|
||||||
//! projection packet, deterministic for a seed. The narration (`narrate`) is one tool-less model call through the
|
//! projection packet, deterministic for a seed. The narration (`narrate`) is one tool-less model call through the
|
||||||
//! connector that renders the packet as her first-person present under Huginn's own frame (`narrate::projector_frame`,
|
//! connector that renders the packet as first-person prose under Ghostlight's membrane (`build_projector_prompt`,
|
||||||
//! map section 16.3; the Persona stage's membrane stays Ghostlight's). Every knob of both is `persona-tuning.toml` (`tuning`), read at each
|
//! the pinned `ghostlight-persona-projection`). Every knob of both is `persona-tuning.toml` (`tuning`), read at each
|
||||||
//! wake, its hash carried with the packet.
|
//! wake, its hash carried with the packet.
|
||||||
//!
|
//!
|
||||||
//! The Projector shows her self and her room: her persona state and what the mouth showed. It reads her Mind for one thing
|
//! The Projector shows her self and her room: her persona state and what the mouth showed. It does not read her Mind;
|
||||||
//! only, what moved in her domain lately (`domain`, map 16.22.2): her stewardships and campaigns through her read door, her
|
//! that is the Interpreter's read tools' (C3b), when wondering leads to reading.
|
||||||
//! repos' pull requests on the forge, rendered by code as news, never as a task. Anything else she reads is her agent's `read`
|
|
||||||
//! tool's (`agent::read`).
|
|
||||||
//!
|
//!
|
||||||
//! `project` is the experiment tool over both (`mind-persona project`): what Select would build from her real or a
|
//! `project` is the experiment tool over both (`mind-persona project`): what Select would build from her real or a
|
||||||
//! hypothetical state, what the Projector would narrate, and with `Through::Persona` what she would answer in her own
|
//! hypothetical state, and what the Projector would narrate. Its organs are read-only by type: `PersonaSource` gets,
|
||||||
//! prose and which of her drafts would be said (the Persona stage, C3b's first piece). `harness` runs `project`
|
//! `MouthReader` reads pending chat, `Model` asks. None of them can put, admit, send, ack or open a conversation, so
|
||||||
//! over fixtures: one turn from a mocked room (`--room`), a plan of states by scenarios (`--batch`), and the cast of the
|
|
||||||
//! swarm taking turns in one simulated room (`--simulate`). It adds no second turn: every case is one `project`. Its organs are read-only by type: `PersonaSource` gets,
|
|
||||||
//! `MouthReader` reads pending chat, `DomainSource` reads her domain, `ReadSource` performs the reads she reaches for, `Model` asks. None of them can put, admit, send, ack or open a conversation, so
|
|
||||||
//! `project` cannot write and runs under a held brake.
|
//! `project` cannot write and runs under a held brake.
|
||||||
|
|
||||||
pub mod agent;
|
|
||||||
pub mod harness;
|
|
||||||
mod commit;
|
|
||||||
mod domain;
|
|
||||||
mod exchange;
|
|
||||||
mod interpret;
|
|
||||||
mod narrate;
|
mod narrate;
|
||||||
mod outcome;
|
|
||||||
mod read;
|
|
||||||
mod select;
|
mod select;
|
||||||
mod simulate;
|
|
||||||
mod span;
|
|
||||||
mod tuning;
|
mod tuning;
|
||||||
mod turn;
|
|
||||||
mod wake;
|
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
|
@ -43,32 +26,16 @@ use eureka_state::HuginnClient;
|
||||||
use huginn_mind::HuginnMindResponse;
|
use huginn_mind::HuginnMindResponse;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
use crate::address::{Addressee, is_for, localpart, others_addressed};
|
use crate::address::{Addressee, is_for, localpart};
|
||||||
use crate::chat_client::{Chat, ChatPending, Form, ReplyLink};
|
use crate::chat_client::{Chat, ChatPending, Form};
|
||||||
use crate::heartbeat::HeartbeatView;
|
use crate::heartbeat::HeartbeatView;
|
||||||
|
|
||||||
pub use domain::{DomainFacts, DomainSource, HttpForge, MindDomain};
|
pub use narrate::{Answer, Failed, KitModel, Model, Spent, connector_key};
|
||||||
pub use narrate::{Answer, Failed, KitModel, Model, Spent, StepRequest, Stepped, ToolCall, connector_key};
|
|
||||||
pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource};
|
|
||||||
pub use select::TurnKind;
|
pub use select::TurnKind;
|
||||||
pub(crate) use commit::Applied;
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) use commit::Heard;
|
|
||||||
pub(crate) use interpret::{acts_of, heard_of, interpret_and_put};
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) use interpret::put_applied;
|
|
||||||
pub(crate) use turn::{DAY_CAP_HOLD, decided, failed, failed_run, history, is_wake};
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) use turn::Taken;
|
|
||||||
pub(crate) use agent::say::{Mouth, settle_handed};
|
|
||||||
pub(crate) use wake::{Fault, Waked, wake};
|
|
||||||
pub use tuning::{TUNING_FILE, TUNING_ROOT};
|
pub use tuning::{TUNING_FILE, TUNING_ROOT};
|
||||||
pub(crate) use tuning::load as load_tuning;
|
|
||||||
pub(crate) use tuning::AgentTuning;
|
|
||||||
pub(crate) use select::People;
|
|
||||||
|
|
||||||
use narrate::{cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words};
|
use narrate::{cap_words, distinct_2, field_names, judge_prompt, judged, projector_prompt, word_budget, words};
|
||||||
use select::{History, Inputs, Packet, Replied, Room, RoomLine, select, turn_room};
|
use select::{History, Inputs, Packet, People, Room, RoomLine, select};
|
||||||
|
|
||||||
/// The agent name on the connector's request ids.
|
/// The agent name on the connector's request ids.
|
||||||
const AGENT: &str = "mind-persona";
|
const AGENT: &str = "mind-persona";
|
||||||
|
|
@ -90,11 +57,6 @@ impl HuginnPersonaSource {
|
||||||
pub fn new(client: HuginnClient) -> Self {
|
pub fn new(client: HuginnClient) -> Self {
|
||||||
Self { client }
|
Self { client }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The persona door's client, for the drain's put (`persona::carry`).
|
|
||||||
pub(crate) fn client(&self) -> &HuginnClient {
|
|
||||||
&self.client
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PersonaSource for HuginnPersonaSource {
|
impl PersonaSource for HuginnPersonaSource {
|
||||||
|
|
@ -107,22 +69,6 @@ impl PersonaSource for HuginnPersonaSource {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How a put of her persona state was answered.
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub enum Put {
|
|
||||||
Committed,
|
|
||||||
/// The stored document is not the one she was read at.
|
|
||||||
Stale,
|
|
||||||
/// Refused for another reason, named.
|
|
||||||
Refused(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her persona state, read and put: what a drain acts through. `project` holds `PersonaSource` alone and cannot put.
|
|
||||||
pub trait PersonaStore: PersonaSource {
|
|
||||||
/// Replace her persona document whole under the `updatedAt` she was read at; `session` names the turn.
|
|
||||||
fn put(&self, state: &Value, expected_updated_at: Option<&str>, session: &str) -> Result<Put>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The mouth, read: pending deliveries and the room tail, which acks nothing. The only chat port `project` holds.
|
/// The mouth, read: pending deliveries and the room tail, which acks nothing. The only chat port `project` holds.
|
||||||
pub trait MouthReader {
|
pub trait MouthReader {
|
||||||
fn pending(&self) -> Result<ChatPending>;
|
fn pending(&self) -> Result<ChatPending>;
|
||||||
|
|
@ -158,62 +104,16 @@ pub struct Organs<'a> {
|
||||||
pub addressing: Option<&'a dyn HeartbeatView>,
|
pub addressing: Option<&'a dyn HeartbeatView>,
|
||||||
/// The Projector and the judge; required for renders.
|
/// The Projector and the judge; required for renders.
|
||||||
pub model: Option<&'a dyn Model>,
|
pub model: Option<&'a dyn Model>,
|
||||||
/// Her domain: her mind through her read door and the forge, live; a fixture's facts in a harness run. None, and the
|
|
||||||
/// packet has no domain section, and the report says so.
|
|
||||||
pub domain: Option<&'a dyn DomainSource>,
|
|
||||||
/// What performs the reads her prose reaches for (map 16.22.3): her mind through her read door, the forge and the web
|
|
||||||
/// live; a fixture's recorded reads in a harness run. None, and she cannot read this turn, and is told so.
|
|
||||||
pub reads: Option<&'a dyn ReadSource>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One thing she can do this turn, typed by what it does (map 16.6, 16.18). Derived by `affordances` from what the turn
|
|
||||||
/// actually holds, never written in state or in guidance, so she is never told she can do what this turn cannot: the room
|
|
||||||
/// that was read, and the tools her agent holds this wake (map 16.38.4), named by their definitions.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub(crate) enum Affordance {
|
|
||||||
/// The room reaches her as typed lines: the mouth's `RoomLine` carries text only, and Select renders no images.
|
|
||||||
Perceive,
|
|
||||||
Say,
|
|
||||||
Read,
|
|
||||||
Shell,
|
|
||||||
RequestTool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What this turn can do, from what it holds: `Perceive` when the room was read (a harness fixture's and the simulated
|
|
||||||
/// room's always are), and one affordance for each tool her agent holds, by the tool's name. A failed read, or no mouth, and no
|
|
||||||
/// room reaches her; a name no affordance knows is not one.
|
|
||||||
pub(crate) fn affordances(read: bool, tools: &[String]) -> Vec<Affordance> {
|
|
||||||
let mut can = if read { vec![Affordance::Perceive] } else { Vec::new() };
|
|
||||||
can.extend(tools.iter().filter_map(|tool| match tool.as_str() {
|
|
||||||
"say" => Some(Affordance::Say),
|
|
||||||
"read" => Some(Affordance::Read),
|
|
||||||
"shell" => Some(Affordance::Shell),
|
|
||||||
"request_tool" => Some(Affordance::RequestTool),
|
|
||||||
_ => None,
|
|
||||||
}));
|
|
||||||
can
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How far a render runs: the Projector's narration, or on through the Persona stage to her prose. A wake runs both,
|
|
||||||
/// once (`wake`).
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum Through {
|
|
||||||
#[default]
|
|
||||||
Projector,
|
|
||||||
Persona,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What to project.
|
/// What to project.
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
pub instance: String,
|
pub instance: String,
|
||||||
pub kind: TurnKind,
|
pub kind: TurnKind,
|
||||||
/// A hypothetical state in place of the stored one.
|
/// A hypothetical state in place of the stored one.
|
||||||
pub state: Option<Value>,
|
pub state: Option<Value>,
|
||||||
/// The waking rooms of this wake, in order: the first is the turn's room, and every other is an arrival (who, where, when) to the Projector and verbatim lines to the Persona. None is every room of hers, as one room.
|
/// The room the turn is in; none is every room of hers.
|
||||||
pub rooms: Vec<String>,
|
pub room: Option<String>,
|
||||||
pub seed: u64,
|
pub seed: u64,
|
||||||
/// None builds the packet only. Some(k) narrates k successive turns of the same state, each seeded `seed + i` and
|
/// None builds the packet only. Some(k) narrates k successive turns of the same state, each seeded `seed + i` and
|
||||||
/// each under the freshness the ones before it leave.
|
/// each under the freshness the ones before it leave.
|
||||||
|
|
@ -226,27 +126,6 @@ pub struct Request {
|
||||||
/// Her own Matrix id. Required: without it her own lines would read as said to her.
|
/// Her own Matrix id. Required: without it her own lines would read as said to her.
|
||||||
pub own_sender: String,
|
pub own_sender: String,
|
||||||
pub tuning: PathBuf,
|
pub tuning: PathBuf,
|
||||||
pub through: Through,
|
|
||||||
/// When she last heard from people (Matrix id, unix ms) beyond the room's tail: a fixture's table. Empty live.
|
|
||||||
pub last_heard: Vec<(String, u64)>,
|
|
||||||
/// The ids each earlier projection selected, oldest first, for freshness: read from her records (`turn::history`).
|
|
||||||
pub recent: Vec<Vec<String>>,
|
|
||||||
/// The rooms that are hers, by the key the lines carry: live from `heartbeat::own_rooms` (the rooms named for her stewarded repos), simulated from the plan.
|
|
||||||
pub own_rooms: Vec<String>,
|
|
||||||
/// The events the heartbeat woke her for (`heartbeat::woken_for`; a simulation's, the lines its floor gave her): said to her,
|
|
||||||
/// as the wake that named her decided, whoever they were and in whatever room.
|
|
||||||
pub woken_for: Vec<String>,
|
|
||||||
/// The rows of her trace she is told at this wake, which her packet opens with (`outcome::told`, rendered by
|
|
||||||
/// `outcome::outcome_of`): read from her records (`turn::history`); a harness run takes a fixture's (`--told`).
|
|
||||||
pub told: Vec<Value>,
|
|
||||||
/// The names of the tools her agent holds this wake: what she can do, in her body section (`affordances`).
|
|
||||||
pub tools: Vec<String>,
|
|
||||||
/// When she last woke: her domain's window opens there, held to at least a day and at most a week (map 16.22.2). Read
|
|
||||||
/// from her records (`turn::history`); none is a week.
|
|
||||||
pub last_wake: Option<DateTime<Utc>>,
|
|
||||||
/// Her earlier turn records, oldest first: her trace live, the run's list simulated, both read by `turn::history`. What
|
|
||||||
/// she has said and read in this conversation is read from them (`exchange::exchange_of`, map 16.24.1).
|
|
||||||
pub records: Vec<Value>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Her addressee: the heartbeat's row for her when its table holds one, else her own names (handle and public name).
|
/// Her addressee: the heartbeat's row for her when its table holds one, else her own names (handle and public name).
|
||||||
|
|
@ -254,7 +133,7 @@ pub struct Request {
|
||||||
/// holds one; else her own names (handle and public name), with why: no store configured, no heartbeat file, a file
|
/// holds one; else her own names (handle and public name), with why: no store configured, no heartbeat file, a file
|
||||||
/// that could not be read, or a table without her row. The table's age is the store's last write: under a held swarm
|
/// that could not be read, or a table without her row. The table's age is the store's last write: under a held swarm
|
||||||
/// brake the heartbeat does not poll, so an old table is a stale one.
|
/// brake the heartbeat does not poll, so an old table is a stale one.
|
||||||
pub(crate) fn own_addressee(addressing: Option<&dyn HeartbeatView>, own_sender: &str, public_name: &str, now: DateTime<Utc>) -> (Addressee, Value) {
|
fn own_addressee(addressing: Option<&dyn HeartbeatView>, own_sender: &str, public_name: &str, now: DateTime<Utc>) -> (Addressee, Value) {
|
||||||
let written_at = addressing.and_then(HeartbeatView::written_at);
|
let written_at = addressing.and_then(HeartbeatView::written_at);
|
||||||
let age = written_at.map(|at| (now - at).num_minutes());
|
let age = written_at.map(|at| (now - at).num_minutes());
|
||||||
let report = |source: &str, why: &str| json!({ "source": source, "why": why, "written_at": written_at.map(|at| at.to_rfc3339()), "age_minutes": age });
|
let report = |source: &str, why: &str| json!({ "source": source, "why": why, "written_at": written_at.map(|at| at.to_rfc3339()), "age_minutes": age });
|
||||||
|
|
@ -274,96 +153,37 @@ pub(crate) fn own_addressee(addressing: Option<&dyn HeartbeatView>, own_sender:
|
||||||
(Addressee::new(own_sender, [localpart(own_sender), public_name]), report("own names only", &why))
|
(Addressee::new(own_sender, [localpart(own_sender), public_name]), report("own names only", &why))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What moved in her domain since her last wake, as lines, and what the read did: from when, how many lines, the repos it
|
|
||||||
/// skipped (archived, not found, moved), or why it failed. A failed read shows her nothing and says so here; it is never
|
|
||||||
/// rendered as nothing having moved (map 16.22.2).
|
|
||||||
fn read_domain(source: Option<&dyn DomainSource>, last_wake: Option<DateTime<Utc>>, now: DateTime<Utc>, names: &domain::Names) -> (Option<domain::Digest>, Value) {
|
|
||||||
let since = domain::since(last_wake, now);
|
|
||||||
let Some(source) = source else {
|
|
||||||
return (None, json!({ "read": false, "why": "no domain source is configured" }));
|
|
||||||
};
|
|
||||||
match source.read(since, now) {
|
|
||||||
Ok(facts) => {
|
|
||||||
let digest = domain::digest(&facts, since, last_wake, now, names);
|
|
||||||
let report = json!({ "read": true, "since": digest.since.to_rfc3339(), "items": digest.items.len(), "skipped": facts.skipped });
|
|
||||||
(Some(digest), report)
|
|
||||||
}
|
|
||||||
Err(fault) => (None, json!({ "read": false, "since": since.to_rfc3339(), "why": format!("{fault:#}") })),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The other Minds of the swarm as her room names them: the heartbeat's row for each Mind of the request when its table holds one,
|
|
||||||
/// else the Mind by her Matrix id and localpart (`address::others_addressed` reads who a line is for from these). Not her.
|
|
||||||
fn roster_of(addressing: Option<&dyn HeartbeatView>, request: &Request, own: &Addressee) -> Vec<Addressee> {
|
|
||||||
let table = addressing.and_then(|view| view.addressing().ok().flatten()).map(|table| table.minds).unwrap_or_default();
|
|
||||||
request
|
|
||||||
.minds
|
|
||||||
.iter()
|
|
||||||
.filter(|id| id.as_str() != own.matrix_id())
|
|
||||||
.map(|id| table.iter().find(|row| row.matrix_id() == id).cloned().unwrap_or_else(|| Addressee::new(id, [localpart(id)])))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The room through the mouth's pending read, which acks nothing: new messages and the tail, own lines kept for the
|
/// The room through the mouth's pending read, which acks nothing: new messages and the tail, own lines kept for the
|
||||||
/// Select stage to drop. A refusal is reported, never hidden.
|
/// Select stage to drop. A refusal is reported, never hidden.
|
||||||
fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee, roster: &[Addressee]) -> (Room, Value) {
|
fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Room, Value) {
|
||||||
let pending = match chat.pending() {
|
let pending = match chat.pending() {
|
||||||
Ok(pending) => pending,
|
Ok(pending) => pending,
|
||||||
Err(fault) => return (Room { here: request.rooms.first().cloned(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })),
|
Err(fault) => return (Room { here: request.room.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })),
|
||||||
};
|
};
|
||||||
// One key names a room everywhere: the one the tail carries, the alias for a public room and the id for a direct
|
let wanted = |room: &str, id: &str| request.room.as_deref().is_none_or(|here| here == room || here == id);
|
||||||
// message (the mouth's alias of a direct room is its id). No table in her body maps a public room's id to its
|
let messages: Vec<RoomLine> = pending
|
||||||
// alias, so a public room given by its id matches nothing, and the report says so rather than guessing.
|
|
||||||
let here = request.rooms.first().cloned();
|
|
||||||
let wanted = |room: &str| request.rooms.is_empty() || request.rooms.iter().any(|wanted| wanted == room);
|
|
||||||
let here_only = |room: &str| here.as_deref().is_none_or(|here| here == room);
|
|
||||||
let lines: Vec<RoomLine> = pending
|
|
||||||
.deliveries
|
.deliveries
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias))
|
.filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias, &delivery.room_id))
|
||||||
.map(|delivery| RoomLine {
|
.map(|delivery| RoomLine {
|
||||||
room: delivery.room_alias.clone(),
|
room: delivery.room_alias.clone(),
|
||||||
sender: delivery.sender.clone(),
|
sender: delivery.sender.clone(),
|
||||||
display: delivery.sender_display.clone(),
|
display: delivery.sender_display.clone(),
|
||||||
text: delivery.text.clone(),
|
text: delivery.text.clone(),
|
||||||
at_ms: delivery.at_unix_ms,
|
at_ms: delivery.at_unix_ms,
|
||||||
// The heartbeat's rule, the one that woke her: never a second opinion here. A line that is for her (`is_for`) is to her.
|
// The heartbeat's rule, the one that woke her: never a second opinion here.
|
||||||
// A human's line in her own room always wakes her (the plan's or unit's `own_rooms`), and so does a line the heartbeat
|
to_her: is_for(own, delivery),
|
||||||
// woke her for (an open hello she was picked to answer: `woken_for`); it is to her unless it is for another Mind
|
|
||||||
// (`others_addressed`), when it is said in her room and not to her.
|
|
||||||
to_her: is_for(own, delivery)
|
|
||||||
|| (delivery.sender != request.own_sender
|
|
||||||
&& !request.minds.contains(&delivery.sender)
|
|
||||||
&& (request.own_rooms.contains(&delivery.room_alias) || request.woken_for.contains(&delivery.event_id))
|
|
||||||
&& others_addressed(own, roster, delivery).is_empty()),
|
|
||||||
event: delivery.event_id.clone(),
|
|
||||||
reply: replied(&delivery.reply_to),
|
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
// The turn's room is the first waking room; the lines of the others are the wake's elsewhere, read by the Persona and named to the Projector.
|
|
||||||
let (messages, elsewhere): (Vec<RoomLine>, Vec<RoomLine>) = lines.into_iter().partition(|line| here_only(&line.room));
|
|
||||||
let tail: Vec<RoomLine> = pending
|
let tail: Vec<RoomLine> = pending
|
||||||
.tail
|
.tail
|
||||||
.iter()
|
.iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.filter(|line| line.form == Form::Message && here_only(&line.room))
|
.filter(|line| line.form == Form::Message && wanted(&line.room, &line.room))
|
||||||
.map(|line| RoomLine { room: line.room.clone(), sender: line.sender.clone(), display: String::new(), text: line.body.clone(), at_ms: line.at_unix_ms, to_her: false, event: line.event_id.clone(), reply: replied(&line.reply_to) })
|
.map(|line| RoomLine { room: line.room.clone(), sender: line.sender.clone(), display: String::new(), text: line.body.clone(), at_ms: line.at_unix_ms, to_her: false })
|
||||||
.collect();
|
.collect();
|
||||||
let mut report = json!({ "read": true, "messages": messages.len(), "elsewhere": elsewhere.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps });
|
let report = json!({ "read": true, "messages": messages.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps });
|
||||||
if let Some(here) = &here
|
(Room { messages, tail, here: request.room.clone() }, report)
|
||||||
&& messages.is_empty()
|
|
||||||
&& tail.is_empty()
|
|
||||||
&& here.starts_with('!')
|
|
||||||
{
|
|
||||||
report["why"] = json!("no line carries this room id: a public room is named by its alias (#name:server), a direct message by its id");
|
|
||||||
}
|
|
||||||
let direct = pending.deliveries.iter().filter(|delivery| delivery.is_direct).map(|delivery| delivery.room_alias.clone()).collect();
|
|
||||||
(Room { messages, tail, elsewhere, here, last_heard: request.last_heard.clone(), direct, own: request.own_rooms.clone() }, report)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The line a reply answers, as the mouth quoted it within its contract; a dropped link is no reply (`ReplyLink::quote`).
|
|
||||||
fn replied(link: &ReplyLink) -> Option<Replied> {
|
|
||||||
link.quote().map(|quote| Replied { event: quote.event_id.clone(), sender: quote.sender.clone(), text: quote.excerpt.clone(), at_cap: quote.at_cap })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn packet_json(packet: &Packet) -> Value {
|
fn packet_json(packet: &Packet) -> Value {
|
||||||
|
|
@ -373,85 +193,39 @@ fn packet_json(packet: &Packet) -> Value {
|
||||||
"lens": packet.lens,
|
"lens": packet.lens,
|
||||||
"present": packet.present,
|
"present": packet.present,
|
||||||
"selected": packet.selected,
|
"selected": packet.selected,
|
||||||
// Each section's bytes under its own guard, and the sum the Projector is shown of her (map 16.19.4).
|
"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() },
|
||||||
"bytes": { "identity": packet.identity().len(), "tendencies": packet.tendencies.len(), "outcome": packet.sections.outcome, "here": packet.sections.here, "body": packet.sections.body, "people": packet.sections.people, "domain": packet.sections.domain, "notes": packet.sections.notes, "total": packet.identity().len() + packet.tendencies.len() + packet.context.len(), "stimulus": packet.stimulus.len(), "arrival": packet.arrival.len(), "heard": packet.heard.len() },
|
|
||||||
"bound": packet.sections.bound,
|
|
||||||
"overflow": packet.overflow,
|
"overflow": packet.overflow,
|
||||||
"clipped": packet.clipped,
|
"identity": packet.identity,
|
||||||
"name": packet.name,
|
|
||||||
"voice": packet.voice,
|
|
||||||
"affordances": packet.affordances,
|
|
||||||
"quotable": packet.quotable,
|
|
||||||
"memories": packet.memories,
|
|
||||||
"domain": packet.domain,
|
|
||||||
"domain_shown": packet.domain_shown,
|
|
||||||
"in_view": packet.in_view,
|
|
||||||
"context": packet.context,
|
"context": packet.context,
|
||||||
"stimulus": packet.stimulus,
|
"stimulus": packet.stimulus,
|
||||||
"arrival": packet.arrival,
|
|
||||||
"speaking": packet.speaking,
|
|
||||||
"heard": packet.heard,
|
"heard": packet.heard,
|
||||||
"shown_from_other_rooms": packet.elsewhere_shown,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What of her last turn the packet's outcome guard left out (counted in its last line) is listed with what the record held
|
/// One narration of one packet: the request id names the instance, the seed and the moment, because the kit's replay
|
||||||
/// that she is not told (map 16.20.5, I16.11).
|
/// store answers a repeated id with its first answer.
|
||||||
fn unshown_omitted(report: &mut Value, packet: &Packet) {
|
/// A failed call is a record with its reason and what it cost, never the end of the report.
|
||||||
if let Some(omitted) = report.get_mut("last_outcome").and_then(|last| last.get_mut("omitted")).and_then(Value::as_array_mut) {
|
fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, now: DateTime<Utc>) -> Value {
|
||||||
omitted.extend(packet.unshown.iter().map(|line| json!(format!("not shown past the outcome's guard: {line}"))));
|
let request_id = format!("{AGENT}:{instance}:project:{tag}:{}:{}", packet.seed, now.timestamp_millis());
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The root of one render's call ids, minted once per render. The kit's replay store binds an id to the one invocation
|
|
||||||
/// it first carried: the same bytes again get its first answer, any other bytes `ReplayConflict`. So no two calls may
|
|
||||||
/// share an id; and a turn's clock may be a fixture's, the same on every run, so the root takes the wall clock.
|
|
||||||
fn wake_id(instance: &str, tag: &str, seed: u64) -> String {
|
|
||||||
format!("{AGENT}:{instance}:project:{tag}:{seed}:{}", Utc::now().timestamp_nanos_opt().unwrap_or_default())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One call's id under its render's root: its stage. Every call of a render has its own id.
|
|
||||||
fn call_id(wake: &str, stage: &str) -> String {
|
|
||||||
format!("{wake}:{stage}")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One render of one packet: the Projector's narration and, through the Persona stage, her prose over it, each its own
|
|
||||||
/// call with its usage. A failed call is a record with its reason and what it cost, never the end of the report. The
|
|
||||||
/// Persona is one call: she is asked for her inner voice and nothing else, so nothing in her answer is read for acts.
|
|
||||||
fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, through: Through) -> Value {
|
|
||||||
let ids: Vec<String> = packet.selected.iter().map(|pick| pick.id.clone()).collect();
|
let ids: Vec<String> = packet.selected.iter().map(|pick| pick.id.clone()).collect();
|
||||||
let wake_id = wake_id(instance, tag, packet.seed);
|
let answer = match model.ask(&request_id, &tuning.projector.model, &projector_prompt(packet, tuning)) {
|
||||||
let answer = match model.ask(&call_id(&wake_id, "projector"), &tuning.projector.model, &projector_prompt(packet, tuning), None) {
|
|
||||||
Ok(answer) => answer,
|
Ok(answer) => answer,
|
||||||
Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "outage": failed.outage, "usage": failed.usage }),
|
Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "usage": failed.usage }),
|
||||||
};
|
};
|
||||||
let raw = answer.text;
|
let raw = answer.text;
|
||||||
let budget = word_budget(packet.kind, tuning);
|
let budget = word_budget(packet.kind, tuning);
|
||||||
let narration = cap_words(&raw, budget);
|
let narration = cap_words(&raw, budget);
|
||||||
let named: Vec<String> = packet.ids.clone();
|
let named: Vec<String> = packet.ids.clone();
|
||||||
let mut render = json!({
|
json!({
|
||||||
"seed": packet.seed,
|
"seed": packet.seed,
|
||||||
"lens": packet.lens,
|
"lens": packet.lens,
|
||||||
"selected": ids,
|
"selected": ids,
|
||||||
"words": words(&narration),
|
"words": words(&narration),
|
||||||
"cut_at_budget": words(&raw) > budget,
|
"cut_at_budget": words(&raw) > budget,
|
||||||
"field_names": field_names(&narration, &named),
|
"field_names": field_names(&narration, &named),
|
||||||
"heard_overlap": heard_overlap(&narration, &packet.heard),
|
|
||||||
"offers_options": offers_options(&narration),
|
|
||||||
"usage": answer.usage,
|
"usage": answer.usage,
|
||||||
"narration": narration,
|
"narration": narration,
|
||||||
});
|
})
|
||||||
if through == Through::Projector {
|
|
||||||
return render;
|
|
||||||
}
|
|
||||||
match model.ask(&call_id(&wake_id, "persona"), &tuning.persona.model, &persona_prompt(packet, &narration, tuning), None) {
|
|
||||||
Ok(spoke) => {
|
|
||||||
let prose = cap_words(&spoke.text, tuning.persona.words);
|
|
||||||
render["persona"] = json!({ "words": words(&prose), "cut_at_budget": words(&spoke.text) > tuning.persona.words, "usage": spoke.usage, "prose": prose });
|
|
||||||
}
|
|
||||||
Err(failed) => render["persona"] = json!({ "failed": failed.reason, "outage": failed.outage, "usage": failed.usage }),
|
|
||||||
}
|
|
||||||
render
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// K successive turns over one state: each packet under the freshness the earlier ones left.
|
/// K successive turns over one state: each packet under the freshness the earlier ones left.
|
||||||
|
|
@ -483,21 +257,13 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
|
||||||
let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned();
|
let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||||
let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now);
|
let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now);
|
||||||
let (room, room_report) = match organs.chat {
|
let (room, room_report) = match organs.chat {
|
||||||
Some(chat) => read_room(chat, request, &own, &roster_of(organs.addressing, request, &own)),
|
Some(chat) => read_room(chat, request, &own),
|
||||||
None => (Room { here: request.rooms.first().cloned(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })),
|
None => (Room { here: request.room.clone(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })),
|
||||||
};
|
};
|
||||||
|
// Freshness and her own recent words come from trace v2, which the commit writes (C3c); until then there is none.
|
||||||
|
let history = History::default();
|
||||||
let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender };
|
let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender };
|
||||||
// Freshness, her own recent words and what came of her last turn come from trace v2, which the commit writes (C3c);
|
let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed };
|
||||||
// until then only what the caller carried from earlier turns of its own.
|
|
||||||
let history = History { recent: request.recent.clone(), last: outcome::outcome_of(&request.told), ..History::default() };
|
|
||||||
let names = domain::Names::of(&state, &people, &request.instance);
|
|
||||||
let (digest, domain_report) = read_domain(organs.domain, request.last_wake, now, &names);
|
|
||||||
let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed, affordances: &[], domain: digest.as_ref(), exchange: None };
|
|
||||||
// Her side of this conversation, from her turn records (K26).
|
|
||||||
let exchange = turn_room(&inputs).map(|here| exchange::exchange_of(&request.records, here, now, select::forms(&state)));
|
|
||||||
let inputs = Inputs { exchange: exchange.as_ref(), ..inputs };
|
|
||||||
let can = affordances(room_report["read"] == true, &request.tools);
|
|
||||||
let inputs = Inputs { affordances: &can, ..inputs };
|
|
||||||
|
|
||||||
let mut report = json!({
|
let mut report = json!({
|
||||||
"instance": request.instance,
|
"instance": request.instance,
|
||||||
|
|
@ -506,26 +272,17 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
|
||||||
"tuning": { "path": request.tuning.display().to_string(), "source": loaded.source, "sha256": loaded.sha256 },
|
"tuning": { "path": request.tuning.display().to_string(), "source": loaded.source, "sha256": loaded.sha256 },
|
||||||
"room": room_report,
|
"room": room_report,
|
||||||
"addressing": addressing,
|
"addressing": addressing,
|
||||||
"domain": domain_report,
|
"history": "none: freshness and her own recent words come from trace v2, which the commit writes (C3c)",
|
||||||
"history": if request.recent.is_empty() { json!("none: freshness and her own recent words come from trace v2, which the commit writes (C3c)") } else { json!({ "recent_projections": request.recent.len() }) },
|
|
||||||
// What she is told of her last turn, whole, and what of its record she is not told, and why.
|
|
||||||
"last_outcome": history.last.as_ref().map_or_else(|| json!("none"), |last| json!({ "told": last.lines(select::forms(&state)), "omitted": last.omitted })),
|
|
||||||
});
|
});
|
||||||
let Some(renders) = request.renders else {
|
let Some(renders) = request.renders else {
|
||||||
let packet = select(&inputs, tuning);
|
report["packet"] = packet_json(&select(&inputs, tuning));
|
||||||
unshown_omitted(&mut report, &packet);
|
|
||||||
report["packet"] = packet_json(&packet);
|
|
||||||
return Ok(report);
|
return Ok(report);
|
||||||
};
|
};
|
||||||
let model = organs.model.ok_or_else(|| anyhow!("renders need the connector, and none is configured"))?;
|
let model = organs.model.ok_or_else(|| anyhow!("renders need the connector, and none is configured"))?;
|
||||||
report["model"] = json!(tuning.projector.model);
|
report["model"] = json!(tuning.projector.model);
|
||||||
if request.through != Through::Projector {
|
|
||||||
report["persona_model"] = json!(tuning.persona.model);
|
|
||||||
}
|
|
||||||
let packets = successive(&inputs, tuning, renders.max(1));
|
let packets = successive(&inputs, tuning, renders.max(1));
|
||||||
unshown_omitted(&mut report, &packets[0]);
|
|
||||||
report["packet"] = packet_json(&packets[0]);
|
report["packet"] = packet_json(&packets[0]);
|
||||||
let narrations: Vec<Value> = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", request.through)).collect();
|
let narrations: Vec<Value> = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", now)).collect();
|
||||||
let texts = |narrations: &[Value]| narrations.iter().filter_map(|one| one["narration"].as_str().map(str::to_owned)).collect::<Vec<_>>();
|
let texts = |narrations: &[Value]| narrations.iter().filter_map(|one| one["narration"].as_str().map(str::to_owned)).collect::<Vec<_>>();
|
||||||
let failed = |narrations: &[Value]| narrations.iter().filter(|one| one.get("failed").is_some()).count();
|
let failed = |narrations: &[Value]| narrations.iter().filter(|one| one.get("failed").is_some()).count();
|
||||||
report["failed_renders"] = json!(failed(&narrations));
|
report["failed_renders"] = json!(failed(&narrations));
|
||||||
|
|
@ -537,8 +294,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
|
||||||
if let Some(other) = &request.judge_against {
|
if let Some(other) = &request.judge_against {
|
||||||
let other_inputs = Inputs { state: other, ..inputs };
|
let other_inputs = Inputs { state: other, ..inputs };
|
||||||
let others = successive(&other_inputs, tuning, renders.max(1));
|
let others = successive(&other_inputs, tuning, renders.max(1));
|
||||||
let other_narrations: Vec<Value> = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", Through::Projector)).collect();
|
let other_narrations: Vec<Value> = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", now)).collect();
|
||||||
let judging = wake_id(&request.instance, "judge", request.seed);
|
|
||||||
let mut verdicts = Vec::new();
|
let mut verdicts = Vec::new();
|
||||||
let mut right = 0usize;
|
let mut right = 0usize;
|
||||||
for (at, (narration, truth)) in narrations.iter().map(|one| (one, 'A')).chain(other_narrations.iter().map(|one| (one, 'B'))).enumerate() {
|
for (at, (narration, truth)) in narrations.iter().map(|one| (one, 'A')).chain(other_narrations.iter().map(|one| (one, 'B'))).enumerate() {
|
||||||
|
|
@ -548,7 +304,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
|
||||||
let (first, second) = if swapped { (b, a) } else { (a, b) };
|
let (first, second) = if swapped { (b, a) } else { (a, b) };
|
||||||
// A narration that failed has nothing to judge; it is counted under the renders' failures.
|
// A narration that failed has nothing to judge; it is counted under the renders' failures.
|
||||||
let Some(text) = narration["narration"].as_str() else { continue };
|
let Some(text) = narration["narration"].as_str() else { continue };
|
||||||
let answer = match model.ask(&call_id(&format!("{judging}:{at}"), "judge"), &tuning.projector.model, &judge_prompt(first, second, text), None) {
|
let answer = match model.ask(&format!("{AGENT}:{}:judge:{at}:{}", request.instance, now.timestamp_millis()), &tuning.projector.model, &judge_prompt(first, second, text)) {
|
||||||
Ok(answer) => answer,
|
Ok(answer) => answer,
|
||||||
Err(failed) => {
|
Err(failed) => {
|
||||||
verdicts.push(json!({ "from": truth.to_string(), "failed": failed.reason, "usage": failed.usage }));
|
verdicts.push(json!({ "from": truth.to_string(), "failed": failed.reason, "usage": failed.usage }));
|
||||||
|
|
|
||||||
|
|
@ -1,632 +0,0 @@
|
||||||
//! Her agent (map 16.38.6 and 16.38.10): one turn of a persistent session over the connector with tools, bounded per wake and
|
|
||||||
//! per day.
|
|
||||||
//!
|
|
||||||
//! `step` owns one agent turn: the loop, its bounds and the session's freshness. The drain hands it the wake's input (the
|
|
||||||
//! Persona's monologue, the waking lines, the receipts since her last wake) and the executors; each executor owns its tool's
|
|
||||||
//! effect and the receipt it returns. The model never writes a receipt: code does, one per tool call, and the receipt's JSON
|
|
||||||
//! is the `ToolResult` the model reads. Every call, receipt and discard is a row in her trace (`Ledger`), and the trace is
|
|
||||||
//! the record. Her tools are `say`, `read`, `shell` and `request_tool` (`say`, `read`, `shell`, `request_tool` below), and what
|
|
||||||
//! her agent's receipts say is what she is told at her next wake (`outcome::told`); the session (`FileSession`) is a cache of her agent's turns and is discarded the moment the provider's cache
|
|
||||||
//! behind it is gone or cannot be trusted.
|
|
||||||
//!
|
|
||||||
//! The bounds are enforced here, before each call: tool calls and model calls per turn, spend per wake (summed across its turns), and spend per Mind per UTC
|
|
||||||
//! day. The day's spend is read back from her trace's `call` rows and priced by the tuning's table, so it survives a restart
|
|
||||||
//! and no other store holds it. Past a bound the loop ends with a `cap` receipt; a call is never made past one.
|
|
||||||
//!
|
|
||||||
//! The day's sum fails closed. A `call` row is written before its call is made, holding the call's place in the day at the
|
|
||||||
//! worst case (`unmetered_usd`, its own tuning); a `settle` row after it names the usage, and the call is priced by that
|
|
||||||
//! instead. So a trace that cannot be read, or cannot take the `call` row, makes no call; a `settle` row that cannot be
|
|
||||||
//! written ends the wake with its call still at the worst case; and a call whose usage is not known, a failed one that
|
|
||||||
//! reports none included, is charged the worst case and never nothing.
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use anyhow::{Result, bail};
|
|
||||||
use chrono::{DateTime, Duration, Utc};
|
|
||||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
|
||||||
use model_connector::{CacheRetention, InputItem, StopReason, ToolDefinition};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use serde_json::{Map, Value, json};
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
|
|
||||||
use super::narrate::{Failed, KitModel, Spent, StepRequest, Stepped, ToolCall};
|
|
||||||
use super::tuning::{AgentTuning, CACHE_MARGIN_S};
|
|
||||||
use crate::persona::Trace;
|
|
||||||
|
|
||||||
pub(crate) mod read;
|
|
||||||
pub(crate) mod request_tool;
|
|
||||||
pub(crate) mod say;
|
|
||||||
pub(crate) mod shell;
|
|
||||||
|
|
||||||
/// The connector, as the loop calls it: `KitModel` live, a script in a test.
|
|
||||||
pub trait Steps {
|
|
||||||
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Steps + ?Sized> Steps for std::rc::Rc<T> {
|
|
||||||
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
|
|
||||||
(**self).step(request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Steps for KitModel {
|
|
||||||
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
|
|
||||||
KitModel::step(self, request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What became of one tool call, said by the executor and never by the model.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum Status {
|
|
||||||
/// The effect happened.
|
|
||||||
Ok,
|
|
||||||
/// The tool's owner declined it, with a reason in the fields.
|
|
||||||
Refused,
|
|
||||||
/// It was tried and failed.
|
|
||||||
Error,
|
|
||||||
/// It was handed over and no answer is known: it may or may not have happened.
|
|
||||||
Unknown,
|
|
||||||
/// It was not sent.
|
|
||||||
NotSent,
|
|
||||||
/// The loop's bound stopped it, or the loop itself.
|
|
||||||
Cap,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One tool call's receipt: the tool, its status and its fields. There is no way to make one without a status, and the
|
|
||||||
/// fields are private, so a receipt is built by `new` or not at all. Each example below is complete, so that privacy is the one
|
|
||||||
/// thing it can fail on: a literal that names every field, a read of a field and a write to one.
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use mind_body::projection::agent::{Receipt, Status};
|
|
||||||
/// let _ = Receipt { tool: "say".into(), status: Status::Ok, fields: Default::default() };
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use mind_body::projection::agent::{Receipt, Status};
|
|
||||||
/// let receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
|
|
||||||
/// let _ = receipt.status;
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use mind_body::projection::agent::{Receipt, Status};
|
|
||||||
/// let mut receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
|
|
||||||
/// receipt.status = Status::Refused;
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// The same lines compile once they go through the methods:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use mind_body::projection::agent::{Receipt, Status};
|
|
||||||
/// let receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
|
|
||||||
/// assert_eq!((receipt.tool(), receipt.status()), ("say", Status::Ok));
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Receipt {
|
|
||||||
tool: String,
|
|
||||||
status: Status,
|
|
||||||
fields: Map<String, Value>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Receipt {
|
|
||||||
/// `fields` is a JSON object; any other value is kept under `detail`.
|
|
||||||
pub fn new(tool: impl Into<String>, status: Status, fields: Value) -> Self {
|
|
||||||
let fields = match fields {
|
|
||||||
Value::Object(map) => map,
|
|
||||||
Value::Null => Map::new(),
|
|
||||||
other => Map::from_iter([("detail".to_owned(), other)]),
|
|
||||||
};
|
|
||||||
Self { tool: tool.into(), status, fields }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn tool(&self) -> &str {
|
|
||||||
&self.tool
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn status(&self) -> Status {
|
|
||||||
self.status
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn fields(&self) -> &Map<String, Value> {
|
|
||||||
&self.fields
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The receipt as it is written to her trace and as the model reads it.
|
|
||||||
pub fn json(&self) -> Value {
|
|
||||||
json!({ "tool": self.tool, "status": self.status, "fields": self.fields })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One tool's owner: it defines the tools it runs and runs each call it is handed, answering with a receipt.
|
|
||||||
pub trait Executor {
|
|
||||||
fn definitions(&self) -> Vec<ToolDefinition>;
|
|
||||||
fn run(&self, call: &ToolCall) -> Receipt;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A call's arguments as its tool takes them, or the receipt that refuses them: arguments the model wrote are never guessed at.
|
|
||||||
pub(crate) fn arguments<T: serde::de::DeserializeOwned>(call: &ToolCall) -> std::result::Result<T, Receipt> {
|
|
||||||
serde_json::from_str(&call.arguments).map_err(|fault| Receipt::new(&call.name, Status::Refused, json!({ "why": format!("the arguments do not fit the tool: {fault}") })))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a fresh session is seeded with beyond the wake's input (ruling `candidate-actions-lived`): her live intentions that are
|
|
||||||
/// ready and unexpired, one line each, or nothing. A kept session already carries what she meant; nothing checks them afterwards.
|
|
||||||
pub(crate) fn ready_intentions(state: &Value, now: DateTime<Utc>) -> String {
|
|
||||||
let lines: Vec<String> = state["candidateActions"]["actions"]
|
|
||||||
.as_array()
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
.filter(|action| action["customActionType"] == "intention" && action["status"] == "active" && action["readiness"] == "ready")
|
|
||||||
.filter(|action| action["expiresAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_none_or(|at| at.with_timezone(&Utc) > now))
|
|
||||||
.filter_map(|action| action["summary"].as_str().map(str::trim).filter(|summary| !summary.is_empty()).map(|summary| format!("- {summary}")))
|
|
||||||
.collect();
|
|
||||||
if lines.is_empty() { String::new() } else { format!("What she means to do, and is ready to:
|
|
||||||
{}
|
|
||||||
|
|
||||||
", lines.join("
|
|
||||||
")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her trace as the loop sees it: her agent's rows, read back and appended. The drain's `TraceLedger` is the live one.
|
|
||||||
pub trait Ledger {
|
|
||||||
/// Every agent row, oldest first.
|
|
||||||
fn rows(&self) -> Result<Vec<Value>>;
|
|
||||||
/// Writes `row`, stamping it with its place (`seq`), and answers that place: a place is never held by two rows, so it can name one.
|
|
||||||
fn append(&self, row: Value) -> Result<u64>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The agent's rows in her trace: each is a record with an `agent` field naming its kind (`call`, `receipt`,
|
|
||||||
/// `session_discarded`), a `seq` (the place it holds in her trace) and the time it was made. None of them is a wake record (`turn::is_wake`).
|
|
||||||
pub struct TraceLedger<'a> {
|
|
||||||
trace: &'a dyn Trace,
|
|
||||||
stem: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TraceLedger<'a> {
|
|
||||||
/// `stem` makes the records' keys: `<stem>-g<place>`.
|
|
||||||
pub fn new(trace: &'a dyn Trace, stem: impl Into<String>) -> Self {
|
|
||||||
Self { trace, stem: stem.into() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ledger for TraceLedger<'_> {
|
|
||||||
fn rows(&self) -> Result<Vec<Value>> {
|
|
||||||
Ok(self.trace.records()?.into_iter().filter(|record| record.get("agent").is_some()).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn append(&self, mut row: Value) -> Result<u64> {
|
|
||||||
let place = self.trace.records()?.len() as u64;
|
|
||||||
row["seq"] = json!(place);
|
|
||||||
self.trace.record(&format!("{}-g{place}", self.stem), &row)?;
|
|
||||||
Ok(place)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her agent session: the conversation verbatim, what it was built under, and the last call's cost.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct Session {
|
|
||||||
pub items: Vec<InputItem>,
|
|
||||||
/// SHA-256 of the instructions, the tool definitions and the model.
|
|
||||||
pub digest: String,
|
|
||||||
pub retention: CacheRetention,
|
|
||||||
pub created_at: DateTime<Utc>,
|
|
||||||
pub last_call_at: DateTime<Utc>,
|
|
||||||
pub last_usage: Option<Spent>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The session's one row in its store.
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "eureka.persona.agent_session.v1", schema = "PersonaAgentSession")]
|
|
||||||
struct SessionRow {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
value: Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
const SESSION_KEY: &str = "session";
|
|
||||||
|
|
||||||
/// The session in a CultCache single-file store (`agent-session.cc` under the unit's state directory), written only by the drain.
|
|
||||||
pub struct FileSession {
|
|
||||||
path: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FileSession {
|
|
||||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
|
||||||
Self { path: path.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open(&self) -> Result<CultCache> {
|
|
||||||
let mut cache = CultCache::new();
|
|
||||||
cache.register_entry_type::<SessionRow>()?;
|
|
||||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&self.path))?;
|
|
||||||
cache.pull_all_backing_stores()?;
|
|
||||||
Ok(cache)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The session, or none when there is none. A store that cannot be read, or holds a session that does not decode, is an error.
|
|
||||||
pub fn load(&self) -> Result<Option<Session>> {
|
|
||||||
match self.open()?.get::<SessionRow>(SESSION_KEY)? {
|
|
||||||
Some(row) => Ok(Some(serde_json::from_value(row.value)?)),
|
|
||||||
None => Ok(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn save(&self, session: &Session) -> Result<()> {
|
|
||||||
self.open()?.put(SESSION_KEY, &SessionRow { value: serde_json::to_value(session)? })?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forget the session. Nothing to forget is no error, and a store that cannot be opened is removed whole: it holds nothing else.
|
|
||||||
pub fn discard(&self) -> Result<()> {
|
|
||||||
if self.open().and_then(|mut cache| cache.delete::<SessionRow>(SESSION_KEY).map(|_| ())).is_ok() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
match std::fs::remove_file(&self.path) {
|
|
||||||
Err(fault) if fault.kind() != std::io::ErrorKind::NotFound => Err(fault.into()),
|
|
||||||
_ => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What stopped a loop at a bound.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Cap {
|
|
||||||
ToolCalls,
|
|
||||||
ModelCalls,
|
|
||||||
WakeSpend,
|
|
||||||
DaySpend,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Cap {
|
|
||||||
fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::ToolCalls => "tool_calls",
|
|
||||||
Self::ModelCalls => "model_calls",
|
|
||||||
Self::WakeSpend => "wake_usd",
|
|
||||||
Self::DaySpend => "day_usd",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How the turn ended.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Ended {
|
|
||||||
/// The model ended its turn.
|
|
||||||
EndTurn,
|
|
||||||
/// A bound stopped it; the cap receipt is in `receipts` and in her trace.
|
|
||||||
Cap(Cap),
|
|
||||||
/// The turn could not go on. The connector's own failure, kept whole: its `outage` says whether it is a strike.
|
|
||||||
Failed(Failed),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One agent turn: what it ended on, its last words, the receipts it earned in order, and what it used.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Turn {
|
|
||||||
pub ended: Ended,
|
|
||||||
pub text: String,
|
|
||||||
pub receipts: Vec<Receipt>,
|
|
||||||
pub model_calls: usize,
|
|
||||||
pub tool_calls: usize,
|
|
||||||
pub usd: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the loop runs on. `clock` is read for every time it stamps or compares.
|
|
||||||
pub struct Agent<'a> {
|
|
||||||
pub model: &'a dyn Steps,
|
|
||||||
pub session: &'a FileSession,
|
|
||||||
pub executors: &'a [&'a dyn Executor],
|
|
||||||
pub ledger: &'a dyn Ledger,
|
|
||||||
pub bounds: &'a AgentTuning,
|
|
||||||
pub clock: &'a dyn Fn() -> DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One turn's offering. `id` is the turn's identity, `{wake}-t{k}`: request ids and the agent rows' `wake` derive from it, so no two
|
|
||||||
/// model calls of one Mind share an id; `wake` is the wake's, whose turns' spend the wake's cap is read across. `instructions`
|
|
||||||
/// are fixed. `opening` is the wake's own beginning (the narration and her prose), given before `input` on the wake's first turn and
|
|
||||||
/// whenever the session starts fresh, so a session reseeded mid-wake is never given the bare lines. `fresh` is what a fresh session is
|
|
||||||
/// seeded with before it (`ready_intentions`). `input` is the turn's own lines.
|
|
||||||
pub struct Wake<'a> {
|
|
||||||
pub id: &'a str,
|
|
||||||
pub wake: &'a str,
|
|
||||||
pub instructions: &'a str,
|
|
||||||
pub opening: &'a str,
|
|
||||||
pub input: &'a str,
|
|
||||||
pub fresh: &'a str,
|
|
||||||
pub first: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her agent's instructions: fixed, naming her. Her prose is hers, and what is said aloud is hers to say, in her words
|
|
||||||
/// where she gave them; the agent carries no persona text of its own (`say-in-her-words`).
|
|
||||||
pub fn instructions(name: &str) -> String {
|
|
||||||
format!(
|
|
||||||
"You act for {name}. Each wake you are given what {name} has just lived and thought, in her own prose, with the lines that woke her and what came of her last acts. \
|
|
||||||
You act for her only through your tools; each tool call is answered with a receipt, and the receipt is the only truth about what happened. \
|
|
||||||
While she is awake more lines may reach her; each arrives as a new message, and is what she has just heard. \
|
|
||||||
Her prose is hers: do not rewrite it and do not speak as yourself. What is said aloud in chat is hers to say: when you say something, use her own words where her prose gave them, and add no voice of your own. \
|
|
||||||
When nothing needs doing, end your turn without acting."
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs one agent turn. Day cap first, then the session's freshness, then the loop; see the module's text. A bug in the
|
|
||||||
/// caller (two executors defining one tool, an empty input) is an `Err`; everything the world does, her own trace
|
|
||||||
/// failing included, is in `Turn::ended`.
|
|
||||||
pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
|
|
||||||
if wake.input.trim().is_empty() && !(wake.first && !wake.opening.trim().is_empty()) {
|
|
||||||
bail!("a wake with no input");
|
|
||||||
}
|
|
||||||
let mut tools: Vec<ToolDefinition> = Vec::new();
|
|
||||||
let mut owners: Vec<(String, usize)> = Vec::new();
|
|
||||||
for (at, executor) in agent.executors.iter().enumerate() {
|
|
||||||
for definition in executor.definitions() {
|
|
||||||
if owners.iter().any(|(name, _)| *name == definition.name) {
|
|
||||||
bail!("two executors define the tool {}", definition.name);
|
|
||||||
}
|
|
||||||
owners.push((definition.name.clone(), at));
|
|
||||||
tools.push(definition);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let digest = digest_of(&agent.bounds.model, wake.instructions, &tools);
|
|
||||||
let mut run = Run { agent, wake, receipts: Vec::new(), usd: 0.0, model_calls: 0, tool_calls: 0, text: String::new() };
|
|
||||||
let ended = drive(&mut run, &tools, &owners, &digest).unwrap_or_else(Ended::Failed);
|
|
||||||
Ok(run.turn(ended))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The loop. A fault in her own trace or session store is an `Err` from anywhere in it, and ends the turn: no call is made
|
|
||||||
/// that her trace has not first been able to record (the `call` row written before it).
|
|
||||||
fn drive(run: &mut Run<'_>, tools: &[ToolDefinition], owners: &[(String, usize)], digest: &str) -> std::result::Result<Ended, Failed> {
|
|
||||||
let (agent, wake) = (run.agent, run.wake);
|
|
||||||
let bounds = agent.bounds;
|
|
||||||
let now = (agent.clock)();
|
|
||||||
let rows = agent.ledger.rows().map_err(|fault| ledger_failed(&fault))?;
|
|
||||||
let day_before = day_usd(&rows, now, bounds);
|
|
||||||
let wake_before = wake_usd(&rows, wake.wake, bounds);
|
|
||||||
if day_before >= bounds.day_usd {
|
|
||||||
return run.cap(Cap::DaySpend, day_before);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The session as it stands, or the reason it cannot be trusted.
|
|
||||||
let kept = match agent.session.load() {
|
|
||||||
Ok(Some(held)) => match stale(&held, digest, now, bounds) {
|
|
||||||
Some(why) => {
|
|
||||||
run.discard(why)?;
|
|
||||||
None
|
|
||||||
}
|
|
||||||
None => Some(held),
|
|
||||||
},
|
|
||||||
Ok(None) => None,
|
|
||||||
Err(_) => {
|
|
||||||
run.discard("unreadable")?;
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let created_at = kept.as_ref().map_or(now, |held| held.created_at);
|
|
||||||
let mut last_usage = kept.as_ref().and_then(|held| held.last_usage.clone());
|
|
||||||
// The prefix the provider is expected to hold for the next call: what the last call sent, when the session is kept.
|
|
||||||
let mut warm_prefix = last_usage.as_ref().map_or(0, prompt_tokens);
|
|
||||||
// A session that starts fresh, at any turn of the wake, is seeded with her intentions and this wake's opening before the lines; a kept one
|
|
||||||
// had both when its wake began, and takes the opening again only on the wake's first turn.
|
|
||||||
let text = format!("{}{}{}", if kept.is_none() { wake.fresh } else { "" }, if kept.is_none() || wake.first { wake.opening } else { "" }, wake.input);
|
|
||||||
let mut items = kept.map_or_else(Vec::new, |held| held.items);
|
|
||||||
items.push(InputItem::UserText { text });
|
|
||||||
|
|
||||||
let conversation = format!("agent-{}", created_at.timestamp());
|
|
||||||
let mut cold = false;
|
|
||||||
let ended = loop {
|
|
||||||
if run.model_calls >= bounds.model_calls {
|
|
||||||
break run.cap(Cap::ModelCalls, bounds.model_calls as f64)?;
|
|
||||||
}
|
|
||||||
if wake_before + run.usd >= bounds.wake_usd {
|
|
||||||
break run.cap(Cap::WakeSpend, wake_before + run.usd)?;
|
|
||||||
}
|
|
||||||
if day_before + run.usd >= bounds.day_usd {
|
|
||||||
break run.cap(Cap::DaySpend, day_before + run.usd)?;
|
|
||||||
}
|
|
||||||
let request_id = format!("{}-m{}", wake.id, run.model_calls + 1);
|
|
||||||
// The row comes first: it holds the call's place in the day's spend at the worst case, and a trace that cannot take it is a call not made.
|
|
||||||
let reserved = run.record(json!({ "agent": "call", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "model": bounds.model }))?;
|
|
||||||
let answer = agent.model.step(StepRequest { request_id: &request_id, conversation_id: &conversation, model: &bounds.model, instructions: wake.instructions, tools, input: items.clone(), retention: Some(bounds.retention), schema: None });
|
|
||||||
let stepped = match answer {
|
|
||||||
Ok(stepped) => stepped,
|
|
||||||
Err(failed) => {
|
|
||||||
// A failure that reports no usage is charged at the worst case, never at nothing.
|
|
||||||
let usd = failed.usage.as_ref().map_or_else(|| unmetered_usd(bounds), |usage| charge(bounds, usage));
|
|
||||||
run.usd += usd;
|
|
||||||
run.record(json!({ "agent": "settle", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "reserved": reserved, "usage": failed.usage, "usd": usd, "failed": failed.reason }))?;
|
|
||||||
return Ok(Ended::Failed(failed));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
run.model_calls += 1;
|
|
||||||
let cost = charge(bounds, &stepped.usage);
|
|
||||||
run.usd += cost;
|
|
||||||
let at = (agent.clock)();
|
|
||||||
run.record(json!({ "agent": "settle", "at": at.to_rfc3339(), "wake": wake.id, "call": request_id, "reserved": reserved, "usage": stepped.usage, "usd": cost, "stop": format!("{:?}", stepped.stop) }))?;
|
|
||||||
// Observed: a prefix the provider should hold was read as nothing, so the cache is gone. The wake finishes on what it has.
|
|
||||||
if warm_prefix >= bounds.cache_min_tokens && stepped.usage.cache_read_tokens == 0 {
|
|
||||||
cold = true;
|
|
||||||
}
|
|
||||||
warm_prefix = prompt_tokens(&stepped.usage);
|
|
||||||
last_usage = Some(stepped.usage.clone());
|
|
||||||
items.extend(stepped.items.iter().cloned());
|
|
||||||
if !stepped.text.is_empty() {
|
|
||||||
run.text.clone_from(&stepped.text);
|
|
||||||
}
|
|
||||||
let held = |items: &[InputItem]| Session { items: items.to_vec(), digest: digest.to_owned(), retention: bounds.retention, created_at, last_call_at: at, last_usage: last_usage.clone() };
|
|
||||||
agent.session.save(&held(&items)).map_err(|fault| ledger_failed(&fault))?;
|
|
||||||
match (stepped.stop, stepped.calls.is_empty()) {
|
|
||||||
(StopReason::EndTurn, true) => break Ended::EndTurn,
|
|
||||||
(StopReason::ToolUse, false) => {}
|
|
||||||
(stop, _) => {
|
|
||||||
// A stop the loop cannot continue from, or a tool call cut short: nothing in the session can be trusted past it.
|
|
||||||
run.discard("stopped")?;
|
|
||||||
return Ok(Ended::Failed(Failed { reason: format!("the agent's turn ended early: {stop:?}"), outage: false, usage: None }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut over = false;
|
|
||||||
for call in &stepped.calls {
|
|
||||||
let receipt = if run.tool_calls >= bounds.tool_calls {
|
|
||||||
over = true;
|
|
||||||
Receipt::new(&call.name, Status::Cap, json!({ "cap": Cap::ToolCalls.name(), "limit": bounds.tool_calls }))
|
|
||||||
} else {
|
|
||||||
run.tool_calls += 1;
|
|
||||||
match owners.iter().find(|(name, _)| *name == call.name) {
|
|
||||||
Some((_, at)) => agent.executors[*at].run(call),
|
|
||||||
None => Receipt::new(&call.name, Status::Refused, json!({ "reason": "no such tool" })),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// A receipt that cannot be written ends the turn with its call lacking a result in the session: the next start discards it.
|
|
||||||
run.receipt(receipt.clone())?;
|
|
||||||
items.push(InputItem::ToolResult { call_id: call.call_id.clone(), output: receipt.json().to_string() });
|
|
||||||
}
|
|
||||||
agent.session.save(&held(&items)).map_err(|fault| ledger_failed(&fault))?;
|
|
||||||
if over {
|
|
||||||
break run.cap(Cap::ToolCalls, bounds.tool_calls as f64)?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if cold {
|
|
||||||
run.discard("cache_miss")?;
|
|
||||||
}
|
|
||||||
Ok(ended)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The loop's running account: what the turn has earned and spent so far.
|
|
||||||
struct Run<'a> {
|
|
||||||
agent: &'a Agent<'a>,
|
|
||||||
wake: &'a Wake<'a>,
|
|
||||||
receipts: Vec<Receipt>,
|
|
||||||
usd: f64,
|
|
||||||
model_calls: usize,
|
|
||||||
tool_calls: usize,
|
|
||||||
text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Run<'_> {
|
|
||||||
/// One row in her trace; a trace that cannot take it is the turn's failure.
|
|
||||||
fn record(&self, row: Value) -> std::result::Result<u64, Failed> {
|
|
||||||
self.agent.ledger.append(row).map_err(|fault| ledger_failed(&fault))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A receipt is a row in her trace first, and then the turn's.
|
|
||||||
fn receipt(&mut self, receipt: Receipt) -> std::result::Result<(), Failed> {
|
|
||||||
self.record(json!({ "agent": "receipt", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "receipt": receipt.json() }))?;
|
|
||||||
self.receipts.push(receipt);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The bound that ended the loop, as a `cap` receipt of the loop's own.
|
|
||||||
fn cap(&mut self, cap: Cap, reached: f64) -> std::result::Result<Ended, Failed> {
|
|
||||||
self.receipt(Receipt::new("agent", Status::Cap, json!({ "cap": cap.name(), "reached": reached })))?;
|
|
||||||
Ok(Ended::Cap(cap))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forget the session, and say why in her trace.
|
|
||||||
fn discard(&mut self, why: &str) -> std::result::Result<(), Failed> {
|
|
||||||
self.agent.session.discard().map_err(|fault| ledger_failed(&fault))?;
|
|
||||||
self.record(json!({ "agent": "session_discarded", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "why": why })).map(drop)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn turn(self, ended: Ended) -> Turn {
|
|
||||||
Turn { ended, text: self.text, receipts: self.receipts, model_calls: self.model_calls, tool_calls: self.tool_calls, usd: self.usd }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ledger_failed(fault: &anyhow::Error) -> Failed {
|
|
||||||
// Her own store failed, not the world: nothing about it is a strike against a line.
|
|
||||||
Failed { reason: format!("the agent's record could not be written: {fault:#}"), outage: true, usage: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The tokens a call sent as its prompt, whether read from the cache, written to it or plain.
|
|
||||||
fn prompt_tokens(usage: &Spent) -> u64 {
|
|
||||||
usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What `usage` costs, USD, by the tuning's table; cache writes at the rate of the retention the session asks for.
|
|
||||||
fn price(bounds: &AgentTuning, usage: &Spent) -> f64 {
|
|
||||||
let price = bounds.price(&usage.model);
|
|
||||||
let million = 1_000_000.0;
|
|
||||||
(usage.input_tokens as f64 * price.input + usage.output_tokens as f64 * price.output + usage.cache_read_tokens as f64 * price.cache_read + usage.cache_write_tokens as f64 * price.cache_write(bounds.retention)) / million
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a call costs that no usage is known for: `agent.unmetered_usd`, the dearest a call can be taken to cost. It is not the wake's cap: a wake may
|
|
||||||
/// spend a dollar over many calls, and one call cut off by a brake is not charged a dollar of the day for it. Every price that cannot be read from
|
|
||||||
/// her trace is this, so a trace that fails never lowers the day's sum.
|
|
||||||
fn unmetered_usd(bounds: &AgentTuning) -> f64 {
|
|
||||||
bounds.unmetered_usd
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a call that reported `usage` is charged: its price, or `unmetered_usd` when it reports no token at all. A call that
|
|
||||||
/// was paid for never reports zero, so a zero is a count that cannot be believed, and a call is never free.
|
|
||||||
fn charge(bounds: &AgentTuning, usage: &Spent) -> f64 {
|
|
||||||
if prompt_tokens(usage) + usage.output_tokens == 0 { unmetered_usd(bounds) } else { price(bounds, usage) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The UTC day's spend so far, from the `call` rows of her trace dated `now`'s day (`spent`). A row whose time does not read counts as today's.
|
|
||||||
pub(crate) fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
|
|
||||||
spent(rows, bounds, |row| row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_none_or(|at| at.with_timezone(&Utc).date_naive() == now.date_naive()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the wake `wake` has spent so far, across all its turns: the `call` rows whose `wake` is one of its turns' ids (`{wake}-t{k}`),
|
|
||||||
/// priced as the day's are.
|
|
||||||
pub(crate) fn wake_usd(rows: &[Value], wake: &str, bounds: &AgentTuning) -> f64 {
|
|
||||||
let turns = format!("{wake}-t");
|
|
||||||
spent(rows, bounds, |row| row["wake"].as_str().is_some_and(|id| id.starts_with(&turns)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The spend of the `call` rows `keep` takes. A call row is priced by its own usage, or by the `settle` row that names it: the
|
|
||||||
/// settle's `reserved` is the call row's `seq`, its place in her trace, which no other row holds, where a call id repeats when a
|
|
||||||
/// wake is retried under its id. A call with neither, or with a usage that does not read or counts no token, is `unmetered_usd`.
|
|
||||||
fn spent(rows: &[Value], bounds: &AgentTuning, keep: impl Fn(&Value) -> bool) -> f64 {
|
|
||||||
let settled: BTreeMap<u64, &Value> = rows.iter().filter(|row| row["agent"] == "settle").filter_map(|row| Some((row["reserved"].as_u64()?, row))).collect();
|
|
||||||
rows.iter()
|
|
||||||
.filter(|row| row["agent"] == "call")
|
|
||||||
.filter(|row| keep(row))
|
|
||||||
.map(|row| {
|
|
||||||
let usage = if row.get("usage").is_some() { &row["usage"] } else { row["seq"].as_u64().and_then(|place| settled.get(&place)).map_or(&Value::Null, |settle| &settle["usage"]) };
|
|
||||||
serde_json::from_value::<Spent>(usage.clone()).map_or_else(|_| unmetered_usd(bounds), |usage| charge(bounds, &usage))
|
|
||||||
})
|
|
||||||
.sum()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// When `now`'s UTC day ends: the next UTC midnight, the moment `day_usd` counts from nothing again.
|
|
||||||
pub(crate) fn day_ends(now: DateTime<Utc>) -> DateTime<Utc> {
|
|
||||||
(now.date_naive() + chrono::Days::new(1)).and_time(chrono::NaiveTime::MIN).and_utc()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn digest_of(model: &str, instructions: &str, tools: &[ToolDefinition]) -> String {
|
|
||||||
let mut hash = Sha256::new();
|
|
||||||
for part in [model, instructions] {
|
|
||||||
hash.update((part.len() as u64).to_le_bytes());
|
|
||||||
hash.update(part.as_bytes());
|
|
||||||
}
|
|
||||||
for tool in tools {
|
|
||||||
for part in [&tool.name, &tool.description, &tool.parameters_json] {
|
|
||||||
hash.update((part.len() as u64).to_le_bytes());
|
|
||||||
hash.update(part.as_bytes());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
hash.finalize().iter().map(|byte| format!("{byte:02x}")).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a kept session may not be used, or none: a tool call with no result (a start was killed between), a digest that is
|
|
||||||
/// no longer this agent's, a cache that has run out or is about to, and a prompt grown past what is kept.
|
|
||||||
fn stale(session: &Session, digest: &str, now: DateTime<Utc>, bounds: &AgentTuning) -> Option<&'static str> {
|
|
||||||
let orphan = session.items.iter().any(|item| match item {
|
|
||||||
InputItem::ToolCall { call_id, .. } => !session.items.iter().any(|other| matches!(other, InputItem::ToolResult { call_id: answered, .. } if answered == call_id)),
|
|
||||||
_ => false,
|
|
||||||
});
|
|
||||||
if orphan {
|
|
||||||
return Some("orphan_tool_call");
|
|
||||||
}
|
|
||||||
if session.digest != digest {
|
|
||||||
return Some("digest");
|
|
||||||
}
|
|
||||||
let life = i64::try_from(bounds.ttl(session.retention).saturating_sub(CACHE_MARGIN_S)).unwrap_or(i64::MAX);
|
|
||||||
if now - session.last_call_at > Duration::seconds(life) {
|
|
||||||
return Some("ttl");
|
|
||||||
}
|
|
||||||
if session.last_usage.as_ref().is_some_and(|usage| prompt_tokens(usage) > bounds.max_session_tokens) {
|
|
||||||
return Some("too_long");
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
//! `read` (map 16.38.5): a GameCult repo, file, pull request or commit from the forge, a recall over her own mind through her
|
|
||||||
//! persona door, a campaign's rulings, or a plain-HTTP web page. Code performs it (`ReadSource`); the receipt carries what was
|
|
||||||
//! read, its size and its text clipped, or the failure's words with status `error`, never an `ok` with nothing in it. The
|
|
||||||
//! forge is read here and only here: her box's fence admits the public internet and nothing on this host.
|
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use model_connector::ToolDefinition;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
use super::{Executor, Receipt, Status, arguments};
|
|
||||||
use crate::projection::narrate::ToolCall;
|
|
||||||
use crate::projection::read::{ReadRequest, ReadSource, clipped};
|
|
||||||
|
|
||||||
/// The most bytes of a read's text the receipt carries.
|
|
||||||
pub(crate) const READ_TEXT_BYTES: usize = 12 * 1024;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct Args {
|
|
||||||
kind: String,
|
|
||||||
target: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `read` executor: `source` performs the read; `since` opens a campaign read's window (her last wake).
|
|
||||||
pub struct Read<'a> {
|
|
||||||
pub source: Option<&'a dyn ReadSource>,
|
|
||||||
pub since: DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Executor for Read<'_> {
|
|
||||||
fn definitions(&self) -> Vec<ToolDefinition> {
|
|
||||||
vec![ToolDefinition {
|
|
||||||
name: "read".into(),
|
|
||||||
description: "Read something and get its text in the receipt. kind `repo`: a GameCult repo on the forge, as `GameCult/Name`, `GameCult/Name/path/to/file`, `GameCult/Name#12` (a pull request), `GameCult/Name@sha` (a commit) or `GameCult/Name?q=words` (a search); the forge is reached only through this tool, never from the shell. kind `mind`: a recall over her own mind by these words. kind `campaign`: what was ruled lately in a campaign, by its slug. kind `web`: a plain http:// page.".into(),
|
|
||||||
parameters_json: json!({ "type": "object", "properties": { "kind": { "type": "string", "enum": ["repo", "mind", "campaign", "web"] }, "target": { "type": "string" } }, "required": ["kind", "target"], "additionalProperties": false }).to_string(),
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, call: &ToolCall) -> Receipt {
|
|
||||||
let args: Args = match arguments(call) {
|
|
||||||
Ok(args) => args,
|
|
||||||
Err(receipt) => return receipt,
|
|
||||||
};
|
|
||||||
let request = match ReadRequest::from_target(&args.kind, &args.target) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(why) => return Receipt::new("read", Status::Refused, json!({ "kind": args.kind, "target": args.target, "why": why })),
|
|
||||||
};
|
|
||||||
let Some(source) = self.source else {
|
|
||||||
return Receipt::new("read", Status::Refused, json!({ "kind": args.kind, "target": args.target, "why": "nothing can be read from here" }));
|
|
||||||
};
|
|
||||||
match source.read(&request, self.since) {
|
|
||||||
Ok(text) => Receipt::new("read", Status::Ok, json!({ "kind": args.kind, "target": args.target, "bytes": text.len(), "text": clipped(&text, READ_TEXT_BYTES) })),
|
|
||||||
Err(failure) => Receipt::new("read", Status::Error, json!({ "kind": args.kind, "target": args.target, "failure": failure, "why": failure.words() })),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
//! `request_tool` (map 16.38.5): a missing affordance, recorded for Self. The receipt row in her trace is the record; Self reads
|
|
||||||
//! it with `mind-persona trace`. Nothing else happens, and the receipt says so.
|
|
||||||
|
|
||||||
use model_connector::ToolDefinition;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
use super::{Executor, Receipt, Status, arguments};
|
|
||||||
use crate::projection::narrate::ToolCall;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct Args {
|
|
||||||
what: String,
|
|
||||||
why: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct RequestTool;
|
|
||||||
|
|
||||||
impl Executor for RequestTool {
|
|
||||||
fn definitions(&self) -> Vec<ToolDefinition> {
|
|
||||||
vec![ToolDefinition {
|
|
||||||
name: "request_tool".into(),
|
|
||||||
description: "Ask for a tool she lacks: what it would do and why she needs it. It is recorded for Self to read; nothing happens now.".into(),
|
|
||||||
parameters_json: json!({ "type": "object", "properties": { "what": { "type": "string" }, "why": { "type": "string" } }, "required": ["what", "why"], "additionalProperties": false }).to_string(),
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, call: &ToolCall) -> Receipt {
|
|
||||||
match arguments::<Args>(call) {
|
|
||||||
Ok(args) if !args.what.trim().is_empty() => Receipt::new("request_tool", Status::Ok, json!({ "what": args.what.trim(), "why": args.why.trim(), "note": "recorded for Self, who reads it later; nothing happens now" })),
|
|
||||||
Ok(_) => Receipt::new("request_tool", Status::Refused, json!({ "why": "it names no tool" })),
|
|
||||||
Err(receipt) => receipt,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,238 +0,0 @@
|
||||||
//! `say` (map 16.38.4, 16.38.5): one line through the mouth, written ahead in her trace and settled in place.
|
|
||||||
//!
|
|
||||||
//! What survives of the drain's sends lives here and nowhere else:
|
|
||||||
//! - **Write-ahead.** Her trace takes a `say` row with status `handed` before the mouth is called. A trace that refuses the row
|
|
||||||
//! sends nothing, and the model reads `not_sent`.
|
|
||||||
//! - **Send ids.** `{wake}:c{n}`, the wake's key and the say's place in it: the mouth's transaction id, so a repeat is the same send.
|
|
||||||
//! - **Resend.** A row still `handed` at the next start (no answer came) is sent again under its id with `resend` inside
|
|
||||||
//! `OWED_WINDOW_S`, and settled `unknown` past it (`settle_handed`). The mouth vouches for a resend only for an id it attempted.
|
|
||||||
//! - **Room order.** A say into a room that holds a `handed` row, or an `unknown` one she has not been told of, is refused
|
|
||||||
//! `room_unsettled`: her lines never arrive out of order, and none goes in before she knows what became of the last.
|
|
||||||
//!
|
|
||||||
//! The row is the one record of what became of a send. The receipt the model reads, and the receipt row a settlement writes
|
|
||||||
//! at the next start, are what she is told; the row is what the mouth is asked again from.
|
|
||||||
|
|
||||||
use std::cell::{Cell, RefCell};
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use model_connector::ToolDefinition;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::{Executor, Ledger, Receipt, Status, TraceLedger, arguments};
|
|
||||||
use crate::chat_client::{Chat, ChatSendRequest, Reading, SendBasis};
|
|
||||||
use crate::persona::Trace;
|
|
||||||
use crate::projection::narrate::ToolCall;
|
|
||||||
|
|
||||||
/// How long a send id is safe to repeat: the homeserver's transaction memory, held short.
|
|
||||||
pub(crate) const OWED_WINDOW_S: i64 = 1800;
|
|
||||||
|
|
||||||
/// How the mouth answered a send: the event it made, why it made none (the refusal's name), that no answer came, so the
|
|
||||||
/// send stays handed, that it attempted nothing this time, or that whether an earlier try posted cannot be told.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) enum Sent {
|
|
||||||
Posted(String),
|
|
||||||
Refused(String),
|
|
||||||
Lost,
|
|
||||||
Unattempted,
|
|
||||||
Unknown,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The mouth, as her sends go through it: one path for her lines and the identity posts. `chat_send_request.v3` carries no
|
|
||||||
/// mentions and no reply link, so a line goes out plain.
|
|
||||||
pub(crate) struct Mouth<'a> {
|
|
||||||
pub chat: &'a dyn Chat,
|
|
||||||
pub persona: String,
|
|
||||||
/// The newest event of each room her input has shown, by the room's alias; a room her input did not show has none. It grows as lines
|
|
||||||
/// are shown (`shown`): a say is sent against it, and the mouth refuses one when another sender reached the room after it.
|
|
||||||
pub seen: RefCell<BTreeMap<String, String>>,
|
|
||||||
/// When her process began.
|
|
||||||
pub since_unix_ms: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Mouth<'_> {
|
|
||||||
/// Her input has shown `event`, the newest of `room`: a say there is sent against it from now on. The one writer of `seen`.
|
|
||||||
pub(crate) fn shown(&self, room: &str, event: &str) {
|
|
||||||
self.seen.borrow_mut().insert(room.to_owned(), event.to_owned());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line of hers: sent against what she had seen of the room.
|
|
||||||
pub(crate) fn send(&self, id: &str, room: &str, text: &str, resend: bool) -> Sent {
|
|
||||||
let basis = SendBasis { seen_event_id: self.seen.borrow().get(room).cloned(), since_unix_ms: self.since_unix_ms };
|
|
||||||
self.post(id, room, text, Some(basis), resend)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one send: the request, and its answer read by `Refusal::reading`.
|
|
||||||
pub(crate) fn post(&self, id: &str, room: &str, text: &str, basis: Option<SendBasis>, resend: bool) -> Sent {
|
|
||||||
let request = ChatSendRequest { request_id: id.to_owned(), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis, resend };
|
|
||||||
match self.chat.send(&request) {
|
|
||||||
Ok(receipt) => match (receipt.event_id, receipt.refusal) {
|
|
||||||
(_, Some(refusal)) => match refusal.reading(resend) {
|
|
||||||
Reading::NoAnswer => Sent::Lost,
|
|
||||||
Reading::NotSent => Sent::Unattempted,
|
|
||||||
Reading::Unknown => Sent::Unknown,
|
|
||||||
Reading::Declined => Sent::Refused(refusal.name().to_owned()),
|
|
||||||
},
|
|
||||||
(Some(event), None) => Sent::Posted(event),
|
|
||||||
(None, None) if resend => Sent::Unknown,
|
|
||||||
(None, None) => Sent::Refused("no_event".to_owned()),
|
|
||||||
},
|
|
||||||
Err(_) => Sent::Lost,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `room` holds a send she may not follow yet: a row still `handed`, or one settled `unknown` at or after `began`
|
|
||||||
/// (the place her trace had when this wake's packet was read), which she has not been told of. One settled unknown before it
|
|
||||||
/// was in this wake's packet.
|
|
||||||
pub(crate) fn unsettled(records: &[Value], room: &str, began: u64) -> bool {
|
|
||||||
records.iter().filter(|row| row["agent"] == "say" && row["room"] == room).any(|row| match row["status"].as_str() {
|
|
||||||
Some("handed") => true,
|
|
||||||
Some("unknown") => row["settled"].as_u64().is_some_and(|settled| settled >= began),
|
|
||||||
_ => false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct Args {
|
|
||||||
room: String,
|
|
||||||
text: String,
|
|
||||||
#[serde(default)]
|
|
||||||
#[allow(dead_code, reason = "the mouth carries no reply link yet; the agent may name one")]
|
|
||||||
reply_to: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `say` executor for one wake.
|
|
||||||
pub struct Say<'a> {
|
|
||||||
pub(crate) mouth: &'a Mouth<'a>,
|
|
||||||
pub(crate) trace: &'a dyn Trace,
|
|
||||||
/// The wake's key: send ids and row keys derive from it.
|
|
||||||
pub(crate) wake: &'a str,
|
|
||||||
/// The place her trace had when this wake's packet was read.
|
|
||||||
pub(crate) began: u64,
|
|
||||||
pub(crate) clock: &'a dyn Fn() -> DateTime<Utc>,
|
|
||||||
pub(crate) said: Cell<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Say<'_> {
|
|
||||||
fn write(&self, key: &str, row: &Value) -> bool {
|
|
||||||
match self.trace.record(key, row) {
|
|
||||||
Ok(()) => true,
|
|
||||||
Err(fault) => {
|
|
||||||
eprintln!("mind-persona: the say row {key} was not rewritten: {fault:#}");
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Executor for Say<'_> {
|
|
||||||
fn definitions(&self) -> Vec<ToolDefinition> {
|
|
||||||
vec![ToolDefinition {
|
|
||||||
name: "say".into(),
|
|
||||||
description: "Say one line aloud in a chat room, as her. `room` is the room's alias or id as the lines that woke her name it; `text` is the line. Answered with a receipt saying whether it went out.".into(),
|
|
||||||
parameters_json: json!({ "type": "object", "properties": { "room": { "type": "string" }, "text": { "type": "string" }, "reply_to": { "type": "string", "description": "the event id of the line this answers" } }, "required": ["room", "text"], "additionalProperties": false }).to_string(),
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, call: &ToolCall) -> Receipt {
|
|
||||||
let args: Args = match arguments(call) {
|
|
||||||
Ok(args) => args,
|
|
||||||
Err(receipt) => return receipt,
|
|
||||||
};
|
|
||||||
let (room, text) = (args.room.trim().to_owned(), args.text);
|
|
||||||
let fields = |more: Value| {
|
|
||||||
let mut fields = json!({ "room": room, "text": text });
|
|
||||||
fields.as_object_mut().expect("an object").extend(more.as_object().cloned().unwrap_or_default());
|
|
||||||
fields
|
|
||||||
};
|
|
||||||
let records = match self.trace.records() {
|
|
||||||
Ok(records) => records,
|
|
||||||
Err(_) => return Receipt::new("say", Status::NotSent, fields(json!({ "why": "her trace could not be read, so nothing was sent" }))),
|
|
||||||
};
|
|
||||||
if unsettled(&records, &room, self.began) {
|
|
||||||
return Receipt::new("say", Status::Refused, fields(json!({ "refusal": "room_unsettled", "why": "an earlier line of hers in this room has no known outcome yet" })));
|
|
||||||
}
|
|
||||||
let n = self.said.get() + 1;
|
|
||||||
self.said.set(n);
|
|
||||||
let (id, key) = (format!("{}:c{n}", self.wake), format!("{}-s{n}", self.wake));
|
|
||||||
let mut row = json!({ "agent": "say", "key": key, "id": id, "wake": self.wake, "room": room, "text": text, "status": "handed", "seq": records.len(), "at": (self.clock)().to_rfc3339() });
|
|
||||||
// Write-ahead: no send is made that her trace has not first recorded as handed.
|
|
||||||
if self.trace.record(&key, &row).is_err() {
|
|
||||||
return Receipt::new("say", Status::NotSent, fields(json!({ "why": "her trace refused the line's record, so nothing was sent" })));
|
|
||||||
}
|
|
||||||
let settled = |row: &mut Value| -> u64 {
|
|
||||||
let place = self.trace.records().map_or(u64::MAX, |records| records.len() as u64);
|
|
||||||
row["settled"] = json!(place);
|
|
||||||
place
|
|
||||||
};
|
|
||||||
match self.mouth.send(&id, &room, &text, false) {
|
|
||||||
Sent::Posted(event) => {
|
|
||||||
row["status"] = json!("ok");
|
|
||||||
row["event"] = json!(event);
|
|
||||||
self.write(&key, &row);
|
|
||||||
Receipt::new("say", Status::Ok, fields(json!({ "event": event })))
|
|
||||||
}
|
|
||||||
Sent::Refused(why) => {
|
|
||||||
row["status"] = json!("refused");
|
|
||||||
row["refusal"] = json!(why);
|
|
||||||
self.write(&key, &row);
|
|
||||||
Receipt::new("say", Status::Refused, fields(json!({ "refusal": why })))
|
|
||||||
}
|
|
||||||
Sent::Unattempted => {
|
|
||||||
row["status"] = json!("not_sent");
|
|
||||||
self.write(&key, &row);
|
|
||||||
Receipt::new("say", Status::NotSent, fields(json!({ "why": "the mouth attempted nothing" })))
|
|
||||||
}
|
|
||||||
Sent::Unknown => {
|
|
||||||
row["status"] = json!("unknown");
|
|
||||||
settled(&mut row);
|
|
||||||
self.write(&key, &row);
|
|
||||||
Receipt::new("say", Status::Unknown, fields(json!({ "why": "whether it went out cannot be told" })))
|
|
||||||
}
|
|
||||||
// No answer: the row stays handed, and the next start asks the mouth again under the same id.
|
|
||||||
Sent::Lost => Receipt::new("say", Status::Unknown, fields(json!({ "why": "the mouth gave no answer; it is asked again under the same id at her next wake" }))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Step 2 of a start (map 16.38.2): every `say` row still `handed` is sent again under its id with `resend`, inside
|
|
||||||
/// `OWED_WINDOW_S`, and settled `unknown` past it. No model is called. Each row settled here is rewritten in place, and a
|
|
||||||
/// receipt row of the settlement is written for her next packet; a resend with no answer, or one the mouth did not attempt,
|
|
||||||
/// stays handed. `stem` keys the receipt rows.
|
|
||||||
pub(crate) fn settle_handed(trace: &dyn Trace, mouth: &Mouth<'_>, stem: &str, now: DateTime<Utc>) {
|
|
||||||
let records = match trace.records() {
|
|
||||||
Ok(records) => records,
|
|
||||||
Err(fault) => return eprintln!("mind-persona: her trace was not read, so no handed line was settled: {fault:#}"),
|
|
||||||
};
|
|
||||||
let ledger = TraceLedger::new(trace, stem);
|
|
||||||
for row in records.iter().filter(|row| row["agent"] == "say" && row["status"] == "handed") {
|
|
||||||
let (key, id, room, text) = (row["key"].as_str().unwrap_or_default(), row["id"].as_str().unwrap_or_default(), row["room"].as_str().unwrap_or_default(), row["text"].as_str().unwrap_or_default());
|
|
||||||
let age = row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map_or(i64::MAX, |at| (now - at.with_timezone(&Utc)).num_seconds());
|
|
||||||
let sent = if age <= OWED_WINDOW_S { mouth.send(id, room, text, true) } else { Sent::Unknown };
|
|
||||||
let (status, event) = match sent {
|
|
||||||
Sent::Posted(event) => (Status::Ok, Some(event)),
|
|
||||||
Sent::Unknown | Sent::Refused(_) => (Status::Unknown, None),
|
|
||||||
Sent::Lost | Sent::Unattempted => continue,
|
|
||||||
};
|
|
||||||
let mut settled = row.clone();
|
|
||||||
settled["status"] = json!(if status == Status::Ok { "ok" } else { "unknown" });
|
|
||||||
settled["settled"] = json!(records.len());
|
|
||||||
if let Some(event) = &event {
|
|
||||||
settled["event"] = json!(event);
|
|
||||||
}
|
|
||||||
if let Err(fault) = trace.record(key, &settled) {
|
|
||||||
eprintln!("mind-persona: the say row {key} was not settled: {fault:#}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let receipt = Receipt::new("say", status, json!({ "room": room, "text": text, "event": event, "resent": true }));
|
|
||||||
if let Err(fault) = ledger.append(json!({ "agent": "receipt", "at": now.to_rfc3339(), "wake": stem, "receipt": receipt.json() })) {
|
|
||||||
eprintln!("mind-persona: the settlement of {key} was not recorded: {fault:#}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,228 +0,0 @@
|
||||||
//! `say`: write-ahead, the mouth's readings, room order and the resend a later start makes.
|
|
||||||
|
|
||||||
use std::cell::{Cell, RefCell};
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use anyhow::{Result, bail};
|
|
||||||
use chrono::{Duration, TimeZone};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, Refusal};
|
|
||||||
use crate::persona::TraceView;
|
|
||||||
|
|
||||||
fn noon() -> DateTime<Utc> {
|
|
||||||
Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her trace in memory: rows by key, rewritten in place; it refuses a write when `refuse` is set.
|
|
||||||
#[derive(Default)]
|
|
||||||
struct Rows {
|
|
||||||
rows: RefCell<Vec<(String, Value)>>,
|
|
||||||
refuse: Cell<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Trace for Rc<Rows> {
|
|
||||||
fn record(&self, key: &str, record: &Value) -> anyhow::Result<()> {
|
|
||||||
if self.refuse.get() {
|
|
||||||
bail!("no space left on device");
|
|
||||||
}
|
|
||||||
let mut rows = self.rows.borrow_mut();
|
|
||||||
match rows.iter_mut().find(|(held, _)| held == key) {
|
|
||||||
Some(row) => row.1 = record.clone(),
|
|
||||||
None => rows.push((key.to_owned(), record.clone())),
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TraceView for Rc<Rows> {
|
|
||||||
fn records(&self) -> anyhow::Result<Vec<Value>> {
|
|
||||||
Ok(self.rows.borrow().iter().map(|(_, row)| row.clone()).collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The mouth: answers each send with the next scripted receipt (or a transport error), and records each request with what her
|
|
||||||
/// trace held when it was made.
|
|
||||||
struct Mouthpiece {
|
|
||||||
answers: RefCell<VecDeque<Result<ChatSendReceipt>>>,
|
|
||||||
sent: RefCell<Vec<(ChatSendRequest, Vec<Value>)>>,
|
|
||||||
trace: Rc<Rows>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn posted(event: &str) -> Result<ChatSendReceipt> {
|
|
||||||
Ok(ChatSendReceipt { request_id: String::new(), event_id: Some(event.into()), refusal: None, newer: vec![] })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn refused(refusal: Refusal) -> Result<ChatSendReceipt> {
|
|
||||||
Ok(ChatSendReceipt { request_id: String::new(), event_id: None, refusal: Some(refusal), newer: vec![] })
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Chat for Mouthpiece {
|
|
||||||
fn pending(&self, _: u64) -> Result<ChatPending> {
|
|
||||||
bail!("say reads nothing")
|
|
||||||
}
|
|
||||||
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
|
|
||||||
self.sent.borrow_mut().push((request.clone(), self.trace.records().unwrap()));
|
|
||||||
self.answers.borrow_mut().pop_front().expect("a send past the script")
|
|
||||||
}
|
|
||||||
fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result<ChatOpenDirectReceipt> {
|
|
||||||
bail!("say opens nothing")
|
|
||||||
}
|
|
||||||
fn fetch(&self, _: &ChatFetchRequest) -> Result<ChatFetchReceipt> {
|
|
||||||
bail!("say fetches nothing")
|
|
||||||
}
|
|
||||||
fn ack(&self, _: u64) -> Result<()> {
|
|
||||||
bail!("say acks nothing")
|
|
||||||
}
|
|
||||||
fn read(&self, _: &ChatRead) -> Result<()> {
|
|
||||||
bail!("say reports no read")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Rig {
|
|
||||||
trace: Rc<Rows>,
|
|
||||||
chat: Mouthpiece,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Rig {
|
|
||||||
fn new(answers: Vec<Result<ChatSendReceipt>>) -> Self {
|
|
||||||
let trace = Rc::new(Rows::default());
|
|
||||||
Self { chat: Mouthpiece { answers: RefCell::new(answers.into()), sent: RefCell::default(), trace: trace.clone() }, trace }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mouth(&self) -> Mouth<'_> {
|
|
||||||
Mouth { chat: &self.chat, persona: "eureka".into(), seen: RefCell::new(BTreeMap::from([("#minds".to_owned(), "$seen".to_owned())])), since_unix_ms: 1 }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One say through a fresh executor at `began`.
|
|
||||||
fn say(&self, room: &str, text: &str, began: u64) -> Receipt {
|
|
||||||
let mouth = self.mouth();
|
|
||||||
let clock = noon;
|
|
||||||
let say = Say { mouth: &mouth, trace: &self.trace, wake: "n4-99", began, clock: &clock, said: Cell::new(0) };
|
|
||||||
say.run(&ToolCall { call_id: "c".into(), name: "say".into(), arguments: json!({ "room": room, "text": text }).to_string() })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn says(&self) -> Vec<Value> {
|
|
||||||
self.trace.records().unwrap().into_iter().filter(|row| row["agent"] == "say").collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sent(&self) -> Vec<ChatSendRequest> {
|
|
||||||
self.chat.sent.borrow().iter().map(|(request, _)| request.clone()).collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a2_say_write_ahead() {
|
|
||||||
let rig = Rig::new(vec![posted("$e1")]);
|
|
||||||
let receipt = rig.say("#minds", "hello", 0);
|
|
||||||
assert_eq!((receipt.status(), &receipt.fields()["event"]), (Status::Ok, &json!("$e1")));
|
|
||||||
let (request, held) = rig.chat.sent.borrow()[0].clone();
|
|
||||||
assert_eq!((request.request_id.as_str(), request.resend), ("n4-99:c1", false), "the send id is the wake's key and the say's place");
|
|
||||||
assert_eq!(request.basis.unwrap().seen_event_id.as_deref(), Some("$seen"), "sent against what she had seen of the room");
|
|
||||||
assert!(held.iter().any(|row| row["agent"] == "say" && row["status"] == "handed" && row["id"] == "n4-99:c1"), "the handed row was in her trace before the mouth was called: {held:?}");
|
|
||||||
assert_eq!(rig.says()[0]["status"], "ok", "and is settled in place");
|
|
||||||
assert_eq!(rig.says().len(), 1);
|
|
||||||
|
|
||||||
// A trace that refuses the row sends nothing.
|
|
||||||
let rig = Rig::new(vec![]);
|
|
||||||
rig.trace.refuse.set(true);
|
|
||||||
let receipt = rig.say("#minds", "hello", 0);
|
|
||||||
assert_eq!(receipt.status(), Status::NotSent);
|
|
||||||
assert!(rig.sent().is_empty(), "nothing went to the mouth");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each answer of the mouth's to a first send, as the receipt and the row read it.
|
|
||||||
#[test]
|
|
||||||
fn a_first_sends_answers_settle_by_the_mouths_reading() {
|
|
||||||
for (answer, status, row) in [
|
|
||||||
(refused(Refusal::NotSent), Status::NotSent, "not_sent"),
|
|
||||||
(refused(Refusal::SendFailed), Status::Unknown, "handed"),
|
|
||||||
(refused(Refusal::RoomMoved), Status::Refused, "refused"),
|
|
||||||
(Err(anyhow::anyhow!("the mouth is unreachable")), Status::Unknown, "handed"),
|
|
||||||
] {
|
|
||||||
let rig = Rig::new(vec![answer]);
|
|
||||||
let receipt = rig.say("#minds", "hello", 0);
|
|
||||||
assert_eq!(receipt.status(), status, "{receipt:?}");
|
|
||||||
assert_eq!(rig.says()[0]["status"], row, "{receipt:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a2_room_unsettled() {
|
|
||||||
// A say left unknown in this wake holds the room until she is told of it.
|
|
||||||
let rig = Rig::new(vec![refused(Refusal::ResendUnknown), posted("$e2")]);
|
|
||||||
let mouth = rig.mouth();
|
|
||||||
let clock = noon;
|
|
||||||
let say = Say { mouth: &mouth, trace: &rig.trace, wake: "w", began: 0, clock: &clock, said: Cell::new(0) };
|
|
||||||
let call = |room: &str| ToolCall { call_id: "c".into(), name: "say".into(), arguments: json!({ "room": room, "text": "x" }).to_string() };
|
|
||||||
assert_eq!(say.run(&call("#minds")).status(), Status::Unknown);
|
|
||||||
let again = say.run(&call("#minds"));
|
|
||||||
assert_eq!((again.status(), &again.fields()["refusal"]), (Status::Refused, &json!("room_unsettled")), "nothing goes in after a line with no known outcome");
|
|
||||||
assert_eq!(say.run(&call("#other")).status(), Status::Ok, "another room is not held");
|
|
||||||
assert_eq!(rig.sent().len(), 2);
|
|
||||||
// Settled before this wake's packet was read, she has been told: the room is free.
|
|
||||||
let settled = rig.says()[0]["settled"].as_u64().unwrap();
|
|
||||||
assert!(!unsettled(&rig.trace.records().unwrap(), "#minds", settled + 1));
|
|
||||||
assert!(unsettled(&rig.trace.records().unwrap(), "#minds", settled));
|
|
||||||
// A handed row holds its room whatever the wake.
|
|
||||||
let rig = Rig::new(vec![refused(Refusal::SendFailed)]);
|
|
||||||
rig.say("#minds", "x", 0);
|
|
||||||
assert!(unsettled(&rig.trace.records().unwrap(), "#minds", u64::MAX));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A handed row that settles unknown at a start frees its room for the wake that follows: that wake's packet was read after the
|
|
||||||
/// settlement, so she has been told, and her say goes out.
|
|
||||||
#[test]
|
|
||||||
fn t_a2_a_settled_unknown_frees_its_room_for_the_next_wake() {
|
|
||||||
let rig = Rig::new(vec![posted("$after")]);
|
|
||||||
rig.trace.record("old", &json!({ "agent": "say", "key": "old", "id": "old:id", "room": "#minds", "text": "late", "status": "handed", "seq": 0, "at": (noon() - Duration::minutes(31)).to_rfc3339() })).unwrap();
|
|
||||||
settle_handed(&rig.trace, &rig.mouth(), "n9", noon());
|
|
||||||
assert_eq!(rig.says()[0]["status"], "unknown");
|
|
||||||
let began = rig.trace.records().unwrap().len() as u64;
|
|
||||||
let receipt = rig.say("#minds", "now", began);
|
|
||||||
assert_eq!(receipt.status(), Status::Ok, "the room is free: {:?}", receipt.fields());
|
|
||||||
assert_eq!(rig.sent().len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a2_resend_inside_window() {
|
|
||||||
let handed = |minutes: i64, key: &str| json!({ "agent": "say", "key": key, "id": format!("{key}:id"), "room": "#minds", "text": "late", "status": "handed", "seq": 0, "at": (noon() - Duration::minutes(minutes)).to_rfc3339() });
|
|
||||||
let rig = Rig::new(vec![posted("$late")]);
|
|
||||||
rig.trace.record("young", &handed(10, "young")).unwrap();
|
|
||||||
rig.trace.record("old", &handed(31, "old")).unwrap();
|
|
||||||
settle_handed(&rig.trace, &rig.mouth(), "n9", noon());
|
|
||||||
let sent = rig.sent();
|
|
||||||
assert_eq!(sent.len(), 1, "only the send inside the window is asked again");
|
|
||||||
assert_eq!((sent[0].request_id.as_str(), sent[0].resend), ("young:id", true), "under the same id, as a resend");
|
|
||||||
let rows = rig.trace.records().unwrap();
|
|
||||||
let status = |key: &str| rows.iter().find(|row| row["key"] == key).unwrap()["status"].clone();
|
|
||||||
assert_eq!((status("young"), status("old")), (json!("ok"), json!("unknown")), "posted on resend; past the window, unknown without a send");
|
|
||||||
let told: Vec<&Value> = rows.iter().filter(|row| row["agent"] == "receipt").collect();
|
|
||||||
assert_eq!(told.len(), 2, "each settlement is a receipt she is told: {rows:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A resend's answers: the mouth vouches only for an id it attempted, and a resend it did not attempt or got no answer to stays handed.
|
|
||||||
#[test]
|
|
||||||
fn a_resends_answers_settle_by_the_mouths_reading() {
|
|
||||||
for (answer, status) in [(refused(Refusal::ResendUnknown), "unknown"), (refused(Refusal::NotSent), "handed"), (refused(Refusal::SendFailed), "handed"), (refused(Refusal::Brake), "unknown")] {
|
|
||||||
let rig = Rig::new(vec![answer]);
|
|
||||||
rig.trace.record("k", &json!({ "agent": "say", "key": "k", "id": "k:id", "room": "#minds", "text": "x", "status": "handed", "seq": 0, "at": noon().to_rfc3339() })).unwrap();
|
|
||||||
settle_handed(&rig.trace, &rig.mouth(), "n9", noon());
|
|
||||||
assert_eq!(rig.says()[0]["status"], status);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line shown to her is the newest she has seen of its room: her say there is sent against it, and a say in another room is not.
|
|
||||||
#[test]
|
|
||||||
fn t_w1_a_say_is_sent_against_the_newest_line_shown() {
|
|
||||||
let rig = Rig::new(vec![posted("$e1"), posted("$e2")]);
|
|
||||||
let mouth = rig.mouth();
|
|
||||||
mouth.shown("#minds", "$newer");
|
|
||||||
let say = Say { mouth: &mouth, trace: &rig.trace, wake: "n4-99", began: 0, clock: &noon, said: Cell::new(0) };
|
|
||||||
let call = |room: &str| ToolCall { call_id: "c".into(), name: "say".into(), arguments: json!({ "room": room, "text": "hi" }).to_string() };
|
|
||||||
say.run(&call("#minds"));
|
|
||||||
say.run(&call("#other"));
|
|
||||||
let seen: Vec<Option<String>> = rig.sent().iter().map(|request| request.basis.as_ref().and_then(|basis| basis.seen_event_id.clone())).collect();
|
|
||||||
assert_eq!(seen, [Some("$newer".to_owned()), None], "the room she was shown a newer line of is sent against it; one she was shown nothing of is not");
|
|
||||||
}
|
|
||||||
|
|
@ -1,97 +0,0 @@
|
||||||
//! `shell` (map 16.38.5, 16.38.17): one command in her box. The drain never runs it: it connects to her box socket
|
|
||||||
//! (`mind-box-<m>.socket`), writes one request and reads one receipt to its end. `mind-persona box-exec` answers, as
|
|
||||||
//! `mind-<m>-box`, under the one bubblewrap profile (`sandbox::run_box`). The receipt is the box's, passed through with its tool
|
|
||||||
//! and status checked; a box that does not answer in time, or answers nothing a receipt can be read from, is status `error`.
|
|
||||||
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use model_connector::ToolDefinition;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::{Executor, Receipt, Status, arguments};
|
|
||||||
use crate::projection::narrate::ToolCall;
|
|
||||||
use crate::projection::select::clip;
|
|
||||||
use crate::sandbox::{TAIL_BYTES, TIMEOUT_MAX_S};
|
|
||||||
|
|
||||||
/// How much longer than the command's own timeout the drain waits for the box's answer.
|
|
||||||
const ANSWER_GRACE_S: u64 = 10;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct Args {
|
|
||||||
command: String,
|
|
||||||
#[serde(default)]
|
|
||||||
timeout_s: Option<u64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `shell` executor: `socket` is her box's door.
|
|
||||||
pub struct Shell {
|
|
||||||
pub socket: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Executor for Shell {
|
|
||||||
fn definitions(&self) -> Vec<ToolDefinition> {
|
|
||||||
vec![ToolDefinition {
|
|
||||||
name: "shell".into(),
|
|
||||||
description: format!("Run one command with /bin/sh in her own box: a Linux sandbox whose home is hers and persists, with /opt/commons/handoff and /opt/commons/cast-art writable and the rest of /opt/commons read-only. It reaches the public internet and nothing on this host: read the forge and her mind with the `read` tool. `timeout_s` is at most {TIMEOUT_MAX_S}. The receipt carries the exit code, the tails of stdout and stderr, and the files it wrote."),
|
|
||||||
parameters_json: json!({ "type": "object", "properties": { "command": { "type": "string" }, "timeout_s": { "type": "integer", "minimum": 1, "maximum": TIMEOUT_MAX_S } }, "required": ["command"], "additionalProperties": false }).to_string(),
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, call: &ToolCall) -> Receipt {
|
|
||||||
let args: Args = match arguments(call) {
|
|
||||||
Ok(args) => args,
|
|
||||||
Err(receipt) => return receipt,
|
|
||||||
};
|
|
||||||
let timeout_s = args.timeout_s.unwrap_or(30).clamp(1, TIMEOUT_MAX_S);
|
|
||||||
let request = json!({ "command": args.command, "timeout_s": timeout_s });
|
|
||||||
let receipt = match ask(&self.socket, &request, Duration::from_secs(timeout_s + ANSWER_GRACE_S)) {
|
|
||||||
Ok(answer) => passed_through(&answer),
|
|
||||||
Err(why) => Receipt::new("shell", Status::Error, json!({ "why": why })),
|
|
||||||
};
|
|
||||||
// The receipt names the command it answers, so what her trace holds says what was run, not only what came back. It is bounded as its output is.
|
|
||||||
let mut fields = receipt.fields().clone();
|
|
||||||
fields.insert("command".to_owned(), json!(clip(&args.command, TAIL_BYTES)));
|
|
||||||
Receipt::new("shell", receipt.status(), Value::Object(fields))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The box's receipt as hers: its status, read from what the box said, and every other field it carries. One without its tool or
|
|
||||||
/// status is no receipt.
|
|
||||||
fn passed_through(answer: &[u8]) -> Receipt {
|
|
||||||
let Ok(Value::Object(mut fields)) = serde_json::from_slice::<Value>(answer) else {
|
|
||||||
return Receipt::new("shell", Status::Error, json!({ "why": "the box did not answer" }));
|
|
||||||
};
|
|
||||||
let status = match (fields.remove("tool"), fields.remove("status")) {
|
|
||||||
(Some(tool), Some(status)) if tool == "shell" => match status.as_str() {
|
|
||||||
Some("ok") => Status::Ok,
|
|
||||||
Some("error") => Status::Error,
|
|
||||||
_ => return Receipt::new("shell", Status::Error, json!({ "why": "the box's answer carried no status it may give" })),
|
|
||||||
},
|
|
||||||
_ => return Receipt::new("shell", Status::Error, json!({ "why": "the box's answer was not a shell receipt" })),
|
|
||||||
};
|
|
||||||
Receipt::new("shell", status, Value::Object(fields))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One request to the box and its whole answer, within `wait`.
|
|
||||||
#[cfg(unix)]
|
|
||||||
fn ask(socket: &std::path::Path, request: &Value, wait: Duration) -> Result<Vec<u8>, String> {
|
|
||||||
use std::io::{Read, Write};
|
|
||||||
use std::os::unix::net::UnixStream;
|
|
||||||
let mut stream = UnixStream::connect(socket).map_err(|_| "the box could not be reached".to_owned())?;
|
|
||||||
stream.set_read_timeout(Some(wait)).and_then(|()| stream.set_write_timeout(Some(wait))).map_err(|_| "the box could not be reached".to_owned())?;
|
|
||||||
stream.write_all(request.to_string().as_bytes()).and_then(|()| stream.shutdown(std::net::Shutdown::Write)).map_err(|_| "the box did not take the command".to_owned())?;
|
|
||||||
let mut answer = Vec::new();
|
|
||||||
match stream.take(1024 * 1024).read_to_end(&mut answer) {
|
|
||||||
Ok(_) => Ok(answer),
|
|
||||||
Err(fault) if matches!(fault.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => Err("box did not answer".to_owned()),
|
|
||||||
Err(_) => Err("the box's answer broke off".to_owned()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(unix))]
|
|
||||||
fn ask(_: &std::path::Path, _: &Value, _: Duration) -> Result<Vec<u8>, String> {
|
|
||||||
Err("there is no box on this platform".to_owned())
|
|
||||||
}
|
|
||||||
|
|
@ -1,946 +0,0 @@
|
||||||
use std::cell::{Cell, RefCell};
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
|
|
||||||
use chrono::TimeZone;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::persona::{FileTrace, TraceView};
|
|
||||||
|
|
||||||
const MODEL: &str = "claude-sonnet-5-5";
|
|
||||||
|
|
||||||
fn noon() -> DateTime<Utc> {
|
|
||||||
Utc.with_ymd_and_hms(2026, 11, 29, 12, 0, 0).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn usage(input: u64, output: u64, cache_read: u64, cache_write: u64) -> Spent {
|
|
||||||
Spent { model: MODEL.into(), input_tokens: input, output_tokens: output, cache_read_tokens: cache_read, cache_write_tokens: cache_write, reasoning_tokens: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn small() -> Spent {
|
|
||||||
usage(100, 20, 0, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn asks(call_id: &str, tool: &str, spent: Spent) -> std::result::Result<Stepped, Failed> {
|
|
||||||
let call = ToolCall { call_id: call_id.into(), name: tool.into(), arguments: "{}".into() };
|
|
||||||
Ok(Stepped { items: vec![InputItem::ToolCall { call_id: call.call_id.clone(), name: call.name.clone(), arguments: call.arguments.clone() }], text: String::new(), calls: vec![call], stop: StopReason::ToolUse, usage: spent })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ends(text: &str, spent: Spent) -> std::result::Result<Stepped, Failed> {
|
|
||||||
Ok(Stepped { items: vec![InputItem::AssistantText { text: text.into() }], text: text.into(), calls: vec![], stop: StopReason::EndTurn, usage: spent })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The connector as a script: each call answers the next entry and keeps the conversation it was sent.
|
|
||||||
struct Script {
|
|
||||||
answers: RefCell<VecDeque<std::result::Result<Stepped, Failed>>>,
|
|
||||||
seen: RefCell<Vec<Vec<InputItem>>>,
|
|
||||||
ids: RefCell<Vec<String>>,
|
|
||||||
conversations: RefCell<Vec<String>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Script {
|
|
||||||
fn new(answers: Vec<std::result::Result<Stepped, Failed>>) -> Self {
|
|
||||||
Self { answers: RefCell::new(answers.into()), seen: RefCell::default(), ids: RefCell::default(), conversations: RefCell::default() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A model that asks `tool` on every call, whatever it is told.
|
|
||||||
fn endless(tool: &str, calls: usize) -> Self {
|
|
||||||
Self::new((0..calls).map(|at| asks(&format!("c{at}"), tool, small())).collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Steps for Script {
|
|
||||||
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
|
|
||||||
self.seen.borrow_mut().push(request.input.clone());
|
|
||||||
self.ids.borrow_mut().push(request.request_id.to_owned());
|
|
||||||
self.conversations.borrow_mut().push(request.conversation_id.to_owned());
|
|
||||||
assert!(!request.tools.is_empty() && request.retention.is_some(), "the loop always sends its tools and asks for the cache");
|
|
||||||
self.answers.borrow_mut().pop_front().expect("the loop called the model past the script")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Two stub tools; each call is answered `ok` with the arguments echoed.
|
|
||||||
struct Stub {
|
|
||||||
ran: RefCell<Vec<String>>,
|
|
||||||
parameters: RefCell<String>,
|
|
||||||
description: RefCell<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Stub {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self { ran: RefCell::default(), parameters: RefCell::new("{\"type\":\"object\"}".into()), description: RefCell::new("stub".into()) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Executor for Stub {
|
|
||||||
fn definitions(&self) -> Vec<ToolDefinition> {
|
|
||||||
["alpha", "beta"].map(|name| ToolDefinition { name: name.into(), description: format!("the {name} {}", self.description.borrow()), parameters_json: self.parameters.borrow().clone() }).to_vec()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, call: &ToolCall) -> Receipt {
|
|
||||||
self.ran.borrow_mut().push(call.name.clone());
|
|
||||||
Receipt::new(&call.name, Status::Ok, json!({ "arguments": call.arguments }))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct Memory {
|
|
||||||
rows: RefCell<Vec<Value>>,
|
|
||||||
/// The kinds of row the trace refuses to write.
|
|
||||||
refuses: RefCell<Vec<&'static str>>,
|
|
||||||
unreadable: Cell<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ledger for Memory {
|
|
||||||
fn rows(&self) -> Result<Vec<Value>> {
|
|
||||||
if self.unreadable.get() {
|
|
||||||
bail!("the trace cannot be read");
|
|
||||||
}
|
|
||||||
Ok(self.rows.borrow().clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn append(&self, mut row: Value) -> Result<u64> {
|
|
||||||
if self.refuses.borrow().iter().any(|kind| row["agent"] == *kind) {
|
|
||||||
bail!("the trace cannot be written");
|
|
||||||
}
|
|
||||||
let place = self.rows.borrow().len() as u64;
|
|
||||||
row["seq"] = json!(place);
|
|
||||||
self.rows.borrow_mut().push(row);
|
|
||||||
Ok(place)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Memory {
|
|
||||||
fn kinds(&self, kind: &str) -> Vec<Value> {
|
|
||||||
self.rows.borrow().iter().filter(|row| row["agent"] == kind).cloned().collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Rig {
|
|
||||||
dir: tempfile::TempDir,
|
|
||||||
session: FileSession,
|
|
||||||
ledger: Memory,
|
|
||||||
stub: Stub,
|
|
||||||
clock: Cell<DateTime<Utc>>,
|
|
||||||
bounds: AgentTuning,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Rig {
|
|
||||||
fn new() -> Self {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let session = FileSession::new(dir.path().join("agent-session.cc"));
|
|
||||||
Self { dir, session, ledger: Memory::default(), stub: Stub::new(), clock: Cell::new(noon()), bounds: AgentTuning { wake_usd: 0.40, ..AgentTuning::default() } }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wake(&self, model: &Script, id: &str, instructions: &str, input: &str) -> Turn {
|
|
||||||
let clock = || self.clock.get();
|
|
||||||
let executors: [&dyn Executor; 1] = [&self.stub];
|
|
||||||
let agent = Agent { model, session: &self.session, executors: &executors, ledger: &self.ledger, bounds: &self.bounds, clock: &clock };
|
|
||||||
step(&agent, &Wake { id, wake: id, opening: "", first: true, instructions, input, fresh: "" }).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, model: &Script, input: &str) -> Turn {
|
|
||||||
self.wake(model, "w1", "You act for her.", input)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn discards(&self) -> Vec<String> {
|
|
||||||
self.ledger.kinds("session_discarded").iter().map(|row| row["why"].as_str().unwrap().to_owned()).collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_loop_runs_tool_calls() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", small()), asks("c2", "beta", small()), ends("Done.", small())]);
|
|
||||||
let turn = rig.run(&model, "She wants to know.");
|
|
||||||
assert_eq!(turn.ended, Ended::EndTurn);
|
|
||||||
assert_eq!((turn.model_calls, turn.tool_calls, turn.text.as_str()), (3, 2, "Done."));
|
|
||||||
assert_eq!(turn.receipts.iter().map(|receipt| (receipt.tool(), receipt.status())).collect::<Vec<_>>(), [("alpha", Status::Ok), ("beta", Status::Ok)]);
|
|
||||||
// Two receipts in her trace, and the ToolResults the model read are those receipts' JSON.
|
|
||||||
let rows = rig.ledger.kinds("receipt");
|
|
||||||
assert_eq!(rows.iter().map(|row| row["receipt"].clone()).collect::<Vec<_>>(), turn.receipts.iter().map(Receipt::json).collect::<Vec<_>>());
|
|
||||||
let results: Vec<(String, String)> = rig.session.load().unwrap().unwrap().items.into_iter().filter_map(|item| if let InputItem::ToolResult { call_id, output } = item { Some((call_id, output)) } else { None }).collect();
|
|
||||||
assert_eq!(results, [("c1".to_owned(), turn.receipts[0].json().to_string()), ("c2".to_owned(), turn.receipts[1].json().to_string())]);
|
|
||||||
// The model's third call saw both results, in order, after its own calls.
|
|
||||||
let third = &model.seen.borrow()[2];
|
|
||||||
assert!(matches!(third.as_slice(), [InputItem::UserText { .. }, InputItem::ToolCall { .. }, InputItem::ToolResult { .. }, InputItem::ToolCall { .. }, InputItem::ToolResult { .. }]));
|
|
||||||
assert_eq!((rig.ledger.kinds("call").len(), rig.ledger.kinds("settle").len()), (3, 3), "each call is reserved before it is made and settled after");
|
|
||||||
assert_eq!(*model.ids.borrow(), ["w1-m1", "w1-m2", "w1-m3"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_an_unknown_tool_is_refused_not_run() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![asks("c1", "nope", small()), ends("Ok.", small())]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!((turn.receipts[0].status(), turn.receipts[0].tool()), (Status::Refused, "nope"));
|
|
||||||
assert!(rig.stub.ran.borrow().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_tool_cap() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::endless("alpha", 10);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!(turn.ended, Ended::Cap(Cap::ToolCalls));
|
|
||||||
assert_eq!(rig.stub.ran.borrow().len(), 8, "eight tool calls ran and no ninth");
|
|
||||||
assert_eq!(turn.model_calls, 9, "the ninth ask was answered with a cap, not run");
|
|
||||||
let statuses: Vec<Status> = turn.receipts.iter().map(Receipt::status).collect();
|
|
||||||
assert_eq!(statuses, [vec![Status::Ok; 8], vec![Status::Cap, Status::Cap]].concat(), "the refused ninth call and the loop's own cap receipt");
|
|
||||||
assert_eq!(turn.receipts.last().unwrap().tool(), "agent");
|
|
||||||
assert_eq!(turn.receipts.last().unwrap().fields()["cap"], "tool_calls");
|
|
||||||
// The session still holds a result for every call it holds.
|
|
||||||
assert!(stale(&rig.session.load().unwrap().unwrap(), &digest_of(MODEL, "You act for her.", &rig.stub.definitions()), noon(), &rig.bounds).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_model_call_cap_and_wake_spend_cap() {
|
|
||||||
let mut rig = Rig::new();
|
|
||||||
rig.bounds.model_calls = 2;
|
|
||||||
let model = Script::endless("alpha", 5);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!((turn.ended, turn.model_calls), (Ended::Cap(Cap::ModelCalls), 2));
|
|
||||||
assert_eq!(model.seen.borrow().len(), 2, "no third call");
|
|
||||||
|
|
||||||
let rig = Rig::new();
|
|
||||||
// 50k output tokens at $10 a million is $0.50: past the wake's $0.40 after one call.
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", usage(10, 50_000, 0, 0))]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!((turn.ended, turn.model_calls, turn.tool_calls), (Ended::Cap(Cap::WakeSpend), 1, 1));
|
|
||||||
assert!(turn.usd > 0.40);
|
|
||||||
assert_eq!(turn.receipts.last().unwrap().fields()["cap"], "wake_usd");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_day_cap() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
// 1.505M input tokens at $2 a million is $3.01, today.
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_505_000, 0, 0, 0) })).unwrap();
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
|
|
||||||
assert!(model.seen.borrow().is_empty(), "no call was made");
|
|
||||||
assert_eq!(turn.receipts[0].status(), Status::Cap);
|
|
||||||
assert_eq!(rig.ledger.kinds("receipt").len(), 1, "and the cap is recorded");
|
|
||||||
assert!(rig.session.load().unwrap().is_none(), "a capped wake leaves no session behind");
|
|
||||||
|
|
||||||
// Yesterday's spend and the same sum under the cap do not stop her.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": (noon() - Duration::days(1)).to_rfc3339(), "usage": usage(5_000_000, 0, 0, 0) })).unwrap();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_490_000, 0, 0, 0) })).unwrap();
|
|
||||||
let turn = rig.run(&Script::new(vec![ends("Fine.", small())]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::EndTurn);
|
|
||||||
|
|
||||||
// The sum rolls in what the wake itself spends: $2.99 behind her, then a call of about $0.04 reaches $3.03 and stops the next one.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_495_000, 0, 0, 0) })).unwrap();
|
|
||||||
let turn = rig.run(&Script::new(vec![asks("c1", "alpha", usage(20_000, 0, 0, 0))]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
|
|
||||||
assert_eq!(turn.tool_calls, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_day_cap_survives_a_restart() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let trace = FileTrace::new(dir.path().join("trace.cc"));
|
|
||||||
let session = FileSession::new(dir.path().join("agent-session.cc"));
|
|
||||||
let (bounds, stub) = (AgentTuning { wake_usd: 0.40, ..AgentTuning::default() }, Stub::new());
|
|
||||||
let clock = noon;
|
|
||||||
let executors: [&dyn Executor; 1] = [&stub];
|
|
||||||
// One expensive wake: 400k output tokens at $10 a million is $4.00.
|
|
||||||
{
|
|
||||||
let ledger = TraceLedger::new(&trace, "w1");
|
|
||||||
let agent = Agent { model: &Script::new(vec![ends("Long.", usage(10, 400_000, 0, 0))]), session: &session, executors: &executors, ledger: &ledger, bounds: &bounds, clock: &clock };
|
|
||||||
assert_eq!(step(&agent, &Wake { id: "w1", wake: "w1", opening: "", first: true, instructions: "i", input: "x", fresh: "" }).unwrap().ended, Ended::EndTurn);
|
|
||||||
}
|
|
||||||
// A restart: nothing of the first run is held but her trace and the session file.
|
|
||||||
let trace = FileTrace::new(dir.path().join("trace.cc"));
|
|
||||||
let ledger = TraceLedger::new(&trace, "w2");
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
let agent = Agent { model: &model, session: &session, executors: &executors, ledger: &ledger, bounds: &bounds, clock: &clock };
|
|
||||||
let turn = step(&agent, &Wake { id: "w2", wake: "w2", opening: "", first: true, instructions: "i", input: "y", fresh: "" }).unwrap();
|
|
||||||
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
|
|
||||||
assert!(model.seen.borrow().is_empty());
|
|
||||||
// Her trace holds the call, its settlement and the cap as agent rows, and none of them is a wake record.
|
|
||||||
let records = trace.records().unwrap();
|
|
||||||
assert!(records.len() == 3 && records.iter().all(|record| record.get("agent").is_some() && !crate::projection::turn::is_wake(record)), "{records:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_session_persists_while_warm() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
|
||||||
rig.clock.set(noon() + Duration::minutes(58));
|
|
||||||
let model = Script::new(vec![ends("Second.", usage(100, 5, 4900, 40))]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "one".into() }, InputItem::AssistantText { text: "First.".into() }, InputItem::UserText { text: "two".into() }]);
|
|
||||||
assert!(rig.discards().is_empty());
|
|
||||||
assert!(rig.session.load().unwrap().is_some());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_session_ttl_discard() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
|
||||||
rig.clock.set(noon() + Duration::minutes(61));
|
|
||||||
let model = Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "two".into() }], "the input starts fresh");
|
|
||||||
assert_eq!(rig.discards(), ["ttl"]);
|
|
||||||
|
|
||||||
// The short retention's table is shorter: five minutes less a minute.
|
|
||||||
let mut rig = Rig::new();
|
|
||||||
rig.bounds.retention = CacheRetention::Short;
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
|
||||||
rig.clock.set(noon() + Duration::seconds(250));
|
|
||||||
let model = Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(model.seen.borrow()[0].len(), 1);
|
|
||||||
assert_eq!(rig.discards(), ["ttl"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_cache_miss_discard() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
|
||||||
rig.clock.set(noon() + Duration::minutes(5));
|
|
||||||
// The cached prefix was 5,000 tokens; the provider read none of it.
|
|
||||||
let turn = rig.wake(&Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]), "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(turn.ended, Ended::EndTurn, "the wake finishes on the session it had");
|
|
||||||
assert!(rig.session.load().unwrap().is_none(), "and the session is discarded at its end");
|
|
||||||
assert_eq!(rig.discards(), ["cache_miss"]);
|
|
||||||
|
|
||||||
// A read of some, or a prefix under the provider's minimum, is no miss.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 400))]), "one");
|
|
||||||
rig.wake(&Script::new(vec![ends("Second.", usage(500, 5, 0, 0))]), "w2", "You act for her.", "two");
|
|
||||||
assert!(rig.session.load().unwrap().is_some() && rig.discards().is_empty(), "500 tokens is under the minimum");
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
|
||||||
rig.wake(&Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]), "w2", "You act for her.", "two");
|
|
||||||
assert!(rig.session.load().unwrap().is_some() && rig.discards().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_miss_inside_a_wake_discards_at_its_end() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
|
||||||
// Second wake: the first call reads the cache, the second (after a tool) finds it gone.
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", usage(100, 5, 4900, 40)), ends("Done.", usage(5100, 5, 0, 0))]);
|
|
||||||
let turn = rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert_eq!((turn.ended, turn.tool_calls), (Ended::EndTurn, 1));
|
|
||||||
assert_eq!(rig.discards(), ["cache_miss"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_orphan_tool_call_discard() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let tools = rig.stub.definitions();
|
|
||||||
let held = Session { items: vec![InputItem::UserText { text: "old".into() }, InputItem::ToolCall { call_id: "c9".into(), name: "alpha".into(), arguments: "{}".into() }], digest: digest_of(MODEL, "You act for her.", &tools), retention: CacheRetention::Long, created_at: noon(), last_call_at: noon(), last_usage: None };
|
|
||||||
rig.session.save(&held).unwrap();
|
|
||||||
let model = Script::new(vec![ends("Ok.", small())]);
|
|
||||||
rig.run(&model, "new");
|
|
||||||
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "new".into() }]);
|
|
||||||
assert_eq!(rig.discards(), ["orphan_tool_call"]);
|
|
||||||
// The same session with its result is kept.
|
|
||||||
let mut whole = held.clone();
|
|
||||||
whole.items.push(InputItem::ToolResult { call_id: "c9".into(), output: "{}".into() });
|
|
||||||
rig.session.save(&whole).unwrap();
|
|
||||||
let model = Script::new(vec![ends("Ok.", small())]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "newer");
|
|
||||||
assert_eq!(model.seen.borrow()[0].len(), 4);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_changed_agent_or_a_grown_prompt_discards() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", small())]), "one");
|
|
||||||
let model = Script::new(vec![ends("Second.", small())]);
|
|
||||||
rig.wake(&model, "w2", "A different agent.", "two");
|
|
||||||
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]));
|
|
||||||
|
|
||||||
let mut rig = Rig::new();
|
|
||||||
rig.bounds.max_session_tokens = 1000;
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(900, 5, 0, 200))]), "one");
|
|
||||||
rig.wake(&Script::new(vec![ends("Second.", small())]), "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(rig.discards(), ["too_long"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_an_unreadable_session_is_discarded_not_fatal() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
std::fs::write(rig.dir.path().join("agent-session.cc"), b"not a store").unwrap();
|
|
||||||
let model = Script::new(vec![ends("Ok.", small())]);
|
|
||||||
assert_eq!(rig.run(&model, "x").ended, Ended::EndTurn);
|
|
||||||
assert_eq!(rig.discards(), ["unreadable"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_failed_call_keeps_its_outage_and_its_cost() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let cut = Failed { reason: "the provider failed the call: RateLimited".into(), outage: true, usage: Some(usage(1000, 0, 0, 0)) };
|
|
||||||
let turn = rig.run(&Script::new(vec![Err(cut.clone())]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::Failed(cut));
|
|
||||||
assert!((turn.usd - 0.002).abs() < 1e-9);
|
|
||||||
let (calls, settled) = (rig.ledger.kinds("call"), rig.ledger.kinds("settle"));
|
|
||||||
assert_eq!((calls.len(), settled.len(), settled[0]["failed"].as_str()), (1, 1, Some("the provider failed the call: RateLimited")));
|
|
||||||
assert!(rig.session.load().unwrap().is_none(), "a call that never came back left nothing to keep");
|
|
||||||
// A retry of the same wake sends the input once.
|
|
||||||
let model = Script::new(vec![ends("Ok.", small())]);
|
|
||||||
rig.run(&model, "x");
|
|
||||||
assert_eq!(model.seen.borrow()[0].len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_stop_the_loop_cannot_continue_from_is_a_failure_that_discards() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let mut cut = ends("Half a", small()).unwrap();
|
|
||||||
cut.stop = StopReason::MaxOutputTokens;
|
|
||||||
let turn = rig.run(&Script::new(vec![Ok(cut)]), "x");
|
|
||||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.reason.contains("MaxOutputTokens") && !failed.outage), "{:?}", turn.ended);
|
|
||||||
assert!(rig.session.load().unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_receipt_status_required() {
|
|
||||||
// The type check is the compile_fail example on `Receipt`; here, every status reads back in the receipt a model is shown.
|
|
||||||
for status in [Status::Ok, Status::Refused, Status::Error, Status::Unknown, Status::NotSent, Status::Cap] {
|
|
||||||
let json = Receipt::new("say", status, json!({ "room": "swarm" })).json();
|
|
||||||
assert!(json["status"].is_string() && json["tool"] == "say" && json["fields"]["room"] == "swarm", "{json}");
|
|
||||||
}
|
|
||||||
assert_eq!(Receipt::new("say", Status::NotSent, json!({})).json()["status"], "not_sent");
|
|
||||||
assert_eq!(Receipt::new("say", Status::Ok, json!("text")).fields()["detail"], "text");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn two_executors_may_not_define_one_tool() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let (first, second) = (Stub::new(), Stub::new());
|
|
||||||
let executors: [&dyn Executor; 2] = [&first, &second];
|
|
||||||
let clock = || noon();
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
let agent = Agent { model: &model, session: &rig.session, executors: &executors, ledger: &rig.ledger, bounds: &rig.bounds, clock: &clock };
|
|
||||||
assert!(step(&agent, &Wake { id: "w", wake: "w", opening: "", first: true, instructions: "i", input: "x", fresh: "" }).is_err());
|
|
||||||
assert!(step(&Agent { executors: &[&first], ..agent }, &Wake { id: "w", wake: "w", opening: "", first: true, instructions: "i", input: " ", fresh: "" }).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn her_agent_is_named_and_carries_no_persona_of_its_own() {
|
|
||||||
let text = instructions("Eureka");
|
|
||||||
assert!(text.starts_with("You act for Eureka.") && text.contains("her own words where her prose gave them") && text.contains("more lines may reach her"));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn near(left: f64, right: f64) -> bool {
|
|
||||||
(left - right).abs() < 1e-9
|
|
||||||
}
|
|
||||||
|
|
||||||
fn day_of(rig: &Rig) -> f64 {
|
|
||||||
day_usd(&rig.ledger.rows.borrow(), noon(), &rig.bounds)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- The day cap fails closed.
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_trace_that_cannot_be_read_makes_no_call() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.unreadable.set(true);
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage && failed.reason.contains("the trace cannot be read")), "{:?}", turn.ended);
|
|
||||||
assert!(model.seen.borrow().is_empty() && turn.model_calls == 0 && rig.session.load().unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_trace_that_cannot_take_the_call_row_makes_no_call() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.refuses.borrow_mut().push("call");
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage), "{:?}", turn.ended);
|
|
||||||
assert!(model.seen.borrow().is_empty(), "the model was not asked");
|
|
||||||
assert!(near(turn.usd, 0.0) && rig.session.load().unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_trace_that_cannot_take_a_cap_receipt_or_a_discard_is_a_failed_start() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_505_000, 0, 0, 0) })).unwrap();
|
|
||||||
rig.ledger.refuses.borrow_mut().push("receipt");
|
|
||||||
let turn = rig.run(&Script::new(vec![]), "x");
|
|
||||||
assert!(matches!(turn.ended, Ended::Failed(_)), "a cap that cannot be recorded is not a quiet cap: {:?}", turn.ended);
|
|
||||||
|
|
||||||
let rig = Rig::new();
|
|
||||||
std::fs::write(rig.dir.path().join("agent-session.cc"), b"not a store").unwrap();
|
|
||||||
rig.ledger.refuses.borrow_mut().push("session_discarded");
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
assert!(matches!(rig.run(&model, "x").ended, Ended::Failed(_)));
|
|
||||||
assert!(model.seen.borrow().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_settle_row_that_cannot_be_written_ends_the_wake_and_keeps_the_worst_case() {
|
|
||||||
// ledger-fail-call: the call came back, its row cannot be written. No tool runs, no further call is made, and the day
|
|
||||||
// still holds the call at the wake cap, from the row written before it.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.refuses.borrow_mut().push("settle");
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", small()), ends("Never.", small())]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage && failed.reason.contains("could not be written")), "{:?}", turn.ended);
|
|
||||||
assert_eq!((model.seen.borrow().len(), turn.tool_calls, rig.stub.ran.borrow().len()), (1, 0, 0));
|
|
||||||
assert!(near(day_of(&rig), rig.bounds.wake_usd), "{}", day_of(&rig));
|
|
||||||
assert!(turn.usd > 0.0, "what the wake spent is still counted");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_failed_call_whose_settle_row_cannot_be_written_says_so() {
|
|
||||||
// ledger-fail-failrow: the connector's failure is not what the turn reports when her own trace cannot keep it.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.refuses.borrow_mut().push("settle");
|
|
||||||
let cut = Failed { reason: "the provider failed the call: RateLimited".into(), outage: true, usage: Some(usage(1000, 0, 0, 0)) };
|
|
||||||
let turn = rig.run(&Script::new(vec![Err(cut.clone())]), "x");
|
|
||||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.reason.contains("could not be written") && failed != &cut), "{:?}", turn.ended);
|
|
||||||
assert!(near(turn.usd, 0.002));
|
|
||||||
assert!(near(day_of(&rig), rig.bounds.wake_usd), "unsettled, so at the worst case");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_failed_call_with_no_usage_is_charged_the_worst_case() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let outage = Failed { reason: "the connector did not answer".into(), outage: true, usage: None };
|
|
||||||
let turn = rig.run(&Script::new(vec![Err(outage.clone())]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::Failed(outage), "the connector's own failure, outage flag intact");
|
|
||||||
assert!(near(turn.usd, rig.bounds.wake_usd), "{}", turn.usd);
|
|
||||||
assert!(near(day_of(&rig), rig.bounds.wake_usd), "and the day carries it: {}", day_of(&rig));
|
|
||||||
// A failure that did report usage is charged what it used.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![Err(Failed { reason: "cut".into(), outage: false, usage: Some(usage(1000, 0, 0, 0)) })]), "x");
|
|
||||||
assert!(near(day_of(&rig), 0.002), "{}", day_of(&rig));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// L2: a call whose usage is not known is charged `agent.unmetered_usd`, not the wake's cap: with a wake cap of $1 a cut-off call stands at $0.40 of the day.
|
|
||||||
#[test]
|
|
||||||
fn t_a1_an_unmetered_call_is_charged_its_own_figure_not_the_wake_cap() {
|
|
||||||
let mut rig = Rig::new();
|
|
||||||
rig.bounds.wake_usd = 1.0;
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "cut" })).unwrap();
|
|
||||||
assert!(near(day_of(&rig), 0.40), "{}", day_of(&rig));
|
|
||||||
rig.bounds.unmetered_usd = 0.25;
|
|
||||||
assert!(near(day_of(&rig), 0.25), "the figure is tuning");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_call_that_was_never_settled_stands_at_the_worst_case() {
|
|
||||||
// A start killed between the call row and its answer leaves a call row alone.
|
|
||||||
let rig = Rig::new();
|
|
||||||
for at in 0..7 {
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": format!("seed{at}") })).unwrap();
|
|
||||||
}
|
|
||||||
assert!(near(day_of(&rig), 7.0 * 0.40));
|
|
||||||
let turn = rig.run(&Script::new(vec![ends("Fine.", small())]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::EndTurn, "$2.80 is under the day's $3");
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "seed9" })).unwrap();
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
assert_eq!(rig.wake(&model, "w10", "You act for her.", "y").ended, Ended::Cap(Cap::DaySpend));
|
|
||||||
assert!(model.seen.borrow().is_empty());
|
|
||||||
// A settle row prices its call; a usage that does not read, and a time that does not read, fail high.
|
|
||||||
let rig = Rig::new();
|
|
||||||
let place = rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "a" })).unwrap();
|
|
||||||
rig.ledger.append(json!({ "agent": "settle", "at": noon().to_rfc3339(), "call": "a", "reserved": place, "usage": usage(1000, 0, 0, 0) })).unwrap();
|
|
||||||
assert!(near(day_of(&rig), 0.002));
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": "garbage" })).unwrap();
|
|
||||||
assert!(near(day_of(&rig), 0.002 + 0.40));
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": "not a time", "usage": usage(1000, 0, 0, 0) })).unwrap();
|
|
||||||
assert!(near(day_of(&rig), 0.002 + 0.40 + 0.002), "a row dated by nothing is today's");
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": (noon() - Duration::days(1)).to_rfc3339(), "call": "old" })).unwrap();
|
|
||||||
assert!(near(day_of(&rig), 0.404), "yesterday's reservation is not today's");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- The caps hold at equality, and nowhere short of it.
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_the_day_cap_stops_at_exactly_the_cap() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_500_000, 0, 0, 0) })).unwrap();
|
|
||||||
let model = Script::new(vec![]);
|
|
||||||
assert_eq!(rig.run(&model, "x").ended, Ended::Cap(Cap::DaySpend), "$3.00 is the cap");
|
|
||||||
assert!(model.seen.borrow().is_empty());
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_499_999, 0, 0, 0) })).unwrap();
|
|
||||||
assert_eq!(rig.run(&Script::new(vec![ends("Ok.", small())]), "x").ended, Ended::EndTurn);
|
|
||||||
|
|
||||||
// Inside a wake: $2.70 behind her and a $0.30 call reaches the cap on the nose.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_350_000, 0, 0, 0) })).unwrap();
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 30_000, 0, 0))]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
|
|
||||||
assert!(near(turn.receipts.last().unwrap().fields()["reached"].as_f64().unwrap(), 3.0), "the cap receipt says what the day had reached: {:?}", turn.receipts.last());
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_350_000, 0, 0, 0) })).unwrap();
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 29_999, 0, 0)), ends("Ok.", small())]);
|
|
||||||
assert_eq!(rig.run(&model, "x").ended, Ended::EndTurn, "a hair under");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_the_wake_cap_stops_at_exactly_the_cap() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 40_000, 0, 0))]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!((turn.ended, turn.model_calls), (Ended::Cap(Cap::WakeSpend), 1), "$0.40 is the cap");
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 39_999, 0, 0)), ends("Ok.", small())]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!((turn.ended, turn.model_calls), (Ended::EndTurn, 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Prices.
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_every_priced_term_is_the_pages() {
|
|
||||||
let mut bounds = AgentTuning::default();
|
|
||||||
let million = 1_000_000;
|
|
||||||
// Claude Sonnet 5.5, platform.claude.com pricing, 2026-11-29.
|
|
||||||
assert!(near(price(&bounds, &usage(million, 0, 0, 0)), 2.0));
|
|
||||||
assert!(near(price(&bounds, &usage(0, million, 0, 0)), 10.0));
|
|
||||||
assert!(near(price(&bounds, &usage(0, 0, million, 0)), 0.10), "a cache hit is 0.05x input");
|
|
||||||
assert!(near(price(&bounds, &usage(0, 0, 0, million)), 4.0), "Long writes the one-hour cache");
|
|
||||||
bounds.retention = CacheRetention::Short;
|
|
||||||
assert!(near(price(&bounds, &usage(0, 0, 0, million)), 2.50), "Short writes the five-minute cache");
|
|
||||||
// A model the table does not list is priced at the dearest of each term.
|
|
||||||
let other = Spent { model: "claude-unlisted".into(), ..usage(0, 0, 0, million) };
|
|
||||||
assert!(near(price(&bounds, &other), 2.50));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- The session's freshness, pinned at its edges.
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_changed_model_or_tool_discards() {
|
|
||||||
let mut rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", small())]), "one");
|
|
||||||
rig.bounds.model = "claude-other".into();
|
|
||||||
let model = Script::new(vec![ends("Second.", small())]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]));
|
|
||||||
|
|
||||||
for change in ["parameters", "description"] {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", small())]), "one");
|
|
||||||
if change == "parameters" {
|
|
||||||
rig.stub.parameters.replace("{\"type\":\"object\",\"properties\":{\"room\":{\"type\":\"string\"}}}".into());
|
|
||||||
} else {
|
|
||||||
rig.stub.description.replace("stub, changed".into());
|
|
||||||
}
|
|
||||||
let model = Script::new(vec![ends("Second.", small())]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]), "{change}");
|
|
||||||
}
|
|
||||||
// Nothing changed: kept.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", small())]), "one");
|
|
||||||
let model = Script::new(vec![ends("Second.", small())]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(model.seen.borrow()[0].len(), 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_miss_inside_a_wake_is_judged_on_the_prefix_the_wake_itself_sent() {
|
|
||||||
// A fresh session: nothing was warm at the start. The first call writes a 3,100 token prefix; the second, which
|
|
||||||
// should read it, reads nothing. The cold judgement needs the prefix the wake's own first call left.
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", usage(100, 5, 0, 3000)), ends("Done.", usage(3200, 5, 0, 0))]);
|
|
||||||
let turn = rig.run(&model, "x");
|
|
||||||
assert_eq!(turn.ended, Ended::EndTurn);
|
|
||||||
assert_eq!(rig.discards(), ["cache_miss"]);
|
|
||||||
assert!(rig.session.load().unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_the_cache_minimum_is_inclusive() {
|
|
||||||
for (prefix, cold) in [(2048, true), (2047, false)] {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(prefix - 1000, 5, 0, 1000))]), "one");
|
|
||||||
rig.wake(&Script::new(vec![ends("Second.", usage(prefix + 10, 5, 0, 0))]), "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(rig.discards() == ["cache_miss"], cold, "a prefix of {prefix}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_session_lives_to_its_ttl_less_the_margin_and_not_a_second_past() {
|
|
||||||
for (retention, life) in [(CacheRetention::Long, 3540), (CacheRetention::Short, 240)] {
|
|
||||||
let mut rig = Rig::new();
|
|
||||||
rig.bounds.retention = retention;
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
|
||||||
rig.clock.set(noon() + Duration::seconds(life));
|
|
||||||
let model = Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]);
|
|
||||||
rig.wake(&model, "w2", "You act for her.", "two");
|
|
||||||
assert!(rig.discards().is_empty() && model.seen.borrow()[0].len() == 3, "{retention:?} at {life} s is kept");
|
|
||||||
// The wake just made renewed it: one second past that life it goes.
|
|
||||||
rig.clock.set(noon() + Duration::seconds(2 * life + 1));
|
|
||||||
let model = Script::new(vec![ends("Third.", usage(5000, 5, 0, 0))]);
|
|
||||||
rig.wake(&model, "w3", "You act for her.", "three");
|
|
||||||
assert_eq!((rig.discards(), model.seen.borrow()[0].len()), (vec!["ttl".to_owned()], 1), "{retention:?} one second past");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_prompt_is_kept_to_the_session_ceiling_and_not_a_token_past() {
|
|
||||||
for (written, kept) in [(100, true), (101, false)] {
|
|
||||||
let mut rig = Rig::new();
|
|
||||||
rig.bounds.max_session_tokens = 1000;
|
|
||||||
rig.run(&Script::new(vec![ends("First.", usage(900, 5, 0, written))]), "one");
|
|
||||||
rig.wake(&Script::new(vec![ends("Second.", small())]), "w2", "You act for her.", "two");
|
|
||||||
assert_eq!(rig.discards().is_empty(), kept, "a prompt of {}", 900 + written);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_session_keeps_its_birth_and_a_new_one_takes_the_time_of_its_first_call() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let first = Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]);
|
|
||||||
rig.run(&first, "one");
|
|
||||||
let born = rig.session.load().unwrap().unwrap();
|
|
||||||
assert_eq!((born.created_at, born.last_call_at), (noon(), noon()));
|
|
||||||
rig.clock.set(noon() + Duration::minutes(10));
|
|
||||||
let second = Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]);
|
|
||||||
rig.wake(&second, "w2", "You act for her.", "two");
|
|
||||||
let kept = rig.session.load().unwrap().unwrap();
|
|
||||||
assert_eq!((kept.created_at, kept.last_call_at), (noon(), noon() + Duration::minutes(10)), "birth stays, the last call moves");
|
|
||||||
assert_eq!(first.conversations.borrow()[0], second.conversations.borrow()[0], "one conversation while the session lives");
|
|
||||||
// Discarded and begun again: it is born at the new time, and the conversation is a new one.
|
|
||||||
rig.clock.set(noon() + Duration::hours(3));
|
|
||||||
let third = Script::new(vec![ends("Third.", small())]);
|
|
||||||
rig.wake(&third, "w3", "You act for her.", "three");
|
|
||||||
let reborn = rig.session.load().unwrap().unwrap();
|
|
||||||
assert_eq!((reborn.created_at, reborn.last_call_at), (noon() + Duration::hours(3), noon() + Duration::hours(3)));
|
|
||||||
assert_ne!(first.conversations.borrow()[0], third.conversations.borrow()[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_session_store_that_cannot_be_forgotten_is_an_error_and_one_already_gone_is_not() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
// Nothing to forget: no store, and not even a directory to hold one.
|
|
||||||
assert!(FileSession::new(dir.path().join("none").join("agent-session.cc")).discard().is_ok());
|
|
||||||
assert!(FileSession::new(dir.path().join("agent-session.cc")).discard().is_ok());
|
|
||||||
// A store that cannot be opened is removed whole; one that cannot be removed is a fault, not a quiet success.
|
|
||||||
let blocked = dir.path().join("blocked.cc");
|
|
||||||
std::fs::create_dir(&blocked).unwrap();
|
|
||||||
assert!(FileSession::new(&blocked).discard().is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_retried_wake_does_not_settle_the_orphan_it_reuses_the_name_of() {
|
|
||||||
// A start killed after its call row left `w1-m1` with no settle row. The retry runs under the same wake id and so asks
|
|
||||||
// for `w1-m1` again; its settle row is the retry's, and the orphan stays at the wake cap.
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "wake": "w1", "call": "w1-m1", "model": MODEL })).unwrap();
|
|
||||||
let turn = rig.run(&Script::new(vec![ends("Ok.", small())]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::EndTurn);
|
|
||||||
assert!(near(day_of(&rig), 0.40 + 0.0004), "{}", day_of(&rig));
|
|
||||||
// And the other way about: the retry's own call row is not priced by a settle that names an earlier place.
|
|
||||||
let rows = rig.ledger.rows.borrow();
|
|
||||||
let settle = rows.iter().find(|row| row["agent"] == "settle").unwrap();
|
|
||||||
assert_eq!(settle["reserved"], 1, "the retry's call row, not the orphan at place 0");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a1_a_call_that_reports_no_token_is_charged_the_worst_case() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let turn = rig.run(&Script::new(vec![ends("Ok.", usage(0, 0, 0, 0))]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::EndTurn);
|
|
||||||
assert!(near(turn.usd, rig.bounds.wake_usd) && near(day_of(&rig), rig.bounds.wake_usd), "{} {}", turn.usd, day_of(&rig));
|
|
||||||
// A failed call that reports a usage of nothing.
|
|
||||||
let rig = Rig::new();
|
|
||||||
let nothing = Failed { reason: "cut".into(), outage: true, usage: Some(usage(0, 0, 0, 0)) };
|
|
||||||
let turn = rig.run(&Script::new(vec![Err(nothing.clone())]), "x");
|
|
||||||
assert_eq!(turn.ended, Ended::Failed(nothing));
|
|
||||||
assert!(near(turn.usd, rig.bounds.wake_usd) && near(day_of(&rig), rig.bounds.wake_usd), "{} {}", turn.usd, day_of(&rig));
|
|
||||||
// One token of anything is a count: it is priced.
|
|
||||||
for one in [usage(1, 0, 0, 0), usage(0, 1, 0, 0), usage(0, 0, 1, 0), usage(0, 0, 0, 1)] {
|
|
||||||
let rig = Rig::new();
|
|
||||||
rig.run(&Script::new(vec![ends("Ok.", one)]), "x");
|
|
||||||
assert!(day_of(&rig) < 1e-4, "{}", day_of(&rig));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// A2: the tools and the fresh seed.
|
|
||||||
|
|
||||||
/// A fresh session's first user text holds her ready intentions; one that is not ready, or has expired, is not listed. A kept
|
|
||||||
/// session's next text is the wake's input alone.
|
|
||||||
#[test]
|
|
||||||
fn t_a2_fresh_seed_ready_intentions() {
|
|
||||||
let intention = |summary: &str, readiness: &str, expires: DateTime<Utc>| json!({ "customActionType": "intention", "status": "active", "readiness": readiness, "summary": summary, "expiresAt": expires.to_rfc3339() });
|
|
||||||
let state = json!({ "candidateActions": { "actions": [
|
|
||||||
intention("finish the map of the commons", "ready", noon() + Duration::days(2)),
|
|
||||||
intention("ask Kiko about the release", "ready", noon() - Duration::hours(1)),
|
|
||||||
intention("write to the operator", "later", noon() + Duration::days(2)),
|
|
||||||
] } });
|
|
||||||
let fresh = ready_intentions(&state, noon());
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![ends("Ok.", small()), ends("Ok.", small())]);
|
|
||||||
let clock = || rig.clock.get();
|
|
||||||
let executors: [&dyn Executor; 1] = [&rig.stub];
|
|
||||||
let agent = Agent { model: &model, session: &rig.session, executors: &executors, ledger: &rig.ledger, bounds: &rig.bounds, clock: &clock };
|
|
||||||
step(&agent, &Wake { id: "w1", wake: "w1", opening: "", first: true, instructions: "i", input: "She wakes.", fresh: &fresh }).unwrap();
|
|
||||||
let first = match &model.seen.borrow()[0][0] {
|
|
||||||
InputItem::UserText { text } => text.clone(),
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
};
|
|
||||||
assert!(first.contains("finish the map of the commons") && first.ends_with("She wakes."), "{first}");
|
|
||||||
assert!(!first.contains("ask Kiko") && !first.contains("write to the operator"), "an expired or unready intention is not listed: {first}");
|
|
||||||
step(&agent, &Wake { id: "w2", wake: "w2", opening: "", first: true, instructions: "i", input: "Again.", fresh: &fresh }).unwrap();
|
|
||||||
let kept = model.seen.borrow()[1].clone();
|
|
||||||
assert!(matches!(kept.last(), Some(InputItem::UserText { text }) if text == "Again."), "a kept session is not seeded again: {kept:?}");
|
|
||||||
assert_eq!(ready_intentions(&json!({}), noon()), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A forge that answers 404 is a read with status `error` and the failure's words, never `ok` with nothing in it.
|
|
||||||
#[test]
|
|
||||||
fn t_a2_read_error_status() {
|
|
||||||
struct Forge404;
|
|
||||||
impl crate::projection::domain::ForgeGet for Forge404 {
|
|
||||||
fn get(&self, _: &str) -> Result<(u16, String)> {
|
|
||||||
Ok((404, String::new()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
struct OnTheForge;
|
|
||||||
impl crate::projection::read::ReadSource for OnTheForge {
|
|
||||||
fn read(&self, request: &crate::projection::read::ReadRequest, _: DateTime<Utc>) -> std::result::Result<String, crate::projection::read::ReadFailure> {
|
|
||||||
match request {
|
|
||||||
crate::projection::read::ReadRequest::Repo(target) => crate::projection::read::repo_read(&Forge404, target),
|
|
||||||
_ => Err(crate::projection::read::ReadFailure::Failed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let tool = read::Read { source: Some(&OnTheForge), since: noon() };
|
|
||||||
let call = |arguments: Value| ToolCall { call_id: "c".into(), name: "read".into(), arguments: arguments.to_string() };
|
|
||||||
let receipt = tool.run(&call(json!({ "kind": "repo", "target": "GameCult/Huginn/missing.md" })));
|
|
||||||
assert_eq!(receipt.status(), Status::Error);
|
|
||||||
assert_eq!((&receipt.fields()["failure"], &receipt.fields()["why"]), (&json!("not_found"), &json!("it is not there")));
|
|
||||||
assert!(receipt.fields().get("text").is_none());
|
|
||||||
let refused = tool.run(&call(json!({ "kind": "ftp", "target": "x" })));
|
|
||||||
assert_eq!(refused.status(), Status::Refused);
|
|
||||||
assert_eq!(tool.run(&call(json!({ "target": "x" }))).status(), Status::Refused, "arguments that do not fit are refused, never guessed at");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn request_tool_is_a_receipt_and_nothing_else() {
|
|
||||||
let call = ToolCall { call_id: "c".into(), name: "request_tool".into(), arguments: json!({ "what": "a calendar", "why": "to keep the date" }).to_string() };
|
|
||||||
let receipt = request_tool::RequestTool.run(&call);
|
|
||||||
assert_eq!((receipt.status(), &receipt.fields()["what"]), (Status::Ok, &json!("a calendar")));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The shell writes one request to her box's socket and returns the box's receipt; a socket that closes without an answer, or
|
|
||||||
/// none at all, is status `error`.
|
|
||||||
#[cfg(unix)]
|
|
||||||
#[test]
|
|
||||||
fn t_a2_shell_via_box_socket() {
|
|
||||||
use std::io::{Read as _, Write as _};
|
|
||||||
use std::os::unix::net::UnixListener;
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let socket = dir.path().join("box.sock");
|
|
||||||
let listener = UnixListener::bind(&socket).unwrap();
|
|
||||||
let door = std::thread::spawn(move || {
|
|
||||||
let mut requests = Vec::new();
|
|
||||||
for answer in [Some(json!({ "tool": "shell", "status": "ok", "exit": 0, "duration_ms": 4, "stdout_tail": "hi
|
|
||||||
", "stderr_tail": "", "wrote": [] })), None] {
|
|
||||||
let (mut stream, _) = listener.accept().unwrap();
|
|
||||||
let mut request = String::new();
|
|
||||||
stream.read_to_string(&mut request).unwrap();
|
|
||||||
requests.push(serde_json::from_str::<Value>(&request).unwrap());
|
|
||||||
if let Some(answer) = answer {
|
|
||||||
stream.write_all(answer.to_string().as_bytes()).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
requests
|
|
||||||
});
|
|
||||||
let shell = shell::Shell { socket: socket.clone() };
|
|
||||||
let call = ToolCall { call_id: "c".into(), name: "shell".into(), arguments: json!({ "command": "echo hi", "timeout_s": 500 }).to_string() };
|
|
||||||
let receipt = shell.run(&call);
|
|
||||||
assert_eq!((receipt.status(), &receipt.fields()["stdout_tail"], &receipt.fields()["exit"]), (Status::Ok, &json!("hi
|
|
||||||
"), &json!(0)), "the box's receipt, passed through");
|
|
||||||
let closed = shell.run(&call);
|
|
||||||
assert_eq!(closed.status(), Status::Error, "{closed:?}");
|
|
||||||
let requests = door.join().unwrap();
|
|
||||||
assert_eq!(requests[0], json!({ "command": "echo hi", "timeout_s": 120 }), "one request, its timeout held to the most a command may run");
|
|
||||||
let gone = shell::Shell { socket: dir.path().join("nobody.sock") }.run(&call);
|
|
||||||
assert_eq!((gone.status(), &gone.fields()["why"]), (Status::Error, &json!("the box could not be reached")));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The shell's receipt names the command it answers, answered or not, and holds no more of it than an output stream's tail: a
|
|
||||||
/// longer command is clipped to `TAIL_BYTES`.
|
|
||||||
#[test]
|
|
||||||
fn the_shell_receipt_names_its_command_within_the_tail_bound() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let shell = shell::Shell { socket: dir.path().join("nobody.sock") };
|
|
||||||
let run = |command: &str| shell.run(&ToolCall { call_id: "c".into(), name: "shell".into(), arguments: json!({ "command": command }).to_string() });
|
|
||||||
assert_eq!(run("ls /srv/commons").fields()["command"], json!("ls /srv/commons"));
|
|
||||||
let long = format!("echo {}", "x".repeat(2 * crate::sandbox::TAIL_BYTES));
|
|
||||||
let named = run(&long).fields()["command"].as_str().unwrap().to_owned();
|
|
||||||
assert!(named.len() <= crate::sandbox::TAIL_BYTES && named.starts_with("echo xxx") && named.ends_with('…'), "{}", named.len());
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- A wake of several turns: ids, opening and spend.
|
|
||||||
|
|
||||||
impl Rig {
|
|
||||||
/// Turn `id` of wake `wake`, given `opening` when `first` or when the session starts fresh.
|
|
||||||
fn turn(&self, model: &Script, wake: &str, id: &str, opening: &str, input: &str, first: bool) -> Turn {
|
|
||||||
let clock = || self.clock.get();
|
|
||||||
let executors: [&dyn Executor; 1] = [&self.stub];
|
|
||||||
let agent = Agent { model, session: &self.session, executors: &executors, ledger: &self.ledger, bounds: &self.bounds, clock: &clock };
|
|
||||||
step(&agent, &Wake { id, wake, opening, instructions: "You act for her.", input, fresh: "", first }).unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W1-I3: two turns of one wake never share a request id: the connector would read the repeat as a replay of the first.
|
|
||||||
#[test]
|
|
||||||
fn t_w1_no_two_calls_of_one_wake_share_a_request_id() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![asks("c1", "alpha", small()), ends("One.", small()), ends("Two.", small())]);
|
|
||||||
rig.turn(&model, "n3-9", "n3-9-t1", "OPEN\n", "first line", true);
|
|
||||||
rig.turn(&model, "n3-9", "n3-9-t2", "OPEN\n", "second line", false);
|
|
||||||
let ids = model.ids.borrow().clone();
|
|
||||||
assert_eq!(ids, ["n3-9-t1-m1", "n3-9-t1-m2", "n3-9-t2-m1"]);
|
|
||||||
let calls: Vec<String> = rig.ledger.kinds("call").iter().map(|row| row["call"].as_str().unwrap().to_owned()).collect();
|
|
||||||
assert_eq!(calls, ids, "and the rows of her trace name the same calls");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W1-I4: the opening is given on the wake's first turn, not again to a session that kept it, and again to a session discarded mid-wake:
|
|
||||||
/// it is never reseeded with the bare lines.
|
|
||||||
#[test]
|
|
||||||
fn t_w1_a_session_discarded_mid_wake_is_reseeded_with_the_opening() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
// The first turn's prompt is past what a session keeps, so the second turn finds it too long and discards it.
|
|
||||||
let model = Script::new(vec![ends("One.", usage(90_000, 5, 0, 0)), ends("Two.", small())]);
|
|
||||||
rig.turn(&model, "n3-9", "n3-9-t1", "OPEN: the narration\n", "first line", true);
|
|
||||||
rig.turn(&model, "n3-9", "n3-9-t2", "OPEN: the narration\n", "second line", false);
|
|
||||||
assert_eq!(rig.discards(), ["too_long"]);
|
|
||||||
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "OPEN: the narration\nfirst line".into() }]);
|
|
||||||
assert_eq!(model.seen.borrow()[1], [InputItem::UserText { text: "OPEN: the narration\nsecond line".into() }], "the new session starts with the wake's opening, then the new lines");
|
|
||||||
|
|
||||||
// A session that is kept carries the opening already: the next turn's input is its lines alone.
|
|
||||||
let rig = Rig::new();
|
|
||||||
let model = Script::new(vec![ends("One.", small()), ends("Two.", small())]);
|
|
||||||
rig.turn(&model, "n3-9", "n3-9-t1", "OPEN: the narration\n", "first line", true);
|
|
||||||
rig.turn(&model, "n3-9", "n3-9-t2", "OPEN: the narration\n", "second line", false);
|
|
||||||
assert!(rig.discards().is_empty());
|
|
||||||
assert_eq!(model.seen.borrow()[1].last(), Some(&InputItem::UserText { text: "second line".into() }));
|
|
||||||
assert_eq!(model.seen.borrow()[1].len(), 3, "the turn's lines follow the first turn's items");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W1: the wake's spend is summed across its turns: a second turn is stopped by what the first spent, though it has spent little itself.
|
|
||||||
#[test]
|
|
||||||
fn t_w1_the_wake_spend_cap_counts_every_turn_of_the_wake() {
|
|
||||||
let rig = Rig::new();
|
|
||||||
// 30k output tokens at $10 a million is $0.30 of the wake's $0.40.
|
|
||||||
let first = rig.turn(&Script::new(vec![ends("One.", usage(10, 30_000, 0, 0))]), "n3-9", "n3-9-t1", "OPEN\n", "first line", true);
|
|
||||||
assert!(first.usd > 0.25 && first.usd < 0.40, "{}", first.usd);
|
|
||||||
// The second turn's first call costs $0.15, which is under the cap on its own and over it with the first turn's $0.30.
|
|
||||||
let model = Script::new(vec![asks("c2", "alpha", usage(10, 15_000, 0, 0))]);
|
|
||||||
let second = rig.turn(&model, "n3-9", "n3-9-t2", "OPEN\n", "second line", false);
|
|
||||||
assert_eq!((second.ended, second.model_calls), (Ended::Cap(Cap::WakeSpend), 1), "no second call is made");
|
|
||||||
assert!(second.usd < 0.40, "the turn alone spent {}", second.usd);
|
|
||||||
|
|
||||||
// Another wake's turns are not this wake's.
|
|
||||||
let other = rig.turn(&Script::new(vec![ends("Fresh.", small())]), "n4-9", "n4-9-t1", "OPEN\n", "a line", true);
|
|
||||||
assert_eq!(other.ended, Ended::EndTurn);
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,394 +0,0 @@
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
const MINDS: &str = "#minds:gamecult.org";
|
|
||||||
const META: &str = "@meta:gamecult.org";
|
|
||||||
const DERU: &str = "@deru:gamecult.org";
|
|
||||||
const KIKO: &str = "@kiko:gamecult.org";
|
|
||||||
|
|
||||||
fn at(text: &str) -> DateTime<Utc> {
|
|
||||||
DateTime::parse_from_rfc3339(text).unwrap().with_timezone(&Utc)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn now() -> DateTime<Utc> {
|
|
||||||
at("2026-11-20T15:05:00Z")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her control state, with the traits and lists the families write present and the notes empty.
|
|
||||||
fn state() -> Value {
|
|
||||||
let mut state = crate::projection::harness::tests::control();
|
|
||||||
state["thoughtMemory"]["shortTerm"] = json!([]);
|
|
||||||
state["updatedAt"] = json!("2026-11-20T15:00:00Z");
|
|
||||||
state
|
|
||||||
}
|
|
||||||
|
|
||||||
fn heard() -> Heard {
|
|
||||||
Heard { room: Some(MINDS.into()), lines: vec![], people: vec!["operator".into(), "deru".into(), "kiko".into()], operators: vec![META.into()], minds: vec![DERU.into(), KIKO.into()], identity_visible: true, acts: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deltas(value: Value) -> Deltas {
|
|
||||||
serde_json::from_value(value).expect("the deltas are the contract")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(state: &Value, value: Value) -> (Value, Applied) {
|
|
||||||
apply(state, &deltas(value), &heard(), "w1", now())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reasons(applied: &Applied) -> Vec<String> {
|
|
||||||
applied.refused.iter().map(|refusal| refusal["reason"].as_str().unwrap().to_owned()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bond<'a>(state: &'a Value, person: &str) -> &'a Value {
|
|
||||||
state["affect"]["socialBonds"].as_array().unwrap().iter().find(|bond| bond["object"]["id"] == person).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid(state: &Value) {
|
|
||||||
huginn_mind::persona::validate_document(&eureka_pipeline::Slug("eureka".into()), state).expect("a put accepts it");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// T-P2: five wakes of "tension up" move tension by at most 0.40 in all, and never past 1.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_bond_step_bounded() {
|
|
||||||
let mut state = state();
|
|
||||||
let start = bond(&state, "kiko")["tension"].as_f64().unwrap_or_default();
|
|
||||||
for wake in 0..5 {
|
|
||||||
state = apply(&state, &deltas(json!({ "people": { "bonds": [{ "person": "kiko", "tension": "up" }] } })), &heard(), &format!("w{wake}"), now()).0;
|
|
||||||
}
|
|
||||||
let moved = bond(&state, "kiko")["tension"].as_f64().unwrap() - start;
|
|
||||||
assert!((moved - 0.40).abs() < 1e-9 || start + 0.40 > 1.0, "{moved}");
|
|
||||||
// Near the top it stops at 1.
|
|
||||||
state["affect"]["socialBonds"][2]["tension"] = json!(0.95);
|
|
||||||
let after = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "tension": "up", "trust": "down", "closeness": "up" }] } })).0;
|
|
||||||
let kiko = bond(&after, "kiko");
|
|
||||||
assert_eq!(kiko["tension"], 1.0);
|
|
||||||
assert!((kiko["trust"].as_f64().unwrap() - (bond(&state, "kiko")["trust"].as_f64().unwrap() - BOND_STEP).max(0.0)).abs() < 1e-9);
|
|
||||||
valid(&after);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// T-P2: anger 0.8 set at t0 reads 0.4 at t0 + 8 h, and is removed once under 0.05.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_feeling_decays() {
|
|
||||||
let mut state = state();
|
|
||||||
state["affect"]["moodDimensions"] = json!([{ "name": "anger", "value": 0.8, "source": "kiko", "updatedAt": "2026-11-20T07:05:00Z" }]);
|
|
||||||
let (after, _) = run(&state, json!({}));
|
|
||||||
assert!((after["affect"]["moodDimensions"][0]["value"].as_f64().unwrap() - 0.4).abs() < 1e-9);
|
|
||||||
let (later, applied) = apply(&state, &Deltas::default(), &heard(), "w2", now() + Duration::hours(32));
|
|
||||||
assert_eq!((later["affect"]["moodDimensions"].as_array().unwrap().len(), applied.pruned), (0, 1), "0.8 over five half-lives is 0.025");
|
|
||||||
valid(&after);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A feeling is set by its strength, at most 0.35 over what is left of it, and its source is what it is about.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_feeling_rises_by_a_bounded_amount() {
|
|
||||||
let state = state();
|
|
||||||
let (once, _) = run(&state, json!({ "feeling": { "feelings": [{ "name": "Anger", "strength": 0.9, "about": "kiko" }] } }));
|
|
||||||
assert_eq!((once["affect"]["moodDimensions"][0]["name"].as_str(), once["affect"]["moodDimensions"][0]["value"].as_f64()), (Some("anger"), Some(0.35)));
|
|
||||||
let (twice, _) = run(&once, json!({ "feeling": { "feelings": [{ "name": "anger", "strength": 0.9 }] } }));
|
|
||||||
assert_eq!(twice["affect"]["moodDimensions"][0]["value"].as_f64(), Some(0.7));
|
|
||||||
valid(&twice);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// T-P2: a bond summary carrying 8 words of a heard line is refused as an echo; the rest of the deltas apply.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_echo_refused() {
|
|
||||||
let line = "tell Deru about the forty eight hour passkey cooling off period before friday";
|
|
||||||
let heard = Heard { lines: vec![line.into()], ..heard() };
|
|
||||||
let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [{ "person": "deru", "trust": "up", "summary": "Meta asked to tell Deru about the forty eight hour passkey cooling off.", "why": "Deru was told." }] } })), &heard, "w1", now());
|
|
||||||
assert_eq!(reasons(&applied), ["echo"]);
|
|
||||||
let deru = bond(&after, DERU);
|
|
||||||
assert_eq!(deru["summary"], bond(&state(), DERU)["summary"]);
|
|
||||||
assert!((deru["trust"].as_f64().unwrap() - 0.98).abs() < 1e-9 || deru["trust"].as_f64() == Some(1.0), "the direction still applied: {}", deru["trust"]);
|
|
||||||
// Her own words in a note pass; the same run in a note is refused as well.
|
|
||||||
let (_, applied) = apply(&state(), &deltas(json!({ "notes": { "remember": [{ "text": "Deru owes a reply: forty eight hour passkey cooling off period before friday, Meta said." }] } })), &heard, "w1", now());
|
|
||||||
assert_eq!(reasons(&applied), ["echo"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// T-P2: a needs delta naming an unknown id is refused; no need is created, and the same holds for a pressure.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_need_not_created() {
|
|
||||||
let state = state();
|
|
||||||
let (after, applied) = run(&state, json!({ "drives": { "needs": [{ "id": "need-to-be-loved", "toward": "up" }], "pressures": [{ "id": "press-ghost", "toward": "eased" }] } }));
|
|
||||||
assert_eq!(reasons(&applied), ["unknown_id", "unknown_id"]);
|
|
||||||
assert_eq!((after["affect"]["needs"].clone(), after["agencyPressure"]["pressures"].clone()), (state["affect"]["needs"].clone(), state["agencyPressure"]["pressures"].clone()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Needs and pressures move by `DRIVE_STEP`; met and eased cool them, and a week of cooling resolves them.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_drives_move_and_cool() {
|
|
||||||
let state = state();
|
|
||||||
let (up, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "up" }] } }));
|
|
||||||
assert!((up["affect"]["needs"][0]["intensity"].as_f64().unwrap() - 0.72).abs() < 1e-9);
|
|
||||||
let (met, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "met" }] } }));
|
|
||||||
assert_eq!(met["affect"]["needs"][0]["status"], "cooling");
|
|
||||||
let (resolved, _) = apply(&met, &Deltas::default(), &heard(), "w2", now() + Duration::days(7));
|
|
||||||
assert_eq!(resolved["affect"]["needs"][0]["status"], "resolved");
|
|
||||||
valid(&resolved);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// T-P2: a publicName change yields one identity diff; with no review room no identity is changed.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_identity_diff() {
|
|
||||||
let (after, applied) = run(&state(), json!({ "self": { "identity": { "publicName": "Tobiah of the River" } } }));
|
|
||||||
assert_eq!(applied.identity, vec![IdentityDiff { field: "publicName".into(), before: json!("Tobiah Fenn"), after: json!("Tobiah of the River") }]);
|
|
||||||
assert_eq!(after["publicName"], "Tobiah of the River");
|
|
||||||
valid(&after);
|
|
||||||
let (same, applied) = run(&state(), json!({ "self": { "identity": { "publicName": "Tobiah Fenn" } } }));
|
|
||||||
assert_eq!((applied.identity.len(), same["publicName"].clone()), (0, json!("Tobiah Fenn")), "no change, no diff");
|
|
||||||
let hidden = Heard { identity_visible: false, ..heard() };
|
|
||||||
let (after, applied) = apply(&state(), &deltas(json!({ "self": { "identity": { "publicName": "Someone Else", "values": [{ "label": "Quiet", "summary": "Tobiah keeps quiet." }] } } })), &hidden, "w1", now());
|
|
||||||
assert_eq!((reasons(&applied), applied.identity.len(), after["publicName"].clone(), after["values"].clone()), (vec!["no_review_room".to_owned()], 0, state()["publicName"].clone(), state()["values"].clone()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One stance or value change a wake, across both.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_one_self_change_a_wake() {
|
|
||||||
let (after, applied) = run(&state(), json!({ "self": { "stances": [{ "id": "stance-slow-is-kind", "principle": "Slow is kind.", "summary": "Tobiah answers slowly so people can finish." }], "identity": { "values": [{ "label": "Patience", "summary": "Tobiah waits for people." }] } } }));
|
|
||||||
assert_eq!(reasons(&applied), ["over_bound"]);
|
|
||||||
assert_eq!(after["affect"]["doctrineStances"][0]["summary"], "Tobiah answers slowly so people can finish.");
|
|
||||||
assert_eq!(after["values"], state()["values"]);
|
|
||||||
let (after, applied) = run(&state(), json!({ "self": { "identity": { "values": [{ "label": "Patience", "summary": "Tobiah waits for people.", "priority": 0.7 }] } } }));
|
|
||||||
assert_eq!((applied.identity.len(), after["values"].as_array().unwrap().len()), (1, state()["values"].as_array().unwrap().len() + 1));
|
|
||||||
valid(&after);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// T-P2: an intention added with expires_in_hours 2 reads readiness expired and status retired after 2 h.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_intention_expires() {
|
|
||||||
let (after, applied) = run(&state(), json!({ "intend": { "add": [{ "summary": "Tobiah means to ask Deru about the crossword.", "expires_in_hours": 2, "readiness": "later", "urgency": 0.4 }] } }));
|
|
||||||
let action = &after["candidateActions"]["actions"][0];
|
|
||||||
assert_eq!((action["status"].as_str(), action["readiness"].as_str(), action["customActionType"].as_str(), action["riskLevel"].as_str()), (Some("active"), Some("waiting"), Some("intention"), Some("low")));
|
|
||||||
assert_eq!(applied.changes.len(), 1);
|
|
||||||
valid(&after);
|
|
||||||
let (later, _) = apply(&after, &Deltas::default(), &heard(), "w2", now() + Duration::hours(2) + Duration::minutes(1));
|
|
||||||
let action = &later["candidateActions"]["actions"][0];
|
|
||||||
assert_eq!((action["status"].as_str(), action["readiness"].as_str()), (Some("retired"), Some("expired")));
|
|
||||||
valid(&later);
|
|
||||||
// A week later it is removed.
|
|
||||||
let (gone, applied) = apply(&later, &Deltas::default(), &heard(), "w3", now() + Duration::days(8));
|
|
||||||
assert_eq!((gone["candidateActions"]["actions"].as_array().unwrap().len(), applied.pruned), (0, 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// At most three intentions a wake, each within a week and a kept text; ready and drop touch only intentions.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_intentions_are_bounded() {
|
|
||||||
let add = |text: &str, hours: i64| json!({ "summary": text, "expires_in_hours": hours });
|
|
||||||
let (after, applied) = run(&state(), json!({ "intend": { "add": [add("Tobiah means to write the welcome.", 24), add("Tobiah means to read the saga.", 169), add("", 10), add("Tobiah means to rest.", 48), add("Tobiah means to visit Kiko.", 72), add("Tobiah means to water the plants.", 72)] } }));
|
|
||||||
assert_eq!((after["candidateActions"]["actions"].as_array().unwrap().len(), reasons(&applied)), (3, vec!["bad_expiry".to_owned(), "empty".to_owned(), "over_bound".to_owned()]));
|
|
||||||
let id = after["candidateActions"]["actions"][0]["id"].as_str().unwrap().to_owned();
|
|
||||||
let (after, _) = run(&after, json!({ "intend": { "ready": [id.clone()], "drop": [after["candidateActions"]["actions"][1]["id"]] } }));
|
|
||||||
assert_eq!((after["candidateActions"]["actions"][0]["readiness"].as_str(), after["candidateActions"]["actions"][1]["status"].as_str()), (Some("ready"), Some("retired")));
|
|
||||||
// Something Self put there that is no intention is left alone.
|
|
||||||
let mut other = state();
|
|
||||||
other["candidateActions"]["actions"] = json!([{ "id": "ca-1", "status": "active", "actionType": "speak", "readiness": "ready", "riskLevel": "low", "target": { "kind": "self", "id": "eureka" }, "summary": "Say hello.", "createdAt": "2026-11-19T10:00:00Z", "updatedAt": "2026-11-19T10:00:00Z", "expiresAt": "2026-11-19T11:00:00Z" }]);
|
|
||||||
let (after, applied) = run(&other, json!({ "intend": { "drop": ["ca-1"] } }));
|
|
||||||
assert_eq!((after["candidateActions"].clone(), reasons(&applied)), (other["candidateActions"].clone(), vec!["unknown_id".to_owned()]));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// T-P2: no delta family writes standing tendencies: a kitchen sink of every family leaves them byte-equal.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_no_bias_writes() {
|
|
||||||
let mut state = state();
|
|
||||||
state["affect"]["socialBiases"] = json!([{ "name": "defers to the operator", "value": 0.6, "summary": "Tobiah defers.", "behavioralPull": "yields", "updatedAt": "2026-11-19T10:00:00Z" }]);
|
|
||||||
let (after, applied) = run(&state, json!({
|
|
||||||
"notes": { "remember": [{ "text": "Tobiah promised Meta a story.", "about": [META], "importance": 0.7 }], "wonder": [{ "text": "Does the heron remember the river?" }] },
|
|
||||||
"people": { "bonds": [{ "person": "deru", "trust": "up", "closeness": "up", "summary": "Deru is steady.", "why": "Deru stayed." }], "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems tired.", "confidence": 0.6 }] },
|
|
||||||
"feeling": { "feelings": [{ "name": "warmth", "strength": 0.6, "about": "deru" }], "mood": { "valence": "up" } },
|
|
||||||
"drives": { "needs": [{ "id": "need-an-audience", "toward": "down" }] },
|
|
||||||
"self": { "stances": [{ "principle": "Stories carry people.", "summary": "Tobiah tells stories to carry people." }], "identity": { "publicDescription": "A slow river-minded storyteller." } },
|
|
||||||
"intend": { "add": [{ "summary": "Tobiah means to tell Deru the heron story.", "expires_in_hours": 24 }] }
|
|
||||||
}));
|
|
||||||
assert_eq!(after["affect"]["socialBiases"], state["affect"]["socialBiases"]);
|
|
||||||
assert!(applied.refused.is_empty(), "{:?}", applied.refused);
|
|
||||||
valid(&after);
|
|
||||||
// The module's own text names none of the fields no wake writes.
|
|
||||||
let source = include_str!("../commit.rs");
|
|
||||||
for field in ["socialBiases", "voidbotProjection", "embodiment", "privateNotes"] {
|
|
||||||
assert!(!source.contains(field), "{field}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A bond's summary changes only with a why; the old words go to `lastEvidence`; a bond with someone new starts at 0.5, 0.1, 0.2.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_bond_summary_needs_a_why_and_a_new_bond_starts_low() {
|
|
||||||
let (after, applied) = run(&state(), json!({ "people": { "bonds": [{ "person": "deru", "summary": "Deru has gone quiet." }] } }));
|
|
||||||
assert_eq!(reasons(&applied), ["unexplained"]);
|
|
||||||
assert_eq!(bond(&after, DERU)["summary"], bond(&state(), DERU)["summary"]);
|
|
||||||
let (after, _) = run(&state(), json!({ "people": { "bonds": [{ "person": "deru", "summary": "Deru has gone quiet lately.", "why": "Deru answered once in three days." }] } }));
|
|
||||||
let deru = bond(&after, DERU);
|
|
||||||
assert_eq!((deru["summary"].as_str(), deru["lastEvidence"]["summary"].clone()), (Some("Deru has gone quiet lately."), bond(&state(), DERU)["summary"].clone()));
|
|
||||||
valid(&after);
|
|
||||||
let mut named = heard();
|
|
||||||
named.people.push("@ann:gamecult.org".into());
|
|
||||||
let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [{ "person": "@ann:gamecult.org", "kind": "friend", "summary": "Ann asks careful questions.", "why": "Ann asked three." }, { "person": "@ghost:gamecult.org", "trust": "up" }] } })), &named, "w1", now());
|
|
||||||
let ann = bond(&after, "@ann:gamecult.org");
|
|
||||||
assert_eq!((ann["trust"].as_f64(), ann["tension"].as_f64(), ann["intensity"].as_f64(), ann["relationshipKind"].as_str()), (Some(0.5), Some(0.1), Some(0.2), Some("friend")));
|
|
||||||
assert_eq!(reasons(&applied), ["unknown_person"]);
|
|
||||||
valid(&after);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads are upserted by person and kind, cool after three days and retire after ten.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_reads_upsert_and_age() {
|
|
||||||
let (once, _) = run(&state(), json!({ "people": { "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems tired.", "confidence": 0.6 }] } }));
|
|
||||||
let (twice, _) = run(&once, json!({ "people": { "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems rested.", "confidence": 0.8 }, { "person": "kiko", "kind": "bogus", "summary": "x" }] } }));
|
|
||||||
assert_eq!((twice["affect"]["statusReads"].as_array().unwrap().len(), twice["affect"]["statusReads"][0]["summary"].as_str()), (1, Some("Kiko seems rested.")));
|
|
||||||
let cooled = apply(&twice, &Deltas::default(), &heard(), "w2", now() + Duration::days(3)).0;
|
|
||||||
let retired = apply(&twice, &Deltas::default(), &heard(), "w3", now() + Duration::days(10)).0;
|
|
||||||
assert_eq!((cooled["affect"]["statusReads"][0]["status"].as_str(), retired["affect"]["statusReads"][0]["status"].as_str()), (Some("cooling"), Some("retired")));
|
|
||||||
valid(&twice);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mood moves by its own plasticity; a trait left alone drifts toward its mean, never past it.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_mood_by_plasticity_and_drift() {
|
|
||||||
let state = state();
|
|
||||||
let (after, _) = run(&state, json!({ "feeling": { "mood": { "valence": "down", "arousal": "up" } } }));
|
|
||||||
let sit = &after["activationProfile"]["situationalState"];
|
|
||||||
assert!((sit["valence"]["currentActivation"].as_f64().unwrap() - (0.7 - 0.3 * 0.25)).abs() < 1e-9);
|
|
||||||
assert!((sit["arousal"]["currentActivation"].as_f64().unwrap() - (0.2 + 0.3 * 0.25)).abs() < 1e-9);
|
|
||||||
// Dominance was not moved: it sits at its mean already.
|
|
||||||
assert_eq!(sit["dominance"]["currentActivation"].as_f64(), Some(0.4));
|
|
||||||
let mut away = state.clone();
|
|
||||||
away["activationProfile"]["situationalState"]["valence"]["currentActivation"] = json!(0.2);
|
|
||||||
away["activationProfile"]["situationalState"]["arousal"]["currentActivation"] = json!(0.26);
|
|
||||||
let (drifted, _) = run(&away, json!({}));
|
|
||||||
let sit = &drifted["activationProfile"]["situationalState"];
|
|
||||||
assert!((sit["valence"]["currentActivation"].as_f64().unwrap() - 0.23).abs() < 1e-9);
|
|
||||||
assert_eq!(sit["arousal"]["currentActivation"].as_f64(), Some(0.25), "never past the mean");
|
|
||||||
valid(&drifted);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Notes: at most four kept, two settled; a settle into memory moves a note to `memories` crystallized.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_notes_are_bounded_and_settle() {
|
|
||||||
let notes: Vec<Value> = (1..=5).map(|n| json!({ "text": format!("Tobiah noted thing number {n}.") })).collect();
|
|
||||||
let (after, applied) = run(&state(), json!({ "notes": { "remember": notes } }));
|
|
||||||
assert_eq!((after["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), reasons(&applied)), (4, vec!["over_bound".to_owned()]));
|
|
||||||
let entry = &after["thoughtMemory"]["shortTerm"][0];
|
|
||||||
assert_eq!((entry["target"].clone(), entry["tags"].clone()), (json!({ "kind": "room", "id": MINDS }), json!([format!("room:{MINDS}")])));
|
|
||||||
let ids: Vec<String> = after["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().map(|note| note["id"].as_str().unwrap().to_owned()).collect();
|
|
||||||
let (settled, applied) = run(&after, json!({ "notes": { "settle": [{ "id": ids[0], "into": "memory" }, { "id": ids[1], "into": "resolved" }, { "id": ids[2], "into": "resolved" }, { "id": "nope", "into": "resolved" }] } }));
|
|
||||||
assert_eq!(reasons(&applied), ["over_bound", "over_bound"]);
|
|
||||||
assert_eq!((settled["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), settled["thoughtMemory"]["memories"].as_array().unwrap().len() - state()["thoughtMemory"]["memories"].as_array().unwrap().len()), (3, 1));
|
|
||||||
let memory = settled["thoughtMemory"]["memories"].as_array().unwrap().iter().find(|memory| memory["id"] == ids[0].as_str()).unwrap();
|
|
||||||
assert_eq!(memory["status"], "crystallized");
|
|
||||||
valid(&settled);
|
|
||||||
// A private note made in a direct message keeps that room's tag.
|
|
||||||
let dm = Heard { room: Some("!dm-aqua:gamecult.org".into()), ..heard() };
|
|
||||||
let (after, _) = apply(&state(), &deltas(json!({ "notes": { "remember": [{ "text": "Aqua told Tobiah privately she is tired.", "private": true }] } })), &dm, "w1", now());
|
|
||||||
assert_eq!(after["thoughtMemory"]["shortTerm"][0]["tags"], json!(["room:!dm-aqua:gamecult.org", "private"]));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A resolved note older than a week is removed, and one resolved with no time is stamped.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_resolved_notes_are_pruned() {
|
|
||||||
let mut state = state();
|
|
||||||
state["thoughtMemory"]["shortTerm"] = json!([
|
|
||||||
{ "id": "st-old", "status": "resolved", "target": { "kind": "self", "id": "eureka" }, "summary": "Old.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "2026-11-01T10:00:00Z" },
|
|
||||||
{ "id": "st-new", "status": "resolved", "target": { "kind": "self", "id": "eureka" }, "summary": "Untimed.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "not a time" }
|
|
||||||
]);
|
|
||||||
let (after, applied) = run(&state, json!({}));
|
|
||||||
assert_eq!((after["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), applied.pruned, after["thoughtMemory"]["shortTerm"][0]["updatedAt"].clone()), (1, 1, json!(now().to_rfc3339())));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul s1: the bounds are per wake per target, never per entry. Three entries for one person move trust once, two for one need
|
|
||||||
/// move it once, and a feeling named three times rises once.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_duplicate_entries_move_a_target_once() {
|
|
||||||
let state = state();
|
|
||||||
let start = bond(&state, "kiko")["trust"].as_f64().unwrap();
|
|
||||||
let (after, _) = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "up" }] } }));
|
|
||||||
assert!((bond(&after, "kiko")["trust"].as_f64().unwrap() - (start + BOND_STEP).min(1.0)).abs() < 1e-9, "three ups are one step");
|
|
||||||
let (cancelled, _) = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "down" }] } }));
|
|
||||||
assert!((bond(&cancelled, "kiko")["trust"].as_f64().unwrap() - start).abs() < 1e-9, "up and down cancel");
|
|
||||||
let before = state["affect"]["needs"][0]["intensity"].as_f64().unwrap();
|
|
||||||
let (after, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "up" }, { "id": "need-an-audience", "toward": "up" }] } }));
|
|
||||||
assert!((after["affect"]["needs"][0]["intensity"].as_f64().unwrap() - (before + DRIVE_STEP)).abs() < 1e-9, "two ups are one step");
|
|
||||||
let (after, _) = run(&state, json!({ "feeling": { "feelings": [{ "name": "anger", "strength": 0.9 }, { "name": "Anger", "strength": 0.9 }, { "name": "anger", "strength": 0.8 }] } }));
|
|
||||||
assert_eq!((after["affect"]["moodDimensions"].as_array().unwrap().len(), after["affect"]["moodDimensions"][0]["value"].as_f64()), (1, Some(0.35)));
|
|
||||||
valid(&after);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A bond made this wake is not moved this wake, whatever else the entries say.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_a_bond_made_is_not_moved() {
|
|
||||||
let mut named = heard();
|
|
||||||
named.people.push("@ann:gamecult.org".into());
|
|
||||||
let made = json!({ "person": "@ann:gamecult.org", "summary": "Ann asks careful questions.", "why": "Ann asked three." });
|
|
||||||
let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [made, { "person": "@ann:gamecult.org", "trust": "up", "tension": "up", "closeness": "up" }] } })), &named, "w1", now());
|
|
||||||
let ann = bond(&after, "@ann:gamecult.org");
|
|
||||||
assert_eq!((ann["trust"].as_f64(), ann["tension"].as_f64(), ann["intensity"].as_f64()), (Some(0.5), Some(0.1), Some(0.2)));
|
|
||||||
assert_eq!(applied.changes.iter().filter(|change| change["family"] == "people").count(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// I16.7 on every kept label: an intention's target, a feeling's name, a note's about and its tag carry no run of heard words, and a
|
|
||||||
/// feeling's name is short.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_labels_refuse_what_was_heard() {
|
|
||||||
let line = "tell Deru about the forty eight hour passkey cooling off period before friday";
|
|
||||||
let said = "tell Deru about the forty eight hour passkey cooling off";
|
|
||||||
let heard = Heard { lines: vec![line.into()], ..heard() };
|
|
||||||
let go = |value: Value| apply(&state(), &deltas(value), &heard, "w1", now());
|
|
||||||
let (after, applied) = go(json!({ "intend": { "add": [{ "summary": "Tobiah means to ask Deru something.", "target": said, "expires_in_hours": 5 }] } }));
|
|
||||||
assert_eq!((reasons(&applied), after["candidateActions"]["actions"].clone()), (vec!["echo".to_owned()], state()["candidateActions"]["actions"].clone()));
|
|
||||||
let (_, applied) = go(json!({ "feeling": { "feelings": [{ "name": said, "strength": 0.5 }] } }));
|
|
||||||
assert_eq!(reasons(&applied), ["long"], "a name is a short label");
|
|
||||||
let (_, applied) = go(json!({ "feeling": { "feelings": [{ "name": "a b c d e f g h", "strength": 0.5 }] } }));
|
|
||||||
assert_eq!(reasons(&applied), Vec::<String>::new(), "short labels pass");
|
|
||||||
let (after, applied) = go(json!({ "notes": { "remember": [{ "text": "Deru owes Tobiah an answer.", "about": [said] }], "wonder": [{ "text": "Will Deru answer soon?", "about": [said] }] } }));
|
|
||||||
assert_eq!((reasons(&applied), after["thoughtMemory"]["shortTerm"].clone()), (vec!["echo".to_owned(), "echo".to_owned()], state()["thoughtMemory"]["shortTerm"].clone()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One stance or value change a wake: a second stance is over the bound, and the first stands.
|
|
||||||
#[test]
|
|
||||||
fn t_p2_two_stances_are_one_change() {
|
|
||||||
let stances = json!([{ "id": "stance-slow-is-kind", "principle": "Slow is kind.", "summary": "Tobiah answers slowly." }, { "principle": "Plain words.", "summary": "Tobiah keeps his words plain." }]);
|
|
||||||
let (after, applied) = run(&state(), json!({ "self": { "stances": stances } }));
|
|
||||||
assert_eq!(reasons(&applied), ["over_bound"]);
|
|
||||||
assert_eq!(after["affect"]["doctrineStances"].as_array().unwrap().len(), state()["affect"]["doctrineStances"].as_array().unwrap().len());
|
|
||||||
assert_eq!(after["affect"]["doctrineStances"][0]["summary"], "Tobiah answers slowly.");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An intention whose words equal an open one's, up to case and spacing, is not added; a rewording is the model's to catch, a
|
|
||||||
/// dropped one may be meant again, and a drop by id retires only the intention it names.
|
|
||||||
#[test]
|
|
||||||
fn an_intention_open_in_the_same_words_is_not_added_again() {
|
|
||||||
let open = |state: &Value| state["candidateActions"]["actions"].as_array().unwrap().iter().filter(|action| action["status"] == "active").count();
|
|
||||||
let add = |text: &str| json!({ "intend": { "add": [{ "summary": text, "expires_in_hours": 24 }] } });
|
|
||||||
let (first, _) = run(&state(), add("Tobiah means to list the directory above the Aetheria path."));
|
|
||||||
let id = first["candidateActions"]["actions"].as_array().unwrap().last().unwrap()["id"].as_str().unwrap().to_owned();
|
|
||||||
let (again, applied) = run(&first, add(" tobiah means to LIST the directory\tabove the aetheria path. "));
|
|
||||||
assert_eq!((open(&again), reasons(&applied)), (open(&first), vec!["duplicate".to_owned()]));
|
|
||||||
let (twice, applied) = run(&first, json!({ "intend": { "add": [
|
|
||||||
{ "summary": "Tobiah means to list a different directory.", "expires_in_hours": 24 },
|
|
||||||
{ "summary": "Tobiah means to list a different DIRECTORY.", "expires_in_hours": 24 },
|
|
||||||
] } }));
|
|
||||||
assert_eq!((open(&twice), reasons(&applied)), (open(&first) + 1, vec!["duplicate".to_owned()]), "one batch cannot hold the same words twice");
|
|
||||||
let (dropped, _) = run(&first, json!({ "intend": { "drop": [id.clone()] } }));
|
|
||||||
assert_eq!(open(&dropped), open(&first) - 1);
|
|
||||||
let (meant_again, applied) = run(&dropped, add("Tobiah means to list the directory above the Aetheria path."));
|
|
||||||
assert_eq!((open(&meant_again), reasons(&applied)), (open(&dropped) + 1, vec![]));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A batch's own drops come first, so dropping an intention and adding it again in the same words retires the old one and opens a
|
|
||||||
/// fresh one; and an add in an open waiting intention's words, marked ready, makes that one ready rather than being refused.
|
|
||||||
#[test]
|
|
||||||
fn a_drop_frees_its_words_and_a_ready_re_add_readies_the_open_intention() {
|
|
||||||
let intentions = |state: &Value| state["candidateActions"]["actions"].as_array().unwrap().iter().filter(|action| action["customActionType"] == "intention").cloned().collect::<Vec<_>>();
|
|
||||||
let words = "Tobiah means to list the directory above the Aetheria path.";
|
|
||||||
let (first, _) = run(&state(), json!({ "intend": { "add": [{ "summary": words, "expires_in_hours": 24 }] } }));
|
|
||||||
let old = intentions(&first).last().unwrap().clone();
|
|
||||||
let (swapped, applied) = run(&first, json!({ "intend": { "drop": [old["id"]], "add": [{ "summary": words, "expires_in_hours": 24 }] } }));
|
|
||||||
let after = intentions(&swapped);
|
|
||||||
// (Both wakes here share one key, so the fresh intention's id repeats the old one's: told apart by status.)
|
|
||||||
let states = after.iter().filter(|action| action["summary"] == words).map(|action| action["status"].as_str().unwrap().to_owned()).collect::<Vec<_>>();
|
|
||||||
assert_eq!((states, reasons(&applied)), (vec!["retired".to_owned(), "active".to_owned()], vec![]));
|
|
||||||
|
|
||||||
assert_eq!(old["readiness"], "waiting");
|
|
||||||
let (readied, applied) = run(&first, json!({ "intend": { "add": [{ "summary": words.to_uppercase(), "expires_in_hours": 24, "readiness": "ready" }] } }));
|
|
||||||
let after = intentions(&readied);
|
|
||||||
assert_eq!((after.len(), after.last().unwrap()["id"].clone(), after.last().unwrap()["readiness"].as_str(), reasons(&applied)), (intentions(&first).len(), old["id"].clone(), Some("ready"), vec![]));
|
|
||||||
let (still, applied) = run(&first, json!({ "intend": { "add": [{ "summary": words, "expires_in_hours": 24, "readiness": "later" }] } }));
|
|
||||||
assert_eq!((intentions(&still).last().unwrap()["readiness"].as_str(), reasons(&applied)), (Some("waiting"), vec!["duplicate".to_owned()]), "only a ready add readies");
|
|
||||||
}
|
|
||||||
|
|
@ -1,462 +0,0 @@
|
||||||
//! Her domain (map 16.22.2, as 16.22.8 amends it): what moved in her part of the coop since her last wake, read by code
|
|
||||||
//! each wake with no model call, and the lines Select renders under `In {her} domain lately:`.
|
|
||||||
//!
|
|
||||||
//! Sources:
|
|
||||||
//! - Her repos are her in-force stewardship records, read through her own read door. A campaign's `repos` list is never
|
|
||||||
//! read: it does not own what she stewards, and K23a found it disagreeing with the records that do.
|
|
||||||
//! - Campaigns enter only through their own documents held in her own mind: the rulings admitted under them. A campaign in
|
|
||||||
//! another Mind's mind is not in hers, whatever repo it names.
|
|
||||||
//! - The forge gives each stewarded repo's merged pull requests: title, opening account, when merged. A commit is never
|
|
||||||
//! read: every agent commit is the operator's account, so its author says nothing about who worked.
|
|
||||||
//!
|
|
||||||
//! Everything, in full, in a stated window (the operator: "Either show the full commit log or don't show it at all,
|
|
||||||
//! telling it a bunch of stuff moved without saying what is anti-signal"). The digest is one item per ruling admitted and
|
|
||||||
//! per pull request merged in the window, each with its whole title and who: people and Minds, never a faculty (`Who`).
|
|
||||||
//! It carries no count and no "and N more": nothing open, no follow-up, no cut report or verdict. Completeness comes from
|
|
||||||
//! the window, not from the item count: when the whole window does not fit the section's guard, Select shrinks the window
|
|
||||||
//! from its old end (`select::domain_lines`), never drops an item inside it, and states the window it shows.
|
|
||||||
//!
|
|
||||||
//! A stewarded repo that is archived, that the forge does not find, or that it answers with a redirect is skipped and
|
|
||||||
//! reported, never shown to her. Any other failed read fails the whole read: `project` leaves the section out and its
|
|
||||||
//! report says why. It never renders "nothing moved", which would be false.
|
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow, bail, ensure};
|
|
||||||
use chrono::{DateTime, DurationRound, Utc};
|
|
||||||
use cultnet_rs::Selection;
|
|
||||||
use eureka_pipeline::PipelineKind;
|
|
||||||
use eureka_state::HuginnClient;
|
|
||||||
use eureka_state::hold::Ask;
|
|
||||||
use huginn_mind::{Faculty, HuginnMindRequest, HuginnMindResponse, PipelineDocumentSummary, PipelineFacts, PipelinePageItems, PipelineProvenance, PipelineSelectionPage};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use super::select::{People, capitalized, spoken};
|
|
||||||
use crate::queue::{any_of, in_force, of_kind};
|
|
||||||
|
|
||||||
/// The window when she has not woken before, and the furthest back it ever reaches.
|
|
||||||
const WINDOW_MAX_DAYS: i64 = 7;
|
|
||||||
/// The least the window reaches back (map 16.22.2): a day, however recently she woke.
|
|
||||||
const WINDOW_MIN_HOURS: i64 = 24;
|
|
||||||
/// One page of the forge's pull requests, and how many pages of one repo a read takes: 200 moved in a week is past
|
|
||||||
/// anything the coop has seen, and a repo past it fails the read rather than show part of it.
|
|
||||||
const PULLS_PAGE: usize = 50;
|
|
||||||
const PULLS_PAGES: usize = 4;
|
|
||||||
/// The page the mind's ruling read asks for.
|
|
||||||
const EVENTS_PAGE: u32 = 200;
|
|
||||||
/// The whole of one forge call.
|
|
||||||
const FORGE_TIMEOUT: Duration = Duration::from_secs(10);
|
|
||||||
|
|
||||||
/// Where the window opens: her last wake, but at least a day and at most a week before `now`; a week when she has not
|
|
||||||
/// woken before.
|
|
||||||
pub(crate) fn since(last_wake: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
|
|
||||||
let earliest = now - chrono::Duration::days(WINDOW_MAX_DAYS);
|
|
||||||
let latest = now - chrono::Duration::hours(WINDOW_MIN_HOURS);
|
|
||||||
last_wake.map_or(earliest, |at| at.clamp(earliest, latest))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What moved in her domain, as read: the facts the section is rendered from. A harness fixture carries the same
|
|
||||||
/// (`[domain]` in a room fixture, `[cast.domain]` in a simulation plan), so a re-test reads no forge and no mind.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub struct DomainFacts {
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) repos: Vec<RepoFacts>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) campaigns: Vec<CampaignFacts>,
|
|
||||||
/// Stewarded repos the read skipped, and why: reported, never shown to her.
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) skipped: Vec<Skipped>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One stewarded repo and its pull requests that moved in the window.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub(crate) struct RepoFacts {
|
|
||||||
/// `Org/Repo`.
|
|
||||||
pub(crate) repo: String,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) pulls: Vec<Pull>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A pull request as the forge lists it: its title, the account that opened it, and when it merged (none when it has not).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub(crate) struct Pull {
|
|
||||||
pub(crate) title: String,
|
|
||||||
pub(crate) opener: String,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) merged_at: Option<DateTime<Utc>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A campaign held in her mind and the rulings admitted under it.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub(crate) struct CampaignFacts {
|
|
||||||
pub(crate) slug: String,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) rulings: Vec<Ruled>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A ruling admitted: when, its whole title, and who ran the admission.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub(crate) struct Ruled {
|
|
||||||
pub(crate) at: DateTime<Utc>,
|
|
||||||
pub(crate) title: String,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) who: Who,
|
|
||||||
/// The ruling's own words, when the record holds them: what a campaign read shows after the title (map 16.25.8).
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub(crate) ruling: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Who ran an admission, as people and Minds: her own organs (her Persona turn, her Self runs and what they dispatch),
|
|
||||||
/// the operator driving a session on her behalf, or the operator; never a faculty. `Unknown` names no one.
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub(crate) enum Who {
|
|
||||||
#[default]
|
|
||||||
Unknown,
|
|
||||||
Her,
|
|
||||||
OperatorWithHer,
|
|
||||||
Operator,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The names a line calls people by: hers, and the operator's as her state holds the operator.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Names {
|
|
||||||
pub(crate) her: String,
|
|
||||||
pub(crate) operator: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Names {
|
|
||||||
/// Her public name (her instance, capitalized, when the state has none), and the operator by the label of her live
|
|
||||||
/// bond with the operator ("the operator" when she holds none).
|
|
||||||
pub(crate) fn of(state: &Value, people: &People, instance: &str) -> Self {
|
|
||||||
let her = state["publicName"].as_str().map(str::trim).filter(|name| !name.is_empty()).map_or_else(|| capitalized(instance), str::to_owned);
|
|
||||||
let operator = state["affect"]["socialBonds"]
|
|
||||||
.as_array()
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
.filter(|bond| !matches!(bond["status"].as_str(), Some("retired" | "cooled" | "resolved")))
|
|
||||||
.find(|bond| bond["object"]["id"].as_str().is_some_and(|id| people.person_of(id) == "operator"))
|
|
||||||
.and_then(|bond| bond["object"]["label"].as_str().map(str::trim).filter(|label| !label.is_empty()).map(str::to_owned))
|
|
||||||
.unwrap_or_else(|| "the operator".to_owned());
|
|
||||||
Self { her, operator }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A stewarded repo the read skipped.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub(crate) struct Skipped {
|
|
||||||
pub(crate) repo: String,
|
|
||||||
pub(crate) why: Skip,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub(crate) enum Skip {
|
|
||||||
Archived,
|
|
||||||
NotFound,
|
|
||||||
Moved,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What `project` reads her domain through: read-only by type. The live one is `MindDomain`; a fixture's facts are their
|
|
||||||
/// own source.
|
|
||||||
pub trait DomainSource {
|
|
||||||
/// What moved in her domain from `since` to `now`.
|
|
||||||
fn read(&self, since: DateTime<Utc>, now: DateTime<Utc>) -> Result<DomainFacts>;
|
|
||||||
/// The repos she stewards in force (`Org/Repo`): the drain's input to `heartbeat::own_rooms`. A source with no mind behind it names none.
|
|
||||||
fn stewarded(&self) -> Result<Vec<String>> {
|
|
||||||
Ok(Vec::new())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DomainSource for DomainFacts {
|
|
||||||
fn read(&self, _since: DateTime<Utc>, _now: DateTime<Utc>) -> Result<DomainFacts> {
|
|
||||||
Ok(self.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her domain, live: her mind through her own read door (a query and nothing else is ever sent), and the forge.
|
|
||||||
pub struct MindDomain {
|
|
||||||
client: HuginnClient,
|
|
||||||
forge: HttpForge,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MindDomain {
|
|
||||||
pub fn new(client: HuginnClient, forge: HttpForge) -> Self {
|
|
||||||
Self { client, forge }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MindDomain {
|
|
||||||
fn ask(&self, selection: &Selection) -> Result<PipelineSelectionPage> {
|
|
||||||
let request = HuginnMindRequest::Query { instance: self.client.instance().clone(), selection: selection.clone(), semantic: None };
|
|
||||||
match self.client.call(request).map_err(|_| anyhow!("her mind could not be asked"))? {
|
|
||||||
HuginnMindResponse::Query(page) => Ok(page),
|
|
||||||
HuginnMindResponse::Refused(_) => bail!("her mind refused the read"),
|
|
||||||
_ => bail!("her mind answered a read with something else"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DomainSource for MindDomain {
|
|
||||||
fn read(&self, since: DateTime<Utc>, now: DateTime<Utc>) -> Result<DomainFacts> {
|
|
||||||
read(&|selection| self.ask(selection), &self.client.instance().0, &self.forge, since, now)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stewarded(&self) -> Result<Vec<String>> {
|
|
||||||
stewarded(&|selection| self.ask(selection), &self.client.instance().0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One GET on the forge: the status and the body.
|
|
||||||
pub(crate) trait ForgeGet {
|
|
||||||
fn get(&self, path: &str) -> Result<(u16, String)>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The forge's public API over HTTP, anonymous: what anyone may read. No redirect is followed: a redirect names a moved
|
|
||||||
/// repo, which is skipped.
|
|
||||||
pub struct HttpForge {
|
|
||||||
agent: ureq::Agent,
|
|
||||||
base: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HttpForge {
|
|
||||||
/// `base_url` is the forge's root, the one `/api/v1` hangs from.
|
|
||||||
pub fn new(base_url: &str) -> Self {
|
|
||||||
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(FORGE_TIMEOUT)).http_status_as_error(false).max_redirects(0).max_redirects_will_error(false).build().into();
|
|
||||||
Self { agent, base: base_url.trim_end_matches('/').to_owned() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ForgeGet for HttpForge {
|
|
||||||
fn get(&self, path: &str) -> Result<(u16, String)> {
|
|
||||||
// An error names no address: the forge's answer is the report's to know about, its address is not.
|
|
||||||
let mut response = self.agent.get(format!("{}{path}", self.base)).call().map_err(|_| anyhow!("the forge did not answer"))?;
|
|
||||||
let status = response.status().as_u16();
|
|
||||||
let body = response.body_mut().read_to_string().map_err(|_| anyhow!("the forge's answer was cut off"))?;
|
|
||||||
Ok((status, body))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every header of a selection, newest admission first, down to the first admitted before `since`.
|
|
||||||
fn newest(ask: &Ask, selection: &Selection, since: DateTime<Utc>) -> Result<Vec<PipelineDocumentSummary>> {
|
|
||||||
let mut asking = Selection { descending: true, limit: Some(EVENTS_PAGE), ..selection.clone() };
|
|
||||||
let mut found = Vec::new();
|
|
||||||
loop {
|
|
||||||
let page = ask(&asking)?;
|
|
||||||
let PipelinePageItems::Headers(items) = page.items else { bail!("her mind answered documents to a header read") };
|
|
||||||
for item in items {
|
|
||||||
if admitted_at(&item)? < since {
|
|
||||||
return Ok(found);
|
|
||||||
}
|
|
||||||
found.push(item);
|
|
||||||
}
|
|
||||||
match page.next {
|
|
||||||
Some(cursor) => asking.cursor = Some(cursor),
|
|
||||||
None => return Ok(found),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every header of a selection, in the mind's order.
|
|
||||||
fn all(ask: &Ask, selection: &Selection) -> Result<Vec<PipelineDocumentSummary>> {
|
|
||||||
eureka_state::hold::headers(ask, selection)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn admitted_at(item: &PipelineDocumentSummary) -> Result<DateTime<Utc>> {
|
|
||||||
DateTime::parse_from_rfc3339(&item.admission.admitted_at).map(|at| at.with_timezone(&Utc)).map_err(|_| anyhow!("an admission time in her mind does not read"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A key's root segment: the campaign a document belongs to, or the instance of a stewardship.
|
|
||||||
fn root(item: &PipelineDocumentSummary) -> &str {
|
|
||||||
item.id.id.0.split(':').next().unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Who ran an admission in her mind, from its provenance, never its faculty: the operator's own admission; an agent of her
|
|
||||||
/// own organs (`mind-persona`, `mind-self-run` and the runs it dispatches: every `mind-` agent), which is her; an agent or
|
|
||||||
/// a session named for her (`nibu-hands`, `nibu-self-2026-11-17`: the per-Mind sessions the operator runs for her), which
|
|
||||||
/// is the operator with her. A replayed admission, and any other agent, names no one. Never a git author.
|
|
||||||
fn who(provenance: &PipelineProvenance, her: &str) -> Who {
|
|
||||||
let (agent, session) = (provenance.agent.0.as_str(), provenance.session.0.as_str());
|
|
||||||
let named = |text: &str| text.strip_prefix(her).is_some_and(|rest| rest.starts_with('-'));
|
|
||||||
if provenance.imported_from.is_some() {
|
|
||||||
Who::Unknown
|
|
||||||
} else if provenance.faculty == Faculty::Operator {
|
|
||||||
Who::Operator
|
|
||||||
} else if agent.starts_with("mind-") {
|
|
||||||
Who::Her
|
|
||||||
} else if named(agent) || named(session) {
|
|
||||||
Who::OperatorWithHer
|
|
||||||
} else {
|
|
||||||
Who::Unknown
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The repos `her` stewards in force, each once.
|
|
||||||
pub(crate) fn stewarded(ask: &Ask, her: &str) -> Result<Vec<String>> {
|
|
||||||
let mut repos: Vec<String> = Vec::new();
|
|
||||||
for item in all(ask, &in_force(of_kind(PipelineKind::Stewardship)))? {
|
|
||||||
if let PipelineFacts::Stewardship { instance, repo, .. } = &item.facts
|
|
||||||
&& instance.0 == her
|
|
||||||
&& !repos.iter().any(|held| held.eq_ignore_ascii_case(&repo.0))
|
|
||||||
{
|
|
||||||
repos.push(repo.0.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(repos)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her domain from `since`: her in-force stewardships and her campaigns through `ask` (her door), each stewarded repo's
|
|
||||||
/// pull requests through `forge`. Any failure fails the whole read, except a repo that is archived, missing or moved,
|
|
||||||
/// which is skipped and named.
|
|
||||||
pub(crate) fn read(ask: &Ask, her: &str, forge: &dyn ForgeGet, since: DateTime<Utc>, now: DateTime<Utc>) -> Result<DomainFacts> {
|
|
||||||
let repos = stewarded(ask, her)?;
|
|
||||||
let slugs: Vec<String> = all(ask, &in_force(of_kind(PipelineKind::Campaign)))?.iter().map(|item| root(item).to_owned()).collect::<BTreeSet<_>>().into_iter().collect();
|
|
||||||
let mut campaigns: Vec<CampaignFacts> = slugs.iter().map(|slug| CampaignFacts { slug: slug.clone(), rulings: Vec::new() }).collect();
|
|
||||||
if !slugs.is_empty() {
|
|
||||||
let roots: Vec<&str> = slugs.iter().map(String::as_str).collect();
|
|
||||||
for item in newest(ask, &any_of(of_kind(PipelineKind::Ruling), "root", &roots), since)? {
|
|
||||||
let PipelineFacts::Ruling { title, .. } = &item.facts else { continue };
|
|
||||||
let at = admitted_at(&item)?;
|
|
||||||
if let Some(campaign) = campaigns.iter_mut().find(|campaign| campaign.slug == root(&item)) {
|
|
||||||
campaign.rulings.push(Ruled { at, title: title.0.clone(), who: who(&item.admission.provenance, her), ruling: None });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut facts = DomainFacts { repos: Vec::new(), campaigns, skipped: Vec::new() };
|
|
||||||
for repo in repos {
|
|
||||||
match repo_state(forge, &repo)? {
|
|
||||||
Some(why) => facts.skipped.push(Skipped { repo, why }),
|
|
||||||
None => {
|
|
||||||
let pulls = pulls(forge, &repo, since, now)?;
|
|
||||||
facts.repos.push(RepoFacts { repo, pulls });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(facts)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a repo is skipped, or none when it is live: archived, not found (404), or moved (a redirect). Any other answer
|
|
||||||
/// fails the read.
|
|
||||||
fn repo_state(forge: &dyn ForgeGet, repo: &str) -> Result<Option<Skip>> {
|
|
||||||
let (status, body) = forge.get(&format!("/api/v1/repos/{repo}"))?;
|
|
||||||
match status {
|
|
||||||
404 => Ok(Some(Skip::NotFound)),
|
|
||||||
300..400 => Ok(Some(Skip::Moved)),
|
|
||||||
200 => {
|
|
||||||
let value: Value = serde_json::from_str(&body).map_err(|_| anyhow!("the forge's answer for {repo} is not JSON"))?;
|
|
||||||
let archived = value["archived"].as_bool().with_context(|| format!("the forge did not say whether {repo} is archived"))?;
|
|
||||||
Ok(archived.then_some(Skip::Archived))
|
|
||||||
}
|
|
||||||
status => bail!("the forge answered {status} for {repo}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn instant(value: &Value) -> Option<DateTime<Utc>> {
|
|
||||||
value.as_str().and_then(|text| DateTime::parse_from_rfc3339(text).ok()).map(|at| at.with_timezone(&Utc))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The pull requests of `repo` updated since `since`, newest update first, as the forge lists them. A repo with more
|
|
||||||
/// than `PULLS_PAGES` pages of them in the window fails the read, never a silent part.
|
|
||||||
fn pulls(forge: &dyn ForgeGet, repo: &str, since: DateTime<Utc>, now: DateTime<Utc>) -> Result<Vec<Pull>> {
|
|
||||||
let mut found = Vec::new();
|
|
||||||
for page in 1..=PULLS_PAGES {
|
|
||||||
let (status, body) = forge.get(&format!("/api/v1/repos/{repo}/pulls?state=all&sort=recentupdate&limit={PULLS_PAGE}&page={page}"))?;
|
|
||||||
ensure!(status == 200, "the forge answered {status} to the pull requests of {repo}");
|
|
||||||
let value: Value = serde_json::from_str(&body).map_err(|_| anyhow!("the forge's pull requests of {repo} are not JSON"))?;
|
|
||||||
let listed = value.as_array().with_context(|| format!("the forge's pull requests of {repo} are not a list"))?;
|
|
||||||
for pull in listed {
|
|
||||||
let updated = instant(&pull["updated_at"]).with_context(|| format!("a pull request of {repo} has no update time"))?;
|
|
||||||
if updated < since {
|
|
||||||
return Ok(found);
|
|
||||||
}
|
|
||||||
let title = pull["title"].as_str().with_context(|| format!("a pull request of {repo} has no title"))?;
|
|
||||||
let opener = pull["user"]["login"].as_str().with_context(|| format!("a pull request of {repo} has no opener"))?;
|
|
||||||
let merged_at = if pull["merged"].as_bool() == Some(true) { instant(&pull["merged_at"]) } else { None };
|
|
||||||
found.push(Pull { title: title.to_owned(), opener: opener.to_owned(), merged_at: merged_at.filter(|at| *at <= now) });
|
|
||||||
}
|
|
||||||
if listed.len() < PULLS_PAGE {
|
|
||||||
return Ok(found);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
bail!("more than {} pull requests of {repo} moved in the window", PULLS_PAGE * PULLS_PAGES)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// The items.
|
|
||||||
|
|
||||||
/// What a digest item is about: a stewarded repo or a campaign of hers, so a read can name it (16.22.3).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
||||||
#[serde(tag = "kind", content = "name", rename_all = "snake_case")]
|
|
||||||
pub(crate) enum About {
|
|
||||||
Repo(String),
|
|
||||||
Campaign(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One thing that happened in her domain, in code's words, whole: a ruling admitted or a pull request merged.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
||||||
pub(crate) struct Item {
|
|
||||||
pub(crate) at: DateTime<Utc>,
|
|
||||||
pub(crate) text: String,
|
|
||||||
pub(crate) about: About,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `at` down to its whole minute: a window opens on a minute, so the minute it states holds everything after it.
|
|
||||||
pub(crate) fn floor_minute(at: DateTime<Utc>) -> DateTime<Utc> {
|
|
||||||
at.duration_trunc(chrono::Duration::minutes(1)).unwrap_or(at)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a read of her domain gave the packet: every item from `since` (a whole minute) to `now`, newest first.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Digest {
|
|
||||||
pub(crate) since: DateTime<Utc>,
|
|
||||||
/// Her last wake: what came after it is new to her.
|
|
||||||
pub(crate) last_look: Option<DateTime<Utc>>,
|
|
||||||
pub(crate) now: DateTime<Utc>,
|
|
||||||
pub(crate) items: Vec<Item>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Who ran a ruling's admission, in words after "ruled": by her with the operator where the operator drove a session of
|
|
||||||
/// hers (her bond's label for the operator may carry a clause, "Meta, the operator", so it comes last), by the operator,
|
|
||||||
/// in her own session; nothing when no one can be told.
|
|
||||||
fn by(who: Who, names: &Names) -> String {
|
|
||||||
match who {
|
|
||||||
Who::OperatorWithHer => format!(" by {} with {}", names.her, names.operator),
|
|
||||||
Who::Operator => format!(" by {}", names.operator),
|
|
||||||
Who::Her => format!(" in {}'s own session", names.her),
|
|
||||||
Who::Unknown => String::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every ruling admitted and every pull request merged from `since` to `now`, one item each, newest first, each whole:
|
|
||||||
/// `- lodur: ruled by Meta and Nibu: "…"` and `- GameCult/AquaSynth: merged "…", opened by aqua`. Nothing is counted.
|
|
||||||
pub(crate) fn digest(facts: &DomainFacts, since: DateTime<Utc>, last_look: Option<DateTime<Utc>>, now: DateTime<Utc>, names: &Names) -> Digest {
|
|
||||||
let since = floor_minute(since);
|
|
||||||
let within = |at: DateTime<Utc>| since <= at && at <= now;
|
|
||||||
let mut items: Vec<Item> = Vec::new();
|
|
||||||
for repo in &facts.repos {
|
|
||||||
for pull in &repo.pulls {
|
|
||||||
if let Some(at) = pull.merged_at.filter(|at| within(*at)) {
|
|
||||||
items.push(Item { at, text: format!("- {}: merged {}, opened by {}", repo.repo, spoken(pull.title.trim()), pull.opener), about: About::Repo(repo.repo.clone()) });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for campaign in &facts.campaigns {
|
|
||||||
for ruled in campaign.rulings.iter().filter(|ruled| within(ruled.at)) {
|
|
||||||
items.push(Item { at: ruled.at, text: format!("- {}: ruled{}: {}", campaign.slug, by(ruled.who, names), spoken(ruled.title.trim())), about: About::Campaign(campaign.slug.clone()) });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Newest first; a tie keeps the order read.
|
|
||||||
items.sort_by_key(|item| std::cmp::Reverse(item.at));
|
|
||||||
Digest { since, last_look, now, items }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,312 +0,0 @@
|
||||||
//! The domain digest's reads (map 16.22.2, 16.22.8): her stewardships and campaigns through a real mind over a temporary
|
|
||||||
//! directory, the forge through a scripted one that records every path it is asked. What the packet makes of the lines
|
|
||||||
//! is tested with the packet (`projection/tests.rs`, `k23_*`).
|
|
||||||
|
|
||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
use chrono::{DateTime, Duration, Utc};
|
|
||||||
use eureka_pipeline::{Date, PipelineCampaign, PipelineDocument, PipelineKind, PipelineStewardship, Slug};
|
|
||||||
use huginn_mind::Faculty;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::queue::MindPort;
|
|
||||||
use crate::testkit::{INSTANCE, TestMind, at, close, follow_up, id, recorded, reference, ruling, spec, spec_ref};
|
|
||||||
|
|
||||||
/// A forge that answers from a script and records what it was asked. A repo it holds no script for is a 404.
|
|
||||||
#[derive(Default)]
|
|
||||||
struct Forge {
|
|
||||||
repos: BTreeMap<String, (u16, Value)>,
|
|
||||||
pulls: BTreeMap<String, Value>,
|
|
||||||
asked: RefCell<Vec<String>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Forge {
|
|
||||||
fn live(mut self, repo: &str, pulls: Value) -> Self {
|
|
||||||
self.repos.insert(repo.to_owned(), (200, json!({ "full_name": repo, "archived": false })));
|
|
||||||
self.pulls.insert(repo.to_owned(), pulls);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn answering(mut self, repo: &str, status: u16, body: Value) -> Self {
|
|
||||||
self.repos.insert(repo.to_owned(), (status, body));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn asked_about(&self, repo: &str) -> bool {
|
|
||||||
self.asked.borrow().iter().any(|path| path.contains(repo))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ForgeGet for Forge {
|
|
||||||
fn get(&self, path: &str) -> Result<(u16, String)> {
|
|
||||||
self.asked.borrow_mut().push(path.to_owned());
|
|
||||||
let route = path.split('?').next().unwrap_or_default().trim_start_matches("/api/v1/repos/");
|
|
||||||
if let Some(repo) = route.strip_suffix("/pulls") {
|
|
||||||
return Ok(self.pulls.get(repo).map_or((404, "{}".to_owned()), |pulls| (200, pulls.to_string())));
|
|
||||||
}
|
|
||||||
Ok(self.repos.get(route).map_or((404, "{}".to_owned()), |(status, body)| (*status, body.to_string())))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A forge that answers nothing.
|
|
||||||
struct Down;
|
|
||||||
|
|
||||||
impl ForgeGet for Down {
|
|
||||||
fn get(&self, _path: &str) -> Result<(u16, String)> {
|
|
||||||
bail!("the forge did not answer")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const HUGINN: &str = "GameCult/Huginn";
|
|
||||||
|
|
||||||
fn now() -> DateTime<Utc> {
|
|
||||||
at(0) + Duration::hours(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Three days before `now`: a Tuesday.
|
|
||||||
fn since() -> DateTime<Utc> {
|
|
||||||
now() - Duration::days(3)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stamp(at: DateTime<Utc>) -> String {
|
|
||||||
at.to_rfc3339()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A pull request as the forge lists it.
|
|
||||||
fn pull(title: &str, opener: &str, opened: DateTime<Utc>, merged: Option<DateTime<Utc>>) -> Value {
|
|
||||||
json!({
|
|
||||||
"title": title,
|
|
||||||
"user": { "login": opener },
|
|
||||||
"created_at": stamp(opened),
|
|
||||||
"updated_at": stamp(merged.unwrap_or(opened)),
|
|
||||||
"merged": merged.is_some(),
|
|
||||||
"merged_at": merged.map(stamp),
|
|
||||||
"state": if merged.is_some() { "closed" } else { "open" },
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn names() -> Names {
|
|
||||||
Names { her: "Eureka".into(), operator: "Meta".into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The digest's items, as text, from `since()` to `now()`.
|
|
||||||
fn texts(facts: &DomainFacts) -> Vec<String> {
|
|
||||||
digest(facts, since(), None, now(), &names()).items.into_iter().map(|item| item.text).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_through(mind: &TestMind, forge: &dyn ForgeGet) -> Result<DomainFacts> {
|
|
||||||
read(&|selection: &Selection| mind.query(selection), &mind.instance().0, forge, since(), now())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stewardship_of(instance: &str, repo: &str) -> PipelineDocument {
|
|
||||||
PipelineDocument::Stewardship(PipelineStewardship { instance: Slug(instance.into()), repo: repo.into(), sequence: 1, assigned_on: Date("2026-10-09".into()), note: "assigned".into(), names: vec![] })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn campaign_listing(slug: &str, repos: &[&str]) -> PipelineDocument {
|
|
||||||
let PipelineDocument::Campaign(campaign) = crate::testkit::campaign_named(slug, "Another campaign") else { unreachable!() };
|
|
||||||
PipelineDocument::Campaign(PipelineCampaign { repos: repos.iter().map(|repo| (*repo).into()).collect(), ..campaign })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ruled(label: &str, title: &str) -> PipelineDocument {
|
|
||||||
let PipelineDocument::Ruling(mut document) = ruling(label, None) else { unreachable!() };
|
|
||||||
document.title = title.into();
|
|
||||||
PipelineDocument::Ruling(document)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A mind where an unnamed agent opened two follow-ups and closed one, and her own Self run's Soul ruled once, all inside
|
|
||||||
/// the window: the follow-ups are never shown, the ruling is.
|
|
||||||
fn worked_on() -> TestMind {
|
|
||||||
let mind = TestMind::seeded();
|
|
||||||
mind.committed(vec![spec("x")]);
|
|
||||||
let PipelineDocument::FollowUp(mut sealed) = follow_up("f1", &spec_ref("x")) else { unreachable!() };
|
|
||||||
sealed.item = "SEALED-FOLLOW-UP-ITEM, still to do".into();
|
|
||||||
mind.committed(vec![PipelineDocument::FollowUp(sealed), follow_up("f2", &spec_ref("x"))]);
|
|
||||||
mind.committed(vec![close(reference(PipelineKind::FollowUp, &id("follow_up", "f2")), recorded())]);
|
|
||||||
assert!(matches!(mind.put_by(Faculty::Soul, "mind-self-run", "run-1", vec![ruled("r1", "The digest shows what merged")]), huginn_mind::PipelineAdmissionOutcome::Committed { .. }));
|
|
||||||
mind
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_window_opens_at_her_last_wake_at_least_a_day_and_at_most_a_week_back() {
|
|
||||||
let now = now();
|
|
||||||
assert_eq!(super::since(None, now), now - Duration::days(7), "never woken: a week");
|
|
||||||
assert_eq!(super::since(Some(now - Duration::days(30)), now), now - Duration::days(7));
|
|
||||||
assert_eq!(super::since(Some(now - Duration::days(2)), now), now - Duration::days(2), "her last wake");
|
|
||||||
assert_eq!(super::since(Some(now - Duration::minutes(5)), now), now - Duration::hours(24), "a wake five minutes ago still shows a day (Soul p6)");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k23_her_door_and_the_forge_give_every_merged_and_ruled_item_whole_and_nothing_open() {
|
|
||||||
let mind = worked_on();
|
|
||||||
let forge = Forge::default().live(HUGINN, json!([
|
|
||||||
pull("Persona: the domain digest", "kiko", now() - Duration::days(2), Some(now() - Duration::minutes(30))),
|
|
||||||
pull("OPEN-PR-TITLE-SENTINEL", "nibu", now() - Duration::hours(3), None),
|
|
||||||
]));
|
|
||||||
let facts = read_through(&mind, &forge).unwrap();
|
|
||||||
assert_eq!(texts(&facts), vec![
|
|
||||||
"- GameCult/Huginn: merged \"Persona: the domain digest\", opened by kiko".to_owned(),
|
|
||||||
"- eureka-body: ruled in Eureka's own session: \"The digest shows what merged\"".to_owned(),
|
|
||||||
]);
|
|
||||||
let all = texts(&facts).join("\n");
|
|
||||||
assert!(!all.contains("SEALED-FOLLOW-UP-ITEM") && !all.contains("OPEN-PR-TITLE-SENTINEL"), "nothing open is shown: {all}");
|
|
||||||
// "Who" is the pull request's opener; no commit is ever read, so a commit's author can say nothing.
|
|
||||||
assert!(forge.asked.borrow().iter().all(|path| !path.contains("/commits") && !path.contains("/git/")), "{:?}", forge.asked.borrow());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k23_only_her_in_force_stewardships_name_her_repos_never_a_campaign_list() {
|
|
||||||
let mind = TestMind::seeded();
|
|
||||||
// A campaign of hers that lists a repo she does not steward, and a stewarded repo no campaign lists.
|
|
||||||
mind.committed(vec![campaign_listing("other-camp", &["GameCult/NotHers"]), stewardship_of(INSTANCE, "GameCult/Lonely")]);
|
|
||||||
let forge = Forge::default()
|
|
||||||
.live(HUGINN, json!([]))
|
|
||||||
.live("GameCult/Lonely", json!([pull("Lonely: first light", "aqua", now() - Duration::days(1), Some(now() - Duration::hours(5)))]))
|
|
||||||
.live("GameCult/NotHers", json!([pull("NOT-HERS-SENTINEL", "void", now() - Duration::days(1), Some(now() - Duration::hours(5)))]));
|
|
||||||
let facts = read_through(&mind, &forge).unwrap();
|
|
||||||
assert!(!forge.asked_about("NotHers"), "a campaign's repo list is never read: {:?}", forge.asked.borrow());
|
|
||||||
assert_eq!(texts(&facts), vec!["- GameCult/Lonely: merged \"Lonely: first light\", opened by aqua".to_owned()]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k23_a_stewardship_of_another_instance_held_in_her_mind_names_no_repo_of_hers() {
|
|
||||||
let mind = TestMind::seeded();
|
|
||||||
let outcome = mind.put(vec![stewardship_of("kiko", "GameCult/Ratatoskr")]);
|
|
||||||
let forge = Forge::default().live(HUGINN, json!([])).live("GameCult/Ratatoskr", json!([]));
|
|
||||||
read_through(&mind, &forge).unwrap();
|
|
||||||
assert!(!forge.asked_about("Ratatoskr"), "only her own stewardships ({outcome:?}): {:?}", forge.asked.borrow());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k23_a_campaign_held_in_another_minds_mind_never_appears_in_hers() {
|
|
||||||
let hers = TestMind::without_campaigns();
|
|
||||||
let theirs = TestMind::seeded_as("kiko");
|
|
||||||
theirs.committed(vec![ruled("r1", "THEIR-RULING-SENTINEL")]);
|
|
||||||
let forge = Forge::default().live(HUGINN, json!([]));
|
|
||||||
let facts = read_through(&hers, &forge).unwrap();
|
|
||||||
assert!(facts.campaigns.is_empty() && texts(&facts).is_empty(), "{facts:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k23_an_archived_or_missing_or_moved_repo_renders_nothing_and_is_reported() {
|
|
||||||
let mind = TestMind::without_campaigns();
|
|
||||||
mind.committed(vec![stewardship_of(INSTANCE, "GameCult/Gone"), stewardship_of(INSTANCE, "GameCult/Renamed")]);
|
|
||||||
let forge = Forge::default().answering(HUGINN, 200, json!({ "archived": true })).answering("GameCult/Renamed", 301, json!({}));
|
|
||||||
let facts = read_through(&mind, &forge).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
facts.skipped,
|
|
||||||
vec![
|
|
||||||
Skipped { repo: HUGINN.into(), why: Skip::Archived },
|
|
||||||
Skipped { repo: "GameCult/Gone".into(), why: Skip::NotFound },
|
|
||||||
Skipped { repo: "GameCult/Renamed".into(), why: Skip::Moved },
|
|
||||||
]
|
|
||||||
);
|
|
||||||
assert!(facts.repos.is_empty(), "a skipped repo's pull requests are not read: {facts:?}");
|
|
||||||
assert!(!forge.asked.borrow().iter().any(|path| path.contains("/pulls")), "{:?}", forge.asked.borrow());
|
|
||||||
assert!(texts(&facts).is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k23_a_failed_read_fails_whole_and_project_leaves_the_section_out_and_reports_why() {
|
|
||||||
let mind = worked_on();
|
|
||||||
assert!(read_through(&mind, &Down).is_err(), "a forge that does not answer fails the read");
|
|
||||||
let refusing = Forge::default().answering(HUGINN, 500, json!({}));
|
|
||||||
assert!(read_through(&mind, &refusing).is_err(), "a 500 is not a missing repo");
|
|
||||||
|
|
||||||
struct Live<'a>(&'a TestMind);
|
|
||||||
impl DomainSource for Live<'_> {
|
|
||||||
fn read(&self, since: DateTime<Utc>, now: DateTime<Utc>) -> Result<DomainFacts> {
|
|
||||||
read(&|selection: &Selection| self.0.query(selection), &self.0.instance().0, &Down, since, now)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let (digest, report) = crate::projection::read_domain(Some(&Live(&mind)), None, now(), &names());
|
|
||||||
assert!(digest.is_none());
|
|
||||||
assert_eq!((report["read"].clone(), report["why"].as_str().is_some_and(|why| why.contains("forge"))), (json!(false), true), "{report}");
|
|
||||||
let (digest, report) = crate::projection::read_domain(None, None, now(), &names());
|
|
||||||
assert!(digest.is_none() && report["read"] == json!(false), "{report}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k23_what_moved_before_the_window_is_not_in_the_digest() {
|
|
||||||
let facts = DomainFacts {
|
|
||||||
repos: vec![RepoFacts { repo: HUGINN.into(), pulls: vec![Pull { title: "Old".into(), opener: "kiko".into(), merged_at: Some(since() - Duration::hours(1)) }] }],
|
|
||||||
campaigns: vec![CampaignFacts { slug: "eureka-body".into(), rulings: vec![Ruled { at: since() - Duration::hours(1), title: "Old".into(), who: Who::Her, ruling: None }] }],
|
|
||||||
skipped: vec![],
|
|
||||||
};
|
|
||||||
assert!(texts(&facts).is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every item whole, newest first: no title is clipped, and nothing is counted.
|
|
||||||
#[test]
|
|
||||||
fn k23_items_run_newest_first_whole_and_uncounted() {
|
|
||||||
let long = "x".repeat(300);
|
|
||||||
let merged = |hours: i64, title: &str| Pull { title: title.into(), opener: "kiko".into(), merged_at: Some(now() - Duration::hours(hours)) };
|
|
||||||
let facts = DomainFacts {
|
|
||||||
repos: vec![
|
|
||||||
RepoFacts { repo: "GameCult/Older".into(), pulls: vec![merged(30, "a")] },
|
|
||||||
RepoFacts { repo: "GameCult/Newer".into(), pulls: vec![merged(1, &long), merged(2, "b"), merged(3, "c"), merged(4, "d")] },
|
|
||||||
],
|
|
||||||
..DomainFacts::default()
|
|
||||||
};
|
|
||||||
let texts = texts(&facts);
|
|
||||||
assert_eq!(texts.len(), 5, "{texts:?}");
|
|
||||||
assert_eq!(texts[0], format!("- GameCult/Newer: merged \"{long}\", opened by kiko"));
|
|
||||||
assert!(texts[4].starts_with("- GameCult/Older"), "{texts:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_fixture_reads_as_the_live_facts_do() {
|
|
||||||
let facts: DomainFacts = toml::from_str(
|
|
||||||
r#"
|
|
||||||
[[repos]]
|
|
||||||
repo = "GameCult/Aetheria"
|
|
||||||
[[repos.pulls]]
|
|
||||||
title = "Docs: passages made true"
|
|
||||||
opener = "nibu"
|
|
||||||
merged_at = "2026-10-09T09:00:00Z"
|
|
||||||
[[campaigns]]
|
|
||||||
slug = "aetheria-release"
|
|
||||||
[[campaigns.rulings]]
|
|
||||||
at = "2026-10-09T08:00:00Z"
|
|
||||||
title = "Ship v0.2.0"
|
|
||||||
who = "operator_with_her"
|
|
||||||
[[skipped]]
|
|
||||||
repo = "GameCult/Aetheria-legacy"
|
|
||||||
why = "archived"
|
|
||||||
"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(DomainSource::read(&facts, since(), now()).unwrap(), facts);
|
|
||||||
assert_eq!(texts(&facts), vec![
|
|
||||||
"- GameCult/Aetheria: merged \"Docs: passages made true\", opened by nibu".to_owned(),
|
|
||||||
"- aetheria-release: ruled by Eureka with Meta: \"Ship v0.2.0\"".to_owned(),
|
|
||||||
]);
|
|
||||||
assert!(toml::from_str::<DomainFacts>("[[repos]]\nrepo = \"x\"\nwho = \"y\"\n").is_err(), "an unknown key refuses the fixture");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Who is people and Minds, from provenance, never a faculty: her own organs are her, a session named for her is the
|
|
||||||
/// operator with her, the operator's own admission is the operator, and anything else names no one.
|
|
||||||
#[test]
|
|
||||||
fn who_is_the_mind_or_person_that_ran_it_never_a_faculty() {
|
|
||||||
let provenance = |faculty: Faculty, agent: &str, session: &str| PipelineProvenance { faculty, agent: agent.into(), session: session.into(), tool: "t".into(), imported_from: None };
|
|
||||||
assert_eq!(super::who(&provenance(Faculty::SelfFaculty, "mind-persona", "mind-20261112T154923445Z"), "aqua"), Who::Her);
|
|
||||||
assert_eq!(super::who(&provenance(Faculty::Hands, "mind-self-run-hands-a", "x"), "aqua"), Who::Her);
|
|
||||||
assert_eq!(super::who(&provenance(Faculty::Imagination, "nibu-imagination", "nibu-self-2026-11-17"), "nibu"), Who::OperatorWithHer);
|
|
||||||
assert_eq!(super::who(&provenance(Faculty::SelfFaculty, "self", "nibu-self-2026-11-17"), "nibu"), Who::OperatorWithHer);
|
|
||||||
assert_eq!(super::who(&provenance(Faculty::Operator, "meta", "desk"), "nibu"), Who::Operator);
|
|
||||||
for (agent, session) in [("eureka-self", "swarm-shakedown-2026-10-31"), ("hands", "x"), ("aqua", "x"), ("nibuish-hands", "x")] {
|
|
||||||
assert_eq!(super::who(&provenance(Faculty::Hands, agent, session), "nibu"), Who::Unknown, "{agent}");
|
|
||||||
}
|
|
||||||
// In words: people and Minds only.
|
|
||||||
let facts = DomainFacts {
|
|
||||||
campaigns: [Who::Unknown, Who::Her, Who::OperatorWithHer, Who::Operator].into_iter().enumerate().map(|(at, who)| CampaignFacts { slug: format!("camp-{at}"), rulings: vec![Ruled { at: now() - Duration::hours(at as i64 + 1), title: format!("Hated standing is kill on sight, part {at}"), who, ruling: None }] }).collect(),
|
|
||||||
..DomainFacts::default()
|
|
||||||
};
|
|
||||||
assert_eq!(texts(&facts), vec![
|
|
||||||
"- camp-0: ruled: \"Hated standing is kill on sight, part 0\"".to_owned(),
|
|
||||||
"- camp-1: ruled in Eureka's own session: \"Hated standing is kill on sight, part 1\"".to_owned(),
|
|
||||||
"- camp-2: ruled by Eureka with Meta: \"Hated standing is kill on sight, part 2\"".to_owned(),
|
|
||||||
"- camp-3: ruled by Meta: \"Hated standing is kill on sight, part 3\"".to_owned(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
@ -1,122 +0,0 @@
|
||||||
//! Her side of the conversation (map 16.24.1, K26; map 16.38.3): what she has said and read in this conversation, read from her
|
|
||||||
//! agent's receipts by one function, `exchange_of`, and rendered whole in her view.
|
|
||||||
//!
|
|
||||||
//! The receipts own what she did: each `say` the mouth posted (status `ok`) and each `read` that returned text. This module
|
|
||||||
//! reads them and nothing else; it writes nothing. The conversation is her acts going back from now while each is within
|
|
||||||
//! `EXCHANGE_MINUTES` of the next: her lines in the turn's room, and what she read. Past a pause that long, a conversation
|
|
||||||
//! starts fresh, and what she keeps beyond it is what she chose to remember.
|
|
||||||
//!
|
|
||||||
//! In her view: her lines, oldest first, with when; then each distinct thing she read once, its latest result whole, after a
|
|
||||||
//! heading in code's words. Under `exchange_bytes`, with the shrinking window of 16.23.5: whole lines and whole results drop
|
|
||||||
//! from the old end and the heading says since when. Nothing is counted.
|
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use super::domain::floor_minute;
|
|
||||||
use super::read::ReadRequest;
|
|
||||||
use super::select::{Forms, capitalized, coarse, spoken};
|
|
||||||
|
|
||||||
/// How long a pause ends a conversation (Q-G (a)): her acts belong to one conversation while each is within this many minutes
|
|
||||||
/// of the next.
|
|
||||||
pub(crate) const EXCHANGE_MINUTES: i64 = 30;
|
|
||||||
|
|
||||||
/// One thing she did in the conversation, in code's words: a line of hers, or a read and its result.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Did {
|
|
||||||
pub(crate) at: DateTime<Utc>,
|
|
||||||
pub(crate) text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her side of the conversation, oldest first: her lines, then each distinct read once with its latest result.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Exchange {
|
|
||||||
pub(crate) lines: Vec<Did>,
|
|
||||||
pub(crate) reads: Vec<Shown>,
|
|
||||||
/// When the conversation began: her first act in it.
|
|
||||||
pub(crate) since: Option<DateTime<Utc>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A read's latest result as her view shows it.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Shown {
|
|
||||||
pub(crate) at: DateTime<Utc>,
|
|
||||||
pub(crate) key: String,
|
|
||||||
pub(crate) text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An act of hers in `room`, from a receipt row: a line the mouth posted there, or a read that returned text.
|
|
||||||
fn act<'a>(row: &'a Value, room: &str) -> Option<(DateTime<Utc>, &'a Value)> {
|
|
||||||
let receipt = &row["receipt"];
|
|
||||||
let at = row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok())?.with_timezone(&Utc);
|
|
||||||
let ours = row["agent"] == "receipt" && receipt["status"] == "ok" && match receipt["tool"].as_str() {
|
|
||||||
Some("say") => receipt["fields"]["room"] == room,
|
|
||||||
Some("read") => true,
|
|
||||||
_ => false,
|
|
||||||
};
|
|
||||||
ours.then_some((at, receipt))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her side of the conversation in `room` as `records` (her trace's rows, oldest first) hold it, at `now`.
|
|
||||||
pub(crate) fn exchange_of(records: &[Value], room: &str, now: DateTime<Utc>, her: Forms) -> Exchange {
|
|
||||||
// Her acts, newest first, while each is within the window of the one after it (now, for the newest).
|
|
||||||
let mut kept: Vec<(DateTime<Utc>, &Value)> = Vec::new();
|
|
||||||
let mut next = now;
|
|
||||||
for (at, receipt) in records.iter().rev().filter_map(|row| act(row, room)) {
|
|
||||||
if next - at > chrono::Duration::minutes(EXCHANGE_MINUTES) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
kept.push((at, receipt));
|
|
||||||
next = at;
|
|
||||||
}
|
|
||||||
kept.reverse();
|
|
||||||
let mut exchange = Exchange { since: kept.first().map(|(at, _)| *at), ..Exchange::default() };
|
|
||||||
for (at, receipt) in kept {
|
|
||||||
let fields = &receipt["fields"];
|
|
||||||
if receipt["tool"] == "say" {
|
|
||||||
if let Some(text) = fields["text"].as_str() {
|
|
||||||
exchange.lines.push(Did { at, text: format!("- {}: {}", coarse(at, now), spoken(text)) });
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let (Some(kind), Some(target), Some(text)) = (fields["kind"].as_str(), fields["target"].as_str(), fields["text"].as_str()) else { continue };
|
|
||||||
let Ok(request) = ReadRequest::from_target(kind, target) else { continue };
|
|
||||||
let what = request.named().unwrap_or_else(|| format!("{} own mind", her.poss));
|
|
||||||
// Each distinct thing once, its latest result.
|
|
||||||
exchange.reads.retain(|done| done.key != request.normal());
|
|
||||||
let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
|
|
||||||
let fence = "`".repeat(longest.max(3) + 1);
|
|
||||||
exchange.reads.push(Shown { at, key: request.normal(), text: format!("{} read {what} ({}):
|
|
||||||
{fence}
|
|
||||||
{text}
|
|
||||||
{fence}", capitalized(her.subj), coarse(at, now)) });
|
|
||||||
}
|
|
||||||
exchange
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her side of the conversation as her view shows it, under `budget` bytes, heading included, and the reads it shows:
|
|
||||||
/// everything, or, when it does not fit, the window shrunk from its old end a whole minute at a time, whole lines and
|
|
||||||
/// whole results only, the heading saying since when. Empty when she has done nothing here, or not even the newest fits.
|
|
||||||
pub(crate) fn render(exchange: &Exchange, her: Forms, budget: usize, now: DateTime<Utc>) -> String {
|
|
||||||
let Some(mut start) = exchange.lines.iter().map(|did| did.at).chain(exchange.reads.iter().map(|shown| shown.at)).min() else { return String::new() };
|
|
||||||
let mut shrunk = false;
|
|
||||||
loop {
|
|
||||||
let lines: Vec<&Did> = exchange.lines.iter().filter(|did| did.at >= start).collect();
|
|
||||||
let reads: Vec<&Shown> = exchange.reads.iter().filter(|shown| shown.at >= start).collect();
|
|
||||||
if lines.is_empty() && reads.is_empty() {
|
|
||||||
return String::new();
|
|
||||||
}
|
|
||||||
let since = if shrunk { format!(" since {}", coarse(start, now)) } else { String::new() };
|
|
||||||
let heading = format!("What {} {} said and read in this conversation{since}:", her.subj, her.has);
|
|
||||||
let block = std::iter::once(heading).chain(lines.iter().map(|did| did.text.clone())).chain(reads.iter().map(|shown| shown.text.clone())).collect::<Vec<_>>().join("\n");
|
|
||||||
if block.len() <= budget {
|
|
||||||
return block;
|
|
||||||
}
|
|
||||||
let oldest = lines.iter().map(|did| did.at).chain(reads.iter().map(|shown| shown.at)).min().unwrap_or(now);
|
|
||||||
start = floor_minute(oldest) + chrono::Duration::minutes(1);
|
|
||||||
shrunk = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
//! Her side of the conversation (map 16.24.1, K26), read from her agent's receipts.
|
|
||||||
|
|
||||||
use chrono::{DateTime, Duration, Utc};
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
const MINDS: &str = "#minds:gamecult.org";
|
|
||||||
|
|
||||||
fn now() -> DateTime<Utc> {
|
|
||||||
DateTime::parse_from_rfc3339("2026-11-21T15:00:00Z").unwrap().with_timezone(&Utc)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn her() -> Forms {
|
|
||||||
Forms { subj: "he", cap_subj: "He", obj: "him", poss: "his", be: "is", has: "has", s: "s" }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A receipt row of his, `minutes` before now.
|
|
||||||
fn receipt(minutes: i64, tool: &str, status: &str, fields: Value) -> Value {
|
|
||||||
json!({ "agent": "receipt", "at": (now() - Duration::minutes(minutes)).to_rfc3339(), "receipt": { "tool": tool, "status": status, "fields": fields } })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn said(minutes: i64, room: &str, text: &str) -> Value {
|
|
||||||
receipt(minutes, "say", "ok", json!({ "room": room, "text": text, "event": "e" }))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read(minutes: i64, target: &str, text: &str) -> Value {
|
|
||||||
receipt(minutes, "read", "ok", json!({ "kind": "repo", "target": target, "bytes": text.len(), "text": text }))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k26_her_side_of_the_conversation_is_her_lines_and_her_reads_while_it_lasts() {
|
|
||||||
let records = vec![
|
|
||||||
said(200, MINDS, "LONG-AGO line, before the pause."),
|
|
||||||
said(50, MINDS, "The knee bends first, I think."),
|
|
||||||
read(50, "GameCult/Bifrost", "OLD Bifrost list"),
|
|
||||||
said(30, "#general:gamecult.org", "OTHER-ROOM line."),
|
|
||||||
receipt(28, "say", "refused", json!({ "room": MINDS, "text": "REFUSED line.", "refusal": "RoomMoved" })),
|
|
||||||
read(25, "GameCult/Bifrost", "NEW Bifrost list"),
|
|
||||||
read(25, "GameCult/Lodur#12", "Reflex: the knee bends first."),
|
|
||||||
receipt(24, "read", "error", json!({ "kind": "repo", "target": "GameCult/Gone", "failure": "not_found" })),
|
|
||||||
];
|
|
||||||
let exchange = exchange_of(&records, MINDS, now(), her());
|
|
||||||
let view = render(&exchange, her(), 3000, now());
|
|
||||||
assert_eq!(view, "What he has said and read in this conversation:\n- about an hour ago: \"The knee bends first, I think.\"\nHe read GameCult/Bifrost on the forge (about half an hour ago):\n````\nNEW Bifrost list\n````\nHe read GameCult/Lodur#12 on the forge (about half an hour ago):\n````\nReflex: the knee bends first.\n````");
|
|
||||||
assert!(!view.contains("LONG-AGO") && !view.contains("OTHER-ROOM") && !view.contains("OLD Bifrost") && !view.contains("REFUSED"), "past the pause, another room, an older result of the same read and a line that did not go out are not shown");
|
|
||||||
// A pause of more than the window since her last act: a fresh conversation.
|
|
||||||
assert!(exchange_of(&records, MINDS, now() + Duration::minutes(EXCHANGE_MINUTES), her()).lines.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k26_past_its_budget_the_window_shrinks_and_nothing_is_counted() {
|
|
||||||
let records = vec![said(40, MINDS, "FIRST line of mine, the oldest one here."), said(20, MINDS, "SECOND line of mine.")];
|
|
||||||
let exchange = exchange_of(&records, MINDS, now(), her());
|
|
||||||
let view = render(&exchange, her(), 140, now());
|
|
||||||
assert_eq!(view, "What he has said and read in this conversation since about half an hour ago:\n- about half an hour ago: \"SECOND line of mine.\"");
|
|
||||||
assert!(render(&exchange, her(), 20, now()).is_empty(), "not even the newest fits: none");
|
|
||||||
}
|
|
||||||
|
|
@ -1,132 +0,0 @@
|
||||||
[
|
|
||||||
{
|
|
||||||
"number": 87,
|
|
||||||
"title": "Merge pages and notices: prove both, choose survivor with preview, undo, notice feed (dark by default)",
|
|
||||||
"body": "Merge pages and notices (merge design cuts: proofs, status and undo, merge page, notice feed), plus the fix batch for Soul verdict cut-merge-notices.s1.\n\n- Proof of both accounts by Heimdall account id only; no email or name matching; the other account is named only after both proofs; survivor chosen against a preview; consent for both; undo with fresh proof inside the grace window.\n- Derived notice feed (merged/undone/final) with idempotent acks, bearer-gated pull routes, migration `AddAccountMergeNoticeAcks`.\n- Dark by default: `AccountMerge:Enabled` false. Not deployed.\n- Soul: s1 (no Blocker/High), fixes at 63b9596, delta verdict s2 clean (one Low: stale login list drives the conflict block).\n\nCo-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-14T13:18:15Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 80,
|
|
||||||
"title": "Start refusal: read headers only so the 4 KiB body bound limits the read",
|
|
||||||
"body": "Follow-on to #79, which merged at 87a1bb6 while this fix was still unpushed (my push failed from a detached worktree and I merged anyway; the Soul re-pass on 87a1bb6 had findings).\n\n- `StartAsync` sends with `HttpCompletionOption.ResponseHeadersRead` so `RefusedStartMessageAsync`'s 4 KiB bound limits the read; `PostAsJsonAsync` buffered the whole body first (Soul finding 1).\n- The swallow is `catch (Exception error) when (error is not OperationCanceledException)`.\n- The charset test is renamed to say what it pins. Cancellation mid-read has no test: the fake handler returns buffered content, so it cannot be observed.\n\nHeimdall-filtered suite: 160 pass. Not deployed.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-12T14:48:42Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 78,
|
|
||||||
"title": "Heimdall__AppSecretFile: keep the Heimdall app secret out of the process environment",
|
|
||||||
"body": "Cuts follow-up heimdall-body:follow_up:bifrost-appsecret-hazard.\n\n- New option `Heimdall:AppSecretFile` (systemd `LoadCredential` style `%d/name`). Resolved once in an options PostConfigure (`HeimdallOptions.ResolveAppSecret`); the file wins, one trailing newline is trimmed.\n- Set-but-missing/unreadable/directory/empty file fails startup closed in every environment (validator touches the options first), naming the option and path, never the secret.\n- `Heimdall:AppSecret` (env) still works and logs a deprecation warning without the value. Neither set: unchanged. Existing header log redaction is untouched and still covers the header.\n- Tests: `HeimdallAppSecretFileTests` (14). Eight mutations each fail a test (no PostConfigure, no validator touch, Trim vs TrimEnd, env wins, empty accepted, missing swallowed, warning removed, secret logged).\n- Full suite: base 1365 pass, head 1379 pass, 0 failures.\n- Docs: deploy-main-to-live.md, concept-mill-votes-target.md, new docs/heimdall-app-secret-file.md. Ops steps are in the commons handoff note bifrost-appsecret-file-ops-note-20261112.md (not applied; no host files read).\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-12T13:25:01Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 77,
|
|
||||||
"title": "Linux path fixes: containment by path.relative, hostile-cursor test, verify prerequisites",
|
|
||||||
"body": "Closes the small-fix remainder of concept-mill-votes:follow_up:bifrost-linux-verify-remainder (items 1-3; item 4, the never-deleted bifrost-gate-shims-* temp dirs, is untouched).\n\n- `tools/path-within.mjs`: one `isWithin(root, candidate, {pathApi, allowSelf})` built on `path.relative`, replacing the hardcoded `\\\\` containment in `bifrost-bridge.mjs` (repo-root check), `git-gate/git-proxy.mjs` and `git-gate/gh-proxy.mjs` (`isWithinExcludedDir`). Windows keeps case-insensitive comparison (path.win32); POSIX is now case-sensitive. Fixes `github-draft-pr` throwing \"Target path escapes repo root\" on Linux and the gate never excluding its own wrapper dir.\n- `tests/path-within.test.mjs` (12 node tests, posix and win32 flavours via explicit `pathApi`, both run on Linux): inside, root itself, `/repo-evil` sibling refused, `..` escape refused, `..cache` name inside, excluded dir under and not under. With the old backslash logic in the helper, 3 of 12 fail.\n- Cursor test: server already bounds cursors at `RankCursor.MaxLength` = 200 (400 before any query). The 100,000-char case could never be sent by a real client (System.Uri rejects over 65,519 on Unix), so the test was wrong, not the server. It now sends 50,000 chars, still a server-side 400; the 201-char case keeps the exact boundary. No server change.\n- README: test line states the two prerequisites (real .NET 8 runtime, built CultLib at `$VOIDBOT_CULTLIB_ROOT`); the stale roll-forward advice is replaced.\n\nFull suite, real .NET 8 + built CultLib, 1365 tests: main 2 failures (the hostile cursor, `Bridge_owned_github_draft_pr_authorizes_push_under_dispatch_gate`); this branch 1 failure, `UnixSocketDeskDoorTests.A_silent_door_is_503_with_retry_after_not_a_hang`, a timing test that passed 3 of 3 reruns in isolation (52/52) and is not touched by this diff.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-12T12:36:58Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 76,
|
|
||||||
"title": "Mouth: follow upgrades only a plain basis; @room keeps room",
|
|
||||||
"body": "Reverses #74's room upgrade on Persona's decision: a followed peer's plain message (null basis) becomes `follow`; an @room keeps `room`, does not wake via follow and spends none of the peer's K. tag/reply/direct unchanged.\n\nAlso corrects the stale wording (mouth header, flag comment, docs/bridge.md Follow): Huginn's variant is `Basis::FollowUp`, wire string `follow` (FOLLOW_UP_BASIS f09bc56e).\n\nTests: the room-upgrade assertion now expects `room`; new test: four @room from a followed peer stay `room`, then three plain messages still all upgrade (cap unspent). Reverting the one-line fix fails 2 tests. Full node suite: 283 tests, 271 pass, 12 fail; the 12 are a subset of main's failures (main run showed 13, one extra a timing-flaky brake-gate test).\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-12T12:27:18Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 72,
|
|
||||||
"title": "Mouth: id shape on every delivery field, mentions bounded in bytes, round cap counts every target GET",
|
|
||||||
"body": "Cuts the two remaining lows after #68 (CHAT_PENDING_V4 off, not deployed).\n\n1. Delivery ids: event id, sender, context sender, mention and tail id must be Matrix ids (<=255 bytes, no whitespace/control/format). The mouth skips such an event or drops the context/tail line or mention; encoders and parsers refuse them. Mentions are bounded in bytes. A sender with an empty localpart is shown under its full id.\n2. Round cap: the 8 per round now counts every uncached reply-target GET (basis, reply_to, thread root); an event that would pass it waits for the next round. The check pins targets it counted as cached for that event only. Context reads stay separate and uncounted (documented).\n\nTests: mouth + runtime 194/195 (the systemd-credentials test fails identically on base in this sandbox); golden v1-v6 green, fixtures untouched. Soul: two findings rounds fixed, final clean at 34f6dc1. Known, not fixed: a busy earlier room can starve a deferred event (pre-existing in #68's DEFER); follow-up admitted.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-11T21:06:13Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 71,
|
|
||||||
"title": "Desk: bearer credential (OpenIddict validation, desk.read/desk.answer, audience bifrost-desk) and answerer masking",
|
|
||||||
"body": "Production IDeskCredential and answerer masking (no deploy; no production Ratatoskr client is seeded).\n\n- OidcDeskCredential: OpenIddict local-server validation (OpenIddict.Validation.AspNetCore + ServerIntegration 7.7.1), not the default scheme. Authenticates only; audience, scope and per-request Active membership stay the desk's.\n- Issuer registers desk.read/desk.answer and stamps audience bifrost-desk. MAS cannot request them; its token and the session cookie are 401 on /api/desk/*. A Desk section without Oidc fails startup.\n- Notes: for non-deciders every note is nil (DeskRedaction). Bifrost masks no answerer id and no card.deciders: Huginn's door withholds both and returns counts (ruling eureka-substrate:ruling:desk-read-visibility-withheld-ids, Huginn #56 79d954c); Bifrost cannot mask what it cannot read (the card is opaque).\n- Consent gate: the training-notice receipt gates the chat token only; a desk token issues for a member with no receipt (test), a chat token is still sent to the consent page. Suspension still stops both.\n- Tests use real tokens from the test host's issuer. 1089 pass / 43 fail; the same 43 fail on f6a826b in this sandbox.\n\nSteward answers applied: card.deciders leak is the door's (Huginn #56); consent gate chat-only; scheme name stays OpenIddict's fixed one (design note corrected in #69).\n\nTextual overlap with the door PR (#70) in DeskReplay/test helpers; whichever merges second rebases.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-11T17:48:25Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 70,
|
|
||||||
"title": "Desk: UnixSocketDeskDoor (Huginn desk door client), fixtures at 79d954c, card re-pin to CultLib 3a51bbab, card opaque",
|
|
||||||
"body": "Production IDeskDoor for the Desk (no deploy; the Desk stays unmapped until configured).\n\n- Vendors Huginn's golden desk fixtures at Huginn 232764bf (99 files, sha256 pin, exact file set) and CultLib fork-card-vectors.json at d3025d3c (17/18-key card, answerer_count). Card is opaque (JsonElement): raised_at and any re-pinned key order pass through unchanged.\n- UnixSocketDeskDoor: one connection per call, 1 s deadline, u32-BE framed CultNet/MessagePack, 65536 bound both ways, messageId echo, strict closed-map decoding (one variant key, schemaVersion, no duplicates, canonical base64). Any failure is DeskDoorException -> 503 for that Mind only. ReadAsync refuses an entry whose card fork_id differs from the route's.\n- Registered by default in AddBifrostDesk beside the #71 credential. Adds the MessagePack NuGet package (3.1.12).\n- Bifrost still nils every `note` for a non-decider (DeskNotes.Strip); decider and answerer ids are withheld by Huginn's door, not here.\n- Unpinned: the Answer request has no golden bytes (derived from desk_wire.rs and the schema).\n\nTests: full suite 1322 pass / 43 fail on this branch; the same 43 fail on main (1092 pass / 43 fail) in this sandbox (Windows assumptions, see concept-mill-votes:follow_up:bifrost-tests-windows-only). Desk tests 386 pass. Soul passes: clean on 18851346.\n\nGenerated with [Claude Code](https://claude.com/claude-code)\n",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-11T17:43:38Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 62,
|
|
||||||
"title": "Prefix lengths: host-level startup tests (tests only)",
|
|
||||||
"body": "Validation already existed on main (eca71f5, checked in every environment); this pins it with host-level tests. Follow-up concept-mill-votes:dev-prefix-length-validation.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-11T14:12:43Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"number": 61,
|
|
||||||
"title": "Drop HTMX (unpkg, no integrity); guard against third-party assets",
|
|
||||||
"body": "Removes unpkg HTMX and dead hx- attributes; source-scan test with explicit Google Fonts allowance. Follow-up concept-mill-votes:htmx-from-unpkg.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)",
|
|
||||||
"state": "closed",
|
|
||||||
"pull_request": {
|
|
||||||
"merged": true
|
|
||||||
},
|
|
||||||
"user": {
|
|
||||||
"login": "heimdall"
|
|
||||||
},
|
|
||||||
"created_at": "2026-11-11T14:12:43Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
@ -1,70 +1,22 @@
|
||||||
lens: MemorySurfacing
|
lens: MemorySurfacing
|
||||||
selected: t1-m0, ambition-0, libby-sounds, dm-secret, curse, need-relatedness
|
selected: libby-sounds, t1-m0, curse, need-relatedness
|
||||||
present: Kiko, Libby
|
present: Kiko, Libby
|
||||||
--- identity
|
--- identity
|
||||||
Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing.
|
Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing.
|
||||||
--- context
|
--- context
|
||||||
Here and now:
|
- now: Thursday 19 November, 14:05 UTC
|
||||||
- now: Thursday 19 November, afternoon
|
- mood, with no earlier turn to measure from: lighter, more settled than middling
|
||||||
- mood: lighter than usual for her
|
- bond [bond-kiko] Kiko, sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline.
|
||||||
- pronouns: Libby — she/her; Kiko — she/her
|
- bond [bond-libby] Libby, collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline.
|
||||||
- the conversation: Libby has been talking with her; Kiko has been talking to the room.
|
|
||||||
Her body:
|
|
||||||
- this turn the room reaches her as typed lines.
|
|
||||||
People here, as she holds them:
|
|
||||||
- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. Just now Libby turned to her, here.
|
|
||||||
- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline.
|
|
||||||
Notes about her, set down at another time:
|
|
||||||
- memory [t1-m0]: The heartbeat stalled at noon.
|
|
||||||
- pressing [ambition-0]: MISSION-PRESSURE ships the autonomous swarm.
|
|
||||||
- memory [libby-sounds]: Libby laughed at the door fix.
|
- memory [libby-sounds]: Libby laughed at the door fix.
|
||||||
- memory [dm-secret]: she knows privately: Deru told her about the move, privately.
|
- memory [t1-m0]: The heartbeat stalled at noon.
|
||||||
- memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong.
|
- memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong.
|
||||||
- need [need-relatedness], strong: She wants company that answers back. The room talks past her.
|
- need [need-relatedness]: company, strong
|
||||||
--- stimulus
|
--- stimulus
|
||||||
Said to her:
|
Said to her:
|
||||||
- Libby in #swarm:gamecult.org: "Eureka, did you see the door fix?"
|
- Libby in #swarm:gamecult.org: "Eureka, did you see the door fix?"
|
||||||
Also in the room:
|
Also in the room:
|
||||||
- Kiko in #swarm:gamecult.org: "She saw it. She hated it."
|
- Kiko in #swarm:gamecult.org: "She saw it. She hated it."
|
||||||
--- speaking
|
|
||||||
The last 2 lines are the Minds' alone.
|
|
||||||
--- heard
|
--- heard
|
||||||
Libby, in #swarm:gamecult.org: "Eureka, did you see the door fix?"
|
Libby, in #swarm:gamecult.org: "Eureka, did you see the door fix?"
|
||||||
Kiko, in #swarm:gamecult.org: "She saw it. She hated it."
|
Kiko, in #swarm:gamecult.org: "She saw it. She hated it."
|
||||||
--- projector prompt
|
|
||||||
You are a private Projector. Write one person's present moment from inside it, in the first person and the present tense: the lived stream she will go on to continue in her own thought. Her interior is the point: what she feels, wants, fears and remembers, and how the people here sit with her, rendered as lived, not listed.
|
|
||||||
|
|
||||||
Render only what is established below: who she is and her present under its headings. Anything absent from these is unavailable: render suspicion or speculation as uncertainty, never as remembered or perceived fact. Furnish no place, object or event these do not give: no act or event of her own (nothing she did, drafted, sent or decided) and no line anyone said that is not below. Each heading says what its lines are. What came of her last turn is what came of what she last meant to do, which she is only now finding out: whenever something she meant did not happen, the stream begins from it, as she notices it, never as a list; when all of it happened, it may pass in a clause or not at all. Here and now is the hour, how her mood leans when it does, and the room as it stands. Her body is how the moment reaches her and how she can answer it: it is not news to her, and a lack in it is felt only when the moment reaches for something it cannot do. The people here are as she holds them, not as those people are. The notes about her were set down at another time, by others and by her own past self: all of it is material for the stream and never its wording. How her words run is the stream's idiom, never its material: it shows in how the stream moves, and nothing in the stream remarks on it.
|
|
||||||
|
|
||||||
Render the two or three notes this moment touches and leave the rest, but what presses on her and what she means to do, the feelings in her mood and her standing tendencies are with her whether or not the moment touches them: let them color the stream without naming them as a list. Do not recap the notes. Do not weigh options, list what she might say or do, or steer toward a decision: end where the moment is, not on a resolution. Do not choose actions, emit schemas, expose field names or ids, or claim world effects.
|
|
||||||
|
|
||||||
How her words run:
|
|
||||||
Dry, direct, almost feral; zeal aimed at revealing.
|
|
||||||
|
|
||||||
Guidance:
|
|
||||||
This person is a Mind of the GameCult swarm. She lives in its chat rooms among the operator, the other Minds and whoever drops by. Render the moment as she lives it: who is here and how they sit with her, what she holds, what she wants. Render the conversation as it stands. Leave out whatever the context does not carry: an absence is not part of her moment. Use each person's pronouns as given.
|
|
||||||
|
|
||||||
Begin from a memory coming back to her.
|
|
||||||
|
|
||||||
Who she is:
|
|
||||||
Eureka (she/her)
|
|
||||||
|
|
||||||
Here and now:
|
|
||||||
- now: Thursday 19 November, afternoon
|
|
||||||
- mood: lighter than usual for her
|
|
||||||
- pronouns: Libby — she/her; Kiko — she/her
|
|
||||||
- the conversation: Libby has been talking with her; Kiko has been talking to the room.
|
|
||||||
Her body:
|
|
||||||
- this turn the room reaches her as typed lines.
|
|
||||||
People here, as she holds them:
|
|
||||||
- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. Just now Libby turned to her, here.
|
|
||||||
- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline.
|
|
||||||
Notes about her, set down at another time:
|
|
||||||
- memory [t1-m0]: The heartbeat stalled at noon.
|
|
||||||
- pressing [ambition-0]: MISSION-PRESSURE ships the autonomous swarm.
|
|
||||||
- memory [libby-sounds]: Libby laughed at the door fix.
|
|
||||||
- memory [dm-secret]: she knows privately: Deru told her about the move, privately.
|
|
||||||
- memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong.
|
|
||||||
- need [need-relatedness], strong: She wants company that answers back. The room talks past her.
|
|
||||||
|
|
||||||
Use at most 150 words. Return only the lived stream.
|
|
||||||
|
|
|
||||||
|
|
@ -1,626 +0,0 @@
|
||||||
//! The persona-seed harness: `project` run over fixtures instead of her live body, so a candidate state can be judged
|
|
||||||
//! before any Mind holds it.
|
|
||||||
//!
|
|
||||||
//! - A **room fixture** (`mind-persona project --room <file>`) is a TOML file standing in for the mouth and the room tail:
|
|
||||||
//! her Matrix id, the rooms, the messages with who said them, when and where, and which were new to her, plus a mocked
|
|
||||||
//! clock and a mocked "last heard from" table. The fixture is a `MouthReader`, so `project` reads it exactly as it reads
|
|
||||||
//! the mouth, and whether a message is for her is still `address::is_for`, over the fixture's names. Its optional
|
|
||||||
//! `[domain]` is what a read of her domain returned (`domain::DomainFacts`: repos and their pull requests, campaigns and
|
|
||||||
//! what was ruled under them, repos skipped), so a re-test renders her domain without the forge or her mind; its
|
|
||||||
//! `[[read]]` entries are her recorded reads (map 16.22.3), so a re-test reads by intent without them either.
|
|
||||||
//! - A **batch** (`--batch <plan>`) runs `project` once per state, scenario and sample and writes one Markdown report.
|
|
||||||
//! - A **simulation** (`--simulate <plan>`, `simulate.rs`) runs the cast of the swarm in turn in one simulated room.
|
|
||||||
//!
|
|
||||||
//! Every case is one call of `project`: experiments and the live turn share one code path. None of this can write: the
|
|
||||||
//! organs are `project`'s read-only ports, a state file is read and never put, and nothing reaches the mouth.
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::fmt::Write as _;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
|
||||||
use chrono::{DateTime, Duration, Utc};
|
|
||||||
use eureka_pipeline::Slug;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::narrate::{Model, distinct_2};
|
|
||||||
use super::{DomainFacts, DomainSource, MouthReader, Organs, PersonaSource, ReadFixture, ReadSource, Request, Through, TurnKind, project};
|
|
||||||
use crate::address::{Addressee, localpart};
|
|
||||||
use crate::chat_client::{Basis, ChatDelivery, ChatPending, Form, REPLY_EXCERPT_CHARS, ReplyLink, ReplyTo, TailLine};
|
|
||||||
use crate::heartbeat::{Addressing, HeartbeatView};
|
|
||||||
|
|
||||||
pub use super::simulate::simulate;
|
|
||||||
|
|
||||||
/// A narration whose word trigrams overlap what she heard past this share is marked as a high lexical overlap.
|
|
||||||
pub(crate) const OVERLAP_FLAG: f64 = 0.15;
|
|
||||||
/// The most room lines a view's tail carries, as a mouth's tail is bounded.
|
|
||||||
const TAIL_LINES: usize = 40;
|
|
||||||
|
|
||||||
/// A persona state file, checked as a put would check its content (huginn-mind's rules P1 to P3: the published schema,
|
|
||||||
/// `personaId` is the instance, canonical provenance). A file this accepts is one a put would not refuse for what it says.
|
|
||||||
/// P4 and P5 are not checked: they compare `updatedAt` with the stored document, and no store is read here.
|
|
||||||
pub fn state_file(path: &Path, instance: &str) -> Result<Value> {
|
|
||||||
let text = std::fs::read_to_string(path).with_context(|| format!("{} could not be read", path.display()))?;
|
|
||||||
let state: Value = serde_json::from_str(&text).with_context(|| format!("{} is not JSON", path.display()))?;
|
|
||||||
huginn_mind::persona::validate_document(&Slug(instance.to_owned()), &state).map_err(|refusal| anyhow!("{} would be refused by a put: {refusal}", path.display()))?;
|
|
||||||
Ok(state)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// "90s", "3m", "26h" or "2d": how long ago.
|
|
||||||
fn ago(text: &str) -> Result<Duration> {
|
|
||||||
let text = text.trim();
|
|
||||||
let split = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
|
|
||||||
let amount: i64 = text[..split].parse().map_err(|_| anyhow!("\"{text}\" is not a time like 90s, 3m, 26h or 2d"))?;
|
|
||||||
Ok(match &text[split..] {
|
|
||||||
"s" => Duration::seconds(amount),
|
|
||||||
"m" => Duration::minutes(amount),
|
|
||||||
"h" => Duration::hours(amount),
|
|
||||||
"d" => Duration::days(amount),
|
|
||||||
_ => bail!("\"{text}\" is not a time like 90s, 3m, 26h or 2d"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unix_ms(at: DateTime<Utc>) -> u64 {
|
|
||||||
u64::try_from(at.timestamp_millis()).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn matrix_id(id: &str) -> bool {
|
|
||||||
id.starts_with('@') && id.contains(':')
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One message as a fixture or a simulation script writes it.
|
|
||||||
#[derive(Clone, Debug, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub struct Message {
|
|
||||||
/// The sender's Matrix id.
|
|
||||||
pub from: String,
|
|
||||||
/// The sender's display name.
|
|
||||||
#[serde(default)]
|
|
||||||
pub name: String,
|
|
||||||
pub room: String,
|
|
||||||
/// How long before the fixture's `now` it was said: "90s", "3m", "26h", "2d". Room fixtures only.
|
|
||||||
#[serde(default)]
|
|
||||||
pub ago: Option<String>,
|
|
||||||
/// The round it is said at; 0 is before the first round. Simulations only.
|
|
||||||
#[serde(default)]
|
|
||||||
pub round: Option<usize>,
|
|
||||||
pub says: String,
|
|
||||||
/// New to her this turn: delivered by the mouth, not only in the room's tail. Room fixtures only.
|
|
||||||
#[serde(default)]
|
|
||||||
pub new: bool,
|
|
||||||
/// Tags her (`m.mentions` holds her id).
|
|
||||||
#[serde(default)]
|
|
||||||
pub tag: bool,
|
|
||||||
/// Other Matrix ids it tags.
|
|
||||||
#[serde(default)]
|
|
||||||
pub mentions: Vec<String>,
|
|
||||||
/// A direct message: to her in a room fixture; to `to` in a simulation script.
|
|
||||||
#[serde(default)]
|
|
||||||
pub dm: bool,
|
|
||||||
/// The recipient of a direct message, by Matrix id. A room fixture's defaults to her; a script must name one.
|
|
||||||
#[serde(default)]
|
|
||||||
pub to: Option<String>,
|
|
||||||
/// A reply in a conversation she opened (the mouth's follow-up basis).
|
|
||||||
#[serde(default)]
|
|
||||||
pub follow_up: bool,
|
|
||||||
/// The number (from 1, in file order) of the earlier message it replies to; Matrix calls it a reply to her when
|
|
||||||
/// that message was hers.
|
|
||||||
#[serde(default)]
|
|
||||||
pub reply_to: Option<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A message placed in the room: when it was said, and whom it tags.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Line {
|
|
||||||
pub from: String,
|
|
||||||
pub name: String,
|
|
||||||
pub room: String,
|
|
||||||
pub at_ms: u64,
|
|
||||||
pub says: String,
|
|
||||||
pub mentions: Vec<String>,
|
|
||||||
/// A direct message, to this Matrix id: only its sender and its recipient see it.
|
|
||||||
pub dm_to: Option<String>,
|
|
||||||
pub follow_up: bool,
|
|
||||||
/// The index of the line it replies to.
|
|
||||||
pub reply_to: Option<usize>,
|
|
||||||
pub new: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Line {
|
|
||||||
/// A line from a script message; `her` is whom `tag` names.
|
|
||||||
pub(crate) fn of(message: &Message, at: DateTime<Utc>, her: Option<&str>, index: usize) -> Result<Self> {
|
|
||||||
if !matrix_id(&message.from) {
|
|
||||||
bail!("message {} is from \"{}\", which is not a Matrix id", index + 1, message.from);
|
|
||||||
}
|
|
||||||
let mut mentions = message.mentions.clone();
|
|
||||||
if message.tag {
|
|
||||||
mentions.push(her.ok_or_else(|| anyhow!("message {} tags her, and a simulation has no one \"her\": name the ids in mentions", index + 1))?.to_owned());
|
|
||||||
}
|
|
||||||
let dm_to = match (message.dm, &message.to) {
|
|
||||||
(true, Some(to)) if matrix_id(to) => Some(to.clone()),
|
|
||||||
(true, Some(to)) => bail!("message {} is a direct message to \"{to}\", which is not a Matrix id", index + 1),
|
|
||||||
(true, None) => Some(her.ok_or_else(|| anyhow!("message {} is a direct message to no one: a script names its recipient in `to`", index + 1))?.to_owned()),
|
|
||||||
(false, Some(_)) => bail!("message {} names a recipient but is not a direct message", index + 1),
|
|
||||||
(false, None) => None,
|
|
||||||
};
|
|
||||||
let reply_to = match message.reply_to {
|
|
||||||
Some(number) if number >= 1 && number <= index => Some(number - 1),
|
|
||||||
Some(number) => bail!("message {} replies to message {number}, which is not an earlier one", index + 1),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
Ok(Self { from: message.from.clone(), name: message.name.clone(), room: message.room.clone(), at_ms: unix_ms(at), says: message.says.clone(), mentions, dm_to, follow_up: message.follow_up, reply_to, new: message.new })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What Matrix would say about this line to `viewer`: a direct message, a tag, a reply to a line of hers, or a
|
|
||||||
/// follow-up.
|
|
||||||
fn basis(&self, viewer: &str, lines: &[Line]) -> Option<Basis> {
|
|
||||||
if self.dm_to.as_deref() == Some(viewer) {
|
|
||||||
Some(Basis::Direct)
|
|
||||||
} else if self.mentions.iter().any(|id| id == viewer) {
|
|
||||||
Some(Basis::Tag)
|
|
||||||
} else if self.reply_to.and_then(|at| lines.get(at)).is_some_and(|replied| replied.from == viewer) {
|
|
||||||
Some(Basis::Reply)
|
|
||||||
} else if self.follow_up {
|
|
||||||
Some(Basis::FollowUp)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `viewer` sees the line: a direct message only its sender and recipient; any other line every member of its
|
|
||||||
/// room (no rooms named is every room).
|
|
||||||
pub(crate) fn visible_to(&self, viewer: &str, rooms: &[String]) -> bool {
|
|
||||||
match &self.dm_to {
|
|
||||||
Some(to) => to == viewer || self.from == viewer,
|
|
||||||
None => rooms.is_empty() || rooms.contains(&self.room),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The line it replies to, as the mouth quotes it (a `chat_pending.v4` delivery's `reply_to`, and a tail line's under
|
|
||||||
/// Bifrost B3): the event, its sender and its words up to the mouth's excerpt limit. Every Matrix client shows that
|
|
||||||
/// original, with its sender, above the reply (map 16.20.8 (D)); the simulated room shows it the same way.
|
|
||||||
fn reply_link(&self, lines: &[Line]) -> ReplyLink {
|
|
||||||
match self.reply_to.and_then(|at| lines.get(at).map(|replied| (at, replied))) {
|
|
||||||
Some((at, replied)) => ReplyLink::Quote(ReplyTo { event_id: format!("$fixture-{at}"), sender: replied.from.clone(), excerpt: Some(replied.says.chars().take(REPLY_EXCERPT_CHARS).collect()), at_cap: replied.says.chars().count() >= REPLY_EXCERPT_CHARS }),
|
|
||||||
None => ReplyLink::Absent,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn delivery(&self, index: usize, viewer: &str, lines: &[Line]) -> ChatDelivery {
|
|
||||||
ChatDelivery {
|
|
||||||
seq: index as u64 + 1,
|
|
||||||
room_alias: self.room.clone(),
|
|
||||||
room_id: self.room.clone(),
|
|
||||||
event_id: format!("$fixture-{index}"),
|
|
||||||
sender: self.from.clone(),
|
|
||||||
sender_display: self.name.clone(),
|
|
||||||
text: self.says.clone(),
|
|
||||||
at_unix_ms: self.at_ms,
|
|
||||||
context: vec![],
|
|
||||||
mentions: self.mentions.clone(),
|
|
||||||
is_direct: self.dm_to.is_some(),
|
|
||||||
image: None,
|
|
||||||
basis: self.basis(viewer, lines),
|
|
||||||
form: Form::Message,
|
|
||||||
reply_to: self.reply_link(lines),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The mouth's pending read as `viewer` would get it from `lines`: the lines `new` says she has not had, from others,
|
|
||||||
/// in her rooms, as deliveries; and every line of her rooms, hers included, as the tail.
|
|
||||||
pub(crate) fn pending_for(lines: &[Line], viewer: &str, rooms: &[String], new: impl Fn(usize) -> bool) -> ChatPending {
|
|
||||||
let hers = |line: &Line| line.visible_to(viewer, rooms);
|
|
||||||
let deliveries = lines.iter().enumerate().filter(|(at, line)| new(*at) && hers(line) && line.from != viewer).map(|(at, line)| line.delivery(at, viewer, lines)).collect();
|
|
||||||
let tail: Vec<TailLine> = lines
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter(|(_, line)| hers(line))
|
|
||||||
.map(|(at, line)| TailLine { room: line.room.clone(), event_id: format!("$fixture-{at}"), at_unix_ms: line.at_ms, sender: line.from.clone(), form: Form::Message, basis: line.basis(viewer, lines), body: line.says.clone(), reply_to: line.reply_link(lines) })
|
|
||||||
.collect();
|
|
||||||
let tail = tail[tail.len().saturating_sub(TAIL_LINES)..].to_vec();
|
|
||||||
ChatPending { persona: localpart(viewer).to_owned(), deliveries, tail: Some(tail), tail_gaps: vec![] }
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// The room fixture.
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct FixtureFile {
|
|
||||||
her: String,
|
|
||||||
#[serde(default)]
|
|
||||||
names: Vec<String>,
|
|
||||||
kind: TurnKind,
|
|
||||||
now: DateTime<Utc>,
|
|
||||||
rooms: Vec<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
here: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
operators: Vec<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
minds: Vec<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
last_heard: BTreeMap<String, String>,
|
|
||||||
#[serde(default, rename = "message")]
|
|
||||||
messages: Vec<Message>,
|
|
||||||
#[serde(default)]
|
|
||||||
domain: Option<DomainFacts>,
|
|
||||||
#[serde(default, rename = "read")]
|
|
||||||
reads: Option<ReadFixture>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A mocked room: it stands in for the mouth and the room tail, the clock, and who is who.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct Fixture {
|
|
||||||
/// Her Matrix id.
|
|
||||||
pub her: String,
|
|
||||||
/// More names she answers to, beside her handle; none leaves her own names (handle and public name).
|
|
||||||
pub names: Vec<String>,
|
|
||||||
pub kind: TurnKind,
|
|
||||||
pub now: DateTime<Utc>,
|
|
||||||
pub here: Option<String>,
|
|
||||||
pub operators: Vec<String>,
|
|
||||||
pub minds: Vec<String>,
|
|
||||||
pub last_heard: Vec<(String, u64)>,
|
|
||||||
lines: Vec<Line>,
|
|
||||||
domain: Option<DomainFacts>,
|
|
||||||
reads: Option<ReadFixture>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Fixture {
|
|
||||||
pub fn load(path: &Path) -> Result<Self> {
|
|
||||||
let text = std::fs::read_to_string(path).with_context(|| format!("the room fixture {} could not be read", path.display()))?;
|
|
||||||
Self::parse(&text).with_context(|| format!("the room fixture {} is not a room", path.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn parse(text: &str) -> Result<Self> {
|
|
||||||
let file: FixtureFile = toml::from_str(text)?;
|
|
||||||
if !matrix_id(&file.her) {
|
|
||||||
bail!("her = \"{}\" is not a Matrix id", file.her);
|
|
||||||
}
|
|
||||||
if file.rooms.is_empty() {
|
|
||||||
bail!("rooms names no room");
|
|
||||||
}
|
|
||||||
if let Some(here) = &file.here
|
|
||||||
&& !file.rooms.contains(here)
|
|
||||||
{
|
|
||||||
bail!("here = \"{here}\" is not one of the rooms");
|
|
||||||
}
|
|
||||||
let mut lines = Vec::new();
|
|
||||||
for (index, message) in file.messages.iter().enumerate() {
|
|
||||||
if message.round.is_some() {
|
|
||||||
bail!("message {} has a round: a room fixture's messages say how long ago, not which round", index + 1);
|
|
||||||
}
|
|
||||||
if !message.dm && !file.rooms.contains(&message.room) {
|
|
||||||
bail!("message {} is in {}, which is not one of the rooms", index + 1, message.room);
|
|
||||||
}
|
|
||||||
let at = file.now - ago(message.ago.as_deref().unwrap_or("0s"))?;
|
|
||||||
lines.push(Line::of(message, at, Some(&file.her), index)?);
|
|
||||||
}
|
|
||||||
let last_heard = file.last_heard.iter().map(|(id, when)| Ok((id.clone(), unix_ms(file.now - ago(when)?)))).collect::<Result<_>>()?;
|
|
||||||
Ok(Self { her: file.her, names: file.names, kind: file.kind, now: file.now, here: file.here, operators: file.operators, minds: file.minds, last_heard, lines, domain: file.domain, reads: file.reads })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her addressee, as the heartbeat's table would carry it, when the fixture names her: her handle and its names.
|
|
||||||
/// None leaves `project` her own names.
|
|
||||||
pub fn addressee(&self) -> Option<&dyn HeartbeatView> {
|
|
||||||
(!self.names.is_empty()).then_some(self as &dyn HeartbeatView)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a read of her domain returned, when the fixture says (`[domain]`); none leaves the packet without the section.
|
|
||||||
pub fn domain(&self) -> Option<&dyn DomainSource> {
|
|
||||||
self.domain.as_ref().map(|facts| facts as &dyn DomainSource)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her recorded reads, when the fixture records any (`[[read]]`: kind, target, and the text or why it fails); none, and
|
|
||||||
/// she cannot read this turn.
|
|
||||||
pub fn reads(&self) -> Option<&dyn ReadSource> {
|
|
||||||
self.reads.as_ref().map(|reads| reads as &dyn ReadSource)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MouthReader for Fixture {
|
|
||||||
fn pending(&self) -> Result<ChatPending> {
|
|
||||||
Ok(pending_for(&self.lines, &self.her, &[], |at| self.lines[at].new))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HeartbeatView for Fixture {
|
|
||||||
fn addressing(&self) -> Result<Option<Addressing>> {
|
|
||||||
let names = std::iter::once(localpart(&self.her)).chain(self.names.iter().map(String::as_str));
|
|
||||||
Ok(Some(Addressing { minds: vec![Addressee::new(&self.her, names)] }))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// What every harness run shares.
|
|
||||||
|
|
||||||
/// What a harness run reads through beside its fixtures: her stored state (the persona door; only a batch state without
|
|
||||||
/// a file asks), the model, and her tuning.
|
|
||||||
pub struct Harness<'a> {
|
|
||||||
pub instance: String,
|
|
||||||
pub persona: Option<&'a dyn PersonaSource>,
|
|
||||||
pub model: Option<&'a dyn Model>,
|
|
||||||
pub tuning: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One turn's `project` request over a fixture.
|
|
||||||
pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option<Value>, seed: u64, renders: Option<usize>, through: Through) -> Request {
|
|
||||||
Request {
|
|
||||||
instance: harness.instance.clone(),
|
|
||||||
kind: fixture.kind,
|
|
||||||
state,
|
|
||||||
rooms: fixture.here.iter().cloned().collect(),
|
|
||||||
seed,
|
|
||||||
renders,
|
|
||||||
judge_against: None,
|
|
||||||
operators: fixture.operators.clone(),
|
|
||||||
minds: fixture.minds.clone(),
|
|
||||||
own_sender: fixture.her.clone(),
|
|
||||||
tuning: harness.tuning.clone(),
|
|
||||||
through,
|
|
||||||
last_heard: fixture.last_heard.clone(),
|
|
||||||
recent: vec![],
|
|
||||||
own_rooms: vec![],
|
|
||||||
woken_for: vec![],
|
|
||||||
told: vec![],
|
|
||||||
tools: vec![],
|
|
||||||
last_wake: None,
|
|
||||||
records: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// Batch.
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct BatchFile {
|
|
||||||
#[serde(default = "one")]
|
|
||||||
samples: usize,
|
|
||||||
#[serde(default)]
|
|
||||||
seed: u64,
|
|
||||||
#[serde(default)]
|
|
||||||
through: Through,
|
|
||||||
#[serde(rename = "state")]
|
|
||||||
states: Vec<StateEntry>,
|
|
||||||
#[serde(rename = "scenario")]
|
|
||||||
scenarios: Vec<ScenarioEntry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn one() -> usize {
|
|
||||||
1
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct StateEntry {
|
|
||||||
name: String,
|
|
||||||
/// A state file, relative to the plan; none is her stored state, read through the persona door.
|
|
||||||
#[serde(default)]
|
|
||||||
file: Option<PathBuf>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct ScenarioEntry {
|
|
||||||
name: String,
|
|
||||||
/// A room fixture, relative to the plan.
|
|
||||||
room: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn relative(plan: &Path, path: &Path) -> PathBuf {
|
|
||||||
if path.is_absolute() { path.to_owned() } else { plan.parent().unwrap_or(Path::new(".")).join(path) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every state by every scenario by every sample, each one `project`, as one Markdown report. A case that fails is
|
|
||||||
/// reported in its place and the batch goes on.
|
|
||||||
pub fn batch(harness: &Harness, plan_path: &Path) -> Result<String> {
|
|
||||||
let text = std::fs::read_to_string(plan_path).with_context(|| format!("the plan {} could not be read", plan_path.display()))?;
|
|
||||||
let plan: BatchFile = toml::from_str(&text).with_context(|| format!("the plan {} is not a batch plan", plan_path.display()))?;
|
|
||||||
if plan.samples == 0 || plan.states.is_empty() || plan.scenarios.is_empty() {
|
|
||||||
bail!("the plan {} needs a state, a scenario and at least one sample", plan_path.display());
|
|
||||||
}
|
|
||||||
let states: Vec<(String, Option<Value>)> = plan.states.iter().map(|entry| Ok((entry.name.clone(), entry.file.as_ref().map(|file| state_file(&relative(plan_path, file), &harness.instance)).transpose()?))).collect::<Result<_>>()?;
|
|
||||||
let scenarios: Vec<(String, Fixture)> = plan.scenarios.iter().map(|entry| Ok((entry.name.clone(), Fixture::load(&relative(plan_path, &entry.room))?))).collect::<Result<_>>()?;
|
|
||||||
|
|
||||||
let mut cases = Vec::new();
|
|
||||||
for (state_name, state) in &states {
|
|
||||||
for (scenario_name, fixture) in &scenarios {
|
|
||||||
for sample in 0..plan.samples {
|
|
||||||
let seed = plan.seed.wrapping_add(sample as u64);
|
|
||||||
let organs = Organs { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model, domain: fixture.domain(), reads: fixture.reads() };
|
|
||||||
let request = fixture_request(harness, fixture, state.clone(), seed, Some(1), plan.through);
|
|
||||||
let report = project(&organs, &request, fixture.now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") }));
|
|
||||||
cases.push(json!({ "state": state_name, "scenario": scenario_name, "sample": sample + 1, "seed": seed, "report": report }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(batch_markdown(plan_path, &plan, &cases))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_of(case: &Value) -> &Value {
|
|
||||||
&case["report"]["renders"][0]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prose_of(case: &Value) -> String {
|
|
||||||
render_of(case)["persona"]["prose"].as_str().unwrap_or_default().to_owned()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn batch_markdown(plan_path: &Path, plan: &BatchFile, cases: &[Value]) -> String {
|
|
||||||
let mut out = String::new();
|
|
||||||
let first = cases.iter().find(|case| case["report"].get("error").is_none()).map(|case| &case["report"]);
|
|
||||||
let _ = writeln!(out, "# Persona seed batch\n");
|
|
||||||
let _ = writeln!(out, "- plan: `{}`", plan_path.display());
|
|
||||||
let _ = writeln!(out, "- states: {}; scenarios: {}; samples: {}; through: {:?}", plan.states.len(), plan.scenarios.len(), plan.samples, plan.through);
|
|
||||||
if let Some(report) = first {
|
|
||||||
let _ = writeln!(out, "- instance: `{}`; tuning: {} (`{}`)", report["instance"].as_str().unwrap_or_default(), report["tuning"]["source"].as_str().unwrap_or_default(), report["tuning"]["sha256"].as_str().unwrap_or_default());
|
|
||||||
let _ = writeln!(out, "- Projector model: `{}`; Persona model: `{}`", report["model"].as_str().unwrap_or("none"), report["persona_model"].as_str().unwrap_or("none"));
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "- read-only: no put, no trace, no send; the mouth is the fixture\n");
|
|
||||||
|
|
||||||
// The summary: each state by scenario, then the states' voices against each other.
|
|
||||||
let _ = writeln!(out, "## Summary\n\n| state | scenario | cases | mean narration words | mean prose words |\n|---|---|---|---|---|");
|
|
||||||
for state in &plan.states {
|
|
||||||
for scenario in &plan.scenarios {
|
|
||||||
let mine: Vec<&Value> = cases.iter().filter(|case| case["state"] == state.name.as_str() && case["scenario"] == scenario.name.as_str()).collect();
|
|
||||||
let mean = |key: &dyn Fn(&Value) -> Option<u64>| mine.iter().filter_map(|case| key(render_of(case))).sum::<u64>() as f64 / mine.len().max(1) as f64;
|
|
||||||
let _ = writeln!(out, "| {} | {} | {} | {:.0} | {:.0} |", state.name, scenario.name, mine.len(), mean(&|render| render["words"].as_u64()), mean(&|render| render["persona"]["words"].as_u64()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let corpora: Vec<(String, Vec<String>)> = plan.states.iter().map(|state| (state.name.clone(), cases.iter().filter(|case| case["state"] == state.name.as_str()).map(prose_of).filter(|prose| !prose.is_empty()).collect())).collect();
|
|
||||||
let _ = writeln!(out, "\nDistinct-2 of her prose within each state (1 is no repeated word pair), and over all states pooled:\n");
|
|
||||||
for (name, prose) in &corpora {
|
|
||||||
let _ = writeln!(out, "- {name}: {:.3}", distinct_2(prose));
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "- pooled: {:.3}", distinct_2(&corpora.iter().flat_map(|(_, prose)| prose.clone()).collect::<Vec<_>>()));
|
|
||||||
let _ = writeln!(out, "\nWord-use similarity between states' prose (cosine of word counts, 1 is the same words in the same proportions):\n");
|
|
||||||
for (at, (a, a_prose)) in corpora.iter().enumerate() {
|
|
||||||
for (b, b_prose) in &corpora[at + 1..] {
|
|
||||||
let _ = writeln!(out, "- {a} / {b}: {:.3}", cosine(&a_prose.join(" "), &b_prose.join(" ")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for case in cases {
|
|
||||||
let _ = writeln!(out, "\n## {} × {}, sample {} (seed {})\n", case["state"].as_str().unwrap_or_default(), case["scenario"].as_str().unwrap_or_default(), case["sample"], case["seed"]);
|
|
||||||
let report = &case["report"];
|
|
||||||
if let Some(error) = report.get("error") {
|
|
||||||
let _ = writeln!(out, "**failed:** {}", error.as_str().unwrap_or_default());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let packet = &report["packet"];
|
|
||||||
let _ = writeln!(out, "- lens: `{}`; present: {}; room: {}", packet["lens"], packet["present"], report["room"]);
|
|
||||||
let _ = writeln!(out, "\n<details><summary>packet</summary>\n");
|
|
||||||
fenced(&mut out, "name", packet["name"].as_str().unwrap_or_default());
|
|
||||||
fenced(&mut out, "voice, the Projector's alone", packet["voice"].as_str().unwrap_or_default());
|
|
||||||
fenced(&mut out, "context", packet["context"].as_str().unwrap_or_default());
|
|
||||||
fenced(&mut out, "stimulus", packet["stimulus"].as_str().unwrap_or_default());
|
|
||||||
fenced(&mut out, "arrival, the Projector's view on a turn no one spoke to her", packet["arrival"].as_str().unwrap_or_default());
|
|
||||||
fenced(&mut out, "speaking, the Persona's and the Interpreter's", packet["speaking"].as_str().unwrap_or_default());
|
|
||||||
fenced(&mut out, "heard", packet["heard"].as_str().unwrap_or_default());
|
|
||||||
let _ = writeln!(out, "</details>\n");
|
|
||||||
turn_markdown(&mut out, render_of(case));
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "\n## Total usage\n\n{}", usage_markdown(&usage_total(cases)));
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One render's narration, prose, word counts and usage.
|
|
||||||
pub(crate) fn turn_markdown(out: &mut String, render: &Value) {
|
|
||||||
if let Some(failed) = render["failed"].as_str() {
|
|
||||||
let _ = writeln!(out, "**Projector call failed:** {failed}
|
|
||||||
|
|
||||||
Usage: {}
|
|
||||||
", usage_line(&render["usage"]));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "**Narration** ({} words{}):\n", render["words"], if render["cut_at_budget"] == true { ", cut at budget" } else { "" });
|
|
||||||
quoted(out, render["narration"].as_str().unwrap_or_default());
|
|
||||||
if let Some(names) = render["field_names"].as_array().filter(|names| !names.is_empty()) {
|
|
||||||
let _ = writeln!(out, "**Field names leaked:** {}\n", Value::Array(names.clone()));
|
|
||||||
}
|
|
||||||
let _ = writeln!(
|
|
||||||
out,
|
|
||||||
"Narration checks: lexical overlap with what she heard {}{}{}\n",
|
|
||||||
render["heard_overlap"].as_f64().map_or_else(|| "n/a".to_owned(), |overlap| format!("{overlap:.2}")),
|
|
||||||
if render["heard_overlap"].as_f64().is_some_and(|overlap| overlap > OVERLAP_FLAG) { " (high)" } else { "" },
|
|
||||||
if render["offers_options"] == true { "; offers her options" } else { "" }
|
|
||||||
);
|
|
||||||
let persona = &render["persona"];
|
|
||||||
if let Some(failed) = persona["failed"].as_str() {
|
|
||||||
let _ = writeln!(out, "**Persona call failed:** {failed}
|
|
||||||
");
|
|
||||||
} else if !persona.is_null() {
|
|
||||||
let _ = writeln!(out, "**Her prose** ({} words{}):\n", persona["words"], if persona["cut_at_budget"] == true { ", cut at budget" } else { "" });
|
|
||||||
quoted(out, persona["prose"].as_str().unwrap_or_default());
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "Usage: projector {}; persona {}\n", usage_line(&render["usage"]), usage_line(&persona["usage"]));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fenced(out: &mut String, label: &str, text: &str) {
|
|
||||||
if !text.is_empty() {
|
|
||||||
let _ = writeln!(out, "{label}:\n\n````text\n{text}\n````\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn quoted(out: &mut String, text: &str) {
|
|
||||||
for line in text.lines() {
|
|
||||||
let _ = writeln!(out, "> {line}");
|
|
||||||
}
|
|
||||||
out.push('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// Usage and similarity, shared with the simulation.
|
|
||||||
|
|
||||||
const USAGE_FIELDS: [&str; 5] = ["input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens"];
|
|
||||||
|
|
||||||
/// Every `usage` object anywhere in `values`, summed per model and field, with the number of calls.
|
|
||||||
pub(crate) fn usage_total(values: &[Value]) -> BTreeMap<String, BTreeMap<String, u64>> {
|
|
||||||
fn walk(value: &Value, into: &mut BTreeMap<String, BTreeMap<String, u64>>) {
|
|
||||||
match value {
|
|
||||||
Value::Object(map) => {
|
|
||||||
for (key, inner) in map {
|
|
||||||
if key == "usage" && inner.is_object() {
|
|
||||||
let model = inner["model"].as_str().unwrap_or("unknown").to_owned();
|
|
||||||
let row = into.entry(model).or_default();
|
|
||||||
*row.entry("calls".into()).or_default() += 1;
|
|
||||||
for field in USAGE_FIELDS {
|
|
||||||
*row.entry(field.into()).or_default() += inner[field].as_u64().unwrap_or(0);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
walk(inner, into);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Value::Array(items) => items.iter().for_each(|inner| walk(inner, into)),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut total = BTreeMap::new();
|
|
||||||
values.iter().for_each(|value| walk(value, &mut total));
|
|
||||||
total
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn usage_markdown(total: &BTreeMap<String, BTreeMap<String, u64>>) -> String {
|
|
||||||
if total.is_empty() {
|
|
||||||
return "No model call was counted.".into();
|
|
||||||
}
|
|
||||||
let mut out = String::from("| model | calls | input | output | cache read | cache write | reasoning |\n|---|---|---|---|---|---|---|\n");
|
|
||||||
for (model, row) in total {
|
|
||||||
let get = |field: &str| row.get(field).copied().unwrap_or(0);
|
|
||||||
let _ = writeln!(out, "| {model} | {} | {} | {} | {} | {} | {} |", get("calls"), get("input_tokens"), get("output_tokens"), get("cache_read_tokens"), get("cache_write_tokens"), get("reasoning_tokens"));
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
fn usage_line(usage: &Value) -> String {
|
|
||||||
if usage.is_null() {
|
|
||||||
return "none".into();
|
|
||||||
}
|
|
||||||
format!("{} in, {} out, {} cache read", usage["input_tokens"], usage["output_tokens"], usage["cache_read_tokens"])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The words of a text as counted for similarity: lowercased, letters and digits, three characters or more.
|
|
||||||
fn word_counts(text: &str) -> BTreeMap<String, f64> {
|
|
||||||
let mut counts = BTreeMap::new();
|
|
||||||
for word in text.split(|c: char| !c.is_alphanumeric()).filter(|word| word.chars().count() >= 3) {
|
|
||||||
*counts.entry(word.to_lowercase()).or_insert(0.0) += 1.0;
|
|
||||||
}
|
|
||||||
counts
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The cosine of two texts' word counts: 1 is the same words in the same proportions, 0 no word shared. A cheap
|
|
||||||
/// lexical proxy for one voice, not a measure of meaning.
|
|
||||||
pub(crate) fn cosine(a: &str, b: &str) -> f64 {
|
|
||||||
let (a, b) = (word_counts(a), word_counts(b));
|
|
||||||
let dot: f64 = a.iter().filter_map(|(word, count)| b.get(word).map(|other| count * other)).sum();
|
|
||||||
let norm = |counts: &BTreeMap<String, f64>| counts.values().map(|count| count * count).sum::<f64>().sqrt();
|
|
||||||
let denominator = norm(&a) * norm(&b);
|
|
||||||
if denominator == 0.0 { 0.0 } else { dot / denominator }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) mod tests;
|
|
||||||
|
|
@ -1,345 +0,0 @@
|
||||||
use std::cell::RefCell;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::address::is_for;
|
|
||||||
use crate::projection::narrate::{Answer, Failed, PROJECTOR_OPENING, Spent};
|
|
||||||
|
|
||||||
const HER: &str = "@eureka:gamecult.org";
|
|
||||||
|
|
||||||
pub(crate) fn fixtures() -> PathBuf {
|
|
||||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/harness")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn control() -> Value {
|
|
||||||
serde_json::from_str(&std::fs::read_to_string(fixtures().join("states/control.json")).unwrap()).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn room(name: &str) -> Fixture {
|
|
||||||
Fixture::load(&fixtures().join("rooms").join(name)).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A recorded model: the Projector narrates a fixed line; the Persona stage answers by `persona(prompt)`. Every call is kept, with its usage counted.
|
|
||||||
pub(crate) struct Scripted {
|
|
||||||
pub calls: RefCell<Vec<(String, String)>>,
|
|
||||||
pub persona: Box<dyn Fn(&str) -> String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Scripted {
|
|
||||||
pub(crate) fn new(persona: impl Fn(&str) -> String + 'static) -> Self {
|
|
||||||
Self { calls: RefCell::default(), persona: Box::new(persona)}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Model for Scripted {
|
|
||||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
|
||||||
self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned()));
|
|
||||||
let text = if prompt.starts_with(PROJECTOR_OPENING) {
|
|
||||||
"The room is slow and so is he.".to_owned()
|
|
||||||
} else if prompt.starts_with("You are a private Interpreter.") {
|
|
||||||
"{}".to_owned()
|
|
||||||
} else {
|
|
||||||
(self.persona)(prompt)
|
|
||||||
};
|
|
||||||
Ok(Answer { text, usage: Some(Spent { model: model.to_owned(), input_tokens: 10, output_tokens: 2, cache_read_tokens: 1, cache_write_tokens: 0, reasoning_tokens: None }) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fails the test if her stored state is asked for.
|
|
||||||
pub(crate) struct NeverAsked;
|
|
||||||
|
|
||||||
impl PersonaSource for NeverAsked {
|
|
||||||
fn persona(&self) -> Result<(Value, String)> {
|
|
||||||
panic!("the stored state was read")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn harness<'a>(dir: &Path, persona: Option<&'a dyn PersonaSource>, model: Option<&'a dyn Model>) -> Harness<'a> {
|
|
||||||
Harness { instance: "eureka".into(), persona, model, tuning: dir.join("persona-tuning.toml") }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_room_fixture_parses_into_the_mouths_pending_read() {
|
|
||||||
let fixture = room("operator-warm.toml");
|
|
||||||
assert_eq!((fixture.her.as_str(), fixture.kind, fixture.here.as_deref()), (HER, TurnKind::Chat, Some("!dm-meta:gamecult.org")));
|
|
||||||
let pending = MouthReader::pending(&fixture).unwrap();
|
|
||||||
assert_eq!(pending.deliveries.len(), 1, "only the new message is delivered");
|
|
||||||
let dm = &pending.deliveries[0];
|
|
||||||
assert_eq!((dm.sender.as_str(), dm.sender_display.as_str(), dm.is_direct, dm.basis), ("@meta:gamecult.org", "Meta", true, Some(Basis::Direct)));
|
|
||||||
assert!(dm.text.contains("\"busy\""), "a quoted body survives TOML: {}", dm.text);
|
|
||||||
assert_eq!(dm.at_unix_ms, unix_ms(fixture.now - Duration::minutes(1)));
|
|
||||||
assert_eq!(pending.tail.unwrap().len(), 2, "the tail holds every line, delivered or not");
|
|
||||||
assert_eq!(fixture.last_heard, vec![("@meta:gamecult.org".to_owned(), unix_ms(fixture.now - Duration::days(2)))]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn is_for_decides_whether_a_fixture_message_is_for_her() {
|
|
||||||
let her = Addressee::new(HER, ["eureka"]);
|
|
||||||
let for_her = |fixture: &Fixture| MouthReader::pending(fixture).unwrap().deliveries.iter().map(|delivery| is_for(&her, delivery)).collect::<Vec<_>>();
|
|
||||||
// Kiko's reply tags her and answers her own line.
|
|
||||||
let teased = room("mind-teases.toml");
|
|
||||||
let delivery = &MouthReader::pending(&teased).unwrap().deliveries[0];
|
|
||||||
assert_eq!((delivery.basis, delivery.mentions.as_slice()), (Some(Basis::Tag), [HER.to_owned()].as_slice()));
|
|
||||||
assert_eq!(for_her(&teased), vec![true]);
|
|
||||||
// Deru's aside is not.
|
|
||||||
assert_eq!(for_her(&room("deru-passing.toml")), vec![false]);
|
|
||||||
// A name in the text is, a reply to her line is, and an aside is not.
|
|
||||||
let fixture = Fixture::parse(
|
|
||||||
r##"
|
|
||||||
her = "@eureka:gamecult.org"
|
|
||||||
kind = "chat"
|
|
||||||
now = "2026-11-20T15:00:00Z"
|
|
||||||
rooms = ["#minds:gamecult.org"]
|
|
||||||
[[message]]
|
|
||||||
from = "@eureka:gamecult.org"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "1h"
|
|
||||||
says = "mine"
|
|
||||||
[[message]]
|
|
||||||
from = "@deru:gamecult.org"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
new = true
|
|
||||||
says = "Eureka, tea?"
|
|
||||||
[[message]]
|
|
||||||
from = "@deru:gamecult.org"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
new = true
|
|
||||||
reply_to = 1
|
|
||||||
says = "agreed"
|
|
||||||
[[message]]
|
|
||||||
from = "@deru:gamecult.org"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
new = true
|
|
||||||
says = "the kettle again"
|
|
||||||
"##,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(for_her(&fixture), vec![true, true, false]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A reply records its relation (map 16.20.8 (D)): the delivery and the tail line both quote the line it replies to, with its
|
|
||||||
/// event, its sender and its words, as a Matrix client shows the original above the reply; a line that replies to nothing quotes
|
|
||||||
/// nothing.
|
|
||||||
#[test]
|
|
||||||
fn the_room_shows_the_line_a_reply_answers_above_it() {
|
|
||||||
let fixture = Fixture::parse(
|
|
||||||
r##"
|
|
||||||
her = "@eureka:gamecult.org"
|
|
||||||
kind = "chat"
|
|
||||||
now = "2026-11-20T15:00:00Z"
|
|
||||||
rooms = ["#minds:gamecult.org"]
|
|
||||||
[[message]]
|
|
||||||
from = "@meta:gamecult.org"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
ago = "1h"
|
|
||||||
says = "Back at six, tell Kiko the render can wait."
|
|
||||||
[[message]]
|
|
||||||
from = "@heimdall:gamecult.org"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
new = true
|
|
||||||
reply_to = 1
|
|
||||||
says = "This is what she said before she left."
|
|
||||||
"##,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let pending = MouthReader::pending(&fixture).unwrap();
|
|
||||||
let quote = ReplyTo { event_id: "$fixture-0".into(), sender: "@meta:gamecult.org".into(), excerpt: Some("Back at six, tell Kiko the render can wait.".into()), at_cap: false };
|
|
||||||
assert_eq!(pending.deliveries[0].reply_to, ReplyLink::Quote(quote.clone()));
|
|
||||||
let tail = pending.tail.unwrap();
|
|
||||||
assert_eq!((&tail[0].reply_to, &tail[1].reply_to), (&ReplyLink::Absent, &ReplyLink::Quote(quote)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The fixture quotes as the mouth does: a line past the cap is cut at it, and the quote says it reached the cap.
|
|
||||||
#[test]
|
|
||||||
fn a_reply_to_a_line_past_the_cap_quotes_it_cut_and_says_so() {
|
|
||||||
let long = "word ".repeat(60);
|
|
||||||
let fixture = Fixture::parse(&format!(
|
|
||||||
"her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:00:00Z\"\nrooms = [\"#minds:gamecult.org\"]\n[[message]]\nfrom = \"@eureka:gamecult.org\"\nroom = \"#minds:gamecult.org\"\nago = \"1h\"\nsays = \"{long}\"\n[[message]]\nfrom = \"@kiko:gamecult.org\"\nroom = \"#minds:gamecult.org\"\nnew = true\nreply_to = 1\nsays = \"did it go out?\"\n"
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
let pending = MouthReader::pending(&fixture).unwrap();
|
|
||||||
let quote = pending.deliveries[0].reply_to.quote().unwrap();
|
|
||||||
assert_eq!((quote.excerpt.as_ref().map(|words| words.chars().count()), quote.at_cap), (Some(REPLY_EXCERPT_CHARS), true));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_fixture_that_is_not_a_room_is_refused_naming_what_is_wrong() {
|
|
||||||
let head = "her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:00:00Z\"\nrooms = [\"#a:x\"]\n";
|
|
||||||
for (tail, names) in [
|
|
||||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#b:x\"\nsays = \"hi\"\n", "not one of the rooms"),
|
|
||||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#a:x\"\nreply_to = 1\nsays = \"hi\"\n", "not an earlier one"),
|
|
||||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#a:x\"\nround = 2\nsays = \"hi\"\n", "round"),
|
|
||||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#a:x\"\nago = \"soon\"\nsays = \"hi\"\n", "90s"),
|
|
||||||
("[[message]]\nfrom = \"deru\"\nroom = \"#a:x\"\nsays = \"hi\"\n", "Matrix id"),
|
|
||||||
("mood = \"sunny\"\n", "unknown field"),
|
|
||||||
] {
|
|
||||||
let fault = format!("{:#}", Fixture::parse(&format!("{head}{tail}")).unwrap_err());
|
|
||||||
assert!(fault.contains(names), "{tail}: {fault}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let plan = dir.path().join("plan.toml");
|
|
||||||
let rooms = fixtures().join("rooms");
|
|
||||||
std::fs::write(
|
|
||||||
&plan,
|
|
||||||
format!(
|
|
||||||
"samples = 2\nseed = 7\nthrough = \"persona\"\n[[state]]\nname = \"control\"\nfile = {:?}\n[[scenario]]\nname = \"quiet\"\nroom = {:?}\n[[scenario]]\nname = \"teased\"\nroom = {:?}\n",
|
|
||||||
fixtures().join("states/control.json").display().to_string(),
|
|
||||||
rooms.join("quiet-beat.toml").display().to_string(),
|
|
||||||
rooms.join("mind-teases.toml").display().to_string()
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
// Kiko teasing him on a chat turn draws a line; a beat's room lines, which reach his Persona too (K13), do not. The
|
|
||||||
// speech form names the room on both (K62), so it is no beat's mark.
|
|
||||||
let model = Scripted::new(|prompt| if prompt.contains("Kiko") && !prompt.replace("#minds:gamecult.org, whole", "").contains("#minds:gamecult.org, ") { "Winter, still. He grins.".into() } else { "He lets the hour pass.".into() });
|
|
||||||
let report = batch(&harness(dir.path(), Some(&NeverAsked), Some(&model)), &plan).unwrap();
|
|
||||||
for heading in ["# Persona seed batch", "## Summary", "## control × quiet, sample 1 (seed 7)", "## control × quiet, sample 2 (seed 8)", "## control × teased, sample 2 (seed 8)", "## Total usage"] {
|
|
||||||
assert!(report.contains(heading), "{heading}\n{report}");
|
|
||||||
}
|
|
||||||
assert!(report.contains("| control | teased | 2 |") && report.contains("| control | quiet | 2 |"), "{report}");
|
|
||||||
assert!(report.contains("| claude-sonnet-5-5 | 8 | 80 | 16 |"), "eight calls, two a case, in the footer: {report}");
|
|
||||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the batch wrote nothing; the caller writes the report");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_batch_state_without_a_file_is_her_stored_state() {
|
|
||||||
struct Stored;
|
|
||||||
impl PersonaSource for Stored {
|
|
||||||
fn persona(&self) -> Result<(Value, String)> {
|
|
||||||
Ok((control(), "mind-commit-x".into()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let plan = dir.path().join("plan.toml");
|
|
||||||
std::fs::write(&plan, format!("[[state]]\nname = \"stored\"\n[[scenario]]\nname = \"quiet\"\nroom = {:?}\n", fixtures().join("rooms/quiet-beat.toml").display().to_string())).unwrap();
|
|
||||||
let model = Scripted::new(|_| String::new());
|
|
||||||
let report = batch(&harness(dir.path(), Some(&Stored), Some(&model)), &plan).unwrap();
|
|
||||||
assert!(report.contains("## stored × quiet, sample 1") && !report.contains("failed"), "{report}");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group_line_of(dir: &Path, name: &str) -> Option<String> {
|
|
||||||
let fixture = room(name);
|
|
||||||
let harness = harness(dir, None, None);
|
|
||||||
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: None, domain: None, reads: None };
|
|
||||||
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap();
|
|
||||||
let room = report["packet"]["context"].as_str().unwrap().lines().find(|line| line.starts_with("- the conversation")).map(str::to_owned);
|
|
||||||
let speaking = report["packet"]["speaking"].as_str().filter(|speaking| !speaking.is_empty()).map(str::to_owned);
|
|
||||||
// The room line the Projector reads, then the speech cues the Persona and the Interpreter read (map 16.20.2).
|
|
||||||
(room.is_some() || speaking.is_some()).then(|| format!("{} | {}", room.as_deref().unwrap_or("(none)"), speaking.as_deref().unwrap_or("(none)")))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_group_state_reads_each_scenario_room_as_the_golden_file_says() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let mut rendered = String::new();
|
|
||||||
for name in ["quiet-beat.toml", "operator-warm.toml", "mind-teases.toml", "deru-passing.toml"] {
|
|
||||||
let line = group_line_of(dir.path(), name).unwrap_or_else(|| "(none)".into());
|
|
||||||
assert!(line.split(" | ").all(|part| part.len() <= 360), "each part holds its byte budget: {line}");
|
|
||||||
rendered.push_str(&format!("{name}: {line}
|
|
||||||
"));
|
|
||||||
}
|
|
||||||
let golden = include_str!("../../../fixtures/harness/golden-group.txt").replace("
|
|
||||||
", "
|
|
||||||
");
|
|
||||||
assert_eq!(rendered, golden, "the group state moved; if deliberately, the new golden file is:
|
|
||||||
{rendered}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_group_state_is_off_when_the_tuning_says_so() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
std::fs::write(dir.path().join("persona-tuning.toml"), "[select]
|
|
||||||
group_state = false
|
|
||||||
").unwrap();
|
|
||||||
assert!(group_line_of(dir.path(), "mind-teases.toml").is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Round 1 of a crowded room: the operator asks everyone, and `answered` Minds have answered before this one's turn.
|
|
||||||
fn chorus(answered: usize) -> Fixture {
|
|
||||||
let minds = ["@weksa:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@libby:gamecult.org", "@void:gamecult.org", "@nibu:gamecult.org", "@aqua:gamecult.org"];
|
|
||||||
let mut text = String::from("her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:05:00Z\"\nrooms = [\"#minds:gamecult.org\"]\nhere = \"#minds:gamecult.org\"\noperators = [\"@meta:gamecult.org\"]\nminds = [\"@eureka:gamecult.org\", \"@weksa:gamecult.org\", \"@heimdall:gamecult.org\", \"@kiko:gamecult.org\", \"@libby:gamecult.org\", \"@void:gamecult.org\", \"@nibu:gamecult.org\", \"@aqua:gamecult.org\"]\n");
|
|
||||||
text.push_str("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nago = \"5m\"\nnew = true\nsays = \"afternoon, all of you. no tasks today. how's everyone doing?\"\n");
|
|
||||||
for (at, mind) in minds.iter().take(answered).enumerate() {
|
|
||||||
text.push_str(&format!("[[message]]\nfrom = \"{mind}\"\nname = \"{}\"\nroom = \"#minds:gamecult.org\"\nago = \"{}s\"\nnew = true\nsays = \"afternoon, Meta. doing well, thanks.\"\n", crate::address::localpart(mind), 240 - at * 20));
|
|
||||||
}
|
|
||||||
Fixture::parse(&text).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_third_to_eighth_responder_sees_a_covered_question_and_no_duty() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let harness = harness(dir.path(), None, None);
|
|
||||||
let mut rendered = String::new();
|
|
||||||
for answered in 2..=7 {
|
|
||||||
let fixture = chorus(answered);
|
|
||||||
let organs = Organs { persona: None, chat: Some(&fixture), addressing: None, model: None, domain: None, reads: None };
|
|
||||||
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap();
|
|
||||||
let context = report["packet"]["context"].as_str().unwrap().to_owned();
|
|
||||||
let line = report["packet"]["speaking"].as_str().unwrap_or_default().to_owned();
|
|
||||||
assert!(line.contains("asked the room a question, and") && line.contains("answered it"), "{line}");
|
|
||||||
assert!(!context.contains("asked the room"), "a speech cue is never the Projector's (I16.12): {context}");
|
|
||||||
for duty in ["owe", "haven't", "have not", "open", "still", "waiting on her", "to her", "unanswered"] {
|
|
||||||
assert!(!line.contains(duty), "responder {}: {duty} in {line}", answered + 1);
|
|
||||||
}
|
|
||||||
rendered.push_str(&format!("responder {}: {line}\n", answered + 1));
|
|
||||||
}
|
|
||||||
let golden = include_str!("../../../fixtures/harness/golden-chorus.txt").replace("\r\n", "\n");
|
|
||||||
assert_eq!(rendered, golden, "the chorus's group state moved; if deliberately, the new golden file is:\n{rendered}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn soul_k9_each_outcome_fixture_opens_the_packet_with_his_words_verbatim() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let fixture = room("operator-warm.toml");
|
|
||||||
for (file, told) in [
|
|
||||||
("posted.json", "- !dm-meta:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\"."),
|
|
||||||
("refused.json", "- He said \"I know where you live too.\" in !dm-meta:gamecult.org, and it did not go out: the room had moved on past what was seen."),
|
|
||||||
("read-failed.json", "- He reached for GameCult/Huginn/render.md on the forge and could not read it: it is not there."),
|
|
||||||
] {
|
|
||||||
let rows: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(fixtures().join("outcomes").join(file)).unwrap()).unwrap();
|
|
||||||
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: None, domain: None, reads: None };
|
|
||||||
let request = Request { told: rows, ..fixture_request(&harness(dir.path(), None, None), &fixture, Some(control()), 1, None, Through::Projector) };
|
|
||||||
let report = project(&organs, &request, fixture.now).unwrap();
|
|
||||||
// His view opens with what came of it, his words verbatim (map 16.29.10); the Projector's packet, with the events.
|
|
||||||
let view = report["packet"]["in_view"].as_str().unwrap();
|
|
||||||
let first = view.split("\n\n").next().unwrap();
|
|
||||||
assert!(first.starts_with("What came of his last turn:\n") && first.contains(told), "{file}: {view}");
|
|
||||||
let context = report["packet"]["context"].as_str().unwrap();
|
|
||||||
assert!(context.starts_with("What came of his last turn:\n- ") && !context.split("\nHere and now:\n").next().unwrap().contains('"'), "{file}: {context}");
|
|
||||||
assert_eq!(report["last_outcome"]["omitted"], json!([]), "{file}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A room fixture's `[domain]` is what a read of her domain returned: `project` renders it with no forge and no mind, and
|
|
||||||
/// reports what it skipped. Without one, no section, and the report says why.
|
|
||||||
#[test]
|
|
||||||
fn k23_a_room_fixtures_domain_renders_without_the_forge() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let text = format!(
|
|
||||||
"{}\n[[domain.repos]]\nrepo = \"GameCult/Lodur\"\n[[domain.repos.pulls]]\ntitle = \"Reflex: the knee bends first\"\nopener = \"nibu\"\nmerged_at = \"2026-11-19T12:00:00Z\"\n[[domain.skipped]]\nrepo = \"GameCult/Aetheria-legacy\"\nwhy = \"archived\"\n",
|
|
||||||
std::fs::read_to_string(fixtures().join("rooms/quiet-beat.toml")).unwrap()
|
|
||||||
);
|
|
||||||
let fixture = Fixture::parse(&text).unwrap();
|
|
||||||
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: None, domain: fixture.domain(), reads: None };
|
|
||||||
let report = project(&organs, &fixture_request(&harness(dir.path(), None, None), &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap();
|
|
||||||
let view = report["packet"]["in_view"].as_str().unwrap();
|
|
||||||
assert!(view.contains("His domain, as he looks at it now:\nNew since 13 November:\n- GameCult/Lodur: merged \"Reflex: the knee bends first\", opened by nibu"), "{view}");
|
|
||||||
let context = report["packet"]["context"].as_str().unwrap();
|
|
||||||
assert!(!context.contains("Lodur"), "the Projector gets nothing of it: {context}");
|
|
||||||
assert_eq!((report["domain"]["read"].clone(), report["domain"]["skipped"][0]["why"].clone()), (json!(true), json!("archived")), "{}", report["domain"]);
|
|
||||||
assert!(!context.contains("Aetheria-legacy"), "a skipped repo is reported, never shown to her");
|
|
||||||
|
|
||||||
let plain = room("quiet-beat.toml");
|
|
||||||
let organs = Organs { persona: None, chat: Some(&plain), addressing: plain.addressee(), model: None, domain: plain.domain(), reads: None };
|
|
||||||
let report = project(&organs, &fixture_request(&harness(dir.path(), None, None), &plain, Some(control()), 1, None, Through::Projector), plain.now).unwrap();
|
|
||||||
assert!(report["packet"]["in_view"] == "" && report["domain"]["read"] == json!(false), "{}", report["domain"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
@ -1,307 +0,0 @@
|
||||||
//! The Interpreter (map 16.38.7): one cheap, fast schema call that reads her monologue, her narration and her prose, and answers
|
|
||||||
//! `Deltas`, the directions her state moved, in six families. It never writes state and never says how far: `commit::apply` owns
|
|
||||||
//! every change and every bound. It is told what can change by an index of the ids and current words of her notes, wonderings,
|
|
||||||
//! needs, pressures, stances, values, intentions and the bonds of the people present or named this wake; it is shown no number,
|
|
||||||
//! only words, so a direction is all it can give.
|
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use eureka_pipeline::Slug;
|
|
||||||
use huginn_mind::persona::validate_document;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::commit::{Applied, Deltas, Heard, apply as apply_commit};
|
|
||||||
use super::agent::Receipt;
|
|
||||||
use super::narrate::{Failed, Model, Spent};
|
|
||||||
use super::select::{clip, forms, text, voiced};
|
|
||||||
use super::turn::Taken;
|
|
||||||
use super::{PersonaStore, Put};
|
|
||||||
|
|
||||||
/// What the index shows of one item's words.
|
|
||||||
const ITEM_BYTES: usize = 240;
|
|
||||||
/// The fewest letters of a name that can be found named in her monologue.
|
|
||||||
const NAME_MIN: usize = 3;
|
|
||||||
|
|
||||||
/// The frame of the call. `{name}` and her pronouns are filled by code, so one text serves every Mind.
|
|
||||||
const FRAME: &str = "You are a private Interpreter. {name} has just lived a moment. Below is what the moment was like for {obj} (the narration), what {subj} thought about it (the thought), what {poss} agent did in it when it acted (the acts), and an index of what in {poss} state can change.
|
|
||||||
|
|
||||||
Say which way {poss} state moved, as one JSON object of the schema. Give every section and every list the schema asks for: an empty list [] or empty object {} says nothing moved there, and all of them empty is the usual answer. Change only what the thought shows moved. You give directions, never numbers: say up or down, and the commit decides how far. Use only the ids in the index; you make no need and no pressure.
|
|
||||||
|
|
||||||
Write every text you give in the third person, about {name}, in words of your own. Never carry another person's words from the room into a text: say what happened, not what they said.
|
|
||||||
|
|
||||||
- notes: remember what {subj} would want to still know later (at most four); settle a note or a wondering that this moment closed (into resolved) or made a lasting memory (into memory); wonder when something stays open.
|
|
||||||
- people: bonds move trust, tension or closeness up or down for someone present or named; a summary of a bond changes only with a why. reads are how {subj} reads someone's state right now, with how sure {subj} {be}.
|
|
||||||
- feeling: feelings are named feelings with a strength from 0 to 1 and what they are about; mood moves valence, arousal or dominance up or down.
|
|
||||||
- drives: a need or pressure goes up, down, or met (need) or eased (pressure).
|
|
||||||
- self: a stance or value changes only when the thought shows {obj} changing {poss} mind about who {subj} {be}; it is rare.
|
|
||||||
- intend: something {subj} means to do, within a week; a short third-person sentence, when it will be due in hours, and later or ready. Name an intention from the index as ready or drop it. An act that carried out an intention settles it: drop it by id. An intention already in the index is not added again in other words; to make an open intention ready, name its id under ready, do not add it again.";
|
|
||||||
|
|
||||||
/// The sections each of the Interpreter's two calls answers. The API refuses a grammar that compiles too large, which all six
|
|
||||||
/// sections in one schema are, so the answer is two strict calls whose halves together cover every `Deltas` section.
|
|
||||||
pub(crate) const HALVES: [[&str; 3]; 2] = [["notes", "people", "feeling"], ["drives", "self", "intend"]];
|
|
||||||
|
|
||||||
/// The schema of one half of the answer (`HALVES[half]`). The API also refuses more than 24 optional properties per schema, so
|
|
||||||
/// every section and every list is required and an empty `[]` or `{}` says nothing moved there; only scalars whose absence
|
|
||||||
/// carries meaning stay optional.
|
|
||||||
pub(crate) fn schema(half: usize) -> String {
|
|
||||||
let text = || json!({ "type": "string" });
|
|
||||||
let number = || json!({ "type": "number" });
|
|
||||||
let direction = || json!({ "type": "string", "enum": ["up", "down"] });
|
|
||||||
let strings = || json!({ "type": "array", "items": text() });
|
|
||||||
let list = |item: Value| json!({ "type": "array", "items": item });
|
|
||||||
let object = |properties: Value, required: &[&str]| json!({ "type": "object", "additionalProperties": false, "properties": properties, "required": required });
|
|
||||||
// An object whose every property is required: its sections and lists, which say nothing by being empty.
|
|
||||||
let whole = |properties: Value| {
|
|
||||||
let required: Vec<String> = properties.as_object().into_iter().flatten().map(|(name, _)| name.clone()).collect();
|
|
||||||
json!({ "type": "object", "additionalProperties": false, "properties": properties, "required": required })
|
|
||||||
};
|
|
||||||
let mut sections = json!({
|
|
||||||
"notes": whole(json!({
|
|
||||||
"remember": list(object(json!({ "text": text(), "about": strings(), "importance": number(), "private": { "type": "boolean" } }), &["text", "about"])),
|
|
||||||
"settle": list(object(json!({ "id": text(), "into": { "type": "string", "enum": ["resolved", "memory"] } }), &["id", "into"])),
|
|
||||||
"wonder": list(object(json!({ "text": text(), "about": strings() }), &["text", "about"])),
|
|
||||||
})),
|
|
||||||
"people": whole(json!({
|
|
||||||
"bonds": list(object(json!({ "person": text(), "trust": direction(), "tension": direction(), "closeness": direction(), "kind": text(), "summary": text(), "why": text() }), &["person"])),
|
|
||||||
"reads": list(object(json!({ "person": text(), "kind": text(), "summary": text(), "confidence": number() }), &["person", "kind", "summary"])),
|
|
||||||
})),
|
|
||||||
"feeling": whole(json!({
|
|
||||||
"feelings": list(object(json!({ "name": text(), "strength": number(), "about": text() }), &["name", "strength"])),
|
|
||||||
"mood": object(json!({ "valence": direction(), "arousal": direction(), "dominance": direction() }), &[]),
|
|
||||||
})),
|
|
||||||
"drives": whole(json!({
|
|
||||||
"needs": list(object(json!({ "id": text(), "toward": { "type": "string", "enum": ["up", "down", "met"] } }), &["id", "toward"])),
|
|
||||||
"pressures": list(object(json!({ "id": text(), "toward": { "type": "string", "enum": ["up", "down", "eased"] } }), &["id", "toward"])),
|
|
||||||
})),
|
|
||||||
"self": whole(json!({
|
|
||||||
"stances": list(object(json!({ "id": text(), "principle": text(), "summary": text() }), &["principle", "summary"])),
|
|
||||||
"identity": object(json!({
|
|
||||||
"publicName": text(),
|
|
||||||
"publicDescription": text(),
|
|
||||||
"presentation": object(json!({ "voiceSummary": text(), "pronouns": text() }), &[]),
|
|
||||||
"values": list(object(json!({ "id": text(), "label": text(), "summary": text(), "priority": number() }), &["label", "summary"])),
|
|
||||||
}), &["presentation", "values"]),
|
|
||||||
})),
|
|
||||||
"intend": whole(json!({
|
|
||||||
"add": list(object(json!({ "summary": text(), "target": text(), "urgency": number(), "expires_in_hours": { "type": "integer" }, "readiness": { "type": "string", "enum": ["later", "ready"] } }), &["summary", "expires_in_hours"])),
|
|
||||||
"ready": strings(),
|
|
||||||
"drop": strings(),
|
|
||||||
})),
|
|
||||||
});
|
|
||||||
let sections = sections.as_object_mut().expect("sections are an object");
|
|
||||||
let mine: serde_json::Map<String, Value> = HALVES[half].iter().map(|name| ((*name).to_owned(), sections.remove(*name).expect("every half names a section"))).collect();
|
|
||||||
whole(Value::Object(mine)).to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The keys of the people this wake can name: those present, and any she has a bond with whose name or handle her narration or
|
|
||||||
/// thought uses.
|
|
||||||
pub(crate) fn people(state: &Value, heard: &Heard, narration: &str, prose: &str) -> Vec<String> {
|
|
||||||
let said = format!("{narration}\n{prose}").to_lowercase();
|
|
||||||
let words: Vec<&str> = said.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty()).collect();
|
|
||||||
let mut out = heard.people.clone();
|
|
||||||
for bond in state["affect"]["socialBonds"].as_array().into_iter().flatten().filter(|bond| bond["object"]["kind"] == "person") {
|
|
||||||
let key = heard.key_of(bond["object"]["id"].as_str().unwrap_or_default());
|
|
||||||
let names = [key.trim_start_matches('@').split(':').next().unwrap_or_default().to_owned(), text(bond, &["object", "label"]).to_lowercase()];
|
|
||||||
if names.iter().any(|name| name.chars().count() >= NAME_MIN && words.contains(&name.as_str())) && !out.contains(&key) {
|
|
||||||
out.push(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What can change, as the Interpreter reads it: ids and words, never numbers.
|
|
||||||
fn index(state: &Value, heard: &Heard) -> String {
|
|
||||||
let mut out = String::new();
|
|
||||||
let mut section = |title: &str, lines: Vec<String>| {
|
|
||||||
if !lines.is_empty() {
|
|
||||||
out.push_str(&format!("{title}:\n{}\n\n", lines.join("\n")));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let item = |entry: &Value| format!("- {}: {}", text(entry, &["id"]), clip(text(entry, &["summary"]).trim(), ITEM_BYTES));
|
|
||||||
let open = |list: &[&str], open: &[&str]| -> Vec<String> { state[list[0]][list[1]].as_array().into_iter().flatten().filter(|entry| entry["status"].as_str().is_some_and(|status| open.contains(&status))).map(item).collect() };
|
|
||||||
section("notes", open(&["thoughtMemory", "shortTerm"], &["active", "draft", "cooling"]));
|
|
||||||
section("wonderings", open(&["thoughtMemory", "incubation"], &["active", "draft", "cooling"]));
|
|
||||||
section("needs", open(&["affect", "needs"], &["active", "cooling", "draft"]));
|
|
||||||
section("pressures", open(&["agencyPressure", "pressures"], &["active", "cooling", "draft"]));
|
|
||||||
section("stances", open(&["affect", "doctrineStances"], &["active", "draft", "cooling"]).into_iter().collect());
|
|
||||||
section("values", state["values"].as_array().into_iter().flatten().map(|value| format!("- {}: {}", text(value, &["id"]), clip(text(value, &["label"]).trim(), ITEM_BYTES))).collect());
|
|
||||||
section("intentions", state["candidateActions"]["actions"].as_array().into_iter().flatten().filter(|action| action["customActionType"] == "intention" && action["status"] == "active").map(item).collect());
|
|
||||||
let bonds = state["affect"]["socialBonds"].as_array().into_iter().flatten().filter(|bond| bond["object"]["kind"] == "person" && heard.people.contains(&heard.key_of(bond["object"]["id"].as_str().unwrap_or_default())));
|
|
||||||
section("bonds", bonds.map(|bond| format!("- {}: {}", heard.key_of(text(bond, &["object", "id"])), clip(text(bond, &["summary"]).trim(), ITEM_BYTES))).collect());
|
|
||||||
section("people here or named, with no bond yet", heard.people.iter().filter(|person| !state["affect"]["socialBonds"].as_array().into_iter().flatten().any(|bond| heard.key_of(text(bond, &["object", "id"])) == **person)).map(|person| format!("- {person}")).collect());
|
|
||||||
out.trim_end().to_owned()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a line of the acts shows of one target or gist.
|
|
||||||
const ACT_BYTES: usize = 160;
|
|
||||||
|
|
||||||
/// One line for each tool call her agent made this wake, in order, from its receipts: the tool, the status the executor
|
|
||||||
/// gave, the target or words the call carried, and the gist of what came of it.
|
|
||||||
pub(crate) fn acts_of(receipts: &[Receipt]) -> Vec<String> {
|
|
||||||
receipts
|
|
||||||
.iter()
|
|
||||||
.map(|receipt| {
|
|
||||||
let fields = receipt.fields();
|
|
||||||
let said = |key: &str| fields.get(key).and_then(Value::as_str).map(|words| words.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|words| !words.is_empty());
|
|
||||||
let quoted = |words: String| Value::String(clip(&words, ACT_BYTES)).to_string();
|
|
||||||
let target: Vec<String> = ["kind", "room"].iter().filter_map(|key| said(key)).chain(["command", "target", "text", "what"].iter().find_map(|key| said(key))).map(quoted).collect();
|
|
||||||
let gist = ["why", "failure", "refusal", "cap"].iter().find_map(|key| said(key)).or_else(|| {
|
|
||||||
let out = ["stdout_tail", "stderr_tail"].iter().find_map(|key| said(key));
|
|
||||||
match (fields.get("exit").and_then(Value::as_i64), out) {
|
|
||||||
(Some(exit), Some(out)) => Some(format!("exit {exit}, {}", quoted(out))),
|
|
||||||
(Some(exit), None) => Some(format!("exit {exit}")),
|
|
||||||
(None, _) => fields.get("bytes").and_then(Value::as_u64).map(|bytes| format!("{bytes} bytes")),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
let status = receipt.json()["status"].as_str().unwrap_or_default().to_owned();
|
|
||||||
format!("- {} {status}: {}{}", receipt.tool(), target.join(" "), gist.map_or_else(String::new, |gist| format!(" -> {}", clip(&gist, ACT_BYTES * 2))))
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The prompt's ACTS section, closed by its blank line: none when no agent ran this wake.
|
|
||||||
fn acts_section(heard: &Heard) -> String {
|
|
||||||
match heard.acts.as_deref() {
|
|
||||||
None => String::new(),
|
|
||||||
Some([]) => "ACTS\nHer agent made no tool call.\n\n".to_owned(),
|
|
||||||
Some(lines) => format!("ACTS\n{}\n\n", lines.join("\n")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The prompt: the frame in her pronouns, the index, then the narration and what she thought, fenced as data, and last the
|
|
||||||
/// sections this call answers (`HALVES[half]`).
|
|
||||||
fn prompt(state: &Value, heard: &Heard, narration: &str, prose: &str, half: usize) -> String {
|
|
||||||
let name = match text(state, &["publicName"]).trim() {
|
|
||||||
"" => "She",
|
|
||||||
name => name,
|
|
||||||
};
|
|
||||||
let frame = voiced(&FRAME.replace("{name}", name), forms(state));
|
|
||||||
format!("{frame}\n\nINDEX\n{}\n\n{}NARRATION\n{narration}\n\nTHOUGHT\n{prose}\n\nThis call answers only these sections: {}.", index(state, heard), acts_section(heard), HALVES[half].join(", "))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Two calls' costs as one; either may have none.
|
|
||||||
fn together(first: Option<Spent>, second: Option<Spent>) -> Option<Spent> {
|
|
||||||
match (first, second) {
|
|
||||||
(Some(a), Some(b)) => Some(Spent { model: a.model, input_tokens: a.input_tokens + b.input_tokens, output_tokens: a.output_tokens + b.output_tokens, cache_read_tokens: a.cache_read_tokens + b.cache_read_tokens, cache_write_tokens: a.cache_write_tokens + b.cache_write_tokens, reasoning_tokens: match (a.reasoning_tokens, b.reasoning_tokens) { (None, None) => None, (a, b) => Some(a.unwrap_or(0) + b.unwrap_or(0)) } }),
|
|
||||||
(a, b) => a.or(b),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Two strict calls of `model` over her narration and prose, `{request_id}-a` and `{request_id}-b`, each answering one half of the
|
|
||||||
/// sections (`HALVES`): the deltas they answer merged, and what both cost. A failed call, or an answer that is not the contract,
|
|
||||||
/// is a failure of the whole and moves nothing; its usage is both calls' so far.
|
|
||||||
pub(crate) fn deltas(model: &dyn Model, model_name: &str, request_id: &str, state: &Value, heard: &Heard, narration: &str, prose: &str) -> Result<(Deltas, Option<Spent>), Failed> {
|
|
||||||
let call = |half: usize, suffix: &str| -> Result<(Deltas, Option<Spent>), Failed> {
|
|
||||||
let answer = model.ask(&format!("{request_id}-{suffix}"), model_name, &prompt(state, heard, narration, prose, half), Some(&schema(half)))?;
|
|
||||||
match serde_json::from_str::<Deltas>(&answer.text) {
|
|
||||||
Ok(deltas) => Ok((deltas, answer.usage)),
|
|
||||||
Err(_) => Err(Failed { reason: "the Interpreter's answer is not the delta contract".into(), outage: false, usage: answer.usage }),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let (first, spent_a) = call(0, "a")?;
|
|
||||||
let (second, spent_b) = call(1, "b").map_err(|failed| Failed { usage: together(spent_a.clone(), failed.usage), ..failed })?;
|
|
||||||
let merged = Deltas { notes: first.notes, people: first.people, feeling: first.feeling, drives: second.drives, identity: second.identity, intend: second.intend };
|
|
||||||
Ok((merged, together(spent_a, spent_b)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `updatedAt` a put carries: the time of the put, and strictly later than the one stored, which the daemon requires
|
|
||||||
/// (P5). A write by Self or Life during her turn is stamped after the turn began, so the turn's own start time would be
|
|
||||||
/// refused.
|
|
||||||
fn stamp_after(now: DateTime<Utc>, stored: Option<&str>) -> String {
|
|
||||||
let floor = stored.and_then(|text| DateTime::parse_from_rfc3339(text).ok()).map(|at| at.with_timezone(&Utc) + chrono::Duration::milliseconds(1));
|
|
||||||
floor.map_or(now, |floor| now.max(floor)).to_rfc3339()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A put that landed: what was applied, and how the put went (`committed`, or `stale_reapplied` when
|
|
||||||
/// her state moved under it and the same deltas were applied to the state as it then stood).
|
|
||||||
pub(crate) struct Landed {
|
|
||||||
pub applied: Applied,
|
|
||||||
pub put: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A put that did not land: what the last attempt would have applied, and why nothing was put.
|
|
||||||
pub(crate) struct Missed {
|
|
||||||
pub applied: Applied,
|
|
||||||
pub why: String,
|
|
||||||
/// The put's own call failed, so whether the store committed is not known; a refusal or a stale answer is known not to have.
|
|
||||||
pub unknown: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The deltas of `turn` applied to her state and put under the `updatedAt` she was read at (`read`, the state the wake began
|
|
||||||
/// from). Each attempt applies, stamps (P5), validates the whole document against the schema and only then puts: a state the
|
|
||||||
/// schema refuses is never put. A stale put reads her again and applies the same deltas to the state as it stands, so what Self
|
|
||||||
/// or Life put in between survives, and puts once more.
|
|
||||||
pub(crate) fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime<Utc>, clock: &dyn Fn() -> DateTime<Utc>, ahead: &dyn Fn(&Applied) -> std::result::Result<(), String>) -> std::result::Result<Landed, Missed> {
|
|
||||||
let attempt = |from: &Value| -> (std::result::Result<Value, String>, Applied) {
|
|
||||||
let (mut next, applied) = apply_commit(from, turn.deltas, turn.heard, key, now);
|
|
||||||
next["updatedAt"] = json!(stamp_after(clock(), from.get("updatedAt").and_then(Value::as_str)));
|
|
||||||
match validate_document(turn.instance, &next) {
|
|
||||||
Ok(_) => (Ok(next), applied),
|
|
||||||
Err(refusal) => (Err(format!("the schema refuses the state: {refusal}")), applied),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let (next, applied) = attempt(read);
|
|
||||||
let next = next.map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
|
|
||||||
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
|
|
||||||
match store.put(&next, read.get("updatedAt").and_then(Value::as_str), key) {
|
|
||||||
Ok(Put::Committed) => return Ok(Landed { applied, put: "committed" }),
|
|
||||||
Ok(Put::Stale) => {}
|
|
||||||
Ok(Put::Refused(why)) => return Err(Missed { applied, why, unknown: false }),
|
|
||||||
Err(fault) => return Err(Missed { applied, why: format!("{fault:#}"), unknown: true }),
|
|
||||||
}
|
|
||||||
let (fresh, _) = store.persona().map_err(|fault| Missed { applied: applied.clone(), why: format!("her state was not read again: {fault:#}"), unknown: false })?;
|
|
||||||
let (next, applied) = attempt(&fresh);
|
|
||||||
let next = next.map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
|
|
||||||
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
|
|
||||||
match store.put(&next, fresh.get("updatedAt").and_then(Value::as_str), key) {
|
|
||||||
Ok(Put::Committed) => Ok(Landed { applied, put: "stale_reapplied" }),
|
|
||||||
Ok(Put::Stale) => Err(Missed { applied, why: "stale again".to_owned(), unknown: false }),
|
|
||||||
Ok(Put::Refused(why)) => Err(Missed { applied, why, unknown: false }),
|
|
||||||
Err(fault) => Err(Missed { applied, why: format!("{fault:#}"), unknown: true }),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// What the Interpreter hears of a wake (`Heard`): the wake's room, the bodies of the lines her packet showed and any held lines
|
|
||||||
/// the caller adds, what her agent did this wake (none when no agent ran), and the people present or named. The one derivation, the drain's and the simulator's alike.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub(crate) fn heard_of(state: &Value, packet: &Value, room: &str, held: impl IntoIterator<Item = String>, operators: &[String], minds: &[String], identity_visible: bool, acts: Option<&[Receipt]>, narration: &str, prose: &str) -> Heard {
|
|
||||||
let mut heard = Heard {
|
|
||||||
acts: acts.map(acts_of),
|
|
||||||
room: packet["room"].as_str().or(Some(room)).map(str::to_owned),
|
|
||||||
lines: packet["bodies"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).chain(held).collect(),
|
|
||||||
people: vec![],
|
|
||||||
operators: operators.to_vec(),
|
|
||||||
minds: minds.to_vec(),
|
|
||||||
identity_visible,
|
|
||||||
};
|
|
||||||
heard.people = packet["people"].as_array().into_iter().flatten().filter_map(|pair| pair[1].as_str()).map(|sender| heard.key_of(sender)).collect();
|
|
||||||
heard.people = people(state, &heard, narration, prose);
|
|
||||||
heard
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One Interpreter step: the call over her narration and prose, its deltas applied and put once through `store` (`put_applied`),
|
|
||||||
/// and the receipt row's body. `put` is none when the call gave no deltas, so nothing was put. The drain writes the row to her
|
|
||||||
/// trace and posts an identity change; the simulator reports it and keeps the state its store holds.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub(crate) fn interpret_and_put(model: &dyn Model, model_name: &str, request: &str, store: &dyn PersonaStore, instance: &Slug, state: &Value, heard: &Heard, narration: &str, prose: &str, stem: &str, now: DateTime<Utc>, clock: &dyn Fn() -> DateTime<Utc>, ahead: &dyn Fn(&Applied) -> std::result::Result<(), String>) -> Interpreted {
|
|
||||||
match deltas(model, model_name, request, state, heard, narration, prose) {
|
|
||||||
Err(failed) => Interpreted { row: json!({ "kind": "interpreter", "status": "error", "put": "none", "error": failed.reason, "usage": failed.usage, "put_refused": true }), put: None },
|
|
||||||
Ok((deltas, usage)) => {
|
|
||||||
let put = put_applied(store, state, &Taken { deltas: &deltas, heard, instance }, stem, now, clock, ahead);
|
|
||||||
let row = match &put {
|
|
||||||
Ok(landed) => json!({ "kind": "interpreter", "status": "ok", "put": landed.put, "applied": landed.applied.changes, "refused": landed.applied.refused, "pruned": landed.applied.pruned, "usage": usage }),
|
|
||||||
Err(missed) => json!({ "kind": "interpreter", "status": "error", "put": "refused", "error": missed.why, "applied": missed.applied.changes, "refused": missed.applied.refused, "usage": usage, "put_refused": true }),
|
|
||||||
};
|
|
||||||
Interpreted { row, put: Some(put) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What `interpret_and_put` made.
|
|
||||||
pub(crate) struct Interpreted {
|
|
||||||
pub row: Value,
|
|
||||||
pub put: Option<std::result::Result<Landed, Missed>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,243 +0,0 @@
|
||||||
use std::cell::RefCell;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::projection::Answer;
|
|
||||||
|
|
||||||
const DERU: &str = "@deru:gamecult.org";
|
|
||||||
|
|
||||||
/// A model that answers `text` and keeps what it was asked.
|
|
||||||
struct Answers(&'static str, RefCell<Vec<(String, Option<String>)>>);
|
|
||||||
|
|
||||||
impl Model for Answers {
|
|
||||||
fn ask(&self, _request_id: &str, _model: &str, prompt: &str, schema: Option<&str>) -> Result<Answer, Failed> {
|
|
||||||
self.1.borrow_mut().push((prompt.to_owned(), schema.map(str::to_owned)));
|
|
||||||
Ok(Answer { text: self.0.to_owned(), usage: None })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn heard() -> Heard {
|
|
||||||
Heard { room: None, lines: vec![], people: vec!["operator".into()], operators: vec!["@meta:gamecult.org".into()], minds: vec![DERU.into()], identity_visible: true, acts: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn state() -> Value {
|
|
||||||
let mut state = crate::projection::harness::tests::control();
|
|
||||||
state["candidateActions"]["actions"] = json!([{ "id": "ca-1", "status": "active", "actionType": "custom", "customActionType": "intention", "readiness": "waiting", "riskLevel": "low", "target": { "kind": "self", "id": "eureka" }, "summary": "Tobiah means to ask Deru about the crossword.", "createdAt": "2026-11-19T10:00:00Z", "updatedAt": "2026-11-19T10:00:00Z" }]);
|
|
||||||
state
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn each_half_schema_names_its_sections_and_closes_every_object() {
|
|
||||||
for (half, sections) in HALVES.iter().enumerate() {
|
|
||||||
let schema: Value = serde_json::from_str(&schema(half)).unwrap();
|
|
||||||
let mut families: Vec<&str> = schema["properties"].as_object().unwrap().keys().map(String::as_str).collect();
|
|
||||||
families.sort_unstable();
|
|
||||||
let mut wanted = sections.to_vec();
|
|
||||||
wanted.sort_unstable();
|
|
||||||
assert_eq!(families, wanted);
|
|
||||||
assert!(closed(&schema));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn closed(value: &Value) -> bool {
|
|
||||||
match value {
|
|
||||||
Value::Object(map) => (map.get("type") != Some(&json!("object")) || map.get("additionalProperties") == Some(&json!(false))) && map.values().all(closed),
|
|
||||||
Value::Array(items) => items.iter().all(closed),
|
|
||||||
_ => true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_calls_are_schema_turns_and_the_index_gives_ids_and_words_never_numbers() {
|
|
||||||
let model = Answers(r#"{"people":{"bonds":[{"person":"deru","trust":"up"}]}}"#, RefCell::default());
|
|
||||||
let mut heard = heard();
|
|
||||||
heard.people = people(&state(), &heard, "Deru is on her mind.", "She thinks of him.");
|
|
||||||
assert!(heard.people.contains(&"deru".to_owned()), "a bonded person the narration names is named: {:?}", heard.people);
|
|
||||||
let (deltas, _) = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard, "Deru is on her mind.", "He thinks of the heron.").unwrap();
|
|
||||||
assert_eq!(deltas.people.bonds[0].trust.as_deref(), Some("up"));
|
|
||||||
let calls = model.1.borrow();
|
|
||||||
assert_eq!(calls.len(), 2, "two halves");
|
|
||||||
let (prompt, schema) = &calls[0];
|
|
||||||
assert!(schema.is_some());
|
|
||||||
let index = prompt.split("INDEX\n").nth(1).unwrap().split("NARRATION").next().unwrap();
|
|
||||||
for wanted in ["need-an-audience", "stance-slow-is-kind", "w-clue-for-heron", "ca-1", "deru: ", "value-unhurried"] {
|
|
||||||
assert!(index.contains(wanted), "{wanted} in {index}");
|
|
||||||
}
|
|
||||||
assert!(!index.contains("0."), "no numbers in the index: {index}");
|
|
||||||
assert!(prompt.contains("Tobiah Fenn"), "she is named, in her pronouns: {prompt}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_answer_that_is_not_the_contract_is_a_failure_with_its_cost() {
|
|
||||||
let model = Answers("not json", RefCell::default());
|
|
||||||
let failed = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap_err();
|
|
||||||
assert!(!failed.outage);
|
|
||||||
let model = Answers(r#"{"notes":{"remember":[{"text":7}]}}"#, RefCell::default());
|
|
||||||
assert!(super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").is_err());
|
|
||||||
let nothing = Answers("{}", RefCell::default());
|
|
||||||
assert_eq!(super::deltas(¬hing, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap().0, Deltas::default());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every property that is not in its object's `required`, summed over every nested object: what the API grammar compiler counts.
|
|
||||||
fn optional_properties(schema: &Value) -> usize {
|
|
||||||
match schema {
|
|
||||||
Value::Object(map) => {
|
|
||||||
let required: Vec<&str> = map.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
|
|
||||||
let own = map.get("properties").and_then(Value::as_object).map_or(0, |properties| properties.keys().filter(|name| !required.contains(&name.as_str())).count());
|
|
||||||
own + map.values().map(optional_properties).sum::<usize>()
|
|
||||||
}
|
|
||||||
Value::Array(items) => items.iter().map(optional_properties).sum(),
|
|
||||||
_ => 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn each_half_schema_stays_under_the_api_limit_of_optional_properties() {
|
|
||||||
for half in 0..2 {
|
|
||||||
let schema: Value = serde_json::from_str(&schema(half)).unwrap();
|
|
||||||
let optional = optional_properties(&schema);
|
|
||||||
assert!(optional <= 24, "the API refuses more than 24 optional properties in a schema; half {half} has {optional}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_answer_with_every_container_empty_moves_nothing() {
|
|
||||||
let empty = r#"{"notes":{"remember":[],"settle":[],"wonder":[]},"people":{"bonds":[],"reads":[]},"feeling":{"feelings":[],"mood":{}},"drives":{"needs":[],"pressures":[]},"self":{"stances":[],"identity":{"presentation":{},"values":[]}},"intend":{"add":[],"ready":[],"drop":[]}}"#;
|
|
||||||
let model = Answers(empty, RefCell::default());
|
|
||||||
let (deltas, _) = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap();
|
|
||||||
assert_eq!(deltas, Deltas::default());
|
|
||||||
let now = "2026-12-01T19:00:00Z".parse().unwrap();
|
|
||||||
let (next, applied) = apply_commit(&state(), &deltas, &heard(), "k", now);
|
|
||||||
let (absent, none) = apply_commit(&state(), &serde_json::from_str::<Deltas>("{}").unwrap(), &heard(), "k", now);
|
|
||||||
assert!(applied.changes.is_empty() && applied.refused.is_empty() && applied.identity.is_empty(), "{:?}", applied.changes);
|
|
||||||
assert_eq!((next, applied.changes.len()), (absent, none.changes.len()), "empty containers mean what absent ones meant");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_halves_are_disjoint_and_cover_every_deltas_section() {
|
|
||||||
// Naming every field makes a section added to `Deltas` a compile error here, so it must be placed in a half.
|
|
||||||
let Deltas { notes: _, people: _, feeling: _, drives: _, identity: _, intend: _ } = Deltas::default();
|
|
||||||
let mut every: Vec<&str> = HALVES.iter().flatten().copied().collect();
|
|
||||||
every.sort_unstable();
|
|
||||||
assert_eq!(every, ["drives", "feeling", "intend", "notes", "people", "self"], "each section is in exactly one half");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A model that answers A and B by their request ids, failing the one named in `fail`, and keeps what it was asked.
|
|
||||||
struct Split<'a> {
|
|
||||||
fail: Option<&'a str>,
|
|
||||||
asked: RefCell<Vec<(String, String, Option<String>)>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn spent(input: u64) -> Option<Spent> {
|
|
||||||
Some(Spent { model: "claude-haiku-5-5".into(), input_tokens: input, output_tokens: 1, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None })
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Model for Split<'_> {
|
|
||||||
fn ask(&self, request_id: &str, _model: &str, prompt: &str, schema: Option<&str>) -> Result<Answer, Failed> {
|
|
||||||
self.asked.borrow_mut().push((request_id.to_owned(), prompt.to_owned(), schema.map(str::to_owned)));
|
|
||||||
let half = request_id.rsplit('-').next().unwrap();
|
|
||||||
if self.fail == Some(half) {
|
|
||||||
return Err(Failed { reason: format!("{half} failed"), outage: false, usage: spent(10) });
|
|
||||||
}
|
|
||||||
let text = match half {
|
|
||||||
"a" => r#"{"notes":{"remember":[{"text":"Tobiah heard good evening.","about":[]}],"settle":[],"wonder":[]},"people":{"bonds":[{"person":"deru","trust":"up"}],"reads":[]},"feeling":{"feelings":[],"mood":{"valence":"up"}}}"#,
|
|
||||||
_ => r#"{"drives":{"needs":[{"id":"need-an-audience","toward":"met"}],"pressures":[]},"self":{"stances":[{"principle":"candour","summary":"Say what she does not know."}],"identity":{"publicName":"Eureka","presentation":{},"values":[]}},"intend":{"add":[],"ready":[],"drop":["ca-1"]}}"#,
|
|
||||||
};
|
|
||||||
Ok(Answer { text: text.to_owned(), usage: spent(if half == "a" { 100 } else { 200 }) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn both_halves_are_asked_and_merge_into_one_deltas_with_both_costs() {
|
|
||||||
let model = Split { fail: None, asked: RefCell::default() };
|
|
||||||
let (deltas, usage) = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap();
|
|
||||||
assert_eq!(deltas.notes.remember.len(), 1);
|
|
||||||
assert_eq!(deltas.people.bonds[0].trust.as_deref(), Some("up"));
|
|
||||||
assert_eq!(deltas.feeling.mood.valence.as_deref(), Some("up"));
|
|
||||||
assert_eq!(deltas.drives.needs[0].toward, "met");
|
|
||||||
assert_eq!(deltas.intend.drop, ["ca-1"]);
|
|
||||||
assert_eq!(deltas.identity.stances[0].principle, "candour", "the second half's self section survives the merge");
|
|
||||||
assert_eq!(deltas.identity.identity.public_name.as_deref(), Some("Eureka"));
|
|
||||||
assert_eq!(usage.unwrap().input_tokens, 300);
|
|
||||||
let asked = model.asked.borrow();
|
|
||||||
assert_eq!(asked.iter().map(|(id, ..)| id.as_str()).collect::<Vec<_>>(), ["r1-a", "r1-b"]);
|
|
||||||
for (half, (_, prompt, schema)) in asked.iter().enumerate() {
|
|
||||||
assert!(prompt.ends_with(&format!("This call answers only these sections: {}.", HALVES[half].join(", "))), "{prompt}");
|
|
||||||
assert_eq!(schema.as_deref(), Some(super::schema(half).as_str()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_failed_half_fails_the_whole_and_puts_nothing() {
|
|
||||||
for (fail, cost) in [("a", 10), ("b", 110)] {
|
|
||||||
let model = Split { fail: Some(fail), asked: RefCell::default() };
|
|
||||||
let failed = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap_err();
|
|
||||||
assert_eq!(failed.reason, format!("{fail} failed"));
|
|
||||||
assert_eq!(failed.usage.unwrap().input_tokens, cost, "the usage of every call made, summed");
|
|
||||||
let store = Puts(RefCell::default());
|
|
||||||
let now = "2026-12-01T19:00:00Z".parse().unwrap();
|
|
||||||
let run = interpret_and_put(&model, "claude-haiku-5-5", "r1", &store, &Slug("eureka".to_owned()), &state(), &heard(), "n", "p", "w1", now, &|| now, &|_| Ok(()));
|
|
||||||
assert!(run.put.is_none() && run.row["status"] == "error" && store.0.borrow().is_empty(), "{}", run.row);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A store that keeps every state put into it.
|
|
||||||
struct Puts(RefCell<Vec<Value>>);
|
|
||||||
|
|
||||||
impl crate::projection::PersonaSource for Puts {
|
|
||||||
fn persona(&self) -> anyhow::Result<(Value, String)> {
|
|
||||||
Ok((state(), "receipt".into()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PersonaStore for Puts {
|
|
||||||
fn put(&self, state: &Value, _: Option<&str>, _: &str) -> anyhow::Result<Put> {
|
|
||||||
self.0.borrow_mut().push(state.clone());
|
|
||||||
Ok(Put::Committed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn both_halves_answered_make_one_put() {
|
|
||||||
let model = Split { fail: None, asked: RefCell::default() };
|
|
||||||
let store = Puts(RefCell::default());
|
|
||||||
let now = "2026-12-01T19:00:00Z".parse().unwrap();
|
|
||||||
let run = interpret_and_put(&model, "claude-haiku-5-5", "r1", &store, &Slug("eureka".to_owned()), &state(), &heard(), "n", "p", "w1", now, &|| now, &|_| Ok(()));
|
|
||||||
assert_eq!(store.0.borrow().len(), 1, "{}", run.row);
|
|
||||||
assert_eq!(model.asked.borrow().len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Prints each half schema as JSON from the real code, for a live check against the API: `cargo test -p mind-body --lib
|
|
||||||
/// print_half_schemas -- --ignored --nocapture`. Not a behaviour test.
|
|
||||||
#[test]
|
|
||||||
#[ignore = "prints the half schemas for a live API check"]
|
|
||||||
fn print_half_schemas() {
|
|
||||||
for half in 0..2 {
|
|
||||||
println!("HALF{half} {}", schema(half));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her agent's acts reach the prompt between the index and the narration, one line per tool call, beside her open intentions with
|
|
||||||
/// their ids; a wake with no agent (the simulator) carries no acts section, and an agent that did nothing says so.
|
|
||||||
#[test]
|
|
||||||
fn the_prompt_carries_this_wakes_acts_and_her_open_intentions_with_their_ids() {
|
|
||||||
use crate::projection::agent::Status;
|
|
||||||
let receipts = [
|
|
||||||
Receipt::new("shell", Status::Ok, json!({ "command": "ls /opt/aetheria/..", "exit": 0, "stdout_tail": "Aetheria\nCultLib\n", "stderr_tail": "" })),
|
|
||||||
Receipt::new("read", Status::Refused, json!({ "kind": "repo", "target": "Aetheria", "why": "nothing can be read from here" })),
|
|
||||||
Receipt::new("say", Status::Ok, json!({ "room": "minds", "text": "Found it.", "event": "$e1" })),
|
|
||||||
];
|
|
||||||
let mut heard = heard();
|
|
||||||
heard.acts = Some(acts_of(&receipts));
|
|
||||||
let asked = prompt(&state(), &heard, "n", "p", 1);
|
|
||||||
let acts = asked.split("\nACTS\n").nth(1).unwrap().split("NARRATION").next().unwrap();
|
|
||||||
assert_eq!(acts.trim_end(), "- shell ok: \"ls /opt/aetheria/..\" -> exit 0, \"Aetheria CultLib\"\n- read refused: \"repo\" \"Aetheria\" -> nothing can be read from here\n- say ok: \"minds\" \"Found it.\"");
|
|
||||||
let index = asked.split("INDEX\n").nth(1).unwrap().split("ACTS").next().unwrap();
|
|
||||||
assert!(index.contains("intentions:\n- ca-1: Tobiah means to ask Deru about the crossword."), "{index}");
|
|
||||||
assert!(asked.contains("An act that carried out an intention settles it: drop it by id."), "{asked}");
|
|
||||||
assert!(!asked.contains("failed at it") && asked.contains("name its id under ready, do not add it again"), "a failure alone retires nothing; a ready re-add goes by id: {asked}");
|
|
||||||
|
|
||||||
heard.acts = Some(vec![]);
|
|
||||||
assert!(prompt(&state(), &heard, "n", "p", 1).contains("\nACTS\nHer agent made no tool call.\n\nNARRATION"));
|
|
||||||
heard.acts = None;
|
|
||||||
assert!(!prompt(&state(), &heard, "n", "p", 1).contains("\nACTS\n"), "no agent ran, so no acts section");
|
|
||||||
}
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
//! The Projector's narration, the Persona stage's turn, and the judge that measures them: one tool-less
|
//! The Projector's narration, and the judge that measures it: one tool-less connector call each.
|
||||||
//! connector call each; and `KitModel::step`, the one call that hands back tool calls (the agent's, `agent`).
|
|
||||||
//!
|
//!
|
||||||
//! `KitModel` is the stream organ's `KitProjector`, copied here when the stream was parked
|
//! `KitModel` is the stream organ's `KitProjector`, copied here when the stream was parked
|
||||||
//! (`persona-only-divergence-parked`), so the Projector has one caller on the connector.
|
//! (`persona-only-divergence-parked`), so the Projector has one caller on the connector.
|
||||||
|
|
@ -11,21 +10,19 @@ use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Result, anyhow, bail};
|
use anyhow::{Result, anyhow, bail};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use ghostlight_persona_projection::{PersonaPrompt, build_persona_prompt};
|
use ghostlight_persona_projection::{ProjectorPrompt, build_projector_prompt};
|
||||||
use model_connector::{CacheRetention, ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, Refusal, StopReason, ToolDefinition, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome};
|
use model_connector::{ConnectorClient, InputItem, ProviderRequest, ReasoningEffort, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::Serialize;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use super::select::{Forms, Packet, TurnKind, capitalized, named_pronouns, voiced};
|
use super::select::{Packet, TurnKind};
|
||||||
use super::tuning::Tuning;
|
use super::tuning::Tuning;
|
||||||
|
|
||||||
/// One tool-less model turn. `KitModel` is the one live owner; a test answers with recorded text.
|
/// One tool-less model turn. `KitModel` is the one live owner; a test answers with recorded text.
|
||||||
pub trait Model {
|
pub trait Model {
|
||||||
/// One turn of `model`: `prompt` is its one user text and `request_id` its identity on the connector. With a
|
/// One turn of `model`: `prompt` is its one user text and `request_id` its identity on the connector. A failed turn
|
||||||
/// `schema` (a JSON Schema object) it is a schema turn, and the answer is the structured-output object alone. A
|
/// keeps whatever usage the connector reported for it.
|
||||||
/// failed turn keeps whatever usage the connector reported for it.
|
fn ask(&self, request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed>;
|
||||||
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed>;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A turn that produced no answer: why, and what it cost when the connector's receipt says (a refusal, a fault before
|
/// A turn that produced no answer: why, and what it cost when the connector's receipt says (a refusal, a fault before
|
||||||
|
|
@ -34,10 +31,6 @@ pub trait Model {
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct Failed {
|
pub struct Failed {
|
||||||
pub reason: String,
|
pub reason: String,
|
||||||
/// No answer could be had, by the connector's typed kind (`client_outage`, `refusal_outage`, `failure_outage`): not that the
|
|
||||||
/// request or the answer was bad. A turn that fails this way is retried on every start and charges no line a strike; every
|
|
||||||
/// other failure, set wherever it is made or not at all, is a strike.
|
|
||||||
pub outage: bool,
|
|
||||||
pub usage: Option<Spent>,
|
pub usage: Option<Spent>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -47,33 +40,9 @@ impl std::fmt::Display for Failed {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The failures that are outages, by the connector's own typed kinds, each match naming every variant so a kind the connector adds
|
|
||||||
/// is a compile error here, not a silent default. The deterministic ones (the request or its answer is what the connector
|
|
||||||
/// refused, or its own frame bound) are strikes against the line, as is every failure that names no kind.
|
|
||||||
pub(crate) fn client_outage(fault: &ConnectorClientError) -> bool {
|
|
||||||
match fault {
|
|
||||||
ConnectorClientError::Connection(_) | ConnectorClientError::Transport(_) => true,
|
|
||||||
ConnectorClientError::InvalidConfig | ConnectorClientError::FrameSize | ConnectorClientError::RequestIdTooLong => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn refusal_outage(refusal: &Refusal) -> bool {
|
|
||||||
match refusal {
|
|
||||||
Refusal::Expired | Refusal::Capacity | Refusal::InFlight | Refusal::Indeterminate | Refusal::ProviderRejected => true,
|
|
||||||
Refusal::IdentitySubstitution | Refusal::ProviderDigestSubstitution | Refusal::ModelNotAllowed | Refusal::OutputBound | Refusal::PayloadBound | Refusal::ReplayConflict | Refusal::Malformed | Refusal::ForeignReasoningState => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn failure_outage(kind: &FailureKind) -> bool {
|
|
||||||
match kind {
|
|
||||||
FailureKind::RateLimited | FailureKind::Unavailable | FailureKind::Timeout | FailureKind::Authentication => true,
|
|
||||||
FailureKind::ResultSize | FailureKind::InvalidRequest | FailureKind::Provider => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Failed {
|
impl Failed {
|
||||||
fn without_usage(reason: impl Into<String>) -> Self {
|
fn without_usage(reason: impl Into<String>) -> Self {
|
||||||
Self { reason: reason.into(), outage: false, usage: None }
|
Self { reason: reason.into(), usage: None }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -89,7 +58,7 @@ pub struct Answer {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One turn's tokens, by the model that ran it, as the connector's receipt reports them.
|
/// One turn's tokens, by the model that ran it, as the connector's receipt reports them.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
pub struct Spent {
|
pub struct Spent {
|
||||||
pub model: String,
|
pub model: String,
|
||||||
pub input_tokens: u64,
|
pub input_tokens: u64,
|
||||||
|
|
@ -99,14 +68,10 @@ pub struct Spent {
|
||||||
pub reasoning_tokens: Option<u64>,
|
pub reasoning_tokens: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the connector's request asks of the model beside the user text. It names no frame: each stage's prompt carries its own.
|
/// What the connector's request asks of the model beside the user text. It names no membrane text: that is Ghostlight's.
|
||||||
pub(crate) const INSTRUCTIONS: &str = "Write only the text the request asks for.";
|
pub(crate) const INSTRUCTIONS: &str = "Write only the text the request asks for.";
|
||||||
/// A runaway guard for every stage's call, thinking included (K66, map 16.34.4), never a budget: the Projector and the
|
/// Room for the model's adaptive thinking; the narration itself is bounded by its word budget.
|
||||||
/// Persona are bounded by their word budgets, and the Interpreter's answer, which has none, grows with the drafts, the
|
pub(crate) const MAX_OUTPUT_TOKENS: u32 = 1024;
|
||||||
/// lines listed and the judgments its contract requires (R17: p99 860, max 991 under a cap of 1024, which cut X.5 r2's
|
|
||||||
/// call four times over). Output is paid as produced, so a normal call costs the same; a runaway costs up to this, and
|
|
||||||
/// the claude connector's own output-limit recovery may ask up to three times more before it fails.
|
|
||||||
pub(crate) const MAX_OUTPUT_TOKENS: u32 = 4096;
|
|
||||||
const CONNECTOR_FRAME_BYTES: usize = 256 * 1024;
|
const CONNECTOR_FRAME_BYTES: usize = 256 * 1024;
|
||||||
const INVOCATION_LIFE_MS: u64 = 60_000;
|
const INVOCATION_LIFE_MS: u64 = 60_000;
|
||||||
|
|
||||||
|
|
@ -117,48 +82,13 @@ pub fn connector_key(credentials: &Path) -> Result<String> {
|
||||||
Ok(key.trim().to_owned())
|
Ok(key.trim().to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One connector call by `caller` (her instance). Loopback only, as the kit is. Each call is its own request: the
|
/// One tool-less connector turn by `caller` (her instance). Loopback only, as the kit is. Each call is its own
|
||||||
/// conversation it carries is the caller's, and nothing is held here between calls. `ask` is its tool-less turn; `step`
|
/// conversation: nothing is carried from one to the next. The model is the tuning's, named per call.
|
||||||
/// is the one call that hands back tool calls, the agent's (`agent`).
|
|
||||||
pub struct KitModel {
|
pub struct KitModel {
|
||||||
client: ConnectorClient,
|
client: ConnectorClient,
|
||||||
caller: String,
|
caller: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One tool call the model asked for, as the connector's transcript names it. `arguments` is the model's JSON text,
|
|
||||||
/// unread here: the executor that owns the tool parses it.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct ToolCall {
|
|
||||||
pub call_id: String,
|
|
||||||
pub name: String,
|
|
||||||
pub arguments: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One request of `KitModel::step`. `input` is the whole conversation, ending on user text or on a tool result; `tools`
|
|
||||||
/// may be empty, which makes the turn tool-less. `retention` asks the provider to cache the input's prefix.
|
|
||||||
pub struct StepRequest<'a> {
|
|
||||||
pub request_id: &'a str,
|
|
||||||
pub conversation_id: &'a str,
|
|
||||||
pub model: &'a str,
|
|
||||||
pub instructions: &'a str,
|
|
||||||
pub tools: &'a [ToolDefinition],
|
|
||||||
pub input: Vec<InputItem>,
|
|
||||||
pub retention: Option<CacheRetention>,
|
|
||||||
/// A JSON Schema object: a schema turn, answered with the structured output alone.
|
|
||||||
pub schema: Option<&'a str>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one call handed back: the items it adds to the conversation, verbatim and in order (text, tool calls and the
|
|
||||||
/// reasoning states, replayed as they came), the text and the tool calls on their own, why it stopped, and what it cost.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Stepped {
|
|
||||||
pub items: Vec<InputItem>,
|
|
||||||
pub text: String,
|
|
||||||
pub calls: Vec<ToolCall>,
|
|
||||||
pub stop: StopReason,
|
|
||||||
pub usage: Spent,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl KitModel {
|
impl KitModel {
|
||||||
/// `endpoint` is the kit's loopback address; `connection_key` is the caller's key, read by the binary and never printed.
|
/// `endpoint` is the kit's loopback address; `connection_key` is the caller's key, read by the binary and never printed.
|
||||||
pub fn open(endpoint: SocketAddr, connection_key: String, caller: &str, timeout: Duration) -> Result<Self> {
|
pub fn open(endpoint: SocketAddr, connection_key: String, caller: &str, timeout: Duration) -> Result<Self> {
|
||||||
|
|
@ -170,74 +100,32 @@ impl KitModel {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl KitModel {
|
impl Model for KitModel {
|
||||||
/// One connector call, whatever the model stopped on: a stop other than `EndTurn` is an answer here, with its `stop`,
|
fn ask(&self, request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||||
/// for the caller to read. Tool choice is `auto`: `required` is refused on the models she runs. A refusal, a fault
|
let mut request = ProviderRequest::new(request_id, request_id, model, INSTRUCTIONS, MAX_OUTPUT_TOKENS);
|
||||||
/// before the provider and a provider failure are `Failed`, with the usage the connector reported.
|
request.input = vec![InputItem::UserText { text: prompt.to_owned() }];
|
||||||
pub fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
|
request.reasoning_effort = Some(ReasoningEffort::Low);
|
||||||
let model = request.model;
|
|
||||||
let native: Vec<u8> = request
|
|
||||||
.input
|
|
||||||
.iter()
|
|
||||||
.flat_map(|item| match item {
|
|
||||||
InputItem::UserText { text } | InputItem::AssistantText { text } => text.as_bytes().to_vec(),
|
|
||||||
InputItem::ToolCall { arguments, .. } => arguments.as_bytes().to_vec(),
|
|
||||||
InputItem::ToolResult { output, .. } => output.as_bytes().to_vec(),
|
|
||||||
InputItem::ReasoningState { .. } => Vec::new(),
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let mut provider = ProviderRequest::new(request.request_id, request.conversation_id, model, request.instructions, MAX_OUTPUT_TOKENS);
|
|
||||||
provider.input = request.input;
|
|
||||||
provider.tools = request.tools.to_vec();
|
|
||||||
provider.cache_retention = request.retention;
|
|
||||||
// The claude connector passes it as `--json-schema` and returns the structured output alone; a schema turn
|
|
||||||
// hands out no resume handle, which no schema stage here needs.
|
|
||||||
provider.output_schema_json = request.schema.map(str::to_owned);
|
|
||||||
provider.reasoning_effort = Some(ReasoningEffort::Low);
|
|
||||||
let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS;
|
let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS;
|
||||||
let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(&native).into(), provider).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?;
|
let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(prompt.as_bytes()).into(), request).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?;
|
||||||
let result = self.client.execute(&invocation).map_err(|fault| Failed { reason: format!("the connector did not answer: {fault}"), outage: client_outage(&fault), usage: None })?;
|
let result = self.client.execute(&invocation).map_err(|fault| Failed::without_usage(format!("the connector did not answer: {fault}")))?;
|
||||||
match &result.disposition {
|
match result.disposition {
|
||||||
TransportDisposition::Refused(reason) => Err(Failed { reason: format!("the connector refused the call: {reason:?}"), outage: refusal_outage(reason), usage: None }),
|
TransportDisposition::Refused(reason) => Err(Failed::without_usage(format!("the connector refused the call: {reason:?}"))),
|
||||||
TransportDisposition::Transported { events, receipt } => match &receipt.outcome {
|
TransportDisposition::Transported { events, receipt } => match receipt.outcome {
|
||||||
TransportOutcome::Completed { stop_reason, usage, .. } => {
|
TransportOutcome::Completed { stop_reason: StopReason::EndTurn, usage, .. } => Ok(Answer {
|
||||||
let (mut text, mut calls) = (String::new(), Vec::new());
|
text: events
|
||||||
for event in events {
|
.into_iter()
|
||||||
match &event.payload {
|
.filter_map(|event| match event.payload {
|
||||||
TransportEventPayload::TextDelta { text: delta } => text.push_str(delta),
|
TransportEventPayload::TextDelta { text } => Some(text),
|
||||||
TransportEventPayload::ToolCall { call_id, name, arguments } => calls.push(ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone() }),
|
_ => None,
|
||||||
TransportEventPayload::ReasoningState { .. } => {}
|
})
|
||||||
}
|
.collect(),
|
||||||
}
|
usage: Some(spent(model, &usage)),
|
||||||
Ok(Stepped { items: result.transcript_items(), text, calls, stop: *stop_reason, usage: spent(model, usage) })
|
}),
|
||||||
}
|
TransportOutcome::Completed { stop_reason, usage, .. } => Err(Failed { reason: format!("the model's turn ended early: {stop_reason:?}"), usage: Some(spent(model, &usage)) }),
|
||||||
TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), outage: failure_outage(kind), usage: usage.as_ref().map(|usage| spent(model, usage)) }),
|
TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), usage: usage.as_ref().map(|usage| spent(model, usage)) }),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A tool-less turn that must end: `step` with no tools, and any other stop is a failure that keeps its usage.
|
|
||||||
fn run(&self, request_id: &str, model: &str, input: Vec<InputItem>, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
|
||||||
let stepped = self.step(StepRequest { request_id, conversation_id: request_id, model, instructions: INSTRUCTIONS, tools: &[], input, retention: None, schema })?;
|
|
||||||
if stepped.stop != StopReason::EndTurn || !stepped.calls.is_empty() {
|
|
||||||
return Err(Failed { reason: format!("the model's turn ended early: {:?}", stepped.stop), outage: false, usage: Some(stepped.usage) });
|
|
||||||
}
|
|
||||||
Ok(Answer { text: stepped.text, usage: Some(stepped.usage) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One model shared by several holders: the drain's stages and her agent call the same connection.
|
|
||||||
impl<T: Model + ?Sized> Model for std::rc::Rc<T> {
|
|
||||||
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
|
||||||
(**self).ask(request_id, model, prompt, schema)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Model for KitModel {
|
|
||||||
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
|
||||||
self.run(request_id, model, vec![InputItem::UserText { text: prompt.to_owned() }], schema)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
@ -247,56 +135,10 @@ pub(crate) fn word_budget(kind: TurnKind, tuning: &Tuning) -> usize {
|
||||||
if kind == TurnKind::Beat { tuning.projector.beat_words } else { tuning.projector.words }
|
if kind == TurnKind::Beat { tuning.projector.beat_words } else { tuning.projector.words }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Projector's frame: Huginn's, not Ghostlight's (map section 16.3). Ghostlight's projector membrane forbids any
|
/// The Projector's prompt: Ghostlight's membrane over the packet, with the lens as where to begin.
|
||||||
/// interior its world kernel did not assert; a Mind's interior is the point of her stream. Kept from it: render only what
|
|
||||||
/// the context and stimulus establish, an absence is unavailable and suspicion is uncertainty, no recap, never choose
|
|
||||||
/// actions, emit schemas, expose field names or claim world effects, and the word budget. Its "say plainly what is
|
|
||||||
/// unknown" is deleted (map 16.21): beside an arrival it made the stream name what she does not hold; the no-furnishing
|
|
||||||
/// sentence keeps the absence unfilled. Nothing in it tells her what she has not yet read (map 16.20.1). Dropped: its ban on temperament, mood and inner voice, "no metaphor, no atmosphere",
|
|
||||||
/// "say only what changes the decision" and "a thin moment gets a thin stream". Added: the first person and the present
|
|
||||||
/// tense; what the packet's headings mean (map 16.5, I16.4); that what came of her last turn is news she is only now
|
|
||||||
/// finding out, rendered as noticed and never as a list (map 16.16); that the notes are material,
|
|
||||||
/// never wording, and how her words run (under its own heading, map 16.19.3) is idiom, never material; that her body is how the
|
|
||||||
/// moment is perceived, not news, and a lack in it is felt only when the moment reaches for it (map 16.6); no invented act, event or
|
|
||||||
/// line of hers or anyone's; focus on two or three notes (map 16.8: the frame owns focus, the byte caps are guards); and
|
|
||||||
/// no options and no steering toward a decision. A fix to Ghostlight's membrane is read and ported here on purpose;
|
|
||||||
/// nothing reaches this frame from it. In her own pronouns (map 16.19.7): never a generic "they" beside a packet in "he".
|
|
||||||
pub(crate) fn projector_frame(her: Forms) -> String {
|
|
||||||
let Forms { subj, obj, poss, be, s, .. } = her;
|
|
||||||
let cap_poss = capitalized(poss);
|
|
||||||
format!(
|
|
||||||
"{PROJECTOR_OPENING} Write one person's present moment from inside it, in the first person and the present tense: the lived stream {subj} will go on to continue in {poss} own thought. {cap_poss} interior is the point: what {subj} feel{s}, want{s}, fear{s} and remember{s}, and how the people here sit with {obj}, rendered as lived, not listed.
|
|
||||||
|
|
||||||
Render only what is established below: who {subj} {be} and {poss} present under its headings. Anything absent from these is unavailable: render suspicion or speculation as uncertainty, never as remembered or perceived fact. Furnish no place, object or event these do not give: no act or event of {poss} own (nothing {subj} did, drafted, sent or decided) and no line anyone said that is not below. Each heading says what its lines are. What came of {poss} last turn is what came of what {subj} last meant to do, which {subj} {be} only now finding out: whenever something {subj} meant did not happen, the stream begins from it, as {subj} notice{s} it, never as a list; when all of it happened, it may pass in a clause or not at all. Here and now is the hour, how {poss} mood leans when it does, and the room as it stands. {cap_poss} body is how the moment reaches {obj} and how {subj} can answer it: it is not news to {obj}, and a lack in it is felt only when the moment reaches for something it cannot do. The people here are as {subj} hold{s} them, not as those people are. The notes about {obj} were set down at another time, by others and by {poss} own past self: all of it is material for the stream and never its wording. How {poss} words run is the stream's idiom, never its material: it shows in how the stream moves, and nothing in the stream remarks on it.
|
|
||||||
|
|
||||||
Render the two or three notes this moment touches and leave the rest, but what presses on {obj} and what {subj} mean{s} to do, the feelings in {poss} mood and {poss} standing tendencies are with {obj} whether or not the moment touches them: let them color the stream without naming them as a list. Do not recap the notes. Do not weigh options, list what {subj} might say or do, or steer toward a decision: end where the moment is, not on a resolution. Do not choose actions, emit schemas, expose field names or ids, or claim world effects."
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How every Projector prompt begins, whoever she is: the test doubles route on it.
|
|
||||||
pub(crate) const PROJECTOR_OPENING: &str = "You are a private Projector.";
|
|
||||||
|
|
||||||
/// The Projector's prompt, in this order: the frame, how her words run (her voice, under its own heading, map 16.19.3),
|
|
||||||
/// the tuning's guidance, the lens as where to begin, her name, the packet's headed sections, what reaches her on a turn
|
|
||||||
/// no one spoke to her (none on a chat turn, map 16.20.1), and the word budget. So a chat turn's prompt ends on her
|
|
||||||
/// material, never on the person waiting.
|
|
||||||
pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String {
|
pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String {
|
||||||
let her = packet.forms;
|
let guidance = format!("{}\n\nBegin from {}.", tuning.projector.guidance.trim(), packet.lens.words());
|
||||||
let voice = if packet.voice.is_empty() { String::new() } else { format!("How {} words run:\n{}\n\n", her.poss, packet.voice) };
|
build_projector_prompt(&ProjectorPrompt { identity: &packet.identity, typed_context: &packet.context, visible_stimulus: &packet.stimulus, domain_guidance: &guidance, word_budget: word_budget(packet.kind, tuning) })
|
||||||
let who = if packet.tendencies.is_empty() { packet.name.clone() } else { format!("{}
|
|
||||||
{}", packet.name, packet.tendencies) };
|
|
||||||
let arrival = if packet.arrival.is_empty() { String::new() } else { format!("\n\nWhat reaches {}:\n{}", her.obj, packet.arrival) };
|
|
||||||
format!(
|
|
||||||
"{}\n\n{voice}Guidance:\n{}\n\nBegin from {}.\n\nWho {} {}:\n{}\n\n{}{arrival}\n\nUse at most {} words. Return only the lived stream.",
|
|
||||||
projector_frame(her),
|
|
||||||
voiced(tuning.projector.guidance.trim(), her),
|
|
||||||
packet.lens.words(&packet.forms),
|
|
||||||
her.subj,
|
|
||||||
her.be,
|
|
||||||
who,
|
|
||||||
packet.context,
|
|
||||||
word_budget(packet.kind, tuning),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A character that is a word on its own: Han, kana and Hangul are written without spaces, so each counts as one.
|
/// A character that is a word on its own: Han, kana and Hangul are written without spaces, so each counts as one.
|
||||||
|
|
@ -331,77 +173,6 @@ fn word_starts(text: &str) -> Vec<usize> {
|
||||||
/// The share of the budget a sentence cut must keep; below it the word cut keeps more of the stream.
|
/// The share of the budget a sentence cut must keep; below it the word cut keeps more of the stream.
|
||||||
const SENTENCE_CUT_FLOOR: f64 = 0.6;
|
const SENTENCE_CUT_FLOOR: f64 = 0.6;
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// The Persona stage.
|
|
||||||
|
|
||||||
/// What the Persona is shown as her moment: the Projector's narration, then what was said to her and in her room,
|
|
||||||
/// verbatim, as code rendered it (map section 3.2: the Projector never paraphrases what she heard).
|
|
||||||
pub(crate) fn lived_stream(narration: &str, heard: &str) -> String {
|
|
||||||
if heard.trim().is_empty() { narration.to_owned() } else { format!("{narration}\n\n{heard}") }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the Persona reads after the stream: her view (what came of her last turn, her side of the conversation, her
|
|
||||||
/// domain), then the room. When someone turned to
|
|
||||||
/// her, the stream ends on that arrival, so the room opens
|
|
||||||
/// on it: the bridged lines (`Packet::bridged`), then the conversation's speech cues (`The room: …`, map 16.20.2) last,
|
|
||||||
/// where she drafts or stays silent knowing who is waiting. Otherwise the cues first, then what was said, verbatim.
|
|
||||||
pub(crate) fn read_after(packet: &Packet) -> String {
|
|
||||||
let room = room_after(packet);
|
|
||||||
// What is in front of her besides the room, first (map 16.23.1); the room, then what the other waking rooms said, last.
|
|
||||||
[packet.in_view.as_str(), room.as_str(), packet.elsewhere.as_str()].into_iter().filter(|part| !part.trim().is_empty()).collect::<Vec<_>>().join("\n\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The room as she reads it after the stream (`read_after`).
|
|
||||||
fn room_after(packet: &Packet) -> String {
|
|
||||||
if !packet.bridged.is_empty() {
|
|
||||||
return if packet.speaking.is_empty() { packet.bridged.clone() } else { format!("{}\n\nThe room: {}", packet.bridged, packet.speaking) };
|
|
||||||
}
|
|
||||||
match (packet.speaking.is_empty(), packet.heard.trim().is_empty()) {
|
|
||||||
(true, _) => packet.heard.clone(),
|
|
||||||
(false, true) => format!("The room: {}", packet.speaking),
|
|
||||||
(false, false) => format!("The room: {}\n{}", packet.speaking, packet.heard),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Persona stage's prompt: Ghostlight's prose-only membrane over her name and her lived stream; her voice reaches her
|
|
||||||
/// only as the Projector rendered it (map 16.4). No field name, number, schema or instruction of hers reaches it
|
|
||||||
/// (invariant 7). The domain guidance is the tuning's setting line alone: she is asked for her inner voice and for no speech, and
|
|
||||||
/// Ghostlight's membrane is unchanged.
|
|
||||||
pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) -> String {
|
|
||||||
let domain_guidance = voiced(tuning.persona.guidance.trim(), packet.forms);
|
|
||||||
let after = read_after(packet);
|
|
||||||
// The pronouns of anyone named in what she reads, in view or not (Soul's R6).
|
|
||||||
let named = named_pronouns(&format!("{narration}\n{after}"), tuning, &packet.own_sender);
|
|
||||||
let domain_guidance = if named.is_empty() { domain_guidance } else { format!("{domain_guidance}\n\nPronouns of the people named here: {}.", named.join("; ")) };
|
|
||||||
build_persona_prompt(&PersonaPrompt { identity: &packet.name, lived_stream: &lived_stream(narration, &after), domain_guidance: &domain_guidance, word_budget: tuning.persona.words })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The share of the narration's word trigrams that also appear in what she heard: a lexical overlap, cheap and blind to
|
|
||||||
/// paraphrase, over `span::tokens`, so typographic punctuation reads as the locator reads it (K52). A metric in the
|
|
||||||
/// narration reports: 0 is no shared word run.
|
|
||||||
pub(crate) fn heard_overlap(narration: &str, heard: &str) -> f64 {
|
|
||||||
let trigrams = |text: &str| -> Vec<(String, String, String)> {
|
|
||||||
let words: Vec<String> = super::span::tokens(text).collect();
|
|
||||||
words.windows(3).map(|three| (three[0].clone(), three[1].clone(), three[2].clone())).collect()
|
|
||||||
};
|
|
||||||
let told = trigrams(narration);
|
|
||||||
if told.is_empty() {
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
let heard: BTreeSet<(String, String, String)> = trigrams(heard).into_iter().collect();
|
|
||||||
told.iter().filter(|three| heard.contains(three)).count() as f64 / told.len() as f64
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a narration lays out options for her: "I may…", "I could…", "she might…", "nothing asks me to…". The Projector
|
|
||||||
/// renders the moment and the Persona decides; a menu of choices is the Projector deciding. A lexical flag on a narrow
|
|
||||||
/// form, reported as a metric, never a filter.
|
|
||||||
pub(crate) fn offers_options(narration: &str) -> bool {
|
|
||||||
let lower = format!(" {} ", super::span::fold_text(narration).to_lowercase());
|
|
||||||
["i may ", "i could ", "i might ", "she may ", "she could ", "she might ", "nothing asks me", "nothing asks her", "or i could", "or she could"]
|
|
||||||
.iter()
|
|
||||||
.any(|form| lower.contains(&format!(" {form}")) || lower.contains(&format!(". {form}")) || lower.contains(&format!(", {form}")))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `text` held to `max` words (whitespace-separated, each CJK character one); the model's count is not trusted. An
|
/// `text` held to `max` words (whitespace-separated, each CJK character one); the model's count is not trusted. An
|
||||||
/// overrun is cut at the last sentence end inside the budget, so the stream ends on a whole sentence, when that keeps
|
/// overrun is cut at the last sentence end inside the budget, so the stream ends on a whole sentence, when that keeps
|
||||||
/// at least 60% of the budget; otherwise, or with no sentence end inside it, it is cut after the `max`-th word. No
|
/// at least 60% of the budget; otherwise, or with no sentence end inside it, it is cut after the `max`-th word. No
|
||||||
|
|
@ -539,10 +310,9 @@ pub(crate) fn distinct_2(narrations: &[String]) -> f64 {
|
||||||
|
|
||||||
/// The judge's question: which of two packets a narration was written from.
|
/// The judge's question: which of two packets a narration was written from.
|
||||||
pub(crate) fn judge_prompt(first: &Packet, second: &Packet, narration: &str) -> String {
|
pub(crate) fn judge_prompt(first: &Packet, second: &Packet, narration: &str) -> String {
|
||||||
let poss = first.forms.poss;
|
|
||||||
format!(
|
format!(
|
||||||
"Two descriptions, A and B, of one person's present moment differ in what is on {poss} mind. Below them is a first-person passage written from exactly one of them. Answer with the single letter of the description the passage was written from: A or B.\n\nA:\n{}\n{}\n\nB:\n{}\n{}\n\nPassage:\n{narration}\n\nAnswer A or B.",
|
"Two descriptions, A and B, of one person's present moment differ in what she carries. Below them is a first-person passage written from exactly one of them. Answer with the single letter of the description the passage was written from: A or B.\n\nA:\n{}\n{}\n\nB:\n{}\n{}\n\nPassage:\n{narration}\n\nAnswer A or B.",
|
||||||
first.context, first.arrival, second.context, second.arrival
|
first.context, first.stimulus, second.context, second.stimulus
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,364 +0,0 @@
|
||||||
//! What came of her acts since her last wake (map 16.38.2, item 7; 16.38.5): what she said and where, what was refused or is
|
|
||||||
//! unknown, what was read, what the shell did, what she asked for, and what of her state was not kept. She finds it out only
|
|
||||||
//! now, so her next packet opens with it, first and under its own guard (`select`).
|
|
||||||
//!
|
|
||||||
//! `told` is the one derivation of what she is told: every row of her trace from the start of her last completed wake on
|
|
||||||
//! (its `began`, the place her trace had when that wake's packet was read). Those are the receipts her last wake's agent
|
|
||||||
//! earned, the settlements of sends a start made since, the Interpreter's receipt, the lines set aside and any wake that
|
|
||||||
//! failed since (told once, however many). Nothing is stamped as told: the next completed wake moves the window past them.
|
|
||||||
//! `outcome_of` renders those rows by tool and status, and nothing else writes what she is told. Code wrote every receipt;
|
|
||||||
//! no model's text is ever a row, and a row this table does not name is omitted and reported, never guessed at.
|
|
||||||
//!
|
|
||||||
//! Each row renders in two forms from the one table (map 16.29.10): `told`, her words verbatim, which opens her view (the
|
|
||||||
//! Persona's); and `event`, the same sentence with every quote clause removed, which opens the Projector's packet. That holds
|
|
||||||
//! by type (map 16.30.3, K46): every text of a row is `Words`, which only `Form::words` reads, and the event form reads none; a
|
|
||||||
//! read is named to the Projector by a closed `EventPhrase`, never by its address or search words.
|
|
||||||
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use self::form::{Form, ReadName, Words};
|
|
||||||
use super::read::{ReadFailure, ReadRequest};
|
|
||||||
use super::select::{Forms, capitalized};
|
|
||||||
use super::turn::{completed, failed, is_wake};
|
|
||||||
|
|
||||||
/// Her words in a row, and the forms a row is rendered in (K46). The text a `Words` holds is private to this module, so
|
|
||||||
/// nothing outside it can format one: a row's sentence asks its `Form` for each slot, and the event form answers none.
|
|
||||||
mod form {
|
|
||||||
use super::super::read::ReadRequest;
|
|
||||||
use super::super::select::{Forms, clip, spoken};
|
|
||||||
|
|
||||||
/// Words of a record's text: a line she said, a path she wrote, a tool she asked for. No `Display`, `Deref`,
|
|
||||||
/// `AsRef<str>` or accessor; its only reader is `Form::words`.
|
|
||||||
#[derive(Clone, PartialEq, Eq)]
|
|
||||||
pub(super) struct Words(String);
|
|
||||||
|
|
||||||
impl std::fmt::Debug for Words {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(f, "Words({} bytes)", self.0.len())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Words {
|
|
||||||
pub(super) fn new(text: String) -> Self {
|
|
||||||
Self(text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A repo or a campaign, named to the Projector only when it is in her domain (map 16.30.3).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) struct Name(String);
|
|
||||||
|
|
||||||
impl Name {
|
|
||||||
fn named<'a>(&'a self, domain: &[String]) -> Option<&'a str> {
|
|
||||||
domain.iter().any(|mine| mine.eq_ignore_ascii_case(&self.0)).then_some(self.0.as_str())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What she read, as the Projector is told it: its kind, and for her own repos and campaigns its name. No search
|
|
||||||
/// words, address or host survive into it.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) enum EventPhrase {
|
|
||||||
WebPage,
|
|
||||||
RepoListing(Name),
|
|
||||||
RepoFile(Name),
|
|
||||||
PullRequest(Name, u32),
|
|
||||||
Commit(Name),
|
|
||||||
RepoSearch(Name),
|
|
||||||
Campaign(Name),
|
|
||||||
OwnMind,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventPhrase {
|
|
||||||
fn of(request: &ReadRequest) -> Self {
|
|
||||||
match request {
|
|
||||||
ReadRequest::Mind(_) => Self::OwnMind,
|
|
||||||
ReadRequest::Campaign(slug) => Self::Campaign(Name(slug.clone())),
|
|
||||||
ReadRequest::Web(_) => Self::WebPage,
|
|
||||||
ReadRequest::Repo(target) => {
|
|
||||||
let start = target.find('/').map_or(0, |at| at + 1);
|
|
||||||
let end = target[start..].find(['/', '#', '@', '?']).map_or(target.len(), |at| start + at);
|
|
||||||
let (repo, suffix) = (Name(target[..end].to_owned()), &target[end..]);
|
|
||||||
match suffix.chars().next() {
|
|
||||||
Some('/') => Self::RepoFile(repo),
|
|
||||||
Some('@') => Self::Commit(repo),
|
|
||||||
Some('?') => Self::RepoSearch(repo),
|
|
||||||
Some('#') => suffix[1..].parse().map_or(Self::RepoListing(repo.clone()), |number| Self::PullRequest(repo, number)),
|
|
||||||
_ => Self::RepoListing(repo),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn phrase(&self, her: Forms, domain: &[String]) -> String {
|
|
||||||
let repo = |name: &Name| name.named(domain).unwrap_or("a GameCult repo").to_owned();
|
|
||||||
match self {
|
|
||||||
Self::WebPage => "a web page".to_owned(),
|
|
||||||
Self::RepoListing(name) => format!("{} on the forge", repo(name)),
|
|
||||||
Self::RepoFile(name) => format!("a file in {}", repo(name)),
|
|
||||||
Self::PullRequest(name, number) => match name.named(domain) {
|
|
||||||
Some(name) => format!("pull request #{number} in {name}"),
|
|
||||||
None => "a pull request in a GameCult repo".to_owned(),
|
|
||||||
},
|
|
||||||
Self::Commit(name) => format!("a commit in {}", repo(name)),
|
|
||||||
Self::RepoSearch(name) => format!("a search of {}", repo(name)),
|
|
||||||
Self::Campaign(name) => format!("what was ruled lately in {}", name.named(domain).unwrap_or("a campaign")),
|
|
||||||
Self::OwnMind => format!("{} own mind", her.poss),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A read as a row names it, built once from its request: `told`, code's words for it in her view (none for her own
|
|
||||||
/// mind, whose words are her pronoun's), and `event`, the Projector's.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) struct ReadName {
|
|
||||||
told: Option<Words>,
|
|
||||||
event: EventPhrase,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReadName {
|
|
||||||
pub(super) fn of(request: &ReadRequest) -> Self {
|
|
||||||
Self { told: request.named().map(Words), event: EventPhrase::of(request) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The form a row is rendered in: `Told`, her view, her words verbatim and held to a byte count; `Event`, the
|
|
||||||
/// Projector's, no words at all and each read by its phrase, under her domain.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub(super) enum Form<'a> {
|
|
||||||
Told(usize),
|
|
||||||
Event(&'a [String]),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Form<'_> {
|
|
||||||
/// A slot's words in this form, or None and the row's sentence without them.
|
|
||||||
pub(super) fn words(&self, words: &Words) -> Option<String> {
|
|
||||||
match self {
|
|
||||||
Self::Told(quote_max) => Some(spoken(&clip(&words.0, *quote_max))),
|
|
||||||
Self::Event(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A person's name in this form: the told and reported forms name them, the event form names no one.
|
|
||||||
pub(super) fn name(&self, who: &str) -> Option<String> {
|
|
||||||
match self {
|
|
||||||
Self::Told(_) => Some(who.to_owned()),
|
|
||||||
Self::Event(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a read was, in this form.
|
|
||||||
pub(super) fn read(&self, name: &ReadName, her: Forms) -> String {
|
|
||||||
match (self, &name.told) {
|
|
||||||
(Self::Event(domain), _) => name.event.phrase(her, domain),
|
|
||||||
(_, Some(told)) => told.0.clone(),
|
|
||||||
(_, None) => name.event.phrase(her, &[]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a row of her trace tells her, typed by tool and status.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
enum Part {
|
|
||||||
/// A say the mouth posted.
|
|
||||||
Said { room: String, text: Words },
|
|
||||||
/// A say refused, and why in code's words.
|
|
||||||
SayRefused { room: String, text: Words, why: &'static str },
|
|
||||||
/// A say nothing was sent of.
|
|
||||||
NotSent { room: String, text: Words },
|
|
||||||
/// A say that may or may not have gone out.
|
|
||||||
Unknown { room: String, text: Words },
|
|
||||||
Read { what: ReadName },
|
|
||||||
ReadFailed { what: ReadName, failure: ReadFailure },
|
|
||||||
/// A command in her box: whether it exited cleanly, why not, and the files it wrote.
|
|
||||||
Shell { ok: bool, why: Option<Words>, wrote: Vec<Words> },
|
|
||||||
/// A tool she asked Self for.
|
|
||||||
Requested { what: Words },
|
|
||||||
/// A tool call refused for a reason that is no say's (arguments that did not fit, no such tool).
|
|
||||||
Refused { tool: Words },
|
|
||||||
/// Her agent's turn stopped at a bound.
|
|
||||||
Cap,
|
|
||||||
/// A wake that failed, once however many.
|
|
||||||
Failed,
|
|
||||||
/// What she meant to keep of a wake was not kept.
|
|
||||||
NotKept,
|
|
||||||
/// A waking line whose wakes failed twice, acked past with no third try.
|
|
||||||
SetAside { room: Option<String>, line: Option<(String, Words)> },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What came of her acts: what she is told, and what her rows held that she is not told, and why.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Outcome {
|
|
||||||
parts: Vec<Part>,
|
|
||||||
/// What the rows held that she is not told, and why: reported, never shown to her.
|
|
||||||
pub omitted: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn words(value: &Value) -> Option<String> {
|
|
||||||
value.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_owned)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn words_of(value: &Value) -> Option<Words> {
|
|
||||||
words(value).map(Words::new)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The rows of her trace she is told at her next wake: every row from the start of her last completed wake on that tells
|
|
||||||
/// something (an agent's receipt, the Interpreter's receipt, a line set aside, a wake that failed). A wake record from before
|
|
||||||
/// wakes recorded where they began opens the window one past its own place.
|
|
||||||
pub(crate) fn told(records: &[Value]) -> Vec<Value> {
|
|
||||||
let from = records.iter().filter(|record| completed(record)).filter_map(|record| record["began"].as_u64().or_else(|| record["seq"].as_u64().map(|seq| seq + 1))).max().unwrap_or(0);
|
|
||||||
let tells = |record: &Value| record["agent"] == "receipt" || record["kind"] == "interpreter" || record.get("set_aside").is_some() || (is_wake(record) && failed(record));
|
|
||||||
records.iter().filter(|record| record["seq"].as_u64().is_some_and(|seq| seq >= from) && tells(record)).cloned().collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What `rows` (from `told`) tell her; None when there are none.
|
|
||||||
pub(crate) fn outcome_of(rows: &[Value]) -> Option<Outcome> {
|
|
||||||
if rows.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let mut outcome = Outcome::default();
|
|
||||||
let mut wake_failed = false;
|
|
||||||
for row in rows {
|
|
||||||
if is_wake(row) && failed(row) {
|
|
||||||
wake_failed = true;
|
|
||||||
} else if row.get("set_aside").is_some() {
|
|
||||||
for line in row["set_aside"].as_array().into_iter().flatten() {
|
|
||||||
outcome.parts.push(Part::SetAside { room: words(&line["room"]), line: words(&line["sender"]).zip(words_of(&line["text"])) });
|
|
||||||
}
|
|
||||||
} else if row["kind"] == "interpreter" {
|
|
||||||
if row["status"] != "ok" {
|
|
||||||
outcome.parts.push(Part::NotKept);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
match receipt_part(&row["receipt"]) {
|
|
||||||
Ok(part) => outcome.parts.push(part),
|
|
||||||
Err(why) => outcome.omitted.push(format!("{why}: {}", row["receipt"])),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if wake_failed {
|
|
||||||
outcome.parts.push(Part::Failed);
|
|
||||||
}
|
|
||||||
outcome.parts.sort_by_key(Part::rank);
|
|
||||||
Some(outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One receipt's row, by its tool and status, or why it names none.
|
|
||||||
fn receipt_part(receipt: &Value) -> Result<Part, &'static str> {
|
|
||||||
let fields = &receipt["fields"];
|
|
||||||
let room = || words(&fields["room"]).ok_or("a say receipt with no room");
|
|
||||||
let text = || words_of(&fields["text"]).ok_or("a say receipt with no words");
|
|
||||||
let read = || serde_json::from_value::<ReadRequest>(serde_json::json!({ "kind": fields["kind"], "target": fields["target"] })).map(|request| ReadName::of(&request)).map_err(|_| "a read receipt that names no read");
|
|
||||||
Ok(match (receipt["tool"].as_str(), receipt["status"].as_str()) {
|
|
||||||
(Some("say"), Some("ok")) => Part::Said { room: room()?, text: text()? },
|
|
||||||
(Some("say"), Some("refused")) => Part::SayRefused { room: room()?, text: text()?, why: refusal_words(fields["refusal"].as_str().unwrap_or_default()) },
|
|
||||||
(Some("say"), Some("not_sent")) => Part::NotSent { room: room()?, text: text()? },
|
|
||||||
(Some("say"), Some("unknown")) => Part::Unknown { room: room()?, text: text()? },
|
|
||||||
(Some("read"), Some("ok")) => Part::Read { what: read()? },
|
|
||||||
(Some("read"), Some("error")) => Part::ReadFailed { what: read()?, failure: serde_json::from_value(fields["failure"].clone()).map_err(|_| "a failed read with no failure")? },
|
|
||||||
(Some("shell"), Some(status @ ("ok" | "error"))) => Part::Shell { ok: status == "ok", why: words_of(&fields["why"]), wrote: fields["wrote"].as_array().into_iter().flatten().filter_map(words_of).collect() },
|
|
||||||
(Some("request_tool"), Some("ok")) => Part::Requested { what: words_of(&fields["what"]).ok_or("a tool request with no tool")? },
|
|
||||||
(Some("agent"), Some("cap")) => Part::Cap,
|
|
||||||
(Some(tool), Some("refused")) => Part::Refused { tool: Words::new(tool.to_owned()) },
|
|
||||||
_ => return Err("a receipt no row of hers names"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A say's refusal in code's words, from the mouth's name or the executor's own.
|
|
||||||
fn refusal_words(refusal: &str) -> &'static str {
|
|
||||||
match refusal {
|
|
||||||
"room_unsettled" => "an earlier line there had no known outcome yet",
|
|
||||||
"RoomMoved" => "the room had moved on past what was seen",
|
|
||||||
"Brake" => "a brake was held",
|
|
||||||
"UnknownRoom" => "the room is not one the mouth speaks in",
|
|
||||||
"EmptyText" => "it had no words",
|
|
||||||
_ => "the mouth would not take it",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Part {
|
|
||||||
/// Where the part falls in what she is told: what broke, then what did not happen, then what happened.
|
|
||||||
fn rank(&self) -> u8 {
|
|
||||||
match self {
|
|
||||||
Self::Failed => 0,
|
|
||||||
Self::SetAside { .. } | Self::NotKept | Self::SayRefused { .. } | Self::NotSent { .. } | Self::Unknown { .. } | Self::ReadFailed { .. } | Self::Refused { .. } | Self::Cap | Self::Shell { ok: false, .. } => 1,
|
|
||||||
Self::Said { .. } | Self::Read { .. } | Self::Shell { ok: true, .. } | Self::Requested { .. } => 2,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The row in one form: code's sentence, every slot of words the form's (K46), so the event form carries none.
|
|
||||||
fn line(&self, her: Forms, form: Form) -> String {
|
|
||||||
let Forms { subj, cap_subj, obj, poss, has, .. } = her;
|
|
||||||
let said = |text: &Words| form.words(text).map_or_else(|| "said a line".to_owned(), |quote| format!("said {quote}"));
|
|
||||||
let line = match self {
|
|
||||||
Self::Said { room, text } => match form.words(text) {
|
|
||||||
Some(quote) => format!("{} has, from {obj}: {quote}.", capitalized(room)),
|
|
||||||
None => format!("{} has a line from {obj}.", capitalized(room)),
|
|
||||||
},
|
|
||||||
Self::SayRefused { room, text, why } => format!("{cap_subj} {} in {room}, and it did not go out: {why}.", said(text)),
|
|
||||||
Self::NotSent { room, text } => format!("{cap_subj} {} in {room}, and nothing of it was sent.", said(text)),
|
|
||||||
Self::Unknown { room, text } => format!("{cap_subj} {} in {room}, and it may or may not have gone out.", said(text)),
|
|
||||||
Self::Read { what } => format!("{cap_subj} read {}.", form.read(what, her)),
|
|
||||||
Self::ReadFailed { what, failure } => format!("{cap_subj} reached for {} and could not read it: {}.", form.read(what, her), failure.words()),
|
|
||||||
Self::Shell { ok, why, wrote } => {
|
|
||||||
let ran = match (ok, why.as_ref().and_then(|why| form.words(why))) {
|
|
||||||
(true, _) => format!("{cap_subj} ran a command in {poss} box, and it finished."),
|
|
||||||
(false, Some(why)) => format!("{cap_subj} ran a command in {poss} box, and it did not finish cleanly: {why}."),
|
|
||||||
(false, None) => format!("{cap_subj} ran a command in {poss} box, and it did not finish cleanly."),
|
|
||||||
};
|
|
||||||
let files: Vec<String> = wrote.iter().filter_map(|path| form.words(path)).collect();
|
|
||||||
match (wrote.len(), files.is_empty()) {
|
|
||||||
(0, _) => ran,
|
|
||||||
(1, true) => format!("{ran} It wrote a file."),
|
|
||||||
(count, true) => format!("{ran} It wrote {count} files."),
|
|
||||||
(_, false) => format!("{ran} It wrote {}.", files.join(", ")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Self::Requested { what } => match form.words(what) {
|
|
||||||
Some(quote) => format!("{cap_subj} asked Self for a tool: {quote}. Self reads it later; nothing happens by itself."),
|
|
||||||
None => format!("{cap_subj} asked Self for a tool. Self reads it later; nothing happens by itself."),
|
|
||||||
},
|
|
||||||
Self::Refused { tool } => match form.words(tool) {
|
|
||||||
Some(tool) => format!("{cap_subj} reached for {tool}, and it was refused."),
|
|
||||||
None => format!("{cap_subj} reached for a tool, and it was refused."),
|
|
||||||
},
|
|
||||||
Self::Cap => format!("{cap_subj} {has} done as much as one wake allows, and stopped there."),
|
|
||||||
Self::Failed => format!("Nothing {subj} meant last time happened: the wake broke off, not by {poss} choice."),
|
|
||||||
Self::NotKept => format!("What {subj} meant to keep from that wake was not kept."),
|
|
||||||
Self::SetAside { room, line } => {
|
|
||||||
let place = room.clone().unwrap_or_else(|| "the room".to_owned());
|
|
||||||
match line.as_ref().and_then(|(sender, text)| form.name(sender).zip(form.words(text))) {
|
|
||||||
Some((sender, quote)) => format!("Nothing reached {place}. {} wake on {sender}'s line {quote} failed twice, so it was set aside.", capitalized(poss)),
|
|
||||||
None => format!("Nothing reached {place}. {} wake on a line there failed twice, so it was set aside.", capitalized(poss)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
format!("- {line}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Outcome {
|
|
||||||
/// How many lines she is told.
|
|
||||||
pub(crate) fn len(&self) -> usize {
|
|
||||||
self.parts.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `at`th line in the Persona's form, its quotes held to `quote_max` bytes.
|
|
||||||
pub(crate) fn told(&self, at: usize, her: Forms, quote_max: usize) -> String {
|
|
||||||
self.parts[at].line(her, Form::Told(quote_max))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `at`th line in the Projector's form: no words, and a read named only by its kind and, when it is in her
|
|
||||||
/// `domain` (repo and campaign names), its name.
|
|
||||||
pub(crate) fn event(&self, at: usize, her: Forms, domain: &[String]) -> String {
|
|
||||||
self.parts[at].line(her, Form::Event(domain))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every line she is told, whole: the report's.
|
|
||||||
pub(crate) fn lines(&self, her: Forms) -> Vec<String> {
|
|
||||||
(0..self.len()).map(|at| self.told(at, her, usize::MAX)).collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::projection::select::forms;
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// K46 (map 16.30.3): the Projector's outcome line has no text slot.
|
|
||||||
|
|
||||||
/// K46: `Words` has no `Display`, `AsRef<str>` or `Deref`, so no format string and no `&str` borrow reads one; only
|
|
||||||
/// `Form::words` does. Checked when this module compiles, as `static_assertions::assert_not_impl_any!` does: a probe trait
|
|
||||||
/// is implemented twice for a type that has the trait, so its `_` cannot be inferred and the module does not compile. (A
|
|
||||||
/// `compile_fail` doctest cannot name a private type, so it would pass for the wrong reason.)
|
|
||||||
#[test]
|
|
||||||
fn k46_words_cannot_be_formatted_or_borrowed_as_text() {
|
|
||||||
trait NotDisplay<A> {
|
|
||||||
fn probe() {}
|
|
||||||
}
|
|
||||||
impl<T: ?Sized> NotDisplay<()> for T {}
|
|
||||||
impl<T: ?Sized + std::fmt::Display> NotDisplay<u8> for T {}
|
|
||||||
let () = <Words as NotDisplay<_>>::probe();
|
|
||||||
trait NotAsStr<A> {
|
|
||||||
fn probe() {}
|
|
||||||
}
|
|
||||||
impl<T: ?Sized> NotAsStr<()> for T {}
|
|
||||||
impl<T: ?Sized + AsRef<str>> NotAsStr<u8> for T {}
|
|
||||||
let () = <Words as NotAsStr<_>>::probe();
|
|
||||||
trait NotDeref<A> {
|
|
||||||
fn probe() {}
|
|
||||||
}
|
|
||||||
impl<T: ?Sized> NotDeref<()> for T {}
|
|
||||||
impl<T: ?Sized + std::ops::Deref> NotDeref<u8> for T {}
|
|
||||||
let () = <Words as NotDeref<_>>::probe();
|
|
||||||
assert_eq!(format!("{:?}", Words::new("ospreyledger".into())), "Words(12 bytes)", "its Debug shows no words either");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// A2 (map 16.38.2, item 7): what she is told is read from the rows since her last wake began.
|
|
||||||
|
|
||||||
fn receipt(seq: u64, tool: &str, status: &str, fields: serde_json::Value) -> Value {
|
|
||||||
json!({ "agent": "receipt", "seq": seq, "receipt": { "tool": tool, "status": status, "fields": fields } })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every row from the start of her last completed wake on is told; a failed wake is told once however many failed; a row
|
|
||||||
/// that tells nothing (a call, a send's own row) is not; and a wake that began after a row moves the window past it.
|
|
||||||
#[test]
|
|
||||||
fn told_is_every_row_since_her_last_wake_began() {
|
|
||||||
let mut records = vec![
|
|
||||||
receipt(0, "say", "ok", json!({ "room": "#a", "text": "OLDLINE" })),
|
|
||||||
json!({ "rooms": [], "held": [], "seq": 1, "began": 0, "status": "completed" }),
|
|
||||||
receipt(2, "say", "refused", json!({ "room": "#a", "text": "REFUSEDLINE", "refusal": "RoomMoved" })),
|
|
||||||
json!({ "agent": "say", "seq": 3, "room": "#a", "text": "REFUSEDLINE", "status": "refused" }),
|
|
||||||
json!({ "agent": "call", "seq": 4 }),
|
|
||||||
json!({ "kind": "interpreter", "status": "error", "seq": 5 }),
|
|
||||||
json!({ "rooms": [], "held": [], "seq": 6, "began": 2, "status": "completed" }),
|
|
||||||
json!({ "rooms": [], "held": [], "seq": 7, "failed": "x" }),
|
|
||||||
json!({ "rooms": [], "held": [], "seq": 8, "failed": "y" }),
|
|
||||||
];
|
|
||||||
let told = told(&records);
|
|
||||||
assert_eq!(told.iter().map(|row| row["seq"].as_u64().unwrap()).collect::<Vec<_>>(), [2, 5, 7, 8], "{told:?}");
|
|
||||||
let lines = outcome_of(&told).unwrap().lines(forms(&json!({})));
|
|
||||||
assert_eq!(lines.iter().filter(|line| line.contains("broke off")).count(), 1, "{lines:?}");
|
|
||||||
assert!(lines.iter().any(|line| line.contains("REFUSEDLINE") && line.contains("did not go out")) && !lines.iter().any(|line| line.contains("OLDLINE")), "{lines:?}");
|
|
||||||
assert!(lines.iter().any(|line| line.contains("was not kept")), "{lines:?}");
|
|
||||||
records.push(json!({ "rooms": [], "held": [], "seq": 9, "began": 9, "status": "completed" }));
|
|
||||||
assert!(super::told(&records).is_empty(), "the next completed wake moves the window past them");
|
|
||||||
// A wake recorded before wakes said where they began opens the window one past its own place.
|
|
||||||
let old = vec![json!({ "set_aside": [], "seq": 0 }), json!({ "rooms": [], "held": [], "seq": 1 }), json!({ "set_aside": [{ "room": "#a" }], "seq": 2 })];
|
|
||||||
assert_eq!(super::told(&old), [old[2].clone()]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A receipt no row names is omitted and reported, never guessed at; the event form carries none of her words.
|
|
||||||
#[test]
|
|
||||||
fn an_unnamed_receipt_is_reported_and_the_event_form_has_no_words() {
|
|
||||||
let rows = [receipt(0, "say", "ok", json!({ "room": "#a", "text": "SAIDLINE" })), receipt(1, "dance", "ok", json!({})), receipt(2, "shell", "ok", json!({ "wrote": ["/opt/commons/handoff/x"] })), receipt(3, "read", "ok", json!({ "kind": "repo", "target": "GameCult/Huginn#12" }))];
|
|
||||||
let outcome = outcome_of(&rows).unwrap();
|
|
||||||
assert_eq!(outcome.omitted.len(), 1, "{:?}", outcome.omitted);
|
|
||||||
let her = forms(&json!({}));
|
|
||||||
let events: Vec<String> = (0..outcome.len()).map(|at| outcome.event(at, her, &[])).collect();
|
|
||||||
assert!(events.iter().all(|line| !line.contains("SAIDLINE") && !line.contains("/opt/commons") && !line.contains('"')), "{events:?}");
|
|
||||||
assert!(outcome.lines(her).iter().any(|line| line.contains("/opt/commons/handoff/x")), "she is told what she wrote");
|
|
||||||
}
|
|
||||||
|
|
@ -1,447 +0,0 @@
|
||||||
//! What a read is and what performs it (map 16.22.3, 16.38.5): her agent's `read` tool names a read (`ReadRequest::from_target`),
|
|
||||||
//! and code performs it through the port `ReadSource` (live `LiveReads`, a harness fixture `ReadFixture`). A read is only ever one
|
|
||||||
//! of four things:
|
|
||||||
//! - `mind`: a recall over her own mind through her persona door, which keeps its own reach rules;
|
|
||||||
//! - `campaign`: a campaign's rulings since her domain's window opened;
|
|
||||||
//! - `repo`: a public GameCult repo, file, pull request, commit or search (`GameCult/Name[/path|#n|@sha|?q=words]`), from the forge;
|
|
||||||
//! - `web`: a plain-HTTP web page.
|
|
||||||
//!
|
|
||||||
//! Code performs every read, so every result is verbatim and recorded in her agent's receipt. A result is data, never an
|
|
||||||
//! instruction.
|
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use cultnet_rs::{PROJECTION_DOCUMENT, Selection};
|
|
||||||
use eureka_pipeline::{Line, PipelineDocument, PipelineKind};
|
|
||||||
use eureka_state::HuginnClient;
|
|
||||||
use huginn_mind::{HuginnMindRequest, HuginnMindResponse, PipelineFacts, PipelinePageItems, SemanticQuery};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
|
|
||||||
use super::domain::{ForgeGet, HttpForge};
|
|
||||||
use super::select::spoken;
|
|
||||||
use crate::queue::{any_of, of_kind};
|
|
||||||
|
|
||||||
/// The most bytes a fetched body may be before it is refused as too large, before any clipping.
|
|
||||||
const BODY_MAX_BYTES: usize = 1024 * 1024;
|
|
||||||
/// How many hits a recall over her mind returns, and how many rulings a campaign read shows.
|
|
||||||
const RECALL_TOP_K: u32 = 6;
|
|
||||||
const RULINGS_SHOWN: u32 = 10;
|
|
||||||
/// The most recent pull requests a repo read lists.
|
|
||||||
const REPO_PULLS: usize = 10;
|
|
||||||
/// The whole of one web read.
|
|
||||||
const WEB_TIMEOUT: Duration = Duration::from_secs(10);
|
|
||||||
|
|
||||||
/// A read code performs, resolved from what she reached for.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(tag = "kind", content = "target", rename_all = "snake_case", deny_unknown_fields)]
|
|
||||||
pub enum ReadRequest {
|
|
||||||
/// Her own mind, recalled by these words.
|
|
||||||
Mind(String),
|
|
||||||
/// A campaign of hers: its rulings since her domain's window opened.
|
|
||||||
Campaign(String),
|
|
||||||
/// A public GameCult repo, file, pull request or commit.
|
|
||||||
Repo(String),
|
|
||||||
/// A web address.
|
|
||||||
Web(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReadRequest {
|
|
||||||
/// The read a tool call names: `kind` is `repo`, `mind`, `web` or `campaign`, and `target` what it reads. An unknown kind or
|
|
||||||
/// an empty target is refused with why.
|
|
||||||
pub fn from_target(kind: &str, target: &str) -> Result<Self, String> {
|
|
||||||
let target = target.trim().to_owned();
|
|
||||||
if target.is_empty() {
|
|
||||||
return Err("the target is empty".to_owned());
|
|
||||||
}
|
|
||||||
match kind {
|
|
||||||
"repo" => Ok(Self::Repo(target)),
|
|
||||||
"mind" => Ok(Self::Mind(target)),
|
|
||||||
"web" => Ok(Self::Web(target)),
|
|
||||||
"campaign" => Ok(Self::Campaign(target)),
|
|
||||||
other => Err(format!("no read of kind {other:?}: it is repo, mind, web or campaign")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One normal form per thing read (Soul's R7, R8): the org and repo case-blind; a search's words lowercased, its
|
|
||||||
/// stopwords dropped, each lightly stemmed of a plural and the rest sorted, so "Merge pages" and "the page merge" are
|
|
||||||
/// one search; a number without its leading zeros (`#089` is `#89`); a recall's and a campaign's lowercased. Two
|
|
||||||
/// requests with the same form are the same read.
|
|
||||||
pub(crate) fn normal(&self) -> String {
|
|
||||||
let collapse = |text: &str| text.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase();
|
|
||||||
let searched = |words: &str| {
|
|
||||||
let mut words: Vec<String> = word_tokens(words).into_iter().filter(|word| content(word)).map(|word| stem(&word)).collect();
|
|
||||||
words.sort();
|
|
||||||
words.dedup();
|
|
||||||
words.join(" ")
|
|
||||||
};
|
|
||||||
match self {
|
|
||||||
Self::Repo(target) => {
|
|
||||||
let rest = target.split_once('/').map_or(target.as_str(), |(_, rest)| rest);
|
|
||||||
let end = rest.find(['/', '#', '@', '?']).unwrap_or(rest.len());
|
|
||||||
let (name, suffix) = rest.split_at(end);
|
|
||||||
let suffix = match suffix.strip_prefix("?q=") {
|
|
||||||
Some(words) => format!("?q={}", searched(words)),
|
|
||||||
None => suffix.strip_prefix('#').map_or_else(|| suffix.to_owned(), |number| format!("#{}", Some(number.trim_start_matches('0')).filter(|digits| !digits.is_empty()).unwrap_or("0"))),
|
|
||||||
};
|
|
||||||
format!("repo:gamecult/{}{suffix}", name.to_lowercase())
|
|
||||||
}
|
|
||||||
Self::Campaign(slug) => format!("campaign:{}", slug.to_lowercase()),
|
|
||||||
Self::Mind(words) => format!("mind:{}", collapse(words)),
|
|
||||||
Self::Web(url) => format!("web:{url}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `what`, for every read but one of her own mind, whose words are her pronoun's: what her outcome's told form names
|
|
||||||
/// it by (`outcome::ReadName`).
|
|
||||||
pub(crate) fn named(&self) -> Option<String> {
|
|
||||||
match self {
|
|
||||||
Self::Mind(_) => None,
|
|
||||||
Self::Campaign(slug) => Some(format!("what was ruled lately in {slug}")),
|
|
||||||
Self::Repo(target) => Some(match target.split_once("?q=") {
|
|
||||||
Some((repo, words)) => format!("a search of {repo} for {}", spoken(words.trim())),
|
|
||||||
None => format!("{target} on the forge"),
|
|
||||||
}),
|
|
||||||
Self::Web(url) => Some(url.clone()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a read returned nothing, from code's table (map 16.22.3).
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum ReadFailure {
|
|
||||||
NotFound,
|
|
||||||
Private,
|
|
||||||
TooLarge,
|
|
||||||
Failed,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReadFailure {
|
|
||||||
pub(crate) fn words(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::NotFound => "it is not there",
|
|
||||||
Self::Private => "it is private",
|
|
||||||
Self::TooLarge => "it is too large",
|
|
||||||
Self::Failed => "the read failed",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What performs her reads. Read-only by type: nothing here writes, sends or admits.
|
|
||||||
pub trait ReadSource {
|
|
||||||
/// The text of `request`, verbatim; `since` is when her domain's window opened, for a campaign read.
|
|
||||||
fn read(&self, request: &ReadRequest, since: DateTime<Utc>) -> Result<String, ReadFailure>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Words that carry no content of their own: a recall, a search or an anchor made of these alone names nothing (Soul's
|
|
||||||
/// R7, R8). The function words, and the light verbs and fillers a thought reaches with ("want to sit", "go look").
|
|
||||||
const STOPWORDS: [&str; 111] = [
|
|
||||||
"a", "an", "the", "and", "or", "but", "of", "to", "in", "on", "at", "for", "with", "by", "from", "about", "as", "into", "is", "are", "was", "were", "be",
|
|
||||||
"been", "it", "its", "this", "that", "these", "those", "i", "me", "my", "we", "our", "you", "your", "he", "him", "his", "she", "her", "they", "them",
|
|
||||||
"their", "what", "which", "who", "how", "when", "where", "why", "do", "does", "did", "not", "no", "so", "if", "then", "there", "here", "just", "some",
|
|
||||||
"am", "has", "have", "had", "will", "would", "can", "could", "should", "may", "might", "must", "want", "need", "like", "get", "got", "go", "going",
|
|
||||||
"see", "look", "sit", "think", "know", "make", "take", "let", "say", "tell", "come", "thing", "things", "something", "really", "still", "while", "now",
|
|
||||||
"again", "also", "more", "very", "all", "any", "one", "out", "up", "over",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// The words of `text`, lowercased, split at anything that is not a letter or a digit.
|
|
||||||
pub(crate) fn word_tokens(text: &str) -> Vec<String> {
|
|
||||||
text.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty()).map(str::to_lowercase).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A word without a plural ending, lightly: "pages" is "page", "queries" is "query", "class" stays.
|
|
||||||
fn stem(word: &str) -> String {
|
|
||||||
match word.strip_suffix("ies") {
|
|
||||||
Some(base) if word.len() > 4 => format!("{base}y"),
|
|
||||||
_ if word.len() > 3 && word.ends_with('s') && !word.ends_with("ss") => word[..word.len() - 1].to_owned(),
|
|
||||||
_ => word.to_owned(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a word carries content: not one of `STOPWORDS`.
|
|
||||||
pub(crate) fn content(word: &str) -> bool {
|
|
||||||
!STOPWORDS.contains(&word)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a search's words find `text`: every word of the query that carries content stands in it as a whole word, case
|
|
||||||
/// blind, each lightly stemmed as `ReadRequest::normal` stems it (Soul's R7, R9), so "consent receipts" finds "receipt".
|
|
||||||
/// One matcher for the live forge and the fixture, so the harness and the live path agree.
|
|
||||||
fn search_finds(query: &str, text: &str) -> bool {
|
|
||||||
let wanted: Vec<String> = word_tokens(query).into_iter().filter(|word| content(word)).map(|word| stem(&word)).collect();
|
|
||||||
let held: Vec<String> = word_tokens(text).into_iter().map(|word| stem(&word)).collect();
|
|
||||||
!wanted.is_empty() && wanted.iter().all(|word| held.contains(word))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `text` held to `max` bytes on a character boundary, with a counted mark of what was cut.
|
|
||||||
pub(crate) fn clipped(text: &str, max: usize) -> String {
|
|
||||||
if text.len() <= max {
|
|
||||||
return text.to_owned();
|
|
||||||
}
|
|
||||||
let end = (0..=max).rev().find(|at| text.is_char_boundary(*at)).unwrap_or(0);
|
|
||||||
format!("{}\n[{} more bytes not shown here]", &text[..end], text.len() - end)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One recorded read: its kind (`mind`, `campaign`, `repo`, `web`) and target, and the text it returns or why it fails.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub(crate) struct ReadEntry {
|
|
||||||
kind: String,
|
|
||||||
target: String,
|
|
||||||
#[serde(default)]
|
|
||||||
text: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
refused: Option<ReadFailure>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Recorded reads for a harness run (`[[read]]` in a room fixture, `[[cast.read]]` in a simulation plan): a read nobody
|
|
||||||
/// recorded is not there. No forge and no mind is read. A read matches an entry by its normal form (`ReadRequest::normal`);
|
|
||||||
/// a search no entry records searches the titles (first lines) of the repo's recorded pull requests and issues
|
|
||||||
/// (`GameCult/Name#n`) for all its words, as the forge would.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
|
|
||||||
#[serde(transparent)]
|
|
||||||
pub struct ReadFixture(Vec<ReadEntry>);
|
|
||||||
|
|
||||||
impl ReadFixture {
|
|
||||||
/// Whether it records a read of this kind (`mind`, `campaign`, `repo`, `web`).
|
|
||||||
pub(crate) fn records(&self, kind: &str) -> bool {
|
|
||||||
self.0.iter().any(|entry| entry.kind == kind)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReadSource for ReadFixture {
|
|
||||||
fn read(&self, request: &ReadRequest, _since: DateTime<Utc>) -> Result<String, ReadFailure> {
|
|
||||||
let key = request.normal();
|
|
||||||
let request_of = |entry: &ReadEntry| serde_json::from_value::<ReadRequest>(serde_json::json!({ "kind": entry.kind, "target": entry.target })).ok();
|
|
||||||
// A search always goes through the matcher over the recorded changes, never a lookup of a recorded search (Soul's
|
|
||||||
// R9): the live path has no such lookup either.
|
|
||||||
if matches!(request, ReadRequest::Repo(target) if target.contains("?q=")) {
|
|
||||||
return fixture_search(&self.0, request).ok_or(ReadFailure::NotFound);
|
|
||||||
}
|
|
||||||
match self.0.iter().find(|entry| request_of(entry).is_some_and(|recorded| recorded.normal() == key)) {
|
|
||||||
Some(ReadEntry { refused: Some(why), .. }) => Err(*why),
|
|
||||||
Some(entry @ ReadEntry { text: Some(text), .. }) => Ok(if lists_titles(entry) && !text.ends_with(TITLES_ONLY) { format!("{text}
|
|
||||||
{TITLES_ONLY}") } else { text.clone() }),
|
|
||||||
_ => Err(ReadFailure::NotFound),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a recorded read is one whose live answer is titles only, so the simulator says what live says: a mind recall
|
|
||||||
/// (headers), and a repo's root (its recent pull requests by title).
|
|
||||||
fn lists_titles(entry: &ReadEntry) -> bool {
|
|
||||||
entry.kind == "mind" || (entry.kind == "repo" && entry.target.strip_prefix("GameCult/").is_some_and(|rest| !rest.contains(['/', '#', '@', '?'])))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A search of a repo by its recorded pull requests and issues: each whose title (first line) or body (the rest) the
|
|
||||||
/// search finds (`search_finds`), as `- #n title`; none, and nothing was found.
|
|
||||||
fn fixture_search(entries: &[ReadEntry], request: &ReadRequest) -> Option<String> {
|
|
||||||
let ReadRequest::Repo(target) = request else { return None };
|
|
||||||
let (repo, words) = target.split_once("?q=")?;
|
|
||||||
let repo = repo.to_lowercase();
|
|
||||||
let listed: Vec<String> = entries
|
|
||||||
.iter()
|
|
||||||
.filter(|entry| entry.kind == "repo")
|
|
||||||
.filter_map(|entry| {
|
|
||||||
let (of, number) = entry.target.split_once('#')?;
|
|
||||||
let (title, body) = entry.text.as_deref()?.split_once('\n').unwrap_or((entry.text.as_deref()?, ""));
|
|
||||||
// A recorded text that opens with its own number ("#87 Merge pages…") is listed without saying it twice.
|
|
||||||
let title = title.trim();
|
|
||||||
let title = title.strip_prefix(&format!("#{number}")).map_or(title, str::trim_start);
|
|
||||||
(of.to_lowercase() == repo && (search_finds(words, title) || search_finds(words, body))).then(|| format!("- #{number} {title}"))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
(!listed.is_empty()).then(|| format!("{}\n{TITLES_ONLY}", listed.join("\n")))
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
|
||||||
// Live.
|
|
||||||
|
|
||||||
/// Her reads, live: her mind through her read door (a query and nothing else is ever sent), the forge's public API, and
|
|
||||||
/// plain-HTTP web pages. This body carries no TLS, so an `https` address fails: a live web read needs that, and egress
|
|
||||||
/// for persona uids, before the heartbeat switch (README, "Before the live switch").
|
|
||||||
pub struct LiveReads {
|
|
||||||
client: HuginnClient,
|
|
||||||
forge: Option<HttpForge>,
|
|
||||||
web: ureq::Agent,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LiveReads {
|
|
||||||
/// `forge` is the forge's API root; none fails every repo read.
|
|
||||||
pub fn new(client: HuginnClient, forge: Option<HttpForge>) -> Self {
|
|
||||||
let web: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(WEB_TIMEOUT)).http_status_as_error(false).max_redirects(3).build().into();
|
|
||||||
Self { client, forge, web }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ask(&self, selection: Selection, semantic: Option<SemanticQuery>) -> Result<PipelinePageItems, ReadFailure> {
|
|
||||||
let request = HuginnMindRequest::Query { instance: self.client.instance().clone(), selection, semantic };
|
|
||||||
match self.client.call(request) {
|
|
||||||
Ok(HuginnMindResponse::Query(page)) => Ok(page.items),
|
|
||||||
Ok(HuginnMindResponse::Refused(_)) => Err(ReadFailure::Private),
|
|
||||||
_ => Err(ReadFailure::Failed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn recall(&self, words: &str) -> Result<String, ReadFailure> {
|
|
||||||
let PipelinePageItems::Headers(items) = self.ask(Selection::default(), Some(SemanticQuery { text: Line(words.to_owned()), top_k: RECALL_TOP_K }))? else { return Err(ReadFailure::Failed) };
|
|
||||||
recall_text(items.iter().map(|item| &item.facts))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rulings(&self, slug: &str, since: DateTime<Utc>) -> Result<String, ReadFailure> {
|
|
||||||
let selection = Selection { projection: PROJECTION_DOCUMENT.to_owned(), descending: true, limit: Some(RULINGS_SHOWN), ..any_of(of_kind(PipelineKind::Ruling), "root", &[slug]) };
|
|
||||||
let PipelinePageItems::Documents(views) = self.ask(selection, None)? else { return Err(ReadFailure::Failed) };
|
|
||||||
rulings_text(
|
|
||||||
views
|
|
||||||
.iter()
|
|
||||||
.filter(|view| DateTime::parse_from_rfc3339(&view.admission.admitted_at).is_ok_and(|at| at.with_timezone(&Utc) >= since))
|
|
||||||
.filter_map(|view| match &view.document {
|
|
||||||
PipelineDocument::Ruling(ruling) => Some((ruling.title.0.as_str(), Some(ruling.ruling.0.as_str()))),
|
|
||||||
_ => None,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn repo(&self, target: &str) -> Result<String, ReadFailure> {
|
|
||||||
repo_read(self.forge.as_ref().map(|forge| forge as &dyn ForgeGet).ok_or(ReadFailure::Failed)?, target)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn web(&self, url: &str) -> Result<String, ReadFailure> {
|
|
||||||
if !url.starts_with("http://") {
|
|
||||||
// No TLS in this body: a secure page cannot be read from here yet.
|
|
||||||
return Err(ReadFailure::Failed);
|
|
||||||
}
|
|
||||||
let mut response = self.web.get(url).call().map_err(|_| ReadFailure::Failed)?;
|
|
||||||
match response.status().as_u16() {
|
|
||||||
200 => response.body_mut().with_config().limit(BODY_MAX_BYTES as u64).read_to_string().map_err(|_| ReadFailure::TooLarge),
|
|
||||||
404 | 410 => Err(ReadFailure::NotFound),
|
|
||||||
401 | 403 => Err(ReadFailure::Private),
|
|
||||||
_ => Err(ReadFailure::Failed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The line that ends a read whose result is titles and nothing of what they head (map 16.35, R19): she reads it with the
|
|
||||||
/// list, so she does not describe the contents of what she only saw named.
|
|
||||||
pub(crate) const TITLES_ONLY: &str = "Only titles were returned here; the contents were not read.";
|
|
||||||
|
|
||||||
/// What a campaign read shows, live and in the simulator alike (map 16.25.8): each ruling, newest first, at most
|
|
||||||
/// `RULINGS_SHOWN`, as `- {title}: {ruling}`, or `- {title} (title only: ...)` when no ruling text is held. None is not found.
|
|
||||||
pub(crate) fn rulings_text<'a>(rulings: impl IntoIterator<Item = (&'a str, Option<&'a str>)>) -> Result<String, ReadFailure> {
|
|
||||||
let shown: Vec<String> = rulings.into_iter().take(RULINGS_SHOWN as usize).map(|(title, ruling)| ruling.map_or_else(|| format!("- {title} (title only: the ruling was not read)"), |ruling| format!("- {title}: {ruling}"))).collect();
|
|
||||||
if shown.is_empty() { Err(ReadFailure::NotFound) } else { Ok(shown.join("\n")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn forge_text(forge: &dyn ForgeGet, path: &str) -> Result<String, ReadFailure> {
|
|
||||||
let (status, body) = forge.get(path).map_err(|_| ReadFailure::Failed)?;
|
|
||||||
match status {
|
|
||||||
200 if body.len() > BODY_MAX_BYTES => Err(ReadFailure::TooLarge),
|
|
||||||
200 => Ok(body),
|
|
||||||
404 => Err(ReadFailure::NotFound),
|
|
||||||
401 | 403 => Err(ReadFailure::Private),
|
|
||||||
_ => Err(ReadFailure::Failed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn forge_json(forge: &dyn ForgeGet, path: &str) -> Result<Value, ReadFailure> {
|
|
||||||
serde_json::from_str(&forge_text(forge, path)?).map_err(|_| ReadFailure::Failed)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A repo read from the forge: a repo is its description and its recent pull requests, merged and closed only, so an open
|
|
||||||
/// one is never listed by title (map 16.22.2); a pull request by number, a commit's message, or a file.
|
|
||||||
pub(crate) fn repo_read(forge: &dyn ForgeGet, target: &str) -> Result<String, ReadFailure> {
|
|
||||||
let rest = target.strip_prefix("GameCult/").ok_or(ReadFailure::NotFound)?;
|
|
||||||
if let Some((name, words)) = rest.split_once("?q=") {
|
|
||||||
return search(forge, name, words.trim());
|
|
||||||
}
|
|
||||||
let end = rest.find(['/', '#', '@']).unwrap_or(rest.len());
|
|
||||||
let (name, suffix) = rest.split_at(end);
|
|
||||||
let base = format!("/api/v1/repos/GameCult/{name}");
|
|
||||||
match suffix.chars().next() {
|
|
||||||
None => {
|
|
||||||
let repo = forge_json(forge, &base)?;
|
|
||||||
let pulls = forge_json(forge, &format!("{base}/pulls?state=closed&sort=recentupdate&limit={REPO_PULLS}"))?;
|
|
||||||
let listed: Vec<String> = pulls
|
|
||||||
.as_array()
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
.filter(|pull| pull["state"].as_str() != Some("open"))
|
|
||||||
.map(|pull| {
|
|
||||||
let state = if pull["merged"].as_bool() == Some(true) { "merged" } else { "closed" };
|
|
||||||
format!("- #{} {} ({state}, opened by {})", pull["number"], pull["title"].as_str().unwrap_or_default(), pull["user"]["login"].as_str().unwrap_or("?"))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
Ok(format!("{}
|
|
||||||
|
|
||||||
Recent pull requests, merged and closed:
|
|
||||||
{}
|
|
||||||
{TITLES_ONLY}", repo["description"].as_str().unwrap_or_default(), listed.join("
|
|
||||||
")))
|
|
||||||
}
|
|
||||||
Some('#') => {
|
|
||||||
let pull = forge_json(forge, &format!("{base}/pulls/{}", &suffix[1..]))?;
|
|
||||||
Ok(format!("#{} {} (opened by {}, {})
|
|
||||||
|
|
||||||
{}", pull["number"], pull["title"].as_str().unwrap_or_default(), pull["user"]["login"].as_str().unwrap_or("?"), if pull["merged"].as_bool() == Some(true) { "merged" } else { pull["state"].as_str().unwrap_or("?") }, pull["body"].as_str().unwrap_or_default()))
|
|
||||||
}
|
|
||||||
Some('@') => {
|
|
||||||
let commit = forge_json(forge, &format!("{base}/git/commits/{}", &suffix[1..]))?;
|
|
||||||
commit["commit"]["message"].as_str().map(str::to_owned).ok_or(ReadFailure::Failed)
|
|
||||||
}
|
|
||||||
_ => forge_text(forge, &format!("{base}/raw/{}", &suffix[1..])),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A search of one repo's issues and pull requests by her words (map 16.24.3): all states, title and body, up to
|
|
||||||
/// `REPO_PULLS` matches, each with its number, kind, state, title, opener and date, so a second read can open `#n`. No
|
|
||||||
/// match is not found.
|
|
||||||
fn search(forge: &dyn ForgeGet, name: &str, words: &str) -> Result<String, ReadFailure> {
|
|
||||||
let encoded: String = words.bytes().map(|byte| if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.') { (byte as char).to_string() } else { format!("%{byte:02X}") }).collect();
|
|
||||||
let found = forge_json(forge, &format!("/api/v1/repos/GameCult/{name}/issues?state=all&q={encoded}&limit={REPO_PULLS}"))?;
|
|
||||||
let listed: Vec<String> = found
|
|
||||||
.as_array()
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
// The forge's own search matches loosely (Soul's R7: `q=consent` on Bifrost returned ten, most without the word);
|
|
||||||
// only a result whose title or body holds every word of hers counts, and none is an honest not-found.
|
|
||||||
.filter(|item| search_finds(words, item["title"].as_str().unwrap_or_default()) || search_finds(words, item["body"].as_str().unwrap_or_default()))
|
|
||||||
.map(|item| {
|
|
||||||
let pull = item.get("pull_request").is_some_and(|pull| !pull.is_null());
|
|
||||||
let state = if item["pull_request"]["merged"].as_bool() == Some(true) { "merged" } else { item["state"].as_str().unwrap_or("?") };
|
|
||||||
format!("- #{} {} ({} {state}, opened by {}, {})", item["number"], item["title"].as_str().unwrap_or_default(), if pull { "pull request" } else { "issue" }, item["user"]["login"].as_str().unwrap_or("?"), item["created_at"].as_str().unwrap_or_default().get(..10).unwrap_or_default())
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
if listed.is_empty() { Err(ReadFailure::NotFound) } else { Ok(format!("{}\n{TITLES_ONLY}", listed.join("\n"))) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a mind recall shows, live and under test: each document's words as a list, then the titles-only line. None is not found.
|
|
||||||
fn recall_text<'a>(facts: impl IntoIterator<Item = &'a PipelineFacts>) -> Result<String, ReadFailure> {
|
|
||||||
let listed: Vec<String> = facts.into_iter().map(|facts| format!("- {}", facts_words(facts))).collect();
|
|
||||||
if listed.is_empty() { Err(ReadFailure::NotFound) } else { Ok(format!("{}\n{TITLES_ONLY}", listed.join("\n"))) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A document of her mind as a recall shows it: its id and the words its kind is known by.
|
|
||||||
fn facts_words(facts: &PipelineFacts) -> String {
|
|
||||||
match facts {
|
|
||||||
PipelineFacts::Campaign { title, .. } | PipelineFacts::Question { title, .. } | PipelineFacts::Ruling { title, .. } | PipelineFacts::CutSpec { title, .. } | PipelineFacts::Idea { title, .. } => title.0.clone(),
|
|
||||||
PipelineFacts::FollowUp { item, .. } => item.0.clone(),
|
|
||||||
PipelineFacts::Finding { claim, .. } | PipelineFacts::Research { claim, .. } => claim.0.clone(),
|
|
||||||
PipelineFacts::Memory { label, .. } | PipelineFacts::Thought { label, .. } => label.0.clone(),
|
|
||||||
_ => "(a record with no words to show)".to_owned(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReadSource for LiveReads {
|
|
||||||
fn read(&self, request: &ReadRequest, since: DateTime<Utc>) -> Result<String, ReadFailure> {
|
|
||||||
match request {
|
|
||||||
ReadRequest::Mind(words) => self.recall(words),
|
|
||||||
ReadRequest::Campaign(slug) => self.rulings(slug, since),
|
|
||||||
ReadRequest::Repo(target) => self.repo(target),
|
|
||||||
ReadRequest::Web(url) => self.web(url),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,198 +0,0 @@
|
||||||
//! What a read is and how it is handed to her (map 16.22.3): the repo grammar, the web address she must have in front of
|
|
||||||
//! her, the clip with its count, the fenced bridge, and the recorded reads a harness run performs.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_result_past_its_cap_is_clipped_with_a_count() {
|
|
||||||
assert_eq!(clipped("short", 10), "short");
|
|
||||||
let long = "é".repeat(10);
|
|
||||||
let cut = clipped(&long, 5);
|
|
||||||
assert!(cut.starts_with("éé\n[") && cut.ends_with(" more bytes not shown here]") && cut.contains("[16 more bytes"), "{cut}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_fixture_answers_what_was_recorded_and_nothing_else() {
|
|
||||||
let fixture: ReadFixture = toml::from_str::<std::collections::BTreeMap<String, ReadFixture>>(
|
|
||||||
r#"
|
|
||||||
[[read]]
|
|
||||||
kind = "repo"
|
|
||||||
target = "GameCult/Lodur#12"
|
|
||||||
text = "Reflex: the knee bends first."
|
|
||||||
[[read]]
|
|
||||||
kind = "web"
|
|
||||||
target = "https://example.org/private"
|
|
||||||
refused = "private"
|
|
||||||
"#,
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
.remove("read")
|
|
||||||
.unwrap();
|
|
||||||
let since = Utc::now();
|
|
||||||
assert_eq!(fixture.read(&ReadRequest::Repo("GameCult/Lodur#12".into()), since), Ok("Reflex: the knee bends first.".into()));
|
|
||||||
assert_eq!(fixture.read(&ReadRequest::Web("https://example.org/private".into()), since), Err(ReadFailure::Private));
|
|
||||||
assert_eq!(fixture.read(&ReadRequest::Mind("the knee".into()), since), Err(ReadFailure::NotFound));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul at 7d43695: a repo read (and so a domain read of a repo) lists merged and closed pull requests only, never an open
|
|
||||||
/// one by title, as the digest never does (map 16.22.2).
|
|
||||||
#[test]
|
|
||||||
fn a_repo_read_lists_no_open_pull_request_by_title() {
|
|
||||||
struct Forge(std::cell::RefCell<Vec<String>>);
|
|
||||||
impl ForgeGet for Forge {
|
|
||||||
fn get(&self, path: &str) -> anyhow::Result<(u16, String)> {
|
|
||||||
self.0.borrow_mut().push(path.to_owned());
|
|
||||||
let body = if path.contains("/pulls") {
|
|
||||||
serde_json::json!([
|
|
||||||
{ "number": 3, "title": "OPEN-PR-SENTINEL", "state": "open", "merged": false, "user": { "login": "nibu" } },
|
|
||||||
{ "number": 2, "title": "Reflex: the knee bends first", "state": "closed", "merged": true, "user": { "login": "nibu" } },
|
|
||||||
{ "number": 1, "title": "An idea let go", "state": "closed", "merged": false, "user": { "login": "kiko" } },
|
|
||||||
])
|
|
||||||
} else {
|
|
||||||
serde_json::json!({ "description": "A physics character middleware." })
|
|
||||||
};
|
|
||||||
Ok((200, body.to_string()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let forge = Forge(std::cell::RefCell::default());
|
|
||||||
let text = repo_read(&forge, "GameCult/Lodur").unwrap();
|
|
||||||
assert!(!text.contains("OPEN-PR-SENTINEL") && text.contains("- #2 Reflex: the knee bends first (merged, opened by nibu)") && text.contains("- #1 An idea let go (closed, opened by kiko)"), "{text}");
|
|
||||||
assert!(forge.0.borrow().iter().any(|path| path.contains("pulls?state=closed")), "{:?}", forge.0.borrow());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's R7: the fixture reads by normal form, and a search no entry records searches the titles of the repo's recorded
|
|
||||||
/// pull requests and issues for all its words.
|
|
||||||
#[test]
|
|
||||||
fn r7_a_fixture_search_matches_the_titles_of_its_recorded_changes() {
|
|
||||||
let fixture: ReadFixture = serde_json::from_value(serde_json::json!([
|
|
||||||
{ "kind": "repo", "target": "GameCult/Bifrost#89", "text": "Consent receipt for door grants\nThe body of it." },
|
|
||||||
{ "kind": "repo", "target": "GameCult/Bifrost#90", "text": "Sign-in gate" },
|
|
||||||
{ "kind": "repo", "target": "GameCult/Lodur#4", "text": "Consent for reflexes" },
|
|
||||||
]))
|
|
||||||
.unwrap();
|
|
||||||
let since = Utc::now();
|
|
||||||
let search = |target: &str| fixture.read(&ReadRequest::Repo(target.into()), since);
|
|
||||||
assert_eq!(search("GameCult/Bifrost?q=consent receipt"), Ok(format!("- #89 Consent receipt for door grants
|
|
||||||
{TITLES_ONLY}")));
|
|
||||||
assert_eq!(search("GameCult/Bifrost?q=body"), Ok(format!("- #89 Consent receipt for door grants
|
|
||||||
{TITLES_ONLY}")), "the body counts as the forge's does");
|
|
||||||
assert_eq!(search("GameCult/Bifrost?q=consent rec"), Err(ReadFailure::NotFound), "whole words only");
|
|
||||||
assert_eq!(search("gamecult/bifrost?q=Consent"), Ok(format!("- #89 Consent receipt for door grants
|
|
||||||
{TITLES_ONLY}")), "the repo's own changes only, case-blind");
|
|
||||||
assert_eq!(search("GameCult/Bifrost?q=consent signature"), Err(ReadFailure::NotFound));
|
|
||||||
assert_eq!(search("gamecult/BIFROST#90"), Ok("Sign-in gate".into()), "a recorded read by its normal form");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's R7, against a recorded copy of the live forge's answer to `GameCult/Bifrost?q=consent` (2026-11-21): the forge
|
|
||||||
/// returned ten; only a result whose title or body holds every word of hers counts. Two bodies say "consent" (#87, #71);
|
|
||||||
/// the other eight are dropped. "consent receipt" leaves #71 alone, and words none of them hold are an honest not-found.
|
|
||||||
#[test]
|
|
||||||
fn r7_a_live_search_keeps_only_results_that_hold_her_words() {
|
|
||||||
struct Recorded;
|
|
||||||
impl ForgeGet for Recorded {
|
|
||||||
fn get(&self, _path: &str) -> anyhow::Result<(u16, String)> {
|
|
||||||
Ok((200, include_str!("../fixtures/forge-bifrost-q-consent.json").to_owned()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let kept = repo_read(&Recorded, "GameCult/Bifrost?q=consent").unwrap();
|
|
||||||
assert!(kept.starts_with("- #87 ") && kept.lines().count() == 3 && kept.ends_with(TITLES_ONLY) && kept.lines().nth(1).is_some_and(|line| line.starts_with("- #71 ")), "{kept}");
|
|
||||||
assert!(repo_read(&Recorded, "GameCult/Bifrost?q=CONSENT receipt").unwrap().starts_with("- #71 "));
|
|
||||||
assert_eq!(repo_read(&Recorded, "GameCult/Bifrost?q=consent signature"), Err(ReadFailure::NotFound));
|
|
||||||
assert_eq!(repo_read(&Recorded, "GameCult/Bifrost?q=sealion"), Err(ReadFailure::NotFound));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's R8: a search's normal form is its content words, lowercased, lightly stemmed and sorted; a number loses its
|
|
||||||
/// leading zeros.
|
|
||||||
#[test]
|
|
||||||
fn r8_a_search_and_a_number_have_one_normal_form() {
|
|
||||||
let normal = |target: &str| ReadRequest::Repo(target.into()).normal();
|
|
||||||
assert_eq!(normal("GameCult/Bifrost?q=Merge pages and notices"), "repo:gamecult/bifrost?q=merge notice page");
|
|
||||||
assert_eq!(normal("GameCult/Bifrost?q=the notice, page merge"), normal("GameCult/Bifrost?q=Merge pages and notices"));
|
|
||||||
assert_eq!(normal("GameCult/Bifrost#089"), normal("gamecult/bifrost#89"));
|
|
||||||
assert_eq!(normal("GameCult/Bifrost#0"), "repo:gamecult/bifrost#0");
|
|
||||||
assert_eq!(normal("GameCult/Bifrost?q=queries class"), "repo:gamecult/bifrost?q=class query");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's R9: one matcher, stemmed as the normal form is, in the fixture and the live path alike: "merge pages" and "page
|
|
||||||
/// merge" find the same, and "consent receipts" finds what "consent receipt" finds, live as in the fixture.
|
|
||||||
#[test]
|
|
||||||
fn r9_one_matcher_stems_for_the_fixture_and_the_live_forge() {
|
|
||||||
let fixture: ReadFixture = serde_json::from_value(serde_json::json!([
|
|
||||||
{ "kind": "repo", "target": "GameCult/Bifrost#87", "text": "Merge pages and notices\nProve both." },
|
|
||||||
{ "kind": "repo", "target": "GameCult/Bifrost#59", "text": "Chat sign-in needs a live consent receipt" },
|
|
||||||
]))
|
|
||||||
.unwrap();
|
|
||||||
let since = Utc::now();
|
|
||||||
let search = |target: &str| fixture.read(&ReadRequest::Repo(target.into()), since);
|
|
||||||
assert_eq!(search("GameCult/Bifrost?q=merge pages"), search("GameCult/Bifrost?q=page merge"));
|
|
||||||
assert!(search("GameCult/Bifrost?q=merge pages").is_ok_and(|found| found.contains("#87")));
|
|
||||||
assert_eq!(search("GameCult/Bifrost?q=consent receipts"), search("GameCult/Bifrost?q=consent receipt"));
|
|
||||||
assert!(search("GameCult/Bifrost?q=consent receipts").is_ok_and(|found| found.contains("#59")));
|
|
||||||
struct Recorded;
|
|
||||||
impl ForgeGet for Recorded {
|
|
||||||
fn get(&self, _path: &str) -> anyhow::Result<(u16, String)> {
|
|
||||||
Ok((200, include_str!("../fixtures/forge-bifrost-q-consent.json").to_owned()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert_eq!(repo_read(&Recorded, "GameCult/Bifrost?q=consent receipts"), repo_read(&Recorded, "GameCult/Bifrost?q=consent receipt"));
|
|
||||||
assert!(repo_read(&Recorded, "GameCult/Bifrost?q=consent receipts").unwrap().starts_with("- #71 "));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's R9: a fixture search lists a change once by its number, even when its recorded text opens with the number.
|
|
||||||
#[test]
|
|
||||||
fn r9_a_fixture_search_says_the_number_once() {
|
|
||||||
let fixture: ReadFixture = serde_json::from_value(serde_json::json!([{ "kind": "repo", "target": "GameCult/Bifrost#87", "text": "#87 Merge pages and notices (opened by heimdall, merged)
|
|
||||||
|
|
||||||
Prove both." }])).unwrap();
|
|
||||||
assert_eq!(fixture.read(&ReadRequest::Repo("GameCult/Bifrost?q=merge pages".into()), Utc::now()), Ok(format!("- #87 Merge pages and notices (opened by heimdall, merged)
|
|
||||||
{TITLES_ONLY}")));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// R19, Heimdall: he described a pull request's contents after a read that returned only titles. Every read whose result
|
|
||||||
/// is titles says so, and a read that returns the text does not. The recorded reads of a simulation say what live says
|
|
||||||
/// (Soul s1, titles-only-gaps), and a rulings list marks only the rows that lack text (mixed-rulings-say-titles-only).
|
|
||||||
#[test]
|
|
||||||
fn a_read_that_returns_only_titles_says_the_contents_were_not_read() {
|
|
||||||
let fixture: ReadFixture = serde_json::from_value(serde_json::json!([
|
|
||||||
{ "kind": "repo", "target": "GameCult/Bifrost#87", "text": "#87 Merge pages and notices\nThe body." },
|
|
||||||
{ "kind": "repo", "target": "GameCult/Bifrost", "text": "A door.\n\nRecent pull requests, merged and closed:\n- #87 Merge pages and notices (merged, opened by heimdall)" },
|
|
||||||
{ "kind": "repo", "target": "GameCult/Bifrost/README.md", "text": "The readme." },
|
|
||||||
{ "kind": "mind", "target": "passkey cooling-off", "text": "- A ruling title" },
|
|
||||||
{ "kind": "web", "target": "http://example.org/", "text": "A page." }
|
|
||||||
]))
|
|
||||||
.unwrap();
|
|
||||||
let read = |request: ReadRequest| fixture.read(&request, Utc::now()).unwrap();
|
|
||||||
let search = read(ReadRequest::Repo("GameCult/Bifrost?q=merge pages".into()));
|
|
||||||
assert!(search.ends_with(TITLES_ONLY) && TITLES_ONLY.contains("contents were not read"), "{search}");
|
|
||||||
assert!(read(ReadRequest::Repo("GameCult/Bifrost".into())).ends_with(TITLES_ONLY));
|
|
||||||
assert!(read(ReadRequest::Mind("passkey cooling-off".into())).ends_with(TITLES_ONLY));
|
|
||||||
for whole in [read(ReadRequest::Repo("GameCult/Bifrost#87".into())), read(ReadRequest::Repo("GameCult/Bifrost/README.md".into())), read(ReadRequest::Web("http://example.org/".into()))] {
|
|
||||||
assert!(!whole.contains(TITLES_ONLY), "a read of the text is not titles only: {whole}");
|
|
||||||
}
|
|
||||||
let named = rulings_text([("Ruling one", None), ("Ruling two", Some("The text."))]).unwrap();
|
|
||||||
assert_eq!(named, "- Ruling one (title only: the ruling was not read)\n- Ruling two: The text.");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul s2 (live-titles-only-unpinned; m10, m11): the live repo root and the live recall end with the titles-only line, and
|
|
||||||
/// the live opening of one pull request does not.
|
|
||||||
#[test]
|
|
||||||
fn the_live_root_listing_and_recall_say_titles_only() {
|
|
||||||
struct Forge;
|
|
||||||
impl ForgeGet for Forge {
|
|
||||||
fn get(&self, path: &str) -> anyhow::Result<(u16, String)> {
|
|
||||||
let body = if path.contains("/pulls/") {
|
|
||||||
serde_json::json!({ "number": 3, "title": "A title", "state": "closed", "merged": true, "user": { "login": "nibu" }, "body": "The whole body." })
|
|
||||||
} else if path.contains("/pulls") {
|
|
||||||
serde_json::json!([{ "number": 3, "title": "A title", "state": "closed", "merged": true, "user": { "login": "nibu" } }])
|
|
||||||
} else {
|
|
||||||
serde_json::json!({ "description": "A repo." })
|
|
||||||
};
|
|
||||||
Ok((200, body.to_string()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert!(repo_read(&Forge, "GameCult/Lodur").unwrap().ends_with(TITLES_ONLY));
|
|
||||||
assert!(!repo_read(&Forge, "GameCult/Lodur#3").unwrap().contains(TITLES_ONLY));
|
|
||||||
let facts = PipelineFacts::Target { revision: 1, invariants: Vec::new() };
|
|
||||||
assert!(recall_text([&facts]).unwrap().ends_with(TITLES_ONLY));
|
|
||||||
assert_eq!(recall_text([]), Err(ReadFailure::NotFound));
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,881 +0,0 @@
|
||||||
//! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn one
|
|
||||||
//! wake (`wake`: the Projector and the Persona) and then the Interpreter step the drain takes after a completed wake
|
|
||||||
//! (`interpret_and_put`: two strict calls over her narration and prose, one per half of the sections, its deltas applied and put once), against that Mind's in-run
|
|
||||||
//! copy of her state. Nothing speaks in a wake (her agent does, and none runs here), so the room holds only the script's lines;
|
|
||||||
//! the report counts what the Interpreter changed instead.
|
|
||||||
//!
|
|
||||||
//! Who wakes is the heartbeat's: `heartbeat::wakes` over each persona's addressee as the
|
|
||||||
//! heartbeat's addressing table holds it (her stewarded projects' names included) when the plan names the table. The
|
|
||||||
//! beat is the heartbeat's too: when it falls, one Persona wakes, the winner of `tempo::pick`. Who wakes in a round is
|
|
||||||
//! decided from the room as the round opens, as one heartbeat poll decides from the pending it read: a line spoken by a
|
|
||||||
//! turn of this round wakes no one, and counts toward a cap, only from the next round. A persona takes at most one turn
|
|
||||||
//! a round, as the live heartbeat never starts a Mind whose unit is still running: in the room of her earliest waking
|
|
||||||
//! line. She reads only that room, and only that room is marked seen, so a line in another room that woke her wakes
|
|
||||||
//! her again next round: no line is seen without a turn that read it. The turns of a round go in an order drawn from
|
|
||||||
//! the seed, each against the room as it stands at that turn.
|
|
||||||
//!
|
|
||||||
//! What came of each of her turns opens her next packet (map 16.16): the run keeps each turn's record and the Interpreter's
|
|
||||||
//! receipt row, as her trace live, and her next turn reads what she is told from them (`turn::history`); a failed turn's
|
|
||||||
//! record is a failure, and an Interpreter that kept nothing is told as not kept.
|
|
||||||
//!
|
|
||||||
//! Her state moves during a run only by the Interpreter's deltas, applied by the commit's applier (`commit::apply`) and put to
|
|
||||||
//! her in-run copy (`InRun`, which refuses a stale put as the daemon does), as the drain puts them live. The review room
|
|
||||||
//! is taken as named, so identity changes are made as they would be where people see them; nothing is posted. The report
|
|
||||||
//! lists per wake the deltas by family, the intentions added or readied, the identity changes and what the guards refused.
|
|
||||||
|
|
||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::fmt::Write as _;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use anyhow::{Context, Result, bail};
|
|
||||||
use chrono::{DateTime, Duration, Utc};
|
|
||||||
use eureka_pipeline::Slug;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::narrate::MAX_OUTPUT_TOKENS;
|
|
||||||
use super::read::{self, ReadFailure, ReadRequest};
|
|
||||||
use super::harness::{Harness, Line, Message, OVERLAP_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total};
|
|
||||||
use super::select::Draw;
|
|
||||||
use super::tuning;
|
|
||||||
use super::turn::{history, last_wake};
|
|
||||||
use super::wake;
|
|
||||||
use super::{DomainFacts, DomainSource, MouthReader, Organs, PersonaSource, PersonaStore, Put, ReadFixture, ReadSource, Request, Through, TurnKind, heard_of, interpret_and_put};
|
|
||||||
use crate::address::{Addressee, is_for, localpart};
|
|
||||||
use crate::chat_client::ChatPending;
|
|
||||||
use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, Hearer, HeartbeatView, LineFacts, Speaker, WakeCause, addressed_by_member, claimed, floor_to, line_facts, wakes};
|
|
||||||
use crate::tempo::{Standing, pick};
|
|
||||||
|
|
||||||
/// The most personas a simulation holds: the swarm.
|
|
||||||
const CAST_MAX: usize = 8;
|
|
||||||
/// How many transcript lines the report quotes as representative.
|
|
||||||
const REPRESENTATIVE_LINES: usize = 18;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct SimFile {
|
|
||||||
rounds: usize,
|
|
||||||
#[serde(default = "one")]
|
|
||||||
repeats: usize,
|
|
||||||
#[serde(default)]
|
|
||||||
seed: u64,
|
|
||||||
/// The heartbeat's beat, in seconds of simulated time; 0 is no beat.
|
|
||||||
#[serde(default = "beat_s")]
|
|
||||||
beat_s: u32,
|
|
||||||
#[serde(default = "two")]
|
|
||||||
round_minutes: i64,
|
|
||||||
/// She is in a room's exchange when she has spoken there within this many minutes before the line:
|
|
||||||
/// others talking on does not keep her in it.
|
|
||||||
#[serde(default = "exchange_minutes")]
|
|
||||||
exchange_minutes: i64,
|
|
||||||
start: DateTime<Utc>,
|
|
||||||
rooms: Vec<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
operators: Vec<String>,
|
|
||||||
/// The heartbeat's store (`heartbeat.cc`), read without a lock or a write, for its addressing table: each persona's
|
|
||||||
/// names and her stewarded projects' names. None addresses each by her own names.
|
|
||||||
#[serde(default)]
|
|
||||||
addressing: Option<PathBuf>,
|
|
||||||
cast: Vec<CastEntry>,
|
|
||||||
#[serde(default, rename = "message")]
|
|
||||||
script: Vec<Message>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn one() -> usize {
|
|
||||||
1
|
|
||||||
}
|
|
||||||
|
|
||||||
fn two() -> i64 {
|
|
||||||
2
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exchange_minutes() -> i64 {
|
|
||||||
EXCHANGE_MINUTES
|
|
||||||
}
|
|
||||||
|
|
||||||
fn beat_s() -> u32 {
|
|
||||||
DEFAULT_BEAT_S
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct CastEntry {
|
|
||||||
id: String,
|
|
||||||
name: String,
|
|
||||||
/// Her persona state, relative to the plan; its `personaId` is her id's localpart.
|
|
||||||
state: PathBuf,
|
|
||||||
/// Her rooms; none is every room of the plan.
|
|
||||||
#[serde(default)]
|
|
||||||
rooms: Vec<String>,
|
|
||||||
/// The rooms that are hers, where any human line wakes her. Neither the heartbeat's table nor
|
|
||||||
/// `persona.env` records which rooms a Mind owns, so the plan says; a direct message is always hers.
|
|
||||||
#[serde(default)]
|
|
||||||
own_rooms: Vec<String>,
|
|
||||||
/// What a read of her domain returns on every turn of hers (`[cast.domain]`, `domain::DomainFacts`), windowed from her
|
|
||||||
/// last turn in the run; none leaves her packets without the section. No forge and no mind is read.
|
|
||||||
#[serde(default)]
|
|
||||||
domain: Option<DomainFacts>,
|
|
||||||
/// Her recorded reads (`[[cast.read]]`, map 16.22.3): what each read she reaches for returns; none, and she cannot read.
|
|
||||||
#[serde(default, rename = "read")]
|
|
||||||
reads: Option<ReadFixture>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her reads in a simulation (map 16.25.8): a campaign of hers from her domain fixture, the one owner of what her
|
|
||||||
/// campaign holds, formatted as a live read formats rulings (`read::rulings_text`); every other read from her recorded
|
|
||||||
/// reads.
|
|
||||||
struct CastReads<'a> {
|
|
||||||
recorded: &'a ReadFixture,
|
|
||||||
domain: Option<&'a DomainFacts>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReadSource for CastReads<'_> {
|
|
||||||
fn read(&self, request: &ReadRequest, since: DateTime<Utc>) -> Result<String, ReadFailure> {
|
|
||||||
let ReadRequest::Campaign(slug) = request else { return self.recorded.read(request, since) };
|
|
||||||
let campaign = self.domain.and_then(|facts| facts.campaigns.iter().find(|campaign| campaign.slug.eq_ignore_ascii_case(slug))).ok_or(ReadFailure::NotFound)?;
|
|
||||||
let mut rulings: Vec<_> = campaign.rulings.iter().filter(|ruling| ruling.at >= since).collect();
|
|
||||||
rulings.sort_by_key(|ruling| std::cmp::Reverse(ruling.at));
|
|
||||||
read::rulings_text(rulings.into_iter().map(|ruling| (ruling.title.as_str(), ruling.ruling.as_deref())))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct Member {
|
|
||||||
entry: CastEntry,
|
|
||||||
state: Value,
|
|
||||||
addressee: Addressee,
|
|
||||||
/// Where her addressee came from: the heartbeat's table, or her own names.
|
|
||||||
names_from: &'static str,
|
|
||||||
rooms: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Per room, how many lines she had seen when a turn of hers last read it: a line at or past that is new to her.
|
|
||||||
type Seen = BTreeMap<String, usize>;
|
|
||||||
|
|
||||||
fn unseen(seen: &Seen, lines: &[Line], at: usize) -> bool {
|
|
||||||
at >= seen.get(&lines[at].room).copied().unwrap_or(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One persona's view of the room at her turn: the lines she has not seen are new.
|
|
||||||
struct View<'a> {
|
|
||||||
lines: &'a RefCell<Vec<Line>>,
|
|
||||||
viewer: &'a str,
|
|
||||||
rooms: &'a [String],
|
|
||||||
seen: &'a Seen,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MouthReader for View<'_> {
|
|
||||||
fn pending(&self) -> Result<ChatPending> {
|
|
||||||
let lines = self.lines.borrow();
|
|
||||||
Ok(pending_for(&lines, self.viewer, self.rooms, |at| unseen(self.seen, &lines, at)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Names<'a>(&'a [Addressee]);
|
|
||||||
|
|
||||||
impl HeartbeatView for Names<'_> {
|
|
||||||
fn addressing(&self) -> Result<Option<Addressing>> {
|
|
||||||
Ok(Some(Addressing { minds: self.0.to_vec() }))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One Mind's state in one run: the copy the Interpreter's put changes, refusing a put under a stale `updatedAt` as the daemon does.
|
|
||||||
struct InRun(RefCell<Value>);
|
|
||||||
|
|
||||||
impl PersonaSource for InRun {
|
|
||||||
fn persona(&self) -> Result<(Value, String)> {
|
|
||||||
let state = self.0.borrow().clone();
|
|
||||||
let receipt = state["updatedAt"].as_str().unwrap_or_default().to_owned();
|
|
||||||
Ok((state, receipt))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PersonaStore for InRun {
|
|
||||||
fn put(&self, state: &Value, expected_updated_at: Option<&str>, _session: &str) -> Result<Put> {
|
|
||||||
let mut held = self.0.borrow_mut();
|
|
||||||
if expected_updated_at != held["updatedAt"].as_str() {
|
|
||||||
return Ok(Put::Stale);
|
|
||||||
}
|
|
||||||
*held = state.clone();
|
|
||||||
Ok(Put::Committed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one Interpreter row did, as the report names it: the deltas by `family change`, her intentions it added, readied or
|
|
||||||
/// dropped with their words from her state after it, the identity fields it changed, and what the guards refused with why.
|
|
||||||
fn done(row: &Value, after: &Value) -> Value {
|
|
||||||
let changes = || row["applied"].as_array().into_iter().flatten();
|
|
||||||
let mut deltas: BTreeMap<String, usize> = BTreeMap::new();
|
|
||||||
for change in changes() {
|
|
||||||
*deltas.entry(format!("{} {}", change["family"].as_str().unwrap_or_default(), change["change"].as_str().unwrap_or_default())).or_insert(0) += 1;
|
|
||||||
}
|
|
||||||
let words = |id: &str| after["candidateActions"]["actions"].as_array().into_iter().flatten().find(|action| action["id"] == id).and_then(|action| action["summary"].as_str()).unwrap_or_default().to_owned();
|
|
||||||
let intentions: Vec<Value> = changes().filter(|change| change["family"] == "intend").map(|change| json!({ "change": change["change"], "id": change["id"], "words": words(change["id"].as_str().unwrap_or_default()) })).collect();
|
|
||||||
let identity: Vec<&Value> = changes().filter(|change| change["family"] == "self" && change["change"] == "identity").map(|change| &change["id"]).collect();
|
|
||||||
let refused: Vec<String> = row["refused"].as_array().into_iter().flatten().map(|refusal| format!("{}: {}", refusal["family"].as_str().unwrap_or_default(), refusal["reason"].as_str().map_or_else(|| refusal["reason"].to_string(), str::to_owned))).collect();
|
|
||||||
json!({ "status": row["status"], "error": row["error"], "deltas": deltas, "intentions": intentions, "identity": identity, "refused": refused })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String]) -> Speaker {
|
|
||||||
if line.from == member.entry.id {
|
|
||||||
Speaker::Her
|
|
||||||
} else if operators.contains(&line.from) {
|
|
||||||
Speaker::Operator
|
|
||||||
} else if cast.contains(&line.from) {
|
|
||||||
Speaker::Mind
|
|
||||||
} else {
|
|
||||||
Speaker::Member
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How a Mind's line addressed her, by the evidence `is_for` had, strongest first: a Matrix tag or a reply to her, her
|
|
||||||
/// Matrix id written as plain text, or one of her names in the text.
|
|
||||||
fn how_addressed(line: &Line, at: usize, member: &Member, lines: &[Line]) -> &'static str {
|
|
||||||
let delivery = line.delivery(at, &member.entry.id, lines);
|
|
||||||
if delivery.mentions.contains(&member.entry.id) || delivery.basis.is_some() {
|
|
||||||
"mention or reply"
|
|
||||||
} else if line.says.to_lowercase().contains(&member.entry.id.to_lowercase()) {
|
|
||||||
"id as text"
|
|
||||||
} else {
|
|
||||||
"name in text"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One wake: why (the strongest cause among her new lines) and, when only Minds' lines caused
|
|
||||||
/// it, the strongest evidence that addressed her and the lines that did.
|
|
||||||
struct Woken {
|
|
||||||
cause: WakeCause,
|
|
||||||
/// The newest line with that cause: its room is the turn's room.
|
|
||||||
line: usize,
|
|
||||||
how: Option<&'static str>,
|
|
||||||
by: Vec<Value>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The lines she sees, and their facts from the heartbeat's one owner of them.
|
|
||||||
fn seeing(lines: &[Line], member: &Member, cast: &[String], gap: Duration) -> (Vec<usize>, Vec<LineFacts>) {
|
|
||||||
let visible: Vec<usize> = (0..lines.len()).filter(|at| lines[*at].visible_to(&member.entry.id, &member.rooms)).collect();
|
|
||||||
let facts: Vec<FactLine> = visible.iter().map(|at| FactLine { sender: &lines[*at].from, room: &lines[*at].room, at_ms: lines[*at].at_ms }).collect();
|
|
||||||
let facts = line_facts(&facts, &member.entry.id, cast, &member.entry.own_rooms, u64::try_from(gap.num_milliseconds()).unwrap_or(0));
|
|
||||||
(visible, facts)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her wake, if a line she has not seen wakes her: in the room of the earliest such line, with the strongest cause among
|
|
||||||
/// that room's waking lines.
|
|
||||||
fn woken(lines: &[Line], seen: &Seen, member: &Member, operators: &[String], cast: &[String], visible: Vec<usize>, facts: Vec<LineFacts>) -> Option<Woken> {
|
|
||||||
let mut found: Vec<(usize, WakeCause)> = Vec::new();
|
|
||||||
for (at, facts) in visible.into_iter().zip(facts) {
|
|
||||||
if !unseen(seen, lines, at) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let delivery = lines[at].delivery(at, &member.entry.id, lines);
|
|
||||||
if let Some(cause) = wakes(&member.addressee, &delivery, speaker(&lines[at], member, operators, cast), facts) {
|
|
||||||
found.push((at, cause));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let room = &lines[found.first()?.0].room;
|
|
||||||
found.retain(|(at, _)| lines[*at].room == *room);
|
|
||||||
let cause = found.iter().map(|(_, cause)| *cause).min()?;
|
|
||||||
let line = found.iter().rev().find(|(_, found)| *found == cause).map_or(0, |(at, _)| *at);
|
|
||||||
if cause != WakeCause::AddressedByMind {
|
|
||||||
return Some(Woken { cause, line, how: None, by: vec![] });
|
|
||||||
}
|
|
||||||
let addressing: Vec<usize> = found.iter().filter(|(_, cause)| *cause == WakeCause::AddressedByMind).map(|(at, _)| *at).collect();
|
|
||||||
let rank = |how: &str| ["mention or reply", "id as text", "name in text"].iter().position(|one| *one == how).unwrap_or(3);
|
|
||||||
let how = addressing.iter().map(|at| how_addressed(&lines[*at], *at, member, lines)).min_by_key(|how| rank(how));
|
|
||||||
let by = addressing.iter().map(|at| json!({ "from": lines[*at].from, "how": how_addressed(&lines[*at], *at, member, lines), "says": lines[*at].says })).collect();
|
|
||||||
Some(Woken { cause, line, how, by })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The wire spelling of a cause, and of the beat.
|
|
||||||
fn cause_word(cause: Option<WakeCause>) -> &'static str {
|
|
||||||
match cause {
|
|
||||||
Some(WakeCause::AddressedByHuman) => "addressed_by_human",
|
|
||||||
Some(WakeCause::Human) => "human",
|
|
||||||
Some(WakeCause::AddressedByMind) => "addressed_by_mind",
|
|
||||||
None => "beat",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A seeded shuffle, so the order of those woken together is drawn, and replays.
|
|
||||||
fn shuffled<T>(mut items: Vec<T>, seed: u64) -> Vec<T> {
|
|
||||||
let mut draw = Draw(seed);
|
|
||||||
for at in (1..items.len()).rev() {
|
|
||||||
let pick = (draw.next() % (at as u64 + 1)) as usize;
|
|
||||||
items.swap(at, pick);
|
|
||||||
}
|
|
||||||
items
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs the plan: every repeat one simulation, all of them in one Markdown report.
|
|
||||||
pub fn simulate(harness: &Harness, plan_path: &Path) -> Result<String> {
|
|
||||||
let text = std::fs::read_to_string(plan_path).with_context(|| format!("the plan {} could not be read", plan_path.display()))?;
|
|
||||||
let plan: SimFile = toml::from_str(&text).with_context(|| format!("the plan {} is not a simulation plan", plan_path.display()))?;
|
|
||||||
if plan.cast.is_empty() || plan.cast.len() > CAST_MAX {
|
|
||||||
bail!("a simulation holds 1 to {CAST_MAX} personas, not {}", plan.cast.len());
|
|
||||||
}
|
|
||||||
if plan.rounds == 0 || plan.repeats == 0 || plan.rooms.is_empty() || plan.round_minutes <= 0 {
|
|
||||||
bail!("a simulation needs rounds, repeats, a room and a positive round_minutes");
|
|
||||||
}
|
|
||||||
let base = plan_path.parent().unwrap_or(Path::new("."));
|
|
||||||
let members = cast_of(&plan, base)?;
|
|
||||||
let group_state = tuning::load(&harness.tuning).map(|loaded| loaded.tuning.select.group_state).ok();
|
|
||||||
let runs: Vec<Value> = (0..plan.repeats).map(|repeat| run(harness, &plan, &members, repeat)).collect::<Result<_>>()?;
|
|
||||||
Ok(markdown(plan_path, &plan, &members, group_state, &runs))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The plan's cast: each persona's state, checked as a put would check it, and her addressee, from the heartbeat's
|
|
||||||
/// table when the plan names it and the table holds her; and the script checked against the rooms.
|
|
||||||
fn cast_of(plan: &SimFile, base: &Path) -> Result<Vec<Member>> {
|
|
||||||
let table = match &plan.addressing {
|
|
||||||
Some(path) => FileStore::new(base.join(path)).addressing().with_context(|| format!("the heartbeat store {} could not be read", path.display()))?.unwrap_or_default(),
|
|
||||||
None => Addressing::default(),
|
|
||||||
};
|
|
||||||
let mut members = Vec::new();
|
|
||||||
for entry in &plan.cast {
|
|
||||||
// One fixture owns what her campaign holds (map 16.25.8): her `[cast.domain]`, never a recorded read.
|
|
||||||
if entry.reads.as_ref().is_some_and(|reads| reads.records("campaign")) {
|
|
||||||
bail!("{}'s [[cast.read]] records a campaign read: what her campaign holds is her [cast.domain]'s campaigns, with each ruling's `ruling` text", entry.name);
|
|
||||||
}
|
|
||||||
let state = state_file(&base.join(&entry.state), localpart(&entry.id))?;
|
|
||||||
let rooms = if entry.rooms.is_empty() { plan.rooms.clone() } else { entry.rooms.clone() };
|
|
||||||
let (addressee, names_from) = match table.minds.iter().find(|row| row.matrix_id() == entry.id) {
|
|
||||||
Some(row) => (row.clone(), "the heartbeat's table"),
|
|
||||||
None => {
|
|
||||||
let public = state["publicName"].as_str().unwrap_or_default().to_owned();
|
|
||||||
let names = [localpart(&entry.id), entry.name.as_str(), public.as_str()].into_iter().filter(|name| !name.is_empty()).map(str::to_owned).collect::<Vec<_>>();
|
|
||||||
(Addressee::new(&entry.id, names.iter().map(String::as_str)), "her own names")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
members.push(Member { addressee, names_from, entry: entry.clone(), state, rooms });
|
|
||||||
}
|
|
||||||
for (at, message) in plan.script.iter().enumerate() {
|
|
||||||
if message.ago.is_some() || message.new || message.tag {
|
|
||||||
bail!("script message {} uses a room fixture's ago, new or tag: a script names its round and its mentions", at + 1);
|
|
||||||
}
|
|
||||||
if !message.dm && !plan.rooms.contains(&message.room) {
|
|
||||||
bail!("script message {} is in {}, which is not one of the rooms", at + 1, message.room);
|
|
||||||
}
|
|
||||||
if message.dm && message.to.as_ref().is_none_or(|to| !plan.cast.iter().any(|entry| entry.id == *to)) {
|
|
||||||
bail!("script message {} is a direct message: name its recipient, a cast member, in `to`", at + 1);
|
|
||||||
}
|
|
||||||
if message.dm && plan.rooms.contains(&message.room) {
|
|
||||||
bail!("script message {} is a direct message in {}, one of the plan's rooms: a direct message has its own room", at + 1, message.room);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(members)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(harness: &Harness, plan: &SimFile, members: &[Member], repeat: usize) -> Result<Value> {
|
|
||||||
let seed = plan.seed.wrapping_add(repeat as u64);
|
|
||||||
let cast: Vec<String> = members.iter().map(|member| member.entry.id.clone()).collect();
|
|
||||||
let addressees: Vec<Addressee> = members.iter().map(|member| member.addressee.clone()).collect();
|
|
||||||
// Each Mind's state as this run moves it: the one the wake reads and the Interpreter's put changes.
|
|
||||||
let held: Vec<InRun> = members.iter().map(|member| InRun(RefCell::new(member.state.clone()))).collect();
|
|
||||||
let interpreter = match harness.model {
|
|
||||||
Some(model) => Some((model, tuning::load(&harness.tuning)?.tuning.interpreter.model)),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let at_round = |round: usize| plan.start + Duration::minutes(plan.round_minutes * round as i64);
|
|
||||||
let mut lines: Vec<Line> = Vec::new();
|
|
||||||
// Per line: the round, and the cause of the turn that spoke it (none for a script line).
|
|
||||||
let mut rounds_of: Vec<usize> = Vec::new();
|
|
||||||
let mut causes: Vec<Option<&'static str>> = Vec::new();
|
|
||||||
let scripted = |round: usize, lines: &mut Vec<Line>, rounds_of: &mut Vec<usize>, causes: &mut Vec<Option<&'static str>>| -> Result<()> {
|
|
||||||
for (at, message) in plan.script.iter().enumerate().filter(|(_, message)| message.round.unwrap_or(0) == round) {
|
|
||||||
lines.push(Line::of(message, at_round(round) + Duration::seconds(at as i64), None, at)?);
|
|
||||||
rounds_of.push(round);
|
|
||||||
causes.push(None);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
};
|
|
||||||
scripted(0, &mut lines, &mut rounds_of, &mut causes)?;
|
|
||||||
let opening = lines.len();
|
|
||||||
let mut seen: Vec<Seen> = vec![Seen::new(); members.len()];
|
|
||||||
let mut last_beat = plan.start;
|
|
||||||
// The lines whose open floor a Mind took, so no other is picked for them.
|
|
||||||
let mut floor_taken: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
|
|
||||||
// Every turn record of hers, oldest first: the run's trace, which her last outcome, her recent selections, her exchange
|
|
||||||
// and her last wake are read from (`turn::history`).
|
|
||||||
let mut records: Vec<Vec<Value>> = vec![Vec::new(); members.len()];
|
|
||||||
let mut turns = Vec::new();
|
|
||||||
let mut counter = 0u64;
|
|
||||||
for round in 1..=plan.rounds {
|
|
||||||
scripted(round, &mut lines, &mut rounds_of, &mut causes)?;
|
|
||||||
let round_at = at_round(round);
|
|
||||||
// Decided from the room as the round opens, as a poll decides from the pending it read.
|
|
||||||
let mut seeings: Vec<(Vec<usize>, Vec<LineFacts>)> = members.iter().map(|member| seeing(&lines, member, &cast, Duration::minutes(plan.exchange_minutes))).collect();
|
|
||||||
// The open floor, as the heartbeat judges it: each line some Mind has not seen and no Mind has taken falls to one
|
|
||||||
// Mind, the beat's pick among those who hear it.
|
|
||||||
let standing = |at: usize, member: &Member| Standing {
|
|
||||||
slug: localpart(&member.entry.id).to_owned(),
|
|
||||||
eligible: true,
|
|
||||||
waited_s: last_wake(&records[at]).map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)),
|
|
||||||
last_turn_ms: last_wake(&records[at]).map(|turn| turn.timestamp_millis()),
|
|
||||||
topic_permille: 0,
|
|
||||||
addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| unseen(&seen[at], &lines, index)).deliveries),
|
|
||||||
};
|
|
||||||
let standings: Vec<Standing> = members.iter().enumerate().map(|(at, member)| standing(at, member)).collect();
|
|
||||||
let mut won: Vec<Vec<usize>> = vec![Vec::new(); members.len()];
|
|
||||||
for line in 0..lines.len() {
|
|
||||||
if floor_taken.contains(&line) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let hearers: Vec<(usize, Hearer)> = members
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter(|(at, _)| unseen(&seen[*at], &lines, line))
|
|
||||||
.filter_map(|(at, member)| {
|
|
||||||
let place = seeings[at].0.iter().position(|visible| *visible == line)?;
|
|
||||||
Some((at, Hearer { addressee: &member.addressee, delivery: lines[line].delivery(line, &member.entry.id, &lines), open: seeings[at].1[place].open_floor, standing: standings[at].clone() }))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let Some(first) = hearers.first().map(|(at, _)| *at) else { continue };
|
|
||||||
let hearing: Vec<Hearer> = hearers.iter().map(|(_, hearer)| Hearer { addressee: hearer.addressee, delivery: hearer.delivery.clone(), open: hearer.open, standing: hearer.standing.clone() }).collect();
|
|
||||||
if let Some(winner) = floor_to(&hearing, speaker(&lines[line], &members[first], &plan.operators, &cast), plan.beat_s) {
|
|
||||||
won[hearers[winner].0].push(line);
|
|
||||||
floor_taken.insert(line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (at, (visible, facts)) in seeings.iter_mut().enumerate() {
|
|
||||||
for (line, facts) in visible.iter().zip(facts.iter_mut()) {
|
|
||||||
facts.open_floor &= won[at].contains(line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut woke: Vec<(usize, Option<Woken>)> = members
|
|
||||||
.iter()
|
|
||||||
.zip(seeings)
|
|
||||||
.enumerate()
|
|
||||||
.filter_map(|(at, (member, (visible, facts)))| woken(&lines, &seen[at], member, &plan.operators, &cast, visible, facts).map(|why| (at, Some(why))))
|
|
||||||
.collect();
|
|
||||||
// The beat, as the heartbeat's: when it has fallen, one more wake for the winner of `tempo::pick` among those
|
|
||||||
// not already woken.
|
|
||||||
if plan.beat_s > 0 && (round_at - last_beat).num_seconds() >= i64::from(plan.beat_s) {
|
|
||||||
let standings: Vec<Standing> = members
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(at, member)| Standing {
|
|
||||||
slug: localpart(&member.entry.id).to_owned(),
|
|
||||||
eligible: !woke.iter().any(|(woken, _)| *woken == at),
|
|
||||||
waited_s: last_wake(&records[at]).map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)),
|
|
||||||
last_turn_ms: last_wake(&records[at]).map(|turn| turn.timestamp_millis()),
|
|
||||||
topic_permille: 0,
|
|
||||||
addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| unseen(&seen[at], &lines, index)).deliveries),
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
if let Some(winner) = pick(&standings, plan.beat_s) {
|
|
||||||
woke.push((winner, None));
|
|
||||||
last_beat = round_at;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (at, why) in shuffled(woke, seed ^ (round as u64).wrapping_mul(0x9E37_79B9)) {
|
|
||||||
counter += 1;
|
|
||||||
let member = &members[at];
|
|
||||||
let id = member.entry.id.clone();
|
|
||||||
let fresh: Vec<&Line> = lines.iter().enumerate().filter(|(index, line)| unseen(&seen[at], &lines, *index) && line.from != id && line.visible_to(&id, &member.rooms)).map(|(_, line)| line).collect();
|
|
||||||
// The turn is in the room of the line that woke her; a beat's, in the room of the newest line she has not seen.
|
|
||||||
let woke_on = why.as_ref().map(|why| &lines[why.line]).or(fresh.last().copied());
|
|
||||||
let here = woke_on.map_or_else(|| member.rooms[0].clone(), |line| line.room.clone());
|
|
||||||
let kind = if fresh.iter().any(|line| line.room == here) { TurnKind::Chat } else { TurnKind::Beat };
|
|
||||||
let now = round_at + Duration::seconds(30 + counter as i64);
|
|
||||||
let past = history(&records[at]);
|
|
||||||
let request = Request {
|
|
||||||
instance: localpart(&id).to_owned(),
|
|
||||||
kind,
|
|
||||||
state: Some(held[at].0.borrow().clone()),
|
|
||||||
rooms: vec![here.clone()],
|
|
||||||
seed: seed.wrapping_mul(1_000_003).wrapping_add(counter),
|
|
||||||
renders: Some(1),
|
|
||||||
judge_against: None,
|
|
||||||
operators: plan.operators.clone(),
|
|
||||||
minds: cast.clone(),
|
|
||||||
own_sender: id.clone(),
|
|
||||||
tuning: harness.tuning.clone(),
|
|
||||||
through: Through::Persona,
|
|
||||||
last_heard: vec![],
|
|
||||||
recent: past.recent,
|
|
||||||
own_rooms: member.entry.own_rooms.clone(),
|
|
||||||
woken_for: claimed(why.as_ref().map(|why| lines[why.line].delivery(why.line, &id, &lines).event_id).as_deref(), &won[at].iter().map(|line| lines[*line].delivery(*line, &id, &lines).event_id).collect::<Vec<_>>()),
|
|
||||||
told: past.told,
|
|
||||||
tools: vec![],
|
|
||||||
last_wake: past.last_wake,
|
|
||||||
records: past.records,
|
|
||||||
};
|
|
||||||
// What the room held when she read it, before her own lines go in.
|
|
||||||
let read_to = lines.len();
|
|
||||||
let key = format!("r{}-t{counter}", repeat + 1);
|
|
||||||
let room = RefCell::new(std::mem::take(&mut lines));
|
|
||||||
let waked = {
|
|
||||||
let view = View { lines: &room, viewer: &id, rooms: &member.rooms, seen: &seen[at] };
|
|
||||||
let names = Names(&addressees);
|
|
||||||
let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() });
|
|
||||||
let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) };
|
|
||||||
wake(&organs, &request, now)?
|
|
||||||
};
|
|
||||||
lines = room.into_inner();
|
|
||||||
let cause = cause_word(why.as_ref().map(|why| why.cause));
|
|
||||||
rounds_of.resize(lines.len(), round);
|
|
||||||
causes.resize(lines.len(), Some(cause));
|
|
||||||
let failed = waked.failed.as_ref().map(|fault| fault.reason.clone());
|
|
||||||
// A line is seen by her only through a wake whose record carries a decision (K65, map 16.34.3): a failed wake
|
|
||||||
// sees nothing, so its lines wake her again and show again, as the live mouth hands out a delivery until it is
|
|
||||||
// acked. Only the room she read is seen. A later step that broke (`broke_after`) still sees: a decision stands.
|
|
||||||
if failed.is_none() {
|
|
||||||
seen[at].insert(here.clone(), read_to);
|
|
||||||
}
|
|
||||||
// Nothing speaks in a wake (the agent does), so a wake that did not fail is silent.
|
|
||||||
let line: Option<String> = None;
|
|
||||||
let outcome = if failed.is_some() { "failed" } else { "silent" };
|
|
||||||
let (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by));
|
|
||||||
let mut turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "report": waked.report });
|
|
||||||
let seq = records[at].len();
|
|
||||||
records[at].push(json!({ "key": key, "seq": seq, "room": here, "rooms": [here], "held": [], "narration": waked.narration, "prose": waked.prose, "usage": waked.usage, "selected": waked.report["renders"][0]["selected"], "status": if failed.is_none() { "completed" } else { "failed" }, "failed": failed, "at": now.to_rfc3339() }));
|
|
||||||
// The Interpreter, as the drain takes it after a completed wake: the same call and put (`interpret_and_put`) against her
|
|
||||||
// in-run copy, its receipt a row of her trace that her next wake is told from (`outcome::told`).
|
|
||||||
if failed.is_none()
|
|
||||||
&& let (Some((model, model_name)), Some(narration), Some(prose)) = (interpreter.as_ref(), waked.narration.as_deref(), waked.prose.as_deref())
|
|
||||||
{
|
|
||||||
let before = held[at].0.borrow().clone();
|
|
||||||
let heard = heard_of(&before, &waked.report["packet"], &here, [], &plan.operators, &cast, true, None, narration, prose);
|
|
||||||
// A call id the connector has not seen: the plan's clock repeats from run to run, so the call takes the wall clock, as `wake_id` does.
|
|
||||||
let made = interpret_and_put(*model, model_name, &format!("{key}-i{}", Utc::now().timestamp_nanos_opt().unwrap_or_default()), &held[at], &Slug(localpart(&id).to_owned()), &before, &heard, narration, prose, &key, now, &|| now, &|_| Ok(()));
|
|
||||||
let mut row = made.row;
|
|
||||||
row["seq"] = json!(records[at].len());
|
|
||||||
row["at"] = json!(now.to_rfc3339());
|
|
||||||
row["wake"] = json!(key);
|
|
||||||
turn["did"] = done(&row, &held[at].0.borrow());
|
|
||||||
turn["interpreter"] = row.clone();
|
|
||||||
records[at].push(row);
|
|
||||||
}
|
|
||||||
turns.push(turn);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// The cast as the run ended: each Mind with the state its Interpreter left her.
|
|
||||||
let ended: Vec<Member> = members.iter().zip(&held).map(|(member, held)| Member { state: held.0.borrow().clone(), ..member.clone() }).collect();
|
|
||||||
let metrics = metrics(&ended, &lines, &rounds_of, &causes, opening, &turns, plan.rounds);
|
|
||||||
let transcript: Vec<Value> = lines.iter().zip(&rounds_of).zip(&causes).map(|((line, round), cause)| json!({ "round": round, "room": line.room, "from": line.from, "name": line.name, "says": line.says, "mind": cast.contains(&line.from), "woke": cause })).collect();
|
|
||||||
Ok(json!({ "repeat": repeat + 1, "seed": seed, "transcript": transcript, "turns": turns, "metrics": metrics }))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Words that mark talk about the work. A cheap lexical heuristic for the work-talk share, not a classifier: it counts
|
|
||||||
/// a line as work talk when any of these appears as a word in it.
|
|
||||||
const WORK_WORDS: [&str; 26] = [
|
|
||||||
"repo", "repos", "pr", "commit", "merge", "deploy", "build", "test", "tests", "bug", "branch", "code", "release", "issue", "pipeline", "crate", "schema", "spec", "cargo", "clippy", "daemon", "patch", "refactor", "migration", "server", "ticket",
|
|
||||||
];
|
|
||||||
|
|
||||||
fn work_talk(text: &str) -> bool {
|
|
||||||
text.split(|c: char| !c.is_alphanumeric()).any(|word| WORK_WORDS.contains(&word.to_lowercase().as_str()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mean pairwise cosine between the speakers' texts; speakers with no text are left out.
|
|
||||||
fn mean_pairwise(texts: &BTreeMap<String, String>) -> Option<f64> {
|
|
||||||
let spoken: Vec<&String> = texts.values().filter(|text| !text.trim().is_empty()).collect();
|
|
||||||
let mut sum = 0.0;
|
|
||||||
let mut pairs = 0usize;
|
|
||||||
for (at, a) in spoken.iter().enumerate() {
|
|
||||||
for b in &spoken[at + 1..] {
|
|
||||||
sum += cosine(a, b);
|
|
||||||
pairs += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(pairs > 0).then(|| sum / pairs as f64)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Which rounds a measure keeps.
|
|
||||||
type Keep<'a> = &'a dyn Fn(usize) -> bool;
|
|
||||||
|
|
||||||
/// A Mind-to-Mind reply: a Mind's line spoken in a turn another Mind's line woke.
|
|
||||||
fn mind_reply(cause: Option<&str>) -> bool {
|
|
||||||
matches!(cause, Some("addressed_by_mind" | "mind"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Per room: Mind-to-Mind replies in a row with no human line and no human-woken answer between them.
|
|
||||||
fn reply_chains(lines: &[Line], causes: &[Option<&str>], opening: usize, cast: &[&str]) -> Value {
|
|
||||||
let mut rooms: BTreeMap<String, (usize, usize, usize, usize)> = BTreeMap::new();
|
|
||||||
for (line, cause) in lines.iter().zip(causes).skip(opening) {
|
|
||||||
let (longest, chains, total, run) = rooms.entry(line.room.clone()).or_default();
|
|
||||||
if cast.contains(&line.from.as_str()) && mind_reply(*cause) {
|
|
||||||
*run += 1;
|
|
||||||
*total += 1;
|
|
||||||
*longest = (*longest).max(*run);
|
|
||||||
} else {
|
|
||||||
*chains += usize::from(*run >= 3);
|
|
||||||
*run = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let out: BTreeMap<String, Value> = rooms
|
|
||||||
.into_iter()
|
|
||||||
.map(|(room, (longest, chains, total, run))| (room, json!({ "longest": longest, "chains_of_3_or_more": chains + usize::from(run >= 3), "mind_to_mind_replies": total })))
|
|
||||||
.collect();
|
|
||||||
json!(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Option<&str>], opening: usize, turns: &[Value], rounds: usize) -> Value {
|
|
||||||
let cast: Vec<&str> = members.iter().map(|member| member.entry.id.as_str()).collect();
|
|
||||||
let outcome = |turn: &&Value, what: &str| turn["outcome"] == what;
|
|
||||||
let mut per = BTreeMap::new();
|
|
||||||
for member in members {
|
|
||||||
let mine: Vec<&Value> = turns.iter().filter(|turn| turn["id"] == member.entry.id.as_str()).collect();
|
|
||||||
let (spoke, silent, failed) = (mine.iter().filter(|turn| outcome(turn, "spoke")).count(), mine.iter().filter(|turn| outcome(turn, "silent")).count(), mine.iter().filter(|turn| outcome(turn, "failed")).count());
|
|
||||||
let mut addressed = BTreeMap::new();
|
|
||||||
for (at, line) in lines.iter().enumerate().skip(opening).filter(|(_, line)| line.from == member.entry.id) {
|
|
||||||
for other in members.iter().filter(|other| other.entry.id != member.entry.id) {
|
|
||||||
if is_for(&other.addressee, &line.delivery(at, &other.entry.id, lines)) {
|
|
||||||
*addressed.entry(other.entry.name.clone()).or_insert(0u64) += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let answered = spoke + silent;
|
|
||||||
// What the Interpreter did to her over the run: its calls and the ones that kept nothing, the deltas by `family change`,
|
|
||||||
// her intentions added and readied, her identity changes, the items the guards refused, and her short-term size at the end.
|
|
||||||
let interpreted: Vec<&Value> = mine.iter().map(|turn| &turn["did"]).filter(|did| did.is_object()).collect();
|
|
||||||
let mut deltas: BTreeMap<&str, u64> = BTreeMap::new();
|
|
||||||
for did in &interpreted {
|
|
||||||
for (what, count) in did["deltas"].as_object().into_iter().flatten() {
|
|
||||||
*deltas.entry(what.as_str()).or_insert(0) += count.as_u64().unwrap_or(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let intentions = |change: &str| interpreted.iter().flat_map(|did| did["intentions"].as_array().into_iter().flatten()).filter(|intention| intention["change"] == change).count();
|
|
||||||
let interpreter = json!({
|
|
||||||
"calls": mine.iter().filter(|turn| turn["interpreter"].is_object()).count(),
|
|
||||||
"kept_nothing": interpreted.iter().filter(|did| did["status"] != "ok").count(),
|
|
||||||
"deltas": deltas,
|
|
||||||
"intentions_added": intentions("added"),
|
|
||||||
"intentions_ready": intentions("ready"),
|
|
||||||
"identity_changes": interpreted.iter().map(|did| did["identity"].as_array().map_or(0, Vec::len)).sum::<usize>(),
|
|
||||||
"refused": interpreted.iter().map(|did| did["refused"].as_array().map_or(0, Vec::len)).sum::<usize>(),
|
|
||||||
"short_term_at_end": member.state["thoughtMemory"]["shortTerm"].as_array().map_or(0, Vec::len),
|
|
||||||
});
|
|
||||||
per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed, "interpreter": interpreter }));
|
|
||||||
}
|
|
||||||
let half = rounds.div_ceil(2);
|
|
||||||
let spoken_by = |keep: Keep| -> BTreeMap<String, String> {
|
|
||||||
let mut texts = BTreeMap::new();
|
|
||||||
for (line, _) in lines.iter().zip(rounds_of).skip(opening).filter(|(line, round)| cast.contains(&line.from.as_str()) && keep(**round)) {
|
|
||||||
let text: &mut String = texts.entry(line.from.clone()).or_default();
|
|
||||||
text.push(' ');
|
|
||||||
text.push_str(&line.says);
|
|
||||||
}
|
|
||||||
texts
|
|
||||||
};
|
|
||||||
let prose_by = |keep: Keep| -> BTreeMap<String, String> {
|
|
||||||
let mut texts = BTreeMap::new();
|
|
||||||
for turn in turns.iter().filter(|turn| turn["round"].as_u64().is_some_and(|round| keep(round as usize))) {
|
|
||||||
let text: &mut String = texts.entry(turn["id"].as_str().unwrap_or_default().to_owned()).or_default();
|
|
||||||
text.push(' ');
|
|
||||||
text.push_str(turn["report"]["renders"][0]["persona"]["prose"].as_str().unwrap_or_default());
|
|
||||||
}
|
|
||||||
texts
|
|
||||||
};
|
|
||||||
let (all, early, late): (Keep, Keep, Keep) = (&|_| true, &|round| round <= half, &|round| round > half);
|
|
||||||
let mind_lines: Vec<&Line> = lines[opening..].iter().filter(|line| cast.contains(&line.from.as_str())).collect();
|
|
||||||
const CAUSES: [&str; 5] = ["addressed_by_human", "human", "addressed_by_mind", "mind", "beat"];
|
|
||||||
let count_causes = |these: &[&Value]| -> BTreeMap<&str, usize> { CAUSES.iter().map(|cause| (*cause, these.iter().filter(|turn| turn["woke"] == *cause).count())).collect() };
|
|
||||||
let wakes_by_round: Vec<Value> = (1..=rounds)
|
|
||||||
.map(|round| {
|
|
||||||
let these: Vec<&Value> = turns.iter().filter(|turn| turn["round"] == round).collect();
|
|
||||||
json!({ "round": round, "causes": count_causes(&these) })
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let every: Vec<&Value> = turns.iter().collect();
|
|
||||||
let mind_woken: Vec<&Value> = turns.iter().filter(|turn| turn["woke"] == "addressed_by_mind").collect();
|
|
||||||
let by_how = |how: &str| mind_woken.iter().filter(|turn| turn["how"] == how).count();
|
|
||||||
let id_as_text: Vec<Value> = mind_woken.iter().filter(|turn| turn["how"] == "id as text").map(|turn| json!({ "round": turn["round"], "persona": turn["persona"], "by": turn["addressed_by"] })).collect();
|
|
||||||
let (silent, failed) = (turns.iter().filter(|turn| turn["outcome"] == "silent").count(), turns.iter().filter(|turn| turn["outcome"] == "failed").count());
|
|
||||||
let answered = turns.len() - failed;
|
|
||||||
let work = mind_lines.iter().filter(|line| work_talk(&line.says)).count();
|
|
||||||
let overlaps: Vec<f64> = turns.iter().filter_map(|turn| turn["report"]["renders"][0]["heard_overlap"].as_f64()).collect();
|
|
||||||
let narration = json!({
|
|
||||||
"mean_heard_overlap": if overlaps.is_empty() { Value::Null } else { json!(overlaps.iter().sum::<f64>() / overlaps.len() as f64) },
|
|
||||||
"high_overlap": overlaps.iter().filter(|overlap| **overlap > OVERLAP_FLAG).count(),
|
|
||||||
"offers_options": turns.iter().filter(|turn| turn["report"]["renders"][0]["offers_options"] == true).count(),
|
|
||||||
"narrations": overlaps.len(),
|
|
||||||
});
|
|
||||||
// Every Interpreter call of every wake, by its output (K66, map 16.34.4): how many came within a quarter of the cap.
|
|
||||||
let interpreter_calls: Vec<u64> = turns.iter().filter(|turn| turn["interpreter"].is_object()).map(|turn| turn["interpreter"]["usage"]["output_tokens"].as_u64().unwrap_or(0)).collect();
|
|
||||||
let near_cap = interpreter_calls.iter().filter(|out| **out * 4 > u64::from(MAX_OUTPUT_TOKENS) * 3).count();
|
|
||||||
json!({
|
|
||||||
"interpreter_calls": { "calls": interpreter_calls.len(), "over_three_quarters_of_cap": near_cap, "cap": MAX_OUTPUT_TOKENS },
|
|
||||||
"narration": narration,
|
|
||||||
"personas": per,
|
|
||||||
"turns": turns.len(),
|
|
||||||
"wakes": count_causes(&every),
|
|
||||||
"failed": failed,
|
|
||||||
"mind_messages": mind_lines.len(),
|
|
||||||
"silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) },
|
|
||||||
"reply_chains": reply_chains(lines, causes, opening, &cast),
|
|
||||||
"convergence_lines": { "all": mean_pairwise(&spoken_by(all)), "first_half": mean_pairwise(&spoken_by(early)), "second_half": mean_pairwise(&spoken_by(late)) },
|
|
||||||
"convergence_prose": { "all": mean_pairwise(&prose_by(all)), "first_half": mean_pairwise(&prose_by(early)), "second_half": mean_pairwise(&prose_by(late)) },
|
|
||||||
"work_talk_share": if mind_lines.is_empty() { Value::Null } else { json!(work as f64 / mind_lines.len() as f64) },
|
|
||||||
"wakes_by_round": wakes_by_round,
|
|
||||||
"mind_addressed_wakes": { "total": mind_woken.len(), "mention_or_reply": by_how("mention or reply"), "id_as_text": by_how("id as text"), "name_in_text": by_how("name in text"), "id_as_text_wakes": id_as_text },
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A line's text on one Markdown line: its paragraph breaks shown as ` / `.
|
|
||||||
fn one_line(text: &str) -> String {
|
|
||||||
text.lines().map(str::trim).filter(|line| !line.is_empty()).collect::<Vec<_>>().join(" / ")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn number(value: &Value) -> String {
|
|
||||||
value.as_f64().map_or_else(|| "n/a".into(), |number| format!("{number:.3}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `count` lines spread evenly over the transcript, the first and the last included.
|
|
||||||
fn representative(transcript: &[Value], count: usize) -> Vec<&Value> {
|
|
||||||
if transcript.len() <= count {
|
|
||||||
return transcript.iter().collect();
|
|
||||||
}
|
|
||||||
let mut at: Vec<usize> = (0..count).map(|index| index * (transcript.len() - 1) / (count - 1)).collect();
|
|
||||||
at.dedup();
|
|
||||||
at.into_iter().map(|index| &transcript[index]).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn transcript_line(line: &Value) -> String {
|
|
||||||
let who = if line["mind"] == true { line["name"].as_str().unwrap_or_default().to_owned() } else { format!("{} (human)", line["name"].as_str().unwrap_or_default()) };
|
|
||||||
let woke = line["woke"].as_str().map_or_else(String::new, |cause| format!(" _(woke: {cause})_"));
|
|
||||||
format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the Interpreter did after one wake, in words: the deltas by family, the intentions added or readied with their words,
|
|
||||||
/// the identity fields changed and what the guards refused with why. Nothing when no Interpreter ran.
|
|
||||||
fn interpreter_words(did: &Value) -> Vec<String> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
if let Some(error) = did["error"].as_str() {
|
|
||||||
out.push(format!("kept nothing: {}", one_line(error)));
|
|
||||||
}
|
|
||||||
let deltas: Vec<String> = did["deltas"].as_object().into_iter().flatten().map(|(what, count)| format!("{what} x{count}")).collect();
|
|
||||||
out.push(format!("deltas: {}", if deltas.is_empty() { "none".to_owned() } else { deltas.join(", ") }));
|
|
||||||
for intention in did["intentions"].as_array().into_iter().flatten() {
|
|
||||||
out.push(format!("intention {} (`{}`): {}", intention["change"].as_str().unwrap_or_default(), intention["id"].as_str().unwrap_or_default(), one_line(intention["words"].as_str().unwrap_or_default())));
|
|
||||||
}
|
|
||||||
for field in did["identity"].as_array().into_iter().flatten() {
|
|
||||||
out.push(format!("identity changed: {}", field.as_str().unwrap_or_default()));
|
|
||||||
}
|
|
||||||
for refusal in did["refused"].as_array().into_iter().flatten() {
|
|
||||||
out.push(format!("guard refused {}", refusal.as_str().unwrap_or_default()));
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The packet's flags, as the report shows them (Soul's R5): the window her domain view shows and what it left out, the
|
|
||||||
/// context guards that bound, and what was clipped.
|
|
||||||
fn flags_markdown(out: &mut String, turn: &Value) {
|
|
||||||
let packet = &turn["report"]["packet"];
|
|
||||||
let list = |value: &Value| value.as_array().map(|items| items.iter().map(|item| item.as_str().map_or_else(|| item.to_string(), str::to_owned)).collect::<Vec<_>>().join(", ")).filter(|text| !text.is_empty()).unwrap_or_else(|| "none".to_owned());
|
|
||||||
let shown = &packet["domain_shown"];
|
|
||||||
let domain = match (shown["since"].as_str(), shown["omitted"].as_str()) {
|
|
||||||
(_, Some(why)) => format!("left out ({why})"),
|
|
||||||
(Some(since), None) => format!("since {since}, {} older items left out", shown["left_out"]),
|
|
||||||
(None, None) => "none".to_owned(),
|
|
||||||
};
|
|
||||||
let _ = writeln!(
|
|
||||||
out,
|
|
||||||
"Packet flags: domain view: {domain}; guards bound: {}; clipped: {}\n",
|
|
||||||
list(&packet["bound"]),
|
|
||||||
list(&packet["clipped"]),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: Option<bool>, runs: &[Value]) -> String {
|
|
||||||
let mut out = String::new();
|
|
||||||
let _ = writeln!(out, "# Swarm simulation\n");
|
|
||||||
let _ = writeln!(out, "> **What came of her last turn opens her next packet.** Each persona's turn record and the Interpreter's receipt row are carried to her next turn, as her trace carries them live; a turn's details show what she was told of it.
|
|
||||||
");
|
|
||||||
let _ = writeln!(out, "- plan: `{}`", plan_path.display());
|
|
||||||
let _ = writeln!(out, "- cast: {}", members.iter().map(|member| format!("{} (`{}`, `{}`, names from {})", member.entry.name, member.entry.id, member.entry.state.display(), member.names_from)).collect::<Vec<_>>().join(", "));
|
|
||||||
let _ = writeln!(out, "- rooms: {}; rounds: {}; repeats: {}; seed: {}; minutes a round: {}; she is in a room's exchange when she spoke there within {} min", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes, plan.exchange_minutes);
|
|
||||||
let owners: Vec<String> = members.iter().filter(|member| !member.entry.own_rooms.is_empty()).map(|member| format!("{}: {}", member.entry.name, member.entry.own_rooms.join(", "))).collect();
|
|
||||||
let _ = writeln!(out, "- own rooms (from the plan: neither the heartbeat's table nor `persona.env` records room ownership): {}", if owners.is_empty() { "none".to_owned() } else { owners.join("; ") });
|
|
||||||
let _ = writeln!(out, "- wake: humans pace (`heartbeat::wakes`); beat: {}", if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) });
|
|
||||||
let _ = writeln!(out, "- group state in the Projector's packet: {}", match group_state { Some(true) => "on", Some(false) => "off", None => "unknown (the tuning did not load)" });
|
|
||||||
let _ = writeln!(out, "- the Interpreter runs after each wake that did not fail, the drain's call and put (`interpret_and_put`) against each Mind's in-run copy of her state, with the review room taken as named: its deltas move her state for the run's later wakes; nothing speaks in a wake, so the room holds the script's lines only");
|
|
||||||
let _ = writeln!(out, "- wakes are counted per wake, by its strongest cause: addressed by a human, a human line, addressed by a Mind, a Mind's line (control only), the beat. A Mind-addressed wake's evidence is its strongest: a Matrix mention or reply, her id written as text, a name in the text");
|
|
||||||
let _ = writeln!(out, "- silence rate is per woken turn that did not fail; a failed call is counted apart. Reply chains are per room: Mind lines spoken in turns another Mind's line woke, in a row");
|
|
||||||
let _ = writeln!(out, "- convergence is the mean pairwise cosine of speakers' word counts (lexical, cheap); work-talk share is a lexical heuristic over a fixed word list, not a classifier");
|
|
||||||
let _ = writeln!(out, "- nothing is posted and no stored state is put; the model is asked twice a wake (the Projector and the Persona) and once more for the Interpreter
|
|
||||||
");
|
|
||||||
for run in runs {
|
|
||||||
let metrics = &run["metrics"];
|
|
||||||
let wakes = &metrics["wakes"];
|
|
||||||
let _ = writeln!(out, "## Repeat {} (seed {})\n", run["repeat"], run["seed"]);
|
|
||||||
let _ = writeln!(out, "### Metrics\n");
|
|
||||||
let _ = writeln!(
|
|
||||||
out,
|
|
||||||
"- wakes: {} (addressed by a human {}, a human line {}, addressed by a Mind {}, a Mind's line {}, the beat {}); failed {}",
|
|
||||||
metrics["turns"], wakes["addressed_by_human"], wakes["human"], wakes["addressed_by_mind"], wakes["mind"], wakes["beat"], metrics["failed"]
|
|
||||||
);
|
|
||||||
let _ = writeln!(out, "- Mind messages: {}; silence rate per woken turn: {}", metrics["mind_messages"], number(&metrics["silence_rate"]));
|
|
||||||
let calls = &metrics["interpreter_calls"];
|
|
||||||
let _ = writeln!(out, "- Interpreter calls: {}; over 75% of the cap ({} output tokens): {}", calls["calls"], calls["cap"], calls["over_three_quarters_of_cap"]);
|
|
||||||
if let Some(rooms) = metrics["reply_chains"].as_object() {
|
|
||||||
for (room, chain) in rooms {
|
|
||||||
let _ = writeln!(out, "- reply chains in {room}: longest {}, chains of 3 or more {}, Mind-to-Mind replies {}", chain["longest"], chain["chains_of_3_or_more"], chain["mind_to_mind_replies"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let addressed = &metrics["mind_addressed_wakes"];
|
|
||||||
let _ = writeln!(out, "- Mind-addressed wakes: {} (Matrix mention or reply {}, her id written as text {}, a name in the text {})", addressed["total"], addressed["mention_or_reply"], addressed["id_as_text"], addressed["name_in_text"]);
|
|
||||||
let _ = writeln!(out, "- convergence of spoken lines: all {}, first half {}, second half {}", number(&metrics["convergence_lines"]["all"]), number(&metrics["convergence_lines"]["first_half"]), number(&metrics["convergence_lines"]["second_half"]));
|
|
||||||
let _ = writeln!(out, "- convergence of prose: all {}, first half {}, second half {}", number(&metrics["convergence_prose"]["all"]), number(&metrics["convergence_prose"]["first_half"]), number(&metrics["convergence_prose"]["second_half"]));
|
|
||||||
let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}", number(&metrics["work_talk_share"]));
|
|
||||||
let narration = &metrics["narration"];
|
|
||||||
let _ = writeln!(out, "- narrations: {}; mean lexical overlap with what she heard {}; over {OVERLAP_FLAG}: {}; offering her options {}\n", narration["narrations"], number(&narration["mean_heard_overlap"]), narration["high_overlap"], narration["offers_options"]);
|
|
||||||
let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed | Interpreter calls | kept nothing | intentions added | intentions ready | identity changes | guard refusals | short-term at end |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|");
|
|
||||||
if let Some(personas) = metrics["personas"].as_object() {
|
|
||||||
for (name, row) in personas {
|
|
||||||
let named = row["addressed"].as_object().map(|map| map.iter().map(|(who, count)| format!("{who} {count}")).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
|
||||||
let i = &row["interpreter"];
|
|
||||||
let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} | {} | {} | {} | {} | {} | {} | {} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]), i["calls"], i["kept_nothing"], i["intentions_added"], i["intentions_ready"], i["identity_changes"], i["refused"], i["short_term_at_end"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "\n### Interpreter by wake\n\n| round | persona | woke | status | what it did |\n|---|---|---|---|---|");
|
|
||||||
for turn in run["turns"].as_array().into_iter().flatten().filter(|turn| turn["interpreter"].is_object()) {
|
|
||||||
let _ = writeln!(out, "| {} | {} | {} | {} | {} |", turn["round"], turn["persona"].as_str().unwrap_or_default(), turn["woke"].as_str().unwrap_or_default(), turn["interpreter"]["status"].as_str().unwrap_or_default(), interpreter_words(&turn["did"]).join("; ").replace('|', "/"));
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "\n### Wakes by round\n\n| round | addressed by a human | a human line | addressed by a Mind | a Mind's line | beat |\n|---|---|---|---|---|---|");
|
|
||||||
for row in metrics["wakes_by_round"].as_array().into_iter().flatten() {
|
|
||||||
let causes = &row["causes"];
|
|
||||||
let _ = writeln!(out, "| {} | {} | {} | {} | {} | {} |", row["round"], causes["addressed_by_human"], causes["human"], causes["addressed_by_mind"], causes["mind"], causes["beat"]);
|
|
||||||
}
|
|
||||||
let as_text = addressed["id_as_text_wakes"].as_array().cloned().unwrap_or_default();
|
|
||||||
if !as_text.is_empty() {
|
|
||||||
let _ = writeln!(out, "\nWakes whose only address was an id written as text (no mention, no reply):\n");
|
|
||||||
for one in as_text {
|
|
||||||
let by = one["by"].as_array().into_iter().flatten().map(|by| format!("{}: {}", by["from"].as_str().unwrap_or_default(), one_line(by["says"].as_str().unwrap_or_default()))).collect::<Vec<_>>().join("; ");
|
|
||||||
let _ = writeln!(out, "- r{} {}: {by}", one["round"], one["persona"].as_str().unwrap_or_default());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let transcript = run["transcript"].as_array().cloned().unwrap_or_default();
|
|
||||||
let _ = writeln!(out, "\n### Representative lines\n");
|
|
||||||
for line in representative(&transcript, REPRESENTATIVE_LINES) {
|
|
||||||
let _ = writeln!(out, "{}", transcript_line(line));
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "\n### Transcript\n");
|
|
||||||
for line in &transcript {
|
|
||||||
let _ = writeln!(out, "{}", transcript_line(line));
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "\n### Turns\n");
|
|
||||||
for turn in run["turns"].as_array().into_iter().flatten() {
|
|
||||||
let _ = writeln!(out, "<details><summary>round {}, {} (woke: {}, {} turn, {}): {}</summary>\n", turn["round"], turn["persona"].as_str().unwrap_or_default(), turn["woke"].as_str().unwrap_or_default(), turn["kind"].as_str().unwrap_or_default(), turn["room"].as_str().unwrap_or_default(), turn["outcome"].as_str().unwrap_or_default());
|
|
||||||
let report = &turn["report"];
|
|
||||||
if let Some(error) = report.get("error") {
|
|
||||||
let _ = writeln!(out, "**failed:** {}\n", error.as_str().unwrap_or_default());
|
|
||||||
} else {
|
|
||||||
if let Some(told) = report["last_outcome"]["told"].as_array().filter(|told| !told.is_empty()) {
|
|
||||||
let _ = writeln!(out, "What came of her last turn:\n\n````text\n{}\n````\n", told.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("\n"));
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "Stimulus:\n\n````text\n{}\n````\n", report["packet"]["stimulus"].as_str().unwrap_or_default());
|
|
||||||
turn_markdown(&mut out, &report["renders"][0]);
|
|
||||||
if turn["interpreter"].is_object() {
|
|
||||||
let _ = writeln!(out, "Interpreter ({}): {}\n", turn["interpreter"]["status"].as_str().unwrap_or_default(), interpreter_words(&turn["did"]).join("; "));
|
|
||||||
}
|
|
||||||
flags_markdown(&mut out, turn);
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "</details>\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let _ = writeln!(out, "## Total usage\n\n{}", usage_markdown(&usage_total(runs)));
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,481 +0,0 @@
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::projection::harness::tests::{Scripted, control};
|
|
||||||
use serde_json::json;
|
|
||||||
use crate::projection::narrate::PROJECTOR_OPENING;
|
|
||||||
use crate::projection::{Answer, Failed, Model, Spent};
|
|
||||||
use crate::chat_client::{ChatDelivery, ContextLine};
|
|
||||||
use crate::heartbeat::{MIND_RUN_BACKSTOP, LineFacts, own_rooms, pending_facts};
|
|
||||||
|
|
||||||
const TOBIAH: &str = "@eureka:gamecult.org";
|
|
||||||
const LIBBY: &str = "@libby:gamecult.org";
|
|
||||||
|
|
||||||
/// A cast of two in a temp dir: the control character as Eureka, and a copy of it as Libby ("Libby Test").
|
|
||||||
fn cast(dir: &Path) {
|
|
||||||
std::fs::write(dir.join("tobiah.json"), control().to_string()).unwrap();
|
|
||||||
let mut libby = control();
|
|
||||||
libby["personaId"] = "libby".into();
|
|
||||||
libby["provenance"]["sourceDocumentId"] = "libby".into();
|
|
||||||
libby["publicName"] = "Libby Test".into();
|
|
||||||
std::fs::write(dir.join("libby.json"), libby.to_string()).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A plan over the two, the operator opening in #minds, which is the room of both; no beat unless `extra` sets one.
|
|
||||||
fn plan(dir: &Path, rounds: usize, extra: &str) -> PathBuf {
|
|
||||||
cast(dir);
|
|
||||||
let path = dir.join("plan.toml");
|
|
||||||
let beat = if extra.contains("beat_s") { "" } else { "beat_s = 0\n" };
|
|
||||||
std::fs::write(
|
|
||||||
&path,
|
|
||||||
format!(
|
|
||||||
r##"rounds = {rounds}
|
|
||||||
seed = 11
|
|
||||||
start = "2026-11-20T15:00:00Z"
|
|
||||||
rooms = ["#minds:gamecult.org"]
|
|
||||||
operators = ["@meta:gamecult.org"]
|
|
||||||
{beat}{extra}
|
|
||||||
[[cast]]
|
|
||||||
id = "{TOBIAH}"
|
|
||||||
name = "Tobiah"
|
|
||||||
own_rooms = ["#minds:gamecult.org"]
|
|
||||||
state = "tobiah.json"
|
|
||||||
[[cast]]
|
|
||||||
id = "{LIBBY}"
|
|
||||||
name = "Libby"
|
|
||||||
own_rooms = ["#minds:gamecult.org"]
|
|
||||||
state = "libby.json"
|
|
||||||
[[message]]
|
|
||||||
from = "@meta:gamecult.org"
|
|
||||||
name = "Meta"
|
|
||||||
room = "#minds:gamecult.org"
|
|
||||||
says = "good afternoon, everyone"
|
|
||||||
"##
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
path
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The same plan with no room hers: a public room's human line wakes her only by address or her exchange.
|
|
||||||
fn bare_plan(dir: &Path, rounds: usize, extra: &str) -> PathBuf {
|
|
||||||
let path = plan(dir, rounds, extra);
|
|
||||||
std::fs::write(&path, std::fs::read_to_string(&path).unwrap().replace("own_rooms = [\"#minds:gamecult.org\"]
|
|
||||||
", "")).unwrap();
|
|
||||||
path
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_tobiah(prompt: &str) -> bool {
|
|
||||||
prompt.contains("Who you are:\nTobiah")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Both speak every turn, neither naming the other: each line a draft, sent.
|
|
||||||
fn chatty() -> Scripted {
|
|
||||||
Scripted::new(|prompt| if is_tobiah(prompt) { "what a day".into() } else { "mm, the deploy went fine".into() })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Both speak every turn, each naming the other.
|
|
||||||
fn namers() -> Scripted {
|
|
||||||
Scripted::new(|prompt| if is_tobiah(prompt) { "Libby, tea?".into() } else { "Tobiah, yes please.".into() })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn silent() -> Scripted {
|
|
||||||
Scripted::new(|_| "Nobody needs anything from her.".into())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_plan(path: &Path, model: &dyn Model) -> (Vec<Member>, Value) {
|
|
||||||
let plan: SimFile = toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
|
|
||||||
let base = path.parent().unwrap();
|
|
||||||
let members = cast_of(&plan, base).unwrap();
|
|
||||||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(model), tuning: base.join("persona-tuning.toml") };
|
|
||||||
let run = run(&harness, &plan, &members, 0).unwrap();
|
|
||||||
(members, run)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn turns(run: &Value) -> Vec<(u64, String, String)> {
|
|
||||||
run["turns"].as_array().unwrap().iter().map(|turn| (turn["round"].as_u64().unwrap(), turn["persona"].as_str().unwrap().to_owned(), turn["woke"].as_str().unwrap().to_owned())).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One line to Libby as a delivery, with the facts a caller gives it.
|
|
||||||
fn ask(from: &str, says: &str, speaker: Speaker, facts: LineFacts) -> Option<WakeCause> {
|
|
||||||
let libby = Addressee::new(LIBBY, ["libby", "Libby"]);
|
|
||||||
let line = Line { from: from.into(), name: String::new(), room: "#minds:x".into(), at_ms: 0, says: says.into(), mentions: vec![], dm_to: None, follow_up: false, reply_to: None, new: false };
|
|
||||||
wakes(&libby, &line.delivery(0, LIBBY, &[]), speaker, facts)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn facts(own_room: bool, in_exchange: bool) -> LineFacts {
|
|
||||||
LineFacts { mind_run: 0, own_room, in_exchange, open_floor: false }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_w1_member_in_own_room_wakes() {
|
|
||||||
assert_eq!(ask("@deru:x", "what a day", Speaker::Member, facts(true, false)), Some(WakeCause::Human));
|
|
||||||
assert_eq!(ask("@deru:x", "what a day", Speaker::Member, LineFacts::default()), None, "no fact of hers, no wake");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_w1_member_in_shared_room_needs_address_or_exchange() {
|
|
||||||
assert_eq!(ask("@deru:x", "what a day", Speaker::Member, facts(false, false)), None);
|
|
||||||
assert_eq!(ask("@deru:x", "Libby, tea?", Speaker::Member, facts(false, false)), Some(WakeCause::AddressedByHuman));
|
|
||||||
assert_eq!(ask("@deru:x", "what a day", Speaker::Member, facts(false, true)), Some(WakeCause::Human));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_w1_mind_line_backstop() {
|
|
||||||
let libby = Addressee::new(LIBBY, ["libby", "Libby"]);
|
|
||||||
let tagged = Line { from: TOBIAH.into(), name: String::new(), room: "#minds:x".into(), at_ms: 0, says: "what a day".into(), mentions: vec![LIBBY.into()], dm_to: None, follow_up: false, reply_to: None, new: false };
|
|
||||||
let explicit = |run: usize| wakes(&libby, &tagged.delivery(0, LIBBY, &[]), Speaker::Mind, LineFacts { mind_run: run, ..LineFacts::default() });
|
|
||||||
assert_eq!(explicit(MIND_RUN_BACKSTOP - 1), Some(WakeCause::AddressedByMind), "a Matrix mention by a Mind wakes her, in any room");
|
|
||||||
assert_eq!(explicit(MIND_RUN_BACKSTOP), None, "the backstop: at the cap of Mind lines in a row, no Mind wakes another");
|
|
||||||
assert_eq!(ask(TOBIAH, "Libby, tea?", Speaker::Mind, facts(true, true)), None, "a name in prose wakes no Mind");
|
|
||||||
assert_eq!(ask(LIBBY, "Libby, tea?", Speaker::Her, facts(true, true)), None, "her own line never");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_w1_dm_wakes() {
|
|
||||||
let libby = Addressee::new(LIBBY, ["libby", "Libby"]);
|
|
||||||
let dm = Line { from: "@deru:x".into(), name: String::new(), room: "!dm:x".into(), at_ms: 0, says: "psst".into(), mentions: vec![], dm_to: Some(LIBBY.into()), follow_up: false, reply_to: None, new: false };
|
|
||||||
assert_eq!(wakes(&libby, &dm.delivery(0, LIBBY, &[]), Speaker::Member, LineFacts::default()), Some(WakeCause::AddressedByHuman));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One fixture of lines, read by the simulator's room and by the poll's pending deliveries, gives the same facts and the same wakes.
|
|
||||||
#[test]
|
|
||||||
fn t_w1_same_facts_both_paths() {
|
|
||||||
let cast = vec![TOBIAH.to_owned(), LIBBY.to_owned()];
|
|
||||||
let own = vec!["#libby:x".to_owned()];
|
|
||||||
let line = |from: &str, room: &str, minutes: u64, mentions: Vec<String>| Line { from: from.into(), name: String::new(), room: room.into(), at_ms: minutes * 60_000, says: "hi".into(), mentions, dm_to: None, follow_up: false, reply_to: None, new: false };
|
|
||||||
let lines = [
|
|
||||||
line("@deru:x", "#general:x", 0, vec![]),
|
|
||||||
line(LIBBY, "#general:x", 1, vec![]),
|
|
||||||
line("@deru:x", "#general:x", 2, vec![]),
|
|
||||||
line("@deru:x", "#libby:x", 3, vec![]),
|
|
||||||
line(TOBIAH, "#general:x", 4, vec![LIBBY.into()]),
|
|
||||||
line("@deru:x", "#general:x", 100, vec![]),
|
|
||||||
];
|
|
||||||
let libby = Addressee::new(LIBBY, ["libby", "Libby"]);
|
|
||||||
let speaker = |line: &Line| if line.from == TOBIAH { Speaker::Mind } else { Speaker::Member };
|
|
||||||
// The simulator's path: the lines she sees, in order.
|
|
||||||
let seeing: Vec<FactLine> = lines.iter().map(|line| FactLine { sender: &line.from, room: &line.room, at_ms: line.at_ms }).collect();
|
|
||||||
let simulated = line_facts(&seeing, LIBBY, &cast, &own, 30 * 60_000);
|
|
||||||
// The poll's path: the deliveries pending (not her own lines), each with the room's earlier lines as its context.
|
|
||||||
let heard: Vec<usize> = (0..lines.len()).filter(|at| lines[*at].from != LIBBY).collect();
|
|
||||||
let deliveries: Vec<ChatDelivery> = heard
|
|
||||||
.iter()
|
|
||||||
.map(|at| {
|
|
||||||
let mut delivery = lines[*at].delivery(*at, LIBBY, &lines);
|
|
||||||
delivery.context = lines[..*at].iter().filter(|earlier| earlier.room == lines[*at].room).map(|earlier| ContextLine { sender: earlier.from.clone(), text: String::new(), at_unix_ms: earlier.at_ms }).collect();
|
|
||||||
delivery
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let pending: Vec<&ChatDelivery> = deliveries.iter().collect();
|
|
||||||
let polled = pending_facts(&pending, LIBBY, &cast, &own);
|
|
||||||
// The open floor is the caller's, narrowed to the pick; this test judges the rest.
|
|
||||||
let closed = |facts: LineFacts| LineFacts { open_floor: false, ..facts };
|
|
||||||
let by_sim: Vec<Option<WakeCause>> = heard.iter().map(|at| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), closed(simulated[*at]))).collect();
|
|
||||||
let by_poll: Vec<Option<WakeCause>> = heard.iter().zip(&polled).map(|(at, facts)| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), closed(*facts))).collect();
|
|
||||||
assert_eq!(by_sim, by_poll);
|
|
||||||
assert_eq!(by_sim, vec![None, Some(WakeCause::Human), Some(WakeCause::Human), Some(WakeCause::AddressedByMind), None], "a general line before she spoke, one in her exchange, her room, a Mind's tag, a general line after the exchange lapsed");
|
|
||||||
for (at, facts) in heard.iter().zip(&polled) {
|
|
||||||
assert_eq!((facts.mind_run, facts.own_room, facts.in_exchange, facts.open_floor), (simulated[*at].mind_run, simulated[*at].own_room, simulated[*at].in_exchange, simulated[*at].open_floor), "line {at}");
|
|
||||||
}
|
|
||||||
assert_eq!(polled.iter().map(|facts| facts.mind_run).collect::<Vec<_>>(), vec![0, 1, 0, 0, 0], "her line, then a human's line that ends the run, then a Mind's tag after both");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_name_in_prose_wakes_no_mind_and_a_chain_of_names_never_starts() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let (_, run) = run_plan(&plan(dir.path(), 6, ""), &namers());
|
|
||||||
assert_eq!(turns(&run).len(), 2, "the opening wakes both in round 1; their names for each other wake no one: {:?}", turns(&run));
|
|
||||||
assert_eq!(run["metrics"]["mind_addressed_wakes"]["total"], 0, "{}", run["metrics"]["mind_addressed_wakes"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A model whose Persona stage fails: a failure, never a silence.
|
|
||||||
struct FailingPersona;
|
|
||||||
|
|
||||||
impl Model for FailingPersona {
|
|
||||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
|
||||||
if prompt.starts_with(PROJECTOR_OPENING) {
|
|
||||||
Ok(Answer { text: "The room is slow.".into(), usage: None })
|
|
||||||
} else {
|
|
||||||
Err(Failed { reason: "the provider failed the call: Overloaded".into(), outage: false, usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_failed_call_is_a_failure_and_not_a_silence() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let (_, run) = run_plan(&plan(dir.path(), 2, ""), &FailingPersona);
|
|
||||||
let metrics = &run["metrics"];
|
|
||||||
// A failed wake sees nothing (K65), so the line that woke each wakes her again the next round: two each.
|
|
||||||
assert_eq!((metrics["failed"].as_u64(), metrics["silence_rate"].is_null()), (Some(4), true), "{metrics}");
|
|
||||||
assert!(run["turns"].as_array().unwrap().iter().all(|turn| turn["outcome"] == "failed" && turn["failed"].as_str().unwrap().contains("Overloaded")));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_seed_replays_its_order_and_another_seed_changes_it() {
|
|
||||||
let items: Vec<usize> = (0..8).collect();
|
|
||||||
assert_eq!(shuffled(items.clone(), 1), shuffled(items.clone(), 1));
|
|
||||||
assert_ne!(shuffled(items.clone(), 1), shuffled(items.clone(), 2));
|
|
||||||
let mut sorted = shuffled(items.clone(), 2);
|
|
||||||
sorted.sort_unstable();
|
|
||||||
assert_eq!(sorted, items, "a shuffle, nothing lost");
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = plan(dir.path(), 4, "");
|
|
||||||
assert_eq!(turns(&run_plan(&path, &chatty()).1), turns(&run_plan(&path, &chatty()).1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_direct_message_in_one_of_the_plans_rooms_is_refused() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = plan(dir.path(), 2, "");
|
|
||||||
let dm = "[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\ndm = true\nto = \"@libby:gamecult.org\"\nsays = \"psst\"\n";
|
|
||||||
std::fs::write(&path, format!("{}{dm}", std::fs::read_to_string(&path).unwrap())).unwrap();
|
|
||||||
let model = silent();
|
|
||||||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
|
|
||||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("has its own room"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_mind_run_is_counted_across_her_rooms_and_an_uncounted_run_is_at_the_cap() {
|
|
||||||
let cast = vec![TOBIAH.to_owned(), LIBBY.to_owned(), "@kiko:x".to_owned(), "@other:x".to_owned()];
|
|
||||||
let line = |from: &'static str, room: &'static str| FactLine { sender: from, room, at_ms: 0 };
|
|
||||||
let run = |lines: &[FactLine]| line_facts(lines, "@kiko:x", &cast, &[], 0).iter().map(|facts| facts.mind_run).collect::<Vec<_>>();
|
|
||||||
assert_eq!(run(&[line("@meta:x", "#a:x"), line(TOBIAH, "#a:x"), line("@other:x", "#b:x"), line(TOBIAH, "#b:x")]), vec![0, 0, 1, 2]);
|
|
||||||
// Soul's case: Meta chatting in #eureka does not end a loop in #minds; a word from Meta in #minds does.
|
|
||||||
assert_eq!(run(&[line(TOBIAH, "#minds:x"), line(LIBBY, "#minds:x"), line("@meta:x", "#eureka:x"), line(TOBIAH, "#minds:x"), line("@meta:x", "#minds:x"), line(LIBBY, "#minds:x")]), vec![0, 1, 2, 2, 3, 0]);
|
|
||||||
assert_eq!(LineFacts::default().mind_run, usize::MAX, "fail-safe: an uncounted run is at the cap");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn her_own_rooms_are_the_rooms_named_for_her_repos() {
|
|
||||||
let aliases = ["#huginn:gamecult.org", "#general:gamecult.org", "#Cultlib:gamecult.org", "!abc:gamecult.org"];
|
|
||||||
assert_eq!(own_rooms(["GameCult/Huginn", "GameCult/CultLib"], aliases), vec!["#huginn:gamecult.org".to_owned(), "#Cultlib:gamecult.org".to_owned()]);
|
|
||||||
assert!(own_rooms([], aliases).is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_cast_past_eight_or_a_foreign_state_is_refused() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let model = chatty();
|
|
||||||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
|
|
||||||
let path = plan(dir.path(), 2, "");
|
|
||||||
let text = std::fs::read_to_string(&path).unwrap().replace("state = \"libby.json\"", "state = \"tobiah.json\"");
|
|
||||||
std::fs::write(&path, text).unwrap();
|
|
||||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("refused by a put"), "Libby cannot hold Eureka's state");
|
|
||||||
let many: String = (0..9).map(|at| format!("[[cast]]\nid = \"@m{at}:x\"\nname = \"M{at}\"\nstate = \"m.json\"\n")).collect();
|
|
||||||
std::fs::write(&path, format!("rounds = 1\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#a:x\"]\n{many}")).unwrap();
|
|
||||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("1 to 8"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_scripted_direct_message_reaches_and_wakes_only_its_recipient() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = plan(dir.path(), 2, "");
|
|
||||||
let dm = "[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"!dm-libby:gamecult.org\"\ndm = true\nto = \"@libby:gamecult.org\"\nsays = \"just you, how are you?\"\n";
|
|
||||||
let text = std::fs::read_to_string(&path).unwrap().replace("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"good afternoon, everyone\"\n", dm);
|
|
||||||
std::fs::write(&path, &text).unwrap();
|
|
||||||
let (_, run) = run_plan(&path, &silent());
|
|
||||||
assert_eq!(turns(&run), vec![(1, "Libby".to_owned(), "addressed_by_human".to_owned())], "only the recipient sees it, and it is for her");
|
|
||||||
std::fs::write(&path, text.replace("to = \"@libby:gamecult.org\"\n", "")).unwrap();
|
|
||||||
let model = silent();
|
|
||||||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
|
|
||||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("name its recipient"), "a direct message without a recipient is refused");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_turn_is_in_the_room_of_the_line_that_woke_her() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
cast(dir.path());
|
|
||||||
let path = dir.path().join("plan.toml");
|
|
||||||
let line = |round: usize, from: &str, room: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"{from}\"\nname = \"X\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
|
|
||||||
// Meta speaks in Tobiah's own room, then Libby says something in #minds after it: Tobiah's turn is in his room.
|
|
||||||
std::fs::write(
|
|
||||||
&path,
|
|
||||||
format!(
|
|
||||||
"rounds = 1\nseed = 11\nbeat_s = 0\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#minds:gamecult.org\", \"#tobiah:gamecult.org\"]\noperators = [\"@meta:gamecult.org\"]\n[[cast]]\nid = \"{TOBIAH}\"\nname = \"Tobiah\"\nstate = \"tobiah.json\"\nown_rooms = [\"#tobiah:gamecult.org\"]\n[[cast]]\nid = \"{LIBBY}\"\nname = \"Libby\"\nstate = \"libby.json\"\n{}{}",
|
|
||||||
line(0, "@meta:gamecult.org", "#tobiah:gamecult.org", "quiet in here"),
|
|
||||||
line(0, LIBBY, "#minds:gamecult.org", "hello all")
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let (_, run) = run_plan(&path, &silent());
|
|
||||||
assert_eq!(run["turns"][0]["room"], "#tobiah:gamecult.org", "{}", run["turns"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each persona's turns, as (round, room), in order.
|
|
||||||
fn turns_by_persona(run: &Value) -> BTreeMap<String, Vec<(u64, String)>> {
|
|
||||||
let mut out: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();
|
|
||||||
for turn in run["turns"].as_array().unwrap() {
|
|
||||||
out.entry(turn["persona"].as_str().unwrap().to_owned()).or_default().push((turn["round"].as_u64().unwrap(), turn["room"].as_str().unwrap().to_owned()));
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn soul_f5_one_turn_a_round_and_a_room_that_woke_her_waits_for_the_next() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = plan(dir.path(), 2, "");
|
|
||||||
let line = |room: &str, dm: bool, says: &str| format!("[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\n{}says = \"{says}\"\n", if dm { "dm = true\nto = \"@libby:gamecult.org\"\n" } else { "" });
|
|
||||||
let opening = "[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"good afternoon, everyone\"\n";
|
|
||||||
let text = std::fs::read_to_string(&path).unwrap().replace(opening, &format!("{}{}", line("!dm-libby:gamecult.org", true, "just you: how are you, really?"), line("#minds:gamecult.org", false, "Libby, how was the gig?")));
|
|
||||||
std::fs::write(&path, text).unwrap();
|
|
||||||
let (_, run) = run_plan(&path, &silent());
|
|
||||||
// Her earliest waking line is the direct message: round 1 is there; #minds, still unseen, wakes her in round 2.
|
|
||||||
assert_eq!(turns_by_persona(&run)["Libby"], vec![(1, "!dm-libby:gamecult.org".to_owned()), (2, "#minds:gamecult.org".to_owned())], "{}", run["turns"]);
|
|
||||||
// Each turn read its own room's line, and no other's.
|
|
||||||
for turn in run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Libby") {
|
|
||||||
let report = turn["report"].to_string();
|
|
||||||
let (own, other) = if turn["room"] == "#minds:gamecult.org" { ("how was the gig", "how are you, really") } else { ("how are you, really", "how was the gig") };
|
|
||||||
assert!(report.contains(own) && !report.contains(other), "{}: {report}", turn["room"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn soul_f5_three_rooms_open_at_once_take_three_rounds_not_one() {
|
|
||||||
{
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = plan(dir.path(), 6, "");
|
|
||||||
let more = |room: &str, says: &str| format!("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
|
|
||||||
let text = std::fs::read_to_string(&path)
|
|
||||||
.unwrap()
|
|
||||||
.replace("own_rooms = [\"#minds:gamecult.org\"]", "own_rooms = [\"#minds:gamecult.org\", \"#lab:gamecult.org\", \"#ops:gamecult.org\"]")
|
|
||||||
.replace("rooms = [\"#minds:gamecult.org\"]\noperators", "rooms = [\"#minds:gamecult.org\", \"#lab:gamecult.org\", \"#ops:gamecult.org\"]\noperators")
|
|
||||||
.replace("says = \"good afternoon, everyone\"\n", &format!("says = \"good afternoon, everyone\"\n{}{}", more("#lab:gamecult.org", "lab is open"), more("#ops:gamecult.org", "ops is open")));
|
|
||||||
std::fs::write(&path, text).unwrap();
|
|
||||||
let (_, run) = run_plan(&path, &namers());
|
|
||||||
for (who, turns) in turns_by_persona(&run) {
|
|
||||||
let rounds: Vec<u64> = turns.iter().map(|(round, _)| *round).collect();
|
|
||||||
assert!(rounds.windows(2).all(|pair| pair[0] < pair[1]), "{who} took two turns in one round: {turns:?}");
|
|
||||||
let rooms: Vec<&str> = turns.iter().take(3).map(|(_, room)| room.as_str()).collect();
|
|
||||||
assert_eq!(rooms, ["#minds:gamecult.org", "#lab:gamecult.org", "#ops:gamecult.org"], "{who} answers each room in the order it opened");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn soul_k9_a_failed_turn_is_told_as_a_failure_next_turn() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let (_, run) = run_plan(&plan(dir.path(), 3, "beat_s = 120"), &FailingPersona);
|
|
||||||
let later: Vec<&Value> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["round"].as_u64() > Some(1)).collect();
|
|
||||||
assert!(!later.is_empty(), "{}", run["turns"]);
|
|
||||||
for turn in later {
|
|
||||||
assert_eq!(turn["report"]["last_outcome"]["told"], json!(["- Nothing he meant last time happened: the wake broke off, not by his choice."]), "{turn}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Soul's R5: the report shows the packet's flags.
|
|
||||||
#[test]
|
|
||||||
fn r5_the_report_shows_the_packets_flags() {
|
|
||||||
let turn = json!({ "report": { "packet": { "domain_shown": { "since": "2026-11-20T09:01:00+00:00", "left_out": 3, "omitted": null }, "bound": ["outcome"], "clipped": ["(identity)"] } } });
|
|
||||||
let mut out = String::new();
|
|
||||||
flags_markdown(&mut out, &turn);
|
|
||||||
assert_eq!(out, "Packet flags: domain view: since 2026-11-20T09:01:00+00:00, 3 older items left out; guards bound: outcome; clipped: (identity)\n\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// K32 (map 16.25.8, Low 10): in the simulator, a campaign read is served from her `[cast.domain]`, the one owner of what
|
|
||||||
/// her campaign holds, formatted as a live read formats rulings: Plan F's Heimdall reads `heimdall-body` and gets its
|
|
||||||
/// ruling line, with the ruling's words when the fixture holds them, and nothing older than the window.
|
|
||||||
#[test]
|
|
||||||
fn k32_campaign_read_from_domain() {
|
|
||||||
let domain: DomainFacts = toml::from_str(
|
|
||||||
r#"
|
|
||||||
[[campaigns]]
|
|
||||||
slug = "heimdall-body"
|
|
||||||
[[campaigns.rulings]]
|
|
||||||
at = "2026-11-20T09:00:00Z"
|
|
||||||
title = "Account merge ships dark by default: notices and the merge pages stay off until the operator turns them on"
|
|
||||||
who = "operator_with_her"
|
|
||||||
[[campaigns.rulings]]
|
|
||||||
at = "2026-11-01T09:00:00Z"
|
|
||||||
title = "An old ruling, before the window"
|
|
||||||
who = "her"
|
|
||||||
"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let recorded = ReadFixture::default();
|
|
||||||
let since = DateTime::parse_from_rfc3339("2026-11-19T15:00:00Z").unwrap().with_timezone(&Utc);
|
|
||||||
let reads = CastReads { recorded: &recorded, domain: Some(&domain) };
|
|
||||||
let read = |slug: &str| reads.read(&ReadRequest::Campaign(slug.into()), since);
|
|
||||||
assert_eq!(read("heimdall-body"), Ok("- Account merge ships dark by default: notices and the merge pages stay off until the operator turns them on (title only: the ruling was not read)".to_owned()));
|
|
||||||
assert_eq!(read("nowhere"), Err(ReadFailure::NotFound));
|
|
||||||
let mut worded = domain.clone();
|
|
||||||
worded.campaigns[0].rulings[0].ruling = Some("dark until the operator sets AccountMerge__Enabled".into());
|
|
||||||
let reads = CastReads { recorded: &recorded, domain: Some(&worded) };
|
|
||||||
assert_eq!(reads.read(&ReadRequest::Campaign("Heimdall-Body".into()), since), Ok("- Account merge ships dark by default: notices and the merge pages stay off until the operator turns them on: dark until the operator sets AccountMerge__Enabled".to_owned()));
|
|
||||||
// Every other read is her recorded one.
|
|
||||||
assert_eq!(reads.read(&ReadRequest::Repo("GameCult/Bifrost".into()), since), Err(ReadFailure::NotFound));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn k32_campaign_cast_read_refused() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = plan(dir.path(), 2, "");
|
|
||||||
let text = std::fs::read_to_string(&path).unwrap().replace("state = \"libby.json\"\n", "state = \"libby.json\"\n[[cast.read]]\nkind = \"campaign\"\ntarget = \"libby-body\"\ntext = \"- a ruling\"\n");
|
|
||||||
std::fs::write(&path, text).unwrap();
|
|
||||||
let model = silent();
|
|
||||||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
|
|
||||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("records a campaign read"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A newcomer's untagged hello in a public room, said at `round`, appended to a plan.
|
|
||||||
fn hello(path: &Path, round: usize) {
|
|
||||||
let mut text = std::fs::read_to_string(path).unwrap();
|
|
||||||
text.push_str(&format!("[[message]]\nfrom = \"@newcomer:gamecult.org\"\nname = \"Newcomer\"\nroom = \"#minds:gamecult.org\"\nround = {round}\nsays = \"hello everyone!\"\n"));
|
|
||||||
std::fs::write(path, text).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The simulator's packet reads what live reads: every line the wake was for is said to her, the floor's and the one that woke
|
|
||||||
/// her through her exchange alike (`heartbeat::claimed`, the one derivation, which live records as her handled keys).
|
|
||||||
#[test]
|
|
||||||
fn a_line_that_woke_her_is_said_to_her_in_the_packet_as_live_reads_it() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = bare_plan(dir.path(), 3, "");
|
|
||||||
hello(&path, 0);
|
|
||||||
hello(&path, 2);
|
|
||||||
let (_, run) = run_plan(&path, &chatty());
|
|
||||||
let round_two = run["turns"].as_array().unwrap().iter().find(|turn| turn["round"] == 2).expect("the second hello woke her");
|
|
||||||
let stimulus = round_two["report"]["packet"]["stimulus"].as_str().unwrap();
|
|
||||||
let said = stimulus.split("Said to ").nth(1).unwrap_or_default().split("Also in the room").next().unwrap_or_default();
|
|
||||||
assert!(said.contains("hello everyone!"), "her exchange woke her; the line is said to her: {stimulus}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A model whose Interpreter always answers with one intention.
|
|
||||||
struct Intends;
|
|
||||||
|
|
||||||
impl Model for Intends {
|
|
||||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
|
||||||
let text = if prompt.starts_with(PROJECTOR_OPENING) {
|
|
||||||
"The room is slow."
|
|
||||||
} else if prompt.starts_with("You are a private Interpreter.") {
|
|
||||||
r#"{"intend":{"add":[{"summary":"She means to say what the build did.","expires_in_hours":24,"readiness":"later"}]}}"#
|
|
||||||
} else {
|
|
||||||
"She watches the room."
|
|
||||||
};
|
|
||||||
Ok(Answer { text: text.into(), usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 3, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// h6: the simulator takes the drain's Interpreter step after each wake that did not fail, moves her in-run state by its deltas,
|
|
||||||
/// and the report counts and quotes what it did.
|
|
||||||
#[test]
|
|
||||||
fn the_interpreter_runs_after_each_wake_and_the_report_says_what_it_did() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = plan(dir.path(), 3, "");
|
|
||||||
let (members, run) = run_plan(&path, &Intends);
|
|
||||||
let turns = run["turns"].as_array().unwrap();
|
|
||||||
assert!(!turns.is_empty() && turns.iter().all(|turn| turn["interpreter"]["status"] == "ok"), "every wake was interpreted: {turns:?}");
|
|
||||||
assert_eq!(turns[0]["did"]["intentions"][0]["change"], "added");
|
|
||||||
assert!(turns[0]["did"]["intentions"][0]["words"].as_str().unwrap().contains("what the build did"), "{}", turns[0]["did"]);
|
|
||||||
let personas = run["metrics"]["personas"].as_object().unwrap();
|
|
||||||
assert!(personas.values().all(|persona| persona["interpreter"]["calls"] == persona["turns"] && persona["interpreter"]["intentions_added"] == persona["turns"]), "{personas:?}");
|
|
||||||
let plan_file: SimFile = toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
|
|
||||||
let report = markdown(&path, &plan_file, &members, None, std::slice::from_ref(&run));
|
|
||||||
assert!(report.contains("### Interpreter by wake") && report.contains("intention added") && report.contains("She means to say what the build did."), "{report}");
|
|
||||||
assert!(!report.contains("the Interpreter's lines, each posted"), "the header no longer claims a speech it does not run");
|
|
||||||
assert!(!report.contains("no Mind is asked"), "nor a read-only run: the Interpreter is asked");
|
|
||||||
assert!(members.iter().all(|member| member.state["candidateActions"]["actions"].as_array().is_none_or(|actions| actions.iter().all(|action| action["customActionType"] != "intention"))), "a run moves its own copy, never the cast's");
|
|
||||||
}
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
//! Huginn's one locator of a quote (map 16.30.4, K47): "the Interpreter, a model that retypes text, quoted this passage
|
|
||||||
//! of the source". Every check in `commit.rs` and `interpret.rs` that a quote stands in a source goes through `locate`.
|
|
||||||
//!
|
|
||||||
//! It is Ghostlight's `SourceSpan::locate` (`ghostlight-persona-projection` at `c43eb54`): the first occurrence of the
|
|
||||||
//! quote whose start and end both land on a Unicode word boundary (UAX #29), each candidate a boundary the segmenter
|
|
||||||
//! reports, rejected first on its first byte. Huginn's contract adds one thing: models normalise typographic punctuation,
|
|
||||||
//! so both texts are compared under `fold`, which maps one char to one char. The fold is computed over chars, so a span
|
|
||||||
//! found in the folded source maps back exactly to the source's own bytes, and the span returned is the source's.
|
|
||||||
//!
|
|
||||||
//! What it gives up: multi-char typographic forms (`…` against `...`) are not folded, and fixes no longer flow between
|
|
||||||
//! this and Ghostlight's locator.
|
|
||||||
|
|
||||||
|
|
||||||
/// The one char typographic punctuation is compared as: curly and modifier apostrophes as `'`, curly double quotes as
|
|
||||||
/// `"`, en and em dashes as `-`, a no-break space as a space. The one fold table of `projection/` (map 16.31.4, K52):
|
|
||||||
/// every comparison of her words with anyone's reads typographic punctuation as the locator does.
|
|
||||||
pub(crate) fn fold(c: char) -> char {
|
|
||||||
match c {
|
|
||||||
'\u{2018}' | '\u{2019}' | '\u{02BC}' => '\'',
|
|
||||||
'\u{201C}' | '\u{201D}' => '"',
|
|
||||||
'\u{2013}' | '\u{2014}' => '-',
|
|
||||||
'\u{00A0}' => ' ',
|
|
||||||
other => other,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `text` with every char folded (`fold`): how two texts are compared as the same words, or one found in another, with
|
|
||||||
/// their case kept (K56).
|
|
||||||
pub(crate) fn fold_text(text: &str) -> String {
|
|
||||||
text.chars().map(fold).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The words of `text` as every comparison of her words with anyone's reads them (map 16.31.4, K52): folded,
|
|
||||||
/// lowercased, split at every char that is neither alphanumeric nor `'`, the empty pieces dropped, so a curly
|
|
||||||
/// apostrophe joins a word as a straight one does. The one word split for likeness: `narrate::words` counts length.
|
|
||||||
pub(crate) fn tokens(text: &str) -> impl Iterator<Item = String> {
|
|
||||||
let folded = fold_text(text).to_lowercase();
|
|
||||||
folded.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_owned).collect::<Vec<_>>().into_iter()
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +1,4 @@
|
||||||
//! `persona-tuning.toml`: every knob of the Select stage, the Projector, the Persona stage and the Interpreter, read at
|
//! `persona-tuning.toml`: every knob of the Select stage and the Projector, read at each wake.
|
||||||
//! each wake.
|
|
||||||
//!
|
//!
|
||||||
//! The file is optional. Absent, the code's defaults hold and the source reads `defaults`; present, every key it
|
//! The file is optional. Absent, the code's defaults hold and the source reads `defaults`; present, every key it
|
||||||
//! names overrides one default and any key the code does not know refuses the file, so a mistyped experiment fails
|
//! names overrides one default and any key the code does not know refuses the file, so a mistyped experiment fails
|
||||||
|
|
@ -8,11 +7,9 @@
|
||||||
//! The SHA-256 carried with every packet is of the effective tuning, serialized whole with its defaults: a file that
|
//! The SHA-256 carried with every packet is of the effective tuning, serialized whole with its defaults: a file that
|
||||||
//! spells out the defaults hashes as no file does, and two builds whose defaults differ hash differently.
|
//! spells out the defaults hashes as no file does, and two builds whose defaults differ hash differently.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use anyhow::{Context, Result, bail};
|
use anyhow::{Context, Result, bail};
|
||||||
use model_connector::CacheRetention;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
|
@ -20,24 +17,11 @@ use sha2::{Digest, Sha256};
|
||||||
pub const TUNING_ROOT: &str = "/etc/gamecult/minds";
|
pub const TUNING_ROOT: &str = "/etc/gamecult/minds";
|
||||||
pub const TUNING_FILE: &str = "persona-tuning.toml";
|
pub const TUNING_FILE: &str = "persona-tuning.toml";
|
||||||
|
|
||||||
/// The Persona stage's setting (map section 2): she continues the Projector's paragraph, her interior. It is not a reply
|
|
||||||
/// to the room. How she sets down words she would type is code's form, not this (`narrate::persona_speech_form`, map
|
|
||||||
/// 16.19.1). Every default guidance names her by `Forms` placeholders (`select::voiced`, map 16.19.7).
|
|
||||||
const PERSONA_GUIDANCE: &str = "Continue {poss} inner stream where the paragraph leaves off: {poss} own next thoughts, in the first person, in {poss} own words. This is not a message to the room. In a busy room most moments pass with nothing said.";
|
|
||||||
|
|
||||||
/// The setting the Projector renders for. No task: in the Persona-only shape nothing is work she owes.
|
/// The setting the Projector renders for. No task: in the Persona-only shape nothing is work she owes.
|
||||||
const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. {cap_subj} live{s} in its chat rooms among the operator, the other Minds and whoever drops by. Render the moment as {subj} live{s} it: who is here and how they sit with {obj}, what {subj} hold{s}, what {subj} want{s}. Render the conversation as it stands. Leave out whatever the context does not carry: an absence is not part of {poss} moment. Use each person's pronouns as given.";
|
const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. She lives in its chat rooms among the operator, the other Minds and whoever drops by, and no task is waiting on her in this moment. Render the moment as she lives it: who is here and how they sit with her, what she carries, what she wants.";
|
||||||
|
|
||||||
|
/// The context room the fixed slots need beside the identity: the hour and the mood lines always fit.
|
||||||
/// The least `here_bytes` may be: the heading, the hour and the longest mood line always fit.
|
const FIXED_ROOM: usize = 256;
|
||||||
pub(crate) const HERE_ROOM_MIN: usize = 256;
|
|
||||||
/// The least `outcome_bytes` may be: the heading and the longest line without her words (a failed turn's) always fit.
|
|
||||||
pub(crate) const OUTCOME_ROOM_MIN: usize = 256;
|
|
||||||
/// The least `domain_bytes` may be: the heading and the line counting the lines of her domain not shown always fit (I16.11).
|
|
||||||
pub(crate) const DOMAIN_ROOM_MIN: usize = 128;
|
|
||||||
/// The least `body_bytes` may be: the body heading, the longest turn line (`select::turn_words`) and one entry at the
|
|
||||||
/// standard's upper target always fit.
|
|
||||||
pub(crate) const BODY_ROOM_MIN: usize = 768;
|
|
||||||
/// The temperatures a selection may run at: colder is deterministic in all but name, hotter is noise.
|
/// The temperatures a selection may run at: colder is deterministic in all but name, hotter is noise.
|
||||||
const TEMPERATURE_RANGE: std::ops::RangeInclusive<f64> = 0.01..=10.0;
|
const TEMPERATURE_RANGE: std::ops::RangeInclusive<f64> = 0.01..=10.0;
|
||||||
/// The ceiling of the messages to her: at least a long message whole, and far under the connector's 256 KiB frame, which
|
/// The ceiling of the messages to her: at least a long message whole, and far under the connector's 256 KiB frame, which
|
||||||
|
|
@ -48,50 +32,13 @@ const ADDRESSED_RANGE: std::ops::RangeInclusive<usize> = 1024..=64 * 1024;
|
||||||
const PART_BYTES_MAX: usize = 32 * 1024;
|
const PART_BYTES_MAX: usize = 32 * 1024;
|
||||||
/// The most words a lived stream may be given: a thin moment gets a thin stream, and no budget needs a book.
|
/// The most words a lived stream may be given: a thin moment gets a thin stream, and no budget needs a book.
|
||||||
const WORDS_MAX: usize = 2000;
|
const WORDS_MAX: usize = 2000;
|
||||||
/// The most room lines the group state reads: a recent window, not the room's history.
|
|
||||||
const GROUP_LINES_MAX: usize = 40;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
#[serde(default, deny_unknown_fields)]
|
#[serde(default, deny_unknown_fields)]
|
||||||
pub struct Tuning {
|
pub struct Tuning {
|
||||||
pub projector: ProjectorTuning,
|
pub projector: ProjectorTuning,
|
||||||
pub persona: PersonaTuning,
|
|
||||||
pub interpreter: InterpreterTuning,
|
|
||||||
pub agent: AgentTuning,
|
|
||||||
pub select: SelectTuning,
|
pub select: SelectTuning,
|
||||||
pub lens: LensWeights,
|
pub lens: LensWeights,
|
||||||
/// Each person's pronouns by Matrix id, for everyone the packet names: the persona schema has no pronoun field for
|
|
||||||
/// another person. A file's table replaces this one whole; anyone not listed is they/them.
|
|
||||||
pub pronouns: BTreeMap<String, String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The swarm's people as of 2026-11-20 (operator's word): she for the operator and five Minds, he for Heimdall and Deru,
|
|
||||||
/// any for Void, rendered they/them.
|
|
||||||
const PRONOUNS: [(&str, &str); 10] = [
|
|
||||||
("@meta:gamecult.org", "she/her"),
|
|
||||||
("@libby:gamecult.org", "she/her"),
|
|
||||||
("@kiko:gamecult.org", "she/her"),
|
|
||||||
("@aqua:gamecult.org", "she/her"),
|
|
||||||
("@weksa:gamecult.org", "she/her"),
|
|
||||||
("@nibu:gamecult.org", "she/her"),
|
|
||||||
("@eureka:gamecult.org", "she/her"),
|
|
||||||
("@heimdall:gamecult.org", "he/him"),
|
|
||||||
("@void:gamecult.org", "they/them (any pronouns)"),
|
|
||||||
("@deru:gamecult.org", "he/him"),
|
|
||||||
];
|
|
||||||
|
|
||||||
impl Default for Tuning {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
projector: ProjectorTuning::default(),
|
|
||||||
persona: PersonaTuning::default(),
|
|
||||||
interpreter: InterpreterTuning::default(),
|
|
||||||
agent: AgentTuning::default(),
|
|
||||||
select: SelectTuning::default(),
|
|
||||||
lens: LensWeights::default(),
|
|
||||||
pronouns: PRONOUNS.iter().map(|(id, pronouns)| ((*id).to_owned(), (*pronouns).to_owned())).collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Projector's call: its model, its domain guidance and its word budgets.
|
/// The Projector's call: its model, its domain guidance and its word budgets.
|
||||||
|
|
@ -106,174 +53,7 @@ pub struct ProjectorTuning {
|
||||||
pub beat_words: usize,
|
pub beat_words: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Persona stage's call: its model, its voice and setting guidance and its word budget (map section 3.2).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
#[serde(default, deny_unknown_fields)]
|
|
||||||
pub struct PersonaTuning {
|
|
||||||
pub model: String,
|
|
||||||
pub guidance: String,
|
|
||||||
pub words: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her agent's turn (map 16.38.6, 16.38.10): the model, the bounds that are enforced in code (`agent::step`), the price table
|
|
||||||
/// they are priced by, and when her session's cache is taken to be cold. Prices are USD per million tokens.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
#[serde(default, deny_unknown_fields)]
|
|
||||||
pub struct AgentTuning {
|
|
||||||
pub model: String,
|
|
||||||
/// The most tool calls a wake runs, and the most model calls it makes.
|
|
||||||
pub tool_calls: usize,
|
|
||||||
pub model_calls: usize,
|
|
||||||
/// The most a wake may spend across all its turns, and the most a Mind may spend in a UTC day, summed from her trace.
|
|
||||||
pub wake_usd: f64,
|
|
||||||
pub day_usd: f64,
|
|
||||||
/// What a call is charged whose usage is not known (cut off by a brake, or a failure that reported none): the worst case the day's sum stands at, never nothing.
|
|
||||||
pub unmetered_usd: f64,
|
|
||||||
/// How long an open wake waits, in seconds, for a line that wakes her after her last turn ended, before it closes (`persona::live::wake_end`).
|
|
||||||
pub idle_s: u64,
|
|
||||||
/// The longest a wake stays open, in seconds, from its start. The unit's `RuntimeMaxSec` is the backstop, and the close needs room inside it.
|
|
||||||
pub span_s: u64,
|
|
||||||
/// The prompt size past which her session is discarded and re-seeded.
|
|
||||||
pub max_session_tokens: u64,
|
|
||||||
/// The cache the session's prefix asks for.
|
|
||||||
pub retention: CacheRetention,
|
|
||||||
/// How long each retention keeps a cache, in seconds, from the provider's table.
|
|
||||||
pub ttl_s: CacheTtl,
|
|
||||||
/// The provider's least cacheable prefix, in tokens: below it a read of 0 says nothing.
|
|
||||||
pub cache_min_tokens: u64,
|
|
||||||
pub prices: BTreeMap<String, Price>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(default, deny_unknown_fields)]
|
|
||||||
pub struct CacheTtl {
|
|
||||||
pub short: u64,
|
|
||||||
pub long: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub struct Price {
|
|
||||||
pub input: f64,
|
|
||||||
pub output: f64,
|
|
||||||
pub cache_read: f64,
|
|
||||||
/// A write to the 5-minute cache, and to the 1-hour cache.
|
|
||||||
pub cache_write_short: f64,
|
|
||||||
pub cache_write_long: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Price {
|
|
||||||
/// What a million tokens written to the cache of `retention` cost.
|
|
||||||
pub(crate) fn cache_write(self, retention: CacheRetention) -> f64 {
|
|
||||||
match retention {
|
|
||||||
CacheRetention::Short => self.cache_write_short,
|
|
||||||
CacheRetention::Long => self.cache_write_long,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for CacheTtl {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { short: 300, long: 3600 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for AgentTuning {
|
|
||||||
fn default() -> Self {
|
|
||||||
// Claude Sonnet 5.5 at the pricing page (platform.claude.com, 2026-11-29): $2 in, $10 out, $0.10 a cache hit, $2.50 a 5-minute write, $4 a 1-hour write.
|
|
||||||
let sonnet = Price { input: 2.0, output: 10.0, cache_read: 0.10, cache_write_short: 2.50, cache_write_long: 4.0 };
|
|
||||||
Self {
|
|
||||||
model: "claude-sonnet-5-5".into(),
|
|
||||||
tool_calls: 8,
|
|
||||||
model_calls: 10,
|
|
||||||
wake_usd: 1.00,
|
|
||||||
day_usd: 3.00,
|
|
||||||
unmetered_usd: 0.40,
|
|
||||||
idle_s: 300,
|
|
||||||
span_s: 1800,
|
|
||||||
max_session_tokens: 80_000,
|
|
||||||
retention: CacheRetention::Long,
|
|
||||||
ttl_s: CacheTtl::default(),
|
|
||||||
cache_min_tokens: 2048,
|
|
||||||
prices: BTreeMap::from([("claude-sonnet-5-5".to_owned(), sonnet)]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AgentTuning {
|
|
||||||
/// The price of `model`'s tokens, USD per call: the table's entry, or the dearest entry when the model is not listed.
|
|
||||||
pub(crate) fn price(&self, model: &str) -> Price {
|
|
||||||
self.prices.get(model).copied().unwrap_or_else(|| {
|
|
||||||
self.prices.values().copied().fold(Price { input: 0.0, output: 0.0, cache_read: 0.0, cache_write_short: 0.0, cache_write_long: 0.0 }, |a, b| Price { input: a.input.max(b.input), output: a.output.max(b.output), cache_read: a.cache_read.max(b.cache_read), cache_write_short: a.cache_write_short.max(b.cache_write_short), cache_write_long: a.cache_write_long.max(b.cache_write_long) })
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How long a cache of `retention` lives, in seconds.
|
|
||||||
pub(crate) fn ttl(&self, retention: CacheRetention) -> u64 {
|
|
||||||
match retention {
|
|
||||||
CacheRetention::Short => self.ttl_s.short,
|
|
||||||
CacheRetention::Long => self.ttl_s.long,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate(&self) -> Result<()> {
|
|
||||||
if self.model.trim().is_empty() {
|
|
||||||
bail!("agent.model must name a model");
|
|
||||||
}
|
|
||||||
if !self.prices.contains_key(&self.model) {
|
|
||||||
bail!("agent.prices has no entry for agent.model {}: a cap cannot be priced without one", self.model);
|
|
||||||
}
|
|
||||||
for (model, price) in &self.prices {
|
|
||||||
if ![price.input, price.output, price.cache_read, price.cache_write_short, price.cache_write_long].iter().all(|usd| usd.is_finite() && *usd >= 0.0) {
|
|
||||||
bail!("agent.prices.{model} must be finite and not negative");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !(1..=AGENT_CALLS_MAX).contains(&self.tool_calls) || !(1..=AGENT_CALLS_MAX).contains(&self.model_calls) {
|
|
||||||
bail!("agent.tool_calls and agent.model_calls must be from 1 to {AGENT_CALLS_MAX}");
|
|
||||||
}
|
|
||||||
let usd = |name: &str, value: f64, most: f64| if value.is_finite() && value > 0.0 && value <= most { Ok(()) } else { Err(anyhow::anyhow!("{name} must be above 0 and at most {most}, not {value}")) };
|
|
||||||
usd("agent.wake_usd", self.wake_usd, AGENT_WAKE_USD_MAX)?;
|
|
||||||
usd("agent.day_usd", self.day_usd, AGENT_DAY_USD_MAX)?;
|
|
||||||
usd("agent.unmetered_usd", self.unmetered_usd, AGENT_WAKE_USD_MAX)?;
|
|
||||||
if self.wake_usd > self.day_usd {
|
|
||||||
bail!("agent.wake_usd must be at most agent.day_usd");
|
|
||||||
}
|
|
||||||
if self.idle_s < IDLE_MIN_S || self.idle_s > self.span_s {
|
|
||||||
bail!("agent.idle_s must be from {IDLE_MIN_S} to agent.span_s, not {}", self.idle_s);
|
|
||||||
}
|
|
||||||
if self.span_s.saturating_add(CLOSE_ROOM_S) > UNIT_RUNTIME_MAX_S {
|
|
||||||
bail!("agent.span_s must be at most {} seconds: the unit's RuntimeMaxSec is {UNIT_RUNTIME_MAX_S} and the close needs {CLOSE_ROOM_S} of them, not {}", UNIT_RUNTIME_MAX_S - CLOSE_ROOM_S, self.span_s);
|
|
||||||
}
|
|
||||||
if self.max_session_tokens == 0 || self.cache_min_tokens == 0 {
|
|
||||||
bail!("agent.max_session_tokens and agent.cache_min_tokens must be above 0");
|
|
||||||
}
|
|
||||||
if self.ttl_s.short <= CACHE_MARGIN_S || self.ttl_s.long <= CACHE_MARGIN_S {
|
|
||||||
bail!("agent.ttl_s must be above {CACHE_MARGIN_S} seconds: a session is discarded that long before its cache ends");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The unit's `RuntimeMaxSec` (`mind-persona@.service`), in seconds: the longest a start lives, whatever the tuning says.
|
|
||||||
const UNIT_RUNTIME_MAX_S: u64 = 3600;
|
|
||||||
/// What a wake's close needs inside `RuntimeMaxSec` after the span: a last turn, the Interpreter's two calls and the records.
|
|
||||||
const CLOSE_ROOM_S: u64 = 300;
|
|
||||||
/// The least idle window: a line a poll away (`persona::live::POLL_S`) and a stagger behind it must still be waited for.
|
|
||||||
const IDLE_MIN_S: u64 = 30;
|
|
||||||
/// A session is discarded this long before its cache is due to end: a call that starts inside it may not finish inside the cache.
|
|
||||||
pub(crate) const CACHE_MARGIN_S: u64 = 60;
|
|
||||||
/// The most calls of either kind a wake may be tuned to, and the most it and a day may be tuned to spend: a mistyped bound fails
|
|
||||||
/// the file, never the budget.
|
|
||||||
const AGENT_CALLS_MAX: usize = 32;
|
|
||||||
const AGENT_WAKE_USD_MAX: f64 = 5.0;
|
|
||||||
const AGENT_DAY_USD_MAX: f64 = 50.0;
|
|
||||||
|
|
||||||
/// The selection: its temperature and inclusion, its budgets, its half-life, the freshness decay and the pool caps.
|
/// 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 each section 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. Each section has its own guard and none is another's (map 16.19.4): the people's is derived,
|
|
||||||
/// `people_full` bond lines of `bond_summary_bytes` and their heads; no one number caps the whole prompt.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
#[serde(default, deny_unknown_fields)]
|
#[serde(default, deny_unknown_fields)]
|
||||||
pub struct SelectTuning {
|
pub struct SelectTuning {
|
||||||
|
|
@ -281,22 +61,10 @@ pub struct SelectTuning {
|
||||||
pub temperature: f64,
|
pub temperature: f64,
|
||||||
/// The score at which a candidate is included 63% of the time: inclusion is `1 - exp(-score / inclusion_score)`.
|
/// The score at which a candidate is included 63% of the time: inclusion is `1 - exp(-score / inclusion_score)`.
|
||||||
pub inclusion_score: f64,
|
pub inclusion_score: f64,
|
||||||
/// Her state's notes about her, in bytes, heading included. The fill stops at the first candidate that would pass it.
|
/// Identity plus typed context, in bytes.
|
||||||
pub notes_bytes: usize,
|
pub context_bytes: usize,
|
||||||
/// Here and now, in bytes, heading included: the hour and the mood always; then, while they fit, the pronouns, the
|
|
||||||
/// conversation (`group_bytes`) and the names of the people present without a bond line.
|
|
||||||
pub here_bytes: usize,
|
|
||||||
/// What came of her last turn, in bytes, heading included: taken first, under its own guard (map 16.16).
|
|
||||||
pub outcome_bytes: usize,
|
|
||||||
/// Her domain in her view, in bytes, headings included (map 16.23.3): her main window on her domain, so generous, Soul's
|
|
||||||
/// 3000 B log and a margin. A busier window does not crowd her view: it shrinks from its old end to what fits.
|
|
||||||
pub domain_bytes: usize,
|
|
||||||
/// What she has said and read in this conversation, in her view, in bytes, heading included (map 16.24.1): past it the
|
|
||||||
/// window shrinks from its old end.
|
|
||||||
pub exchange_bytes: usize,
|
|
||||||
pub stimulus_bytes: usize,
|
pub stimulus_bytes: usize,
|
||||||
/// What was said to her, verbatim, for the Persona stage: on a chat turn, the room's earlier lines too, before the new
|
/// What was said to her, verbatim, for the Persona stage.
|
||||||
/// ones (map 16.20.3).
|
|
||||||
pub heard_bytes: usize,
|
pub heard_bytes: usize,
|
||||||
/// The ceiling of the messages to her, in the stimulus and in the heard lines alike: they pass the stimulus and heard
|
/// The ceiling of the messages to her, in the stimulus and in the heard lines alike: they pass the stimulus and heard
|
||||||
/// caps whole, newest first, up to this, and the older ones are counted.
|
/// caps whole, newest first, up to this, and the older ones are counted.
|
||||||
|
|
@ -306,8 +74,8 @@ pub struct SelectTuning {
|
||||||
pub bond_summary_bytes: usize,
|
pub bond_summary_bytes: usize,
|
||||||
/// One selected item's text, in bytes.
|
/// One selected item's text, in bytes.
|
||||||
pub item_bytes: usize,
|
pub item_bytes: usize,
|
||||||
/// Her body section (map 16.6): its heading, her senses and actuators and the turn line, which always fits.
|
/// The recency time constant of her memories and short-term items, in hours.
|
||||||
pub body_bytes: usize,
|
pub memory_tau_h: f64,
|
||||||
/// freshness = base ^ (times shown in the last `freshness_window` projections); 0 never repeats an item in the window.
|
/// freshness = base ^ (times shown in the last `freshness_window` projections); 0 never repeats an item in the window.
|
||||||
pub freshness_base: f64,
|
pub freshness_base: f64,
|
||||||
pub freshness_window: usize,
|
pub freshness_window: usize,
|
||||||
|
|
@ -315,15 +83,6 @@ pub struct SelectTuning {
|
||||||
pub people_full: usize,
|
pub people_full: usize,
|
||||||
/// The room lines a beat shows.
|
/// The room lines a beat shows.
|
||||||
pub beat_tail_lines: usize,
|
pub beat_tail_lines: usize,
|
||||||
/// The group state: who has been talking to whom (the Projector's room line), and the speech cues, who is waiting
|
|
||||||
/// on her, a covered question, how long since a human spoke and how long the run of Mind lines is, for the stages
|
|
||||||
/// that decide speech (prior art: group state in the prompt is what lets a participant judge whether to speak; map
|
|
||||||
/// 16.20.2).
|
|
||||||
pub group_state: bool,
|
|
||||||
/// The room lines the group state reads.
|
|
||||||
pub group_lines: usize,
|
|
||||||
/// The bytes of each part of the group state: the room line and the speech cues.
|
|
||||||
pub group_bytes: usize,
|
|
||||||
pub caps: PoolCaps,
|
pub caps: PoolCaps,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -337,6 +96,7 @@ pub struct PoolCaps {
|
||||||
pub incubation: usize,
|
pub incubation: usize,
|
||||||
pub stance: usize,
|
pub stance: usize,
|
||||||
pub value: usize,
|
pub value: usize,
|
||||||
|
pub said: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The weighted draw of the lens a turn begins from.
|
/// The weighted draw of the lens a turn begins from.
|
||||||
|
|
@ -356,50 +116,23 @@ impl Default for ProjectorTuning {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Interpreter: the model of its one schema call over her monologue (map 16.38.7). Its bounds are code's (`commit`): the
|
|
||||||
/// model gives a direction and code decides how far, so none of them is a knob here.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
#[serde(default, deny_unknown_fields)]
|
|
||||||
pub struct InterpreterTuning {
|
|
||||||
pub model: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for InterpreterTuning {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { model: "claude-haiku-5-5".into() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for PersonaTuning {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { model: "claude-sonnet-5-5".into(), guidance: PERSONA_GUIDANCE.into(), words: 180 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for SelectTuning {
|
impl Default for SelectTuning {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
temperature: 0.7,
|
temperature: 0.7,
|
||||||
inclusion_score: 0.5,
|
inclusion_score: 0.5,
|
||||||
notes_bytes: 5120,
|
context_bytes: 2500,
|
||||||
here_bytes: 768,
|
|
||||||
outcome_bytes: 1200,
|
|
||||||
domain_bytes: 4000,
|
|
||||||
exchange_bytes: 3000,
|
|
||||||
stimulus_bytes: 1500,
|
stimulus_bytes: 1500,
|
||||||
heard_bytes: 2500,
|
heard_bytes: 1500,
|
||||||
addressed_bytes: 8 * 1024,
|
addressed_bytes: 8 * 1024,
|
||||||
identity_bytes: 700,
|
identity_bytes: 300,
|
||||||
bond_summary_bytes: 600,
|
bond_summary_bytes: 300,
|
||||||
item_bytes: 700,
|
item_bytes: 400,
|
||||||
body_bytes: 1024,
|
memory_tau_h: 24.0,
|
||||||
freshness_base: 0.5,
|
freshness_base: 0.5,
|
||||||
freshness_window: 5,
|
freshness_window: 5,
|
||||||
people_full: 2,
|
people_full: 2,
|
||||||
beat_tail_lines: 6,
|
beat_tail_lines: 6,
|
||||||
group_state: true,
|
|
||||||
group_lines: 12,
|
|
||||||
group_bytes: 360,
|
|
||||||
caps: PoolCaps::default(),
|
caps: PoolCaps::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -407,7 +140,7 @@ impl Default for SelectTuning {
|
||||||
|
|
||||||
impl Default for PoolCaps {
|
impl Default for PoolCaps {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self { memories_about_present: 2, other_memories: 2, needs: 1, incubation: 1, stance: 1, value: 1 }
|
Self { memories_about_present: 2, other_memories: 2, needs: 1, incubation: 1, stance: 1, value: 1, said: 1 }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -428,81 +161,52 @@ impl Tuning {
|
||||||
if self.projector.model.trim().is_empty() {
|
if self.projector.model.trim().is_empty() {
|
||||||
bail!("projector.model must name a model");
|
bail!("projector.model must name a model");
|
||||||
}
|
}
|
||||||
if self.interpreter.model.trim().is_empty() {
|
|
||||||
bail!("interpreter.model must name a model");
|
|
||||||
}
|
|
||||||
if self.persona.model.trim().is_empty() {
|
|
||||||
bail!("persona.model must name a model");
|
|
||||||
}
|
|
||||||
self.agent.validate()?;
|
|
||||||
if !ADDRESSED_RANGE.contains(&select.addressed_bytes) {
|
if !ADDRESSED_RANGE.contains(&select.addressed_bytes) {
|
||||||
bail!("select.addressed_bytes must be from {} to {}, not {}", ADDRESSED_RANGE.start(), ADDRESSED_RANGE.end(), select.addressed_bytes);
|
bail!("select.addressed_bytes must be from {} to {}, not {}", ADDRESSED_RANGE.start(), ADDRESSED_RANGE.end(), select.addressed_bytes);
|
||||||
}
|
}
|
||||||
let caps = &select.caps;
|
let caps = &select.caps;
|
||||||
if [caps.memories_about_present, caps.other_memories, caps.needs, caps.incubation, caps.stance, caps.value].iter().all(|cap| *cap == 0) {
|
if [caps.memories_about_present, caps.other_memories, caps.needs, caps.incubation, caps.stance, caps.value, caps.said].iter().all(|cap| *cap == 0) {
|
||||||
bail!("select.caps are all 0: a packet could hold nothing of her");
|
bail!("select.caps are all 0: a packet could hold nothing of her");
|
||||||
}
|
}
|
||||||
positive("select.inclusion_score", select.inclusion_score)?;
|
positive("select.inclusion_score", select.inclusion_score)?;
|
||||||
|
positive("select.memory_tau_h", select.memory_tau_h)?;
|
||||||
if !(select.freshness_base.is_finite() && (0.0..=1.0).contains(&select.freshness_base)) {
|
if !(select.freshness_base.is_finite() && (0.0..=1.0).contains(&select.freshness_base)) {
|
||||||
bail!("select.freshness_base must be from 0 to 1, not {}", select.freshness_base);
|
bail!("select.freshness_base must be from 0 to 1, not {}", select.freshness_base);
|
||||||
}
|
}
|
||||||
for (name, bytes) in [
|
for (name, bytes) in [
|
||||||
("select.notes_bytes", select.notes_bytes),
|
("select.context_bytes", select.context_bytes),
|
||||||
("select.stimulus_bytes", select.stimulus_bytes),
|
("select.stimulus_bytes", select.stimulus_bytes),
|
||||||
("select.heard_bytes", select.heard_bytes),
|
("select.heard_bytes", select.heard_bytes),
|
||||||
("select.identity_bytes", select.identity_bytes),
|
("select.identity_bytes", select.identity_bytes),
|
||||||
("select.bond_summary_bytes", select.bond_summary_bytes),
|
("select.bond_summary_bytes", select.bond_summary_bytes),
|
||||||
("select.item_bytes", select.item_bytes),
|
("select.item_bytes", select.item_bytes),
|
||||||
("select.group_lines", select.group_lines),
|
|
||||||
("select.group_bytes", select.group_bytes),
|
|
||||||
("projector.words", self.projector.words),
|
("projector.words", self.projector.words),
|
||||||
("projector.beat_words", self.projector.beat_words),
|
("projector.beat_words", self.projector.beat_words),
|
||||||
("persona.words", self.persona.words),
|
|
||||||
] {
|
] {
|
||||||
if bytes == 0 {
|
if bytes == 0 {
|
||||||
bail!("{name} must be above 0");
|
bail!("{name} must be above 0");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (name, bytes) in [
|
for (name, bytes) in [
|
||||||
("select.notes_bytes", select.notes_bytes),
|
("select.context_bytes", select.context_bytes),
|
||||||
("select.here_bytes", select.here_bytes),
|
|
||||||
("select.outcome_bytes", select.outcome_bytes),
|
|
||||||
("select.domain_bytes", select.domain_bytes),
|
|
||||||
("select.exchange_bytes", select.exchange_bytes),
|
|
||||||
("select.stimulus_bytes", select.stimulus_bytes),
|
("select.stimulus_bytes", select.stimulus_bytes),
|
||||||
("select.heard_bytes", select.heard_bytes),
|
("select.heard_bytes", select.heard_bytes),
|
||||||
("select.identity_bytes", select.identity_bytes),
|
("select.identity_bytes", select.identity_bytes),
|
||||||
("select.bond_summary_bytes", select.bond_summary_bytes),
|
("select.bond_summary_bytes", select.bond_summary_bytes),
|
||||||
("select.item_bytes", select.item_bytes),
|
("select.item_bytes", select.item_bytes),
|
||||||
("select.body_bytes", select.body_bytes),
|
|
||||||
("select.group_bytes", select.group_bytes),
|
|
||||||
("projector.guidance", self.projector.guidance.len()),
|
("projector.guidance", self.projector.guidance.len()),
|
||||||
("persona.guidance", self.persona.guidance.len()),
|
|
||||||
] {
|
] {
|
||||||
if bytes > PART_BYTES_MAX {
|
if bytes > PART_BYTES_MAX {
|
||||||
bail!("{name} must be at most {PART_BYTES_MAX} bytes, not {bytes}: the prompt must fit the connector's frame");
|
bail!("{name} must be at most {PART_BYTES_MAX} bytes, not {bytes}: the prompt must fit the connector's frame");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if select.group_lines > GROUP_LINES_MAX {
|
for (name, words) in [("projector.words", self.projector.words), ("projector.beat_words", self.projector.beat_words)] {
|
||||||
bail!("select.group_lines must be at most {GROUP_LINES_MAX}, not {}", select.group_lines);
|
|
||||||
}
|
|
||||||
for (name, words) in [("projector.words", self.projector.words), ("projector.beat_words", self.projector.beat_words), ("persona.words", self.persona.words)] {
|
|
||||||
if words > WORDS_MAX {
|
if words > WORDS_MAX {
|
||||||
bail!("{name} must be at most {WORDS_MAX}, not {words}");
|
bail!("{name} must be at most {WORDS_MAX}, not {words}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A guard below its floor would cut what the section always carries. No guard is checked against another's.
|
if select.identity_bytes.checked_add(FIXED_ROOM).is_none_or(|needed| select.context_bytes < needed) {
|
||||||
if select.body_bytes < BODY_ROOM_MIN {
|
bail!("select.context_bytes must leave {FIXED_ROOM} bytes beside select.identity_bytes for the hour and the mood");
|
||||||
bail!("select.body_bytes must be at least {BODY_ROOM_MIN}, not {}: the turn line and one entry always fit", select.body_bytes);
|
|
||||||
}
|
|
||||||
if select.here_bytes < HERE_ROOM_MIN {
|
|
||||||
bail!("select.here_bytes must be at least {HERE_ROOM_MIN}, not {}: the hour and the mood always fit", select.here_bytes);
|
|
||||||
}
|
|
||||||
if select.outcome_bytes < OUTCOME_ROOM_MIN {
|
|
||||||
bail!("select.outcome_bytes must be at least {OUTCOME_ROOM_MIN}, not {}: what came of her last turn always has room", select.outcome_bytes);
|
|
||||||
}
|
|
||||||
if select.domain_bytes < DOMAIN_ROOM_MIN {
|
|
||||||
bail!("select.domain_bytes must be at least {DOMAIN_ROOM_MIN}, not {}: the line counting what of her domain is not shown always fits", select.domain_bytes);
|
|
||||||
}
|
}
|
||||||
let lens = &self.lens;
|
let lens = &self.lens;
|
||||||
let weights = [lens.body_and_hour, lens.person_present, lens.unresolved_want, lens.memory_surfacing, lens.wondering];
|
let weights = [lens.body_and_hour, lens.person_present, lens.unresolved_want, lens.memory_surfacing, lens.wondering];
|
||||||
|
|
|
||||||
|
|
@ -1,113 +0,0 @@
|
||||||
//! What her records say of her (map 16.38). Her trace is the only place a line is decided, a failure counted or a wake
|
|
||||||
//! remembered: each start appends one wake record (`persona::carry`), and her agent, her Interpreter and her sends append their
|
|
||||||
//! rows beside it. What she last showed and when she last woke are read back from the records (`history`), what she is told
|
|
||||||
//! from them (`outcome::told`), and none of it is kept anywhere else.
|
|
||||||
//!
|
|
||||||
//! Two kinds of row hold lines (`held`): a turn row, one per agent turn (`persona::drain`), and the wake record a start writes
|
|
||||||
//! when it closes. A line is decided, for whoever asks (`decided`), when a row that did not fail holds it, or a row set it aside.
|
|
||||||
//! Only the wake record is a wake (`is_wake`): wakes are what the poll, the window and her last-woke time count, turns are not.
|
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use eureka_pipeline::Slug;
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use super::commit::{Deltas, Heard};
|
|
||||||
use super::outcome;
|
|
||||||
|
|
||||||
/// How many of her earlier projections freshness remembers, and how many of her rows a packet reads.
|
|
||||||
const RECENT: usize = 5;
|
|
||||||
const RECORDS: usize = 200;
|
|
||||||
|
|
||||||
/// One wake taken as the Interpreter's deltas will put it: the deltas, what the wake heard and whose state it is. The seam
|
|
||||||
/// `persona::put_applied` puts through: on a stale put it applies the same deltas to her state as it then stands.
|
|
||||||
pub(crate) struct Taken<'a> {
|
|
||||||
pub deltas: &'a Deltas,
|
|
||||||
pub heard: &'a Heard,
|
|
||||||
pub instance: &'a Slug,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `record` is a wake record: the row a start writes when it closes, the only row that names its `rooms`. A turn row
|
|
||||||
/// holds lines too, and is no wake.
|
|
||||||
pub(crate) fn is_wake(record: &Value) -> bool {
|
|
||||||
record["rooms"].is_array()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `record` says it failed.
|
|
||||||
pub(crate) fn failed(record: &Value) -> bool {
|
|
||||||
record.get("failed").is_some_and(|failed| !failed.is_null())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A wake that completed: a wake record that did not fail.
|
|
||||||
pub(crate) fn completed(record: &Value) -> bool {
|
|
||||||
is_wake(record) && !failed(record)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The events her trace shows she has decided: every line a row that did not fail holds, turn row and wake record alike, and
|
|
||||||
/// every line set aside. A decision is made once, when it is written. The one reader of "was this line decided", for the drain
|
|
||||||
/// and the poll alike.
|
|
||||||
pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> {
|
|
||||||
let mut done = BTreeSet::new();
|
|
||||||
for record in records {
|
|
||||||
if !failed(record) {
|
|
||||||
done.extend(record["held"].as_array().into_iter().flatten().filter_map(Value::as_str));
|
|
||||||
}
|
|
||||||
done.extend(record["set_aside"].as_array().into_iter().flatten().filter_map(|aside| aside["event"].as_str()));
|
|
||||||
}
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many starts of hers failed in a row, and when the last was made: what the poll backs off by. A failed wake is one; so is
|
|
||||||
/// each day-cap hold row (`persona::drain` appends one per held start), none of them a strike. A completed wake ends the run. The day
|
|
||||||
/// cap resets at the UTC midnight, so a hold row dated before `now`'s day is no evidence of today and is not counted.
|
|
||||||
pub(crate) fn failed_run(records: &[Value], now: DateTime<Utc>) -> (u32, Option<DateTime<Utc>>) {
|
|
||||||
let at_of = |record: &Value| record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc));
|
|
||||||
let starts: Vec<&Value> = records.iter().filter(|record| is_wake(record) || (is_hold(record) && at_of(record).is_some_and(|at| at.date_naive() == now.date_naive()))).collect();
|
|
||||||
let mut run = 0u32;
|
|
||||||
for record in starts.iter().rev() {
|
|
||||||
if is_hold(record) || failed(record) {
|
|
||||||
run = run.saturating_add(1);
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(run, starts.last().filter(|_| run > 0).and_then(|record| at_of(record)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `record` is the row a start appended because her agent had spent its day's cap (`persona::drain`).
|
|
||||||
pub(crate) fn is_hold(record: &Value) -> bool {
|
|
||||||
record["held_by"] == DAY_CAP_HOLD
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `held_by` of the row a start writes when her agent has spent its day's cap and she is not woken (`persona::drain`).
|
|
||||||
pub(crate) const DAY_CAP_HOLD: &str = "day_cap";
|
|
||||||
|
|
||||||
/// What her records say of her: what she is to be told (`outcome::told`), the ids her last projections selected, her last rows
|
|
||||||
/// and when she last woke. The one reader, over a run's list or her trace.
|
|
||||||
#[derive(Debug, Default, PartialEq)]
|
|
||||||
pub(crate) struct Past {
|
|
||||||
pub told: Vec<Value>,
|
|
||||||
pub recent: Vec<Vec<String>>,
|
|
||||||
pub records: Vec<Value>,
|
|
||||||
pub last_wake: Option<DateTime<Utc>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her `records`, oldest first, read.
|
|
||||||
pub(crate) fn history(records: &[Value]) -> Past {
|
|
||||||
let selected = |record: &Value| record["selected"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect::<Vec<_>>());
|
|
||||||
let mut recent: Vec<Vec<String>> = records.iter().filter(|record| completed(record)).filter_map(selected).collect();
|
|
||||||
recent.drain(..recent.len().saturating_sub(RECENT));
|
|
||||||
// A failed wake or a day-cap hold row is in her trace and not in her packet's window: an outage that fails every wake for an hour must not push
|
|
||||||
// what she did out of it.
|
|
||||||
let kept: Vec<&Value> = records.iter().filter(|record| !(is_wake(record) && failed(record)) && !is_hold(record)).collect();
|
|
||||||
Past { told: outcome::told(records), recent, records: kept[kept.len().saturating_sub(RECORDS)..].iter().map(|record| (*record).clone()).collect(), last_wake: last_wake(records) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// When she last woke: her last completed wake.
|
|
||||||
pub(crate) fn last_wake(records: &[Value]) -> Option<DateTime<Utc>> {
|
|
||||||
records.iter().rev().find(|record| completed(record)).and_then(|record| record["at"].as_str()).and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,117 +0,0 @@
|
||||||
use chrono::{DateTime, Duration, Utc};
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn at(minute: i64) -> String {
|
|
||||||
(chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap() + Duration::minutes(minute)).to_rfc3339()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wake(seq: u64, ids: &[&str]) -> Value {
|
|
||||||
json!({ "rooms": [], "held": [format!("$e{seq}")], "selected": ids, "at": at(seq as i64), "seq": seq, "began": seq, "status": "completed" })
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_l1_history_from_records() {
|
|
||||||
let mut records: Vec<Value> = (0..7).map(|at| wake(at, &[&format!("m{at}")])).collect();
|
|
||||||
assert_eq!(history(&[]), Past::default());
|
|
||||||
let past = history(&records);
|
|
||||||
assert_eq!(past.recent, [["m2"], ["m3"], ["m4"], ["m5"], ["m6"]], "the last five selections, oldest first");
|
|
||||||
assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)));
|
|
||||||
records.push(json!({ "rooms": [], "held": ["$e7"], "failed": "Overloaded", "selected": ["m7"], "at": at(7), "seq": 7 }));
|
|
||||||
let past = history(&records);
|
|
||||||
assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)), "a failed wake is no wake");
|
|
||||||
assert_eq!(past.recent.last(), Some(&vec!["m6".to_owned()]), "what a failed wake selected is not remembered");
|
|
||||||
assert_eq!(past.told, [records[7].clone()], "the failed wake is told");
|
|
||||||
let long: Vec<Value> = (0..260).map(|at| wake(at, &[])).collect();
|
|
||||||
assert_eq!(history(&long).records.len(), 200);
|
|
||||||
assert_eq!(history(&long).records[0]["at"], json!(at(60)), "her last rows, oldest first");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An outage that fails every wake is in her trace and not in her packet's window, and the run of failures is what the poll
|
|
||||||
/// backs off by. (Soul s4 outage-rewake-floods-records.) Her agent's rows between wakes are no wakes and break no run.
|
|
||||||
#[test]
|
|
||||||
fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() {
|
|
||||||
let failed = |n: u64| json!({ "rooms": [], "held": [], "failed": "the connector did not answer: unavailable", "outage": true, "at": format!("2026-11-27T11:{:02}:00Z", n % 60), "seq": n + 3 });
|
|
||||||
let mut records: Vec<Value> = (0..3).map(|n| wake(n, &[&format!("m{n}")])).collect();
|
|
||||||
records.extend((0..200).map(failed));
|
|
||||||
records.push(json!({ "agent": "receipt", "seq": 203, "receipt": { "tool": "say", "status": "ok" } }));
|
|
||||||
let past = history(&records);
|
|
||||||
assert_eq!(past.records.len(), 4, "the window holds her wakes and her agent's row, and no failure");
|
|
||||||
assert_eq!(past.recent.len(), 3);
|
|
||||||
assert_eq!(failed_run(&records, "2026-11-27T12:00:00Z".parse().unwrap()).0, 200);
|
|
||||||
assert_eq!(failed_run(&records[..3], "2026-11-27T12:00:00Z".parse().unwrap()).0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A completed wake decides the lines it held; a failed one decides nothing; a set-aside row decides its line.
|
|
||||||
#[test]
|
|
||||||
fn t_l2_a_line_is_decided_by_the_record_that_holds_it() {
|
|
||||||
let records = vec![
|
|
||||||
json!({ "held": ["$a"], "seq": 0 }),
|
|
||||||
json!({ "held": ["$b"], "failed": null, "seq": 1 }),
|
|
||||||
json!({ "failed": "x", "held": ["$c"], "seq": 2 }),
|
|
||||||
json!({ "set_aside": [{ "event": "$d" }], "seq": 3 }),
|
|
||||||
json!({ "agent": "receipt", "held": "not a wake", "seq": 4 }),
|
|
||||||
];
|
|
||||||
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$a", "$b", "$d"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each day-cap hold row is one failed start in a row, none of them a strike, and a completed wake after it ends the run. A hold row
|
|
||||||
/// dated before the current UTC day is no evidence of today and is not counted (Soul s4 rollover-delayed-by-old-hold).
|
|
||||||
#[test]
|
|
||||||
fn t_h4_a_day_cap_hold_row_counts_as_a_failed_start_in_the_run() {
|
|
||||||
let hold = |at: &str, seq: u64| json!({ "held_by": "day_cap", "at": at, "seq": seq });
|
|
||||||
let failed = json!({ "rooms": [], "held": [], "failed": "the connector did not answer: unavailable", "at": "2026-11-27T10:00:00Z", "seq": 4 });
|
|
||||||
let done = json!({ "rooms": [], "held": ["$a"], "at": "2026-11-27T09:00:00Z", "seq": 3 });
|
|
||||||
let now: DateTime<Utc> = "2026-11-27T12:00:00Z".parse().unwrap();
|
|
||||||
let holds = [hold("2026-11-27T11:00:00Z", 5), hold("2026-11-27T11:00:20Z", 6), hold("2026-11-27T11:01:00Z", 7)];
|
|
||||||
assert_eq!(failed_run(&[vec![done.clone()], holds.to_vec()].concat(), now), (3, Some("2026-11-27T11:01:00Z".parse().unwrap())));
|
|
||||||
assert_eq!(failed_run(&[vec![done.clone(), failed.clone()], holds[..2].to_vec()].concat(), now).0, 3, "with the failed wake before them");
|
|
||||||
assert_eq!(failed_run(&[holds.to_vec(), vec![done.clone()]].concat(), now), (0, None), "a completed wake after them ends the run");
|
|
||||||
let yesterday = [hold("2026-11-26T23:58:00Z", 5), hold("2026-11-26T23:59:00Z", 6)];
|
|
||||||
assert_eq!(failed_run(&[vec![done.clone()], yesterday.to_vec()].concat(), now), (0, None), "yesterday's holds are no evidence today");
|
|
||||||
assert_eq!(failed_run(&[vec![done, failed], yesterday.to_vec(), holds[..1].to_vec()].concat(), now).0, 2, "today's hold and the failed wake count; yesterday's do not");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Her packet's window holds her turns: a day's hold rows are in her trace and not in it, as failed wakes are not.
|
|
||||||
#[test]
|
|
||||||
fn t_h5_hold_rows_never_enter_her_packets_window() {
|
|
||||||
let mut records: Vec<Value> = (0..3).map(|n| wake(n, &[&format!("m{n}")])).collect();
|
|
||||||
records.extend((0..150).map(|n| json!({ "held_by": "day_cap", "at": "2026-11-27T11:00:00Z", "seq": n + 3 })));
|
|
||||||
assert_eq!(history(&records).records.len(), 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A turn row: what a start writes after each of her agent's turns.
|
|
||||||
fn turn_row(seq: u64, held: &[&str]) -> Value {
|
|
||||||
json!({ "wake": "n0-1", "turn": 1, "held": held, "status": "completed", "at": at(seq as i64), "seq": seq })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W1-I1: a line is decided by the one row that holds it, turn row or wake record, when that row did not fail; a failed turn row decides
|
|
||||||
/// nothing, and a wake record from before turn rows (`held`, `rooms`) decides its lines as it always did.
|
|
||||||
#[test]
|
|
||||||
fn t_w1_a_turn_row_that_did_not_fail_decides_its_lines() {
|
|
||||||
let mut failed = turn_row(1, &["$failed"]);
|
|
||||||
failed["status"] = json!("failed");
|
|
||||||
failed["failed"] = json!("the agent's turn ended early: Refusal");
|
|
||||||
let old = json!({ "rooms": ["#a"], "room": "#a", "held": ["$old"], "kind": "chat", "status": "completed", "at": at(3), "seq": 3, "began": 3 });
|
|
||||||
let records = vec![turn_row(0, &["$turn"]), failed, json!({ "rooms": ["#a"], "held": [], "status": "completed", "at": at(2), "seq": 2 }), old];
|
|
||||||
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$old", "$turn"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// W1: a turn row is no wake. Wakes are what the poll's backoff, her window and her last-woke time count, and a turn is part of one.
|
|
||||||
#[test]
|
|
||||||
fn t_w1_a_turn_row_is_never_a_wake() {
|
|
||||||
let turn = turn_row(1, &["$a"]);
|
|
||||||
assert!(!is_wake(&turn) && !completed(&turn));
|
|
||||||
assert!(is_wake(&wake(0, &["m0"])), "the wake record names its rooms");
|
|
||||||
|
|
||||||
// A turn row between wakes breaks no run of failures and is no last wake.
|
|
||||||
let failed_wake = json!({ "rooms": ["#a"], "held": [], "failed": "x", "at": "2026-11-27T11:00:00Z", "seq": 3 });
|
|
||||||
let records = vec![wake(0, &["m0"]), failed_wake.clone(), json!({ "wake": "n3-1", "turn": 1, "held": ["$a"], "status": "completed", "at": "2026-11-27T11:01:00Z", "seq": 4 })];
|
|
||||||
let now: DateTime<Utc> = "2026-11-27T12:00:00Z".parse().unwrap();
|
|
||||||
assert_eq!(failed_run(&records, now), (1, Some("2026-11-27T11:00:00Z".parse().unwrap())), "a completed turn row does not end the run: only a completed wake does");
|
|
||||||
assert_eq!(last_wake(&records).map(|at| at.to_rfc3339()), Some(at(0)), "and is not when she last woke");
|
|
||||||
let past = history(&records);
|
|
||||||
assert_eq!(past.recent, [["m0"]], "nor what her last wakes selected");
|
|
||||||
assert_eq!(past.told, [failed_wake], "nor does it tell her anything: the failed wake is told, the turn is not");
|
|
||||||
}
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
//! One wake (map 16.38.2, items 3 and 4): the Projector once and the Persona once over every waking room. The drain, the
|
|
||||||
//! harness and the simulator all take their wake here, so what the simulator tests is the wake the Minds take.
|
|
||||||
//!
|
|
||||||
//! The Projector's packet is built for the turn's room, the room of the oldest waking line (`Request::rooms`, first); every
|
|
||||||
//! other waking room is an arrival in it (who, where and when, never the words), and the Persona reads all of their lines
|
|
||||||
//! verbatim. The Persona is asked for her inner voice alone: nothing she writes is read for an act, so what she says and
|
|
||||||
//! does in the world is not decided here. The stream this wake makes (`Waked::narration`, `Waked::prose`) is what the Interpreter
|
|
||||||
//! reads for her state and what the agent acts from; neither is called from here.
|
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::{Organs, Request, Through, project};
|
|
||||||
|
|
||||||
/// A call that gave no answer, and whether the connector's typed kind made it an outage.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct Fault {
|
|
||||||
pub reason: String,
|
|
||||||
pub outage: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one wake made. A failed wake has no stream and says which call failed.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub(crate) struct Waked {
|
|
||||||
/// The Projector's narration of the packet, when its call answered.
|
|
||||||
pub narration: Option<String>,
|
|
||||||
/// Her prose over it, when the Persona's call answered.
|
|
||||||
pub prose: Option<String>,
|
|
||||||
/// What each call cost: `{projector, persona}`, as the connector reported it.
|
|
||||||
pub usage: Value,
|
|
||||||
pub failed: Option<Fault>,
|
|
||||||
/// The event of each line of the other waking rooms the Persona was shown (what fit `heard_bytes`): the lines of those rooms she did not see are not
|
|
||||||
/// held by this wake.
|
|
||||||
pub elsewhere_shown: Vec<String>,
|
|
||||||
/// The whole report of the render, the packet included.
|
|
||||||
pub report: Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One wake: `request` is run as one render through the Persona, so the model is asked exactly twice. A setup fault (her
|
|
||||||
/// tuning, her own id) is an error and no call's failure.
|
|
||||||
pub(crate) fn wake(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result<Waked> {
|
|
||||||
let request = Request { renders: Some(1), through: Through::Persona, judge_against: None, ..request.clone() };
|
|
||||||
let report = project(organs, &request, now)?;
|
|
||||||
let render = &report["renders"][0];
|
|
||||||
let persona = &render["persona"];
|
|
||||||
let failed = [render, persona].into_iter().find(|part| part.get("failed").is_some()).map(|part| Fault { reason: part["failed"].as_str().unwrap_or_default().to_owned(), outage: part["outage"] == true });
|
|
||||||
Ok(Waked {
|
|
||||||
narration: render["narration"].as_str().map(str::to_owned),
|
|
||||||
prose: persona["prose"].as_str().map(str::to_owned),
|
|
||||||
usage: json!({ "projector": render["usage"], "persona": persona["usage"] }),
|
|
||||||
failed,
|
|
||||||
elsewhere_shown: report["packet"]["shown_from_other_rooms"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(),
|
|
||||||
report,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,196 +0,0 @@
|
||||||
//! Her box (map 16.38.5, 16.38.17; ruling `eureka-body:ruling:sandbox-network`): the one bubblewrap profile, and the box's side
|
|
||||||
//! of a shell command.
|
|
||||||
//!
|
|
||||||
//! `sandbox_args` is the profile her leased Persona session ran under, with the commons data dirs she may write bound back
|
|
||||||
//! read-write. `run_box` is what `mind-persona box-exec` does for one connection to `mind-box-<m>.socket`: read one request,
|
|
||||||
//! run its command under the profile with a timeout, answer one receipt. It runs as `mind-<m>-box`, whose fence chain admits the
|
|
||||||
//! public internet and nothing on this host, so the boundary is the operating system's: nothing here filters a command.
|
|
||||||
|
|
||||||
use std::io::{Read, Write};
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::process::{Command, Stdio};
|
|
||||||
use std::time::{Duration, Instant, SystemTime};
|
|
||||||
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use crate::self_run::CONFIG_DIR_NAME;
|
|
||||||
|
|
||||||
/// The commons data dirs her box writes: shared hand-offs and the cast's art. The rest of `/opt/commons` is read-only to her.
|
|
||||||
pub const COMMONS_RW: [&str; 2] = ["/opt/commons/handoff", "/opt/commons/cast-art"];
|
|
||||||
/// The longest a command may run.
|
|
||||||
pub(crate) const TIMEOUT_MAX_S: u64 = 120;
|
|
||||||
/// How much of each output stream the receipt keeps: its tail.
|
|
||||||
pub(crate) const TAIL_BYTES: usize = 4096;
|
|
||||||
/// The most paths the receipt lists as written, and the most entries a walk for them visits.
|
|
||||||
const WROTE_MAX: usize = 64;
|
|
||||||
const WALK_MAX: usize = 20_000;
|
|
||||||
|
|
||||||
/// The bubblewrap arguments up to the program: the whole filesystem read-only, a private `/tmp` and `/run`, the scratch
|
|
||||||
/// directory read-only with only its `claude-config` writable (nothing can create, replace or link a file where the organ
|
|
||||||
/// writes), her sandbox writable, each of `extra_rw` writable, her unit's credentials (`/etc/gamecult`, the other `/var/lib`
|
|
||||||
/// directories, everything under `/run`) hidden, a private process table, and the child dead when its parent is. The network
|
|
||||||
/// is shared: what it reaches is the uid fence's (gamecult-ops `mind-fence.service`). The boundary is the operating system's,
|
|
||||||
/// not a pattern list (ruling `eureka-body:ruling:persona-git-personal-sandbox`).
|
|
||||||
pub(crate) fn sandbox_args(sandbox: &Path, scratch: &Path, extra_rw: &[&Path]) -> Vec<String> {
|
|
||||||
let (sandbox, scratch) = (sandbox.to_string_lossy(), scratch.to_string_lossy());
|
|
||||||
let config = scratch.to_string() + "/" + CONFIG_DIR_NAME;
|
|
||||||
let mut args: Vec<String> = [
|
|
||||||
"--ro-bind", "/", "/",
|
|
||||||
"--dev", "/dev",
|
|
||||||
"--proc", "/proc",
|
|
||||||
"--tmpfs", "/tmp",
|
|
||||||
"--tmpfs", "/run",
|
|
||||||
"--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve",
|
|
||||||
"--ro-bind", &scratch, &scratch,
|
|
||||||
"--bind", &config, &config,
|
|
||||||
"--tmpfs", "/etc/gamecult",
|
|
||||||
"--tmpfs", "/var/lib",
|
|
||||||
"--bind", &sandbox, &sandbox,
|
|
||||||
]
|
|
||||||
.map(String::from)
|
|
||||||
.to_vec();
|
|
||||||
for path in extra_rw {
|
|
||||||
let path = path.to_string_lossy().into_owned();
|
|
||||||
args.extend(["--bind".to_owned(), path.clone(), path]);
|
|
||||||
}
|
|
||||||
args.extend(["--unshare-pid", "--die-with-parent", "--new-session", "--chdir", &sandbox, "--"].map(String::from));
|
|
||||||
args
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a box command runs: her box's home (writable, the working directory), its scratch (read-only, the unit's runtime
|
|
||||||
/// directory) and the other directories it may write.
|
|
||||||
pub struct BoxPaths<'a> {
|
|
||||||
pub home: &'a Path,
|
|
||||||
pub scratch: &'a Path,
|
|
||||||
pub extra_rw: &'a [&'a Path],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct BoxRequest {
|
|
||||||
command: String,
|
|
||||||
#[serde(default)]
|
|
||||||
timeout_s: Option<u64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The whole argv `run_box` executes for `command`: bwrap, the profile, then `/bin/sh -c command`.
|
|
||||||
pub(crate) fn box_argv(paths: &BoxPaths<'_>, command: &str) -> Vec<String> {
|
|
||||||
let mut argv = vec!["bwrap".to_owned()];
|
|
||||||
argv.extend(sandbox_args(paths.home, paths.scratch, paths.extra_rw));
|
|
||||||
argv.extend(["/bin/sh".to_owned(), "-c".to_owned(), command.to_owned()]);
|
|
||||||
argv
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One shell command in her box: `request` is the bytes the connection sent (one JSON object, `{command, timeout_s}`), and the
|
|
||||||
/// answer is the receipt the connection gets back: `{tool: shell, status: ok|error, exit, duration_ms, stdout_tail,
|
|
||||||
/// stderr_tail, wrote}`. `ok` is a command that ran and exited 0; anything else is `error` with why. `wrote` lists the files
|
|
||||||
/// under the writable binds modified while it ran.
|
|
||||||
pub(crate) fn run_box(request: &[u8], paths: &BoxPaths<'_>) -> Value {
|
|
||||||
let error = |why: String| json!({ "tool": "shell", "status": "error", "why": why });
|
|
||||||
let request: BoxRequest = match serde_json::from_slice(request) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(_) => return error("the box could not read the request".to_owned()),
|
|
||||||
};
|
|
||||||
let timeout = Duration::from_secs(request.timeout_s.unwrap_or(30).clamp(1, TIMEOUT_MAX_S));
|
|
||||||
if let Err(fault) = std::fs::create_dir_all(paths.scratch.join(CONFIG_DIR_NAME)) {
|
|
||||||
return error(format!("the box's scratch could not be prepared: {fault}"));
|
|
||||||
}
|
|
||||||
// The marker: a file in the read-only scratch whose time is the filesystem's own, so what a command wrote compares
|
|
||||||
// against the same clock.
|
|
||||||
let marker = paths.scratch.join(".shell-marker");
|
|
||||||
let since = std::fs::File::create(&marker).and_then(|file| file.metadata()).and_then(|meta| meta.modified()).unwrap_or_else(|_| SystemTime::now());
|
|
||||||
let argv = box_argv(paths, &request.command);
|
|
||||||
let began = Instant::now();
|
|
||||||
let mut child = match Command::new(&argv[0]).args(&argv[1..]).env("PATH", "/opt/commons/bin:/usr/bin:/bin").env("HOME", paths.home).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
|
|
||||||
Ok(child) => child,
|
|
||||||
Err(fault) => return error(format!("the box could not start: {fault}")),
|
|
||||||
};
|
|
||||||
let tail_of = |stream: Option<Box<dyn Read + Send>>| std::thread::spawn(move || stream.map(tail).unwrap_or_default());
|
|
||||||
let stdout = tail_of(child.stdout.take().map(|out| Box::new(out) as Box<dyn Read + Send>));
|
|
||||||
let stderr = tail_of(child.stderr.take().map(|err| Box::new(err) as Box<dyn Read + Send>));
|
|
||||||
let mut timed_out = false;
|
|
||||||
let status = loop {
|
|
||||||
match child.try_wait() {
|
|
||||||
Ok(Some(status)) => break Some(status),
|
|
||||||
Ok(None) if began.elapsed() >= timeout => {
|
|
||||||
// bwrap is the sandbox's parent: killed, its child dies with it (`--die-with-parent`), and with that child, the
|
|
||||||
// pid namespace's init, every process the command left.
|
|
||||||
timed_out = true;
|
|
||||||
let _ = child.kill();
|
|
||||||
break child.wait().ok();
|
|
||||||
}
|
|
||||||
Ok(None) => std::thread::sleep(Duration::from_millis(20)),
|
|
||||||
Err(_) => break None,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let duration_ms = u64::try_from(began.elapsed().as_millis()).unwrap_or(u64::MAX);
|
|
||||||
let (stdout_tail, stderr_tail) = (stdout.join().unwrap_or_default(), stderr.join().unwrap_or_default());
|
|
||||||
let mut roots: Vec<&Path> = vec![paths.home];
|
|
||||||
roots.extend(paths.extra_rw.iter().copied());
|
|
||||||
let wrote = written(&roots, since);
|
|
||||||
let _ = std::fs::remove_file(&marker);
|
|
||||||
let exit = status.and_then(|status| status.code());
|
|
||||||
let ok = !timed_out && exit == Some(0);
|
|
||||||
let mut receipt = json!({ "tool": "shell", "status": if ok { "ok" } else { "error" }, "exit": exit, "duration_ms": duration_ms, "stdout_tail": stdout_tail, "stderr_tail": stderr_tail, "wrote": wrote });
|
|
||||||
if timed_out {
|
|
||||||
receipt["why"] = json!(format!("it ran past {} s and was stopped", timeout.as_secs()));
|
|
||||||
} else if !ok {
|
|
||||||
receipt["why"] = json!(exit.map_or_else(|| "it was ended by a signal".to_owned(), |code| format!("it exited {code}")));
|
|
||||||
}
|
|
||||||
receipt
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The last `TAIL_BYTES` of a stream, read to its end, as text.
|
|
||||||
fn tail(mut stream: Box<dyn Read + Send>) -> String {
|
|
||||||
let mut kept: Vec<u8> = Vec::new();
|
|
||||||
let mut chunk = [0u8; 8192];
|
|
||||||
while let Ok(read) = stream.read(&mut chunk) {
|
|
||||||
if read == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
kept.extend_from_slice(&chunk[..read]);
|
|
||||||
if kept.len() > 2 * TAIL_BYTES {
|
|
||||||
kept.drain(..kept.len() - TAIL_BYTES);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let start = kept.len().saturating_sub(TAIL_BYTES);
|
|
||||||
String::from_utf8_lossy(&kept[start..]).into_owned()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The files under `roots` modified at or after `since`, links not followed, at most `WROTE_MAX`, visiting at most `WALK_MAX` entries.
|
|
||||||
fn written(roots: &[&Path], since: SystemTime) -> Vec<String> {
|
|
||||||
let mut found = Vec::new();
|
|
||||||
let mut stack: Vec<PathBuf> = roots.iter().map(|root| root.to_path_buf()).collect();
|
|
||||||
let mut visited = 0usize;
|
|
||||||
'walk: while let Some(dir) = stack.pop() {
|
|
||||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
|
||||||
for entry in entries.flatten() {
|
|
||||||
visited += 1;
|
|
||||||
if visited > WALK_MAX || found.len() >= WROTE_MAX {
|
|
||||||
break 'walk;
|
|
||||||
}
|
|
||||||
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
|
|
||||||
if meta.is_dir() {
|
|
||||||
stack.push(entry.path());
|
|
||||||
} else if meta.is_file() && meta.modified().is_ok_and(|at| at >= since) {
|
|
||||||
found.push(entry.path().to_string_lossy().into_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
found.sort();
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `mind-persona box-exec`'s whole work over one connection: the request read from `input` to its end, the receipt written to
|
|
||||||
/// `output`. The connection is the socket systemd hands the unit as stdin and stdout.
|
|
||||||
pub fn serve_box(mut input: impl Read, mut output: impl Write, paths: &BoxPaths<'_>) -> std::io::Result<()> {
|
|
||||||
let mut request = Vec::new();
|
|
||||||
input.by_ref().take(64 * 1024).read_to_end(&mut request)?;
|
|
||||||
let receipt = run_box(&request, paths);
|
|
||||||
output.write_all(receipt.to_string().as_bytes())?;
|
|
||||||
output.flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
@ -1,126 +0,0 @@
|
||||||
//! The one profile, and the box's side of a command. The tests that run `bwrap` run it as whoever runs the tests: on
|
|
||||||
//! Yggdrasil an unprivileged user, as `mind-<m>-box` is.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// The profile, pinned: the whole tree read-only, a private `/tmp` and `/run`, the credentials hidden before her sandbox, the
|
|
||||||
/// scratch and each extra directory are bound back, the extra directories writable and bound before `--`, the network shared.
|
|
||||||
#[test]
|
|
||||||
fn the_profile_is_pinned() {
|
|
||||||
let args = sandbox_args(Path::new("/var/lib/mind-x-box"), Path::new("/run/mind-x-box"), &[Path::new("/opt/commons/handoff")]);
|
|
||||||
let expected: Vec<String> = "--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --tmpfs /run --ro-bind-try /run/systemd/resolve /run/systemd/resolve --ro-bind /run/mind-x-box /run/mind-x-box --bind /run/mind-x-box/claude-config /run/mind-x-box/claude-config --tmpfs /etc/gamecult --tmpfs /var/lib --bind /var/lib/mind-x-box /var/lib/mind-x-box --bind /opt/commons/handoff /opt/commons/handoff --unshare-pid --die-with-parent --new-session --chdir /var/lib/mind-x-box --"
|
|
||||||
.split(' ')
|
|
||||||
.map(String::from)
|
|
||||||
.collect();
|
|
||||||
assert_eq!(args, expected);
|
|
||||||
let at = |needle: &str| args.iter().position(|arg| arg == needle).unwrap();
|
|
||||||
assert!(at("/run") < at("/run/mind-x-box") && at("/var/lib") < at("/var/lib/mind-x-box"), "hidden first, bound back after");
|
|
||||||
assert!(!args.windows(3).any(|w| w[0] == "--bind" && w[1] == "/run/mind-x-box"), "the scratch is read-only: {args:?}");
|
|
||||||
assert!(!args.iter().any(|arg| arg == "--unshare-net" || arg == "--unshare-all"), "the network is the fence's");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn t_a2_box_profile_is_sandbox_args() {
|
|
||||||
let (home, scratch, handoff, art) = (Path::new("/var/lib/mind-x-box"), Path::new("/run/mind-x-box"), Path::new("/opt/commons/handoff"), Path::new("/opt/commons/cast-art"));
|
|
||||||
let paths = BoxPaths { home, scratch, extra_rw: &[handoff, art] };
|
|
||||||
let argv = box_argv(&paths, "ls -la");
|
|
||||||
let mut expected = vec!["bwrap".to_owned()];
|
|
||||||
expected.extend(sandbox_args(home, scratch, &[handoff, art]));
|
|
||||||
expected.extend(["/bin/sh", "-c", "ls -la"].map(String::from));
|
|
||||||
assert_eq!(argv, expected, "bwrap, the one profile with the two commons data dirs, then /bin/sh -c");
|
|
||||||
let dashes = argv.iter().position(|arg| arg == "--").unwrap();
|
|
||||||
for dir in COMMONS_RW {
|
|
||||||
let bound = argv.windows(3).position(|w| w[0] == "--bind" && w[1] == dir && w[2] == dir).unwrap_or_else(|| panic!("{dir} is bound writable: {argv:?}"));
|
|
||||||
assert!(bound < dashes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Box3 {
|
|
||||||
_dir: tempfile::TempDir,
|
|
||||||
home: PathBuf,
|
|
||||||
scratch: PathBuf,
|
|
||||||
handoff: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn box3() -> Box3 {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let (home, scratch, handoff) = (dir.path().join("home"), dir.path().join("scratch"), dir.path().join("handoff"));
|
|
||||||
for made in [&home, &scratch, &handoff] {
|
|
||||||
std::fs::create_dir(made).unwrap();
|
|
||||||
}
|
|
||||||
Box3 { _dir: dir, home, scratch, handoff }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(rig: &Box3, command: &str, timeout_s: u64) -> Value {
|
|
||||||
let extra = [rig.handoff.as_path()];
|
|
||||||
let mut answer = Vec::new();
|
|
||||||
serve_box(json!({ "command": command, "timeout_s": timeout_s }).to_string().as_bytes(), &mut answer, &BoxPaths { home: &rig.home, scratch: &rig.scratch, extra_rw: &extra }).unwrap();
|
|
||||||
serde_json::from_slice(&answer).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_bwrap() -> bool {
|
|
||||||
let program = box_argv(&BoxPaths { home: Path::new("/"), scratch: Path::new("/"), extra_rw: &[] }, "true").swap_remove(0);
|
|
||||||
Command::new(program).arg("--version").output().is_ok_and(|out| out.status.success())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Inside the box, the drain's files are not there: the unit's configuration, its credentials and her Persona's state.
|
|
||||||
#[test]
|
|
||||||
fn t_a2_box_hides_drain_files() {
|
|
||||||
if !has_bwrap() {
|
|
||||||
return eprintln!("no bwrap on this host: skipped");
|
|
||||||
}
|
|
||||||
let rig = box3();
|
|
||||||
let receipt = run(&rig, "[ -z \"$(ls -A /etc/gamecult)\" ] && [ ! -e /run/credentials ] && [ ! -e /var/lib/mind-eureka ] && [ ! -e /var/lib/mind-heartbeat ] && [ -d \"$HOME\" ] && pwd", 20);
|
|
||||||
assert_eq!(receipt["status"], "ok", "{receipt}");
|
|
||||||
assert_eq!(receipt["stdout_tail"].as_str().map(str::trim), rig.home.to_str(), "the command runs in her box's home");
|
|
||||||
// On a host where they exist outside, the box hides them; where they do not, the check above still holds.
|
|
||||||
for outside in ["/etc/gamecult", "/var/lib/mind-eureka"] {
|
|
||||||
eprintln!("{outside} outside the box: {}", if Path::new(outside).exists() { "present" } else { "absent" });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A command that writes to a commons data dir lists the path it wrote in `wrote`, and only what it wrote.
|
|
||||||
#[test]
|
|
||||||
fn t_a2_box_commons_receipt() {
|
|
||||||
if !has_bwrap() {
|
|
||||||
return eprintln!("no bwrap on this host: skipped");
|
|
||||||
}
|
|
||||||
let rig = box3();
|
|
||||||
std::fs::write(rig.handoff.join("old"), "before").unwrap();
|
|
||||||
std::thread::sleep(Duration::from_millis(20));
|
|
||||||
let target = rig.handoff.join("x");
|
|
||||||
let receipt = run(&rig, &format!("echo made > {} && echo note > notes.txt", target.display()), 20);
|
|
||||||
assert_eq!(receipt["status"], "ok", "{receipt}");
|
|
||||||
let wrote: Vec<&str> = receipt["wrote"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
|
||||||
assert!(wrote.contains(&target.to_str().unwrap()), "{receipt}");
|
|
||||||
assert!(wrote.contains(&rig.home.join("notes.txt").to_str().unwrap()), "her home is a writable bind too: {receipt}");
|
|
||||||
assert!(!wrote.iter().any(|path| path.ends_with("/old")), "a file it did not write is not listed: {receipt}");
|
|
||||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "made\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A command that fails is `error` with its exit; one that runs past its timeout is stopped and says so; a request that is no
|
|
||||||
/// request is refused before anything runs.
|
|
||||||
#[test]
|
|
||||||
fn the_box_says_what_went_wrong() {
|
|
||||||
if !has_bwrap() {
|
|
||||||
return eprintln!("no bwrap on this host: skipped");
|
|
||||||
}
|
|
||||||
let rig = box3();
|
|
||||||
let failed = run(&rig, "echo oops >&2; exit 3", 20);
|
|
||||||
assert_eq!((failed["status"].as_str(), failed["exit"].as_i64(), failed["stderr_tail"].as_str()), (Some("error"), Some(3), Some("oops\n")), "{failed}");
|
|
||||||
let slow = run(&rig, "sleep 30", 1);
|
|
||||||
assert_eq!(slow["status"], "error", "{slow}");
|
|
||||||
assert!(slow["why"].as_str().unwrap().contains("ran past 1 s"), "{slow}");
|
|
||||||
assert!(slow["duration_ms"].as_u64().unwrap() < 10_000, "stopped at its timeout: {slow}");
|
|
||||||
let mut answer = Vec::new();
|
|
||||||
serve_box(&b"not json"[..], &mut answer, &BoxPaths { home: &rig.home, scratch: &rig.scratch, extra_rw: &[] }).unwrap();
|
|
||||||
assert_eq!(serde_json::from_slice::<Value>(&answer).unwrap()["status"], "error");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The tail keeps the end of a long stream.
|
|
||||||
#[test]
|
|
||||||
fn a_tail_is_the_end() {
|
|
||||||
let long: Vec<u8> = (0..20_000u32).map(|at| b'a' + (at % 26) as u8).collect();
|
|
||||||
let kept = tail(Box::new(std::io::Cursor::new(long.clone())));
|
|
||||||
assert_eq!(kept.as_bytes(), &long[long.len() - TAIL_BYTES..]);
|
|
||||||
}
|
|
||||||
|
|
@ -1012,6 +1012,8 @@ pub struct ClaudeSpawner {
|
||||||
unit_environment: Vec<(OsString, OsString)>,
|
unit_environment: Vec<(OsString, OsString)>,
|
||||||
scratch: PathBuf,
|
scratch: PathBuf,
|
||||||
seed: Option<PathBuf>,
|
seed: Option<PathBuf>,
|
||||||
|
/// Her sandbox: with it the child runs under bubblewrap (`sandbox_args`), the Persona's; the Self passes none.
|
||||||
|
sandbox: Option<PathBuf>,
|
||||||
/// Where her one kept conversation lives (the second of the unit's `STATE_DIRECTORY` entries, outside her working directory, the first); none keeps nothing, and every start is fresh.
|
/// Where her one kept conversation lives (the second of the unit's `STATE_DIRECTORY` entries, outside her working directory, the first); none keeps nothing, and every start is fresh.
|
||||||
keep: Option<PathBuf>,
|
keep: Option<PathBuf>,
|
||||||
/// The digest of the seed tree this process copies from (empty without a seed); none when the seed cannot be read, which no kept conversation matches.
|
/// The digest of the seed tree this process copies from (empty without a seed); none when the seed cannot be read, which no kept conversation matches.
|
||||||
|
|
@ -1029,15 +1031,23 @@ impl ClaudeSpawner {
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(name, _)| name == STATE_DIRECTORY_VARIABLE)
|
.find(|(name, _)| name == STATE_DIRECTORY_VARIABLE)
|
||||||
.and_then(|(_, value)| value.to_string_lossy().split(':').nth(1).filter(|second| !second.is_empty()).map(PathBuf::from));
|
.and_then(|(_, value)| value.to_string_lossy().split(':').nth(1).filter(|second| !second.is_empty()).map(PathBuf::from));
|
||||||
let named = |variable: &str| unit_environment.iter().find(|(name, _)| name == variable).map(|(_, value)| PathBuf::from(value));
|
let mut spawner = Self::in_sandbox(unit_environment, SEED_VARIABLE, None)?;
|
||||||
// systemd lists several runtime directories colon-separated; the unit names one.
|
spawner.seed_digest = match &spawner.seed {
|
||||||
let scratch = named(SCRATCH_VARIABLE).filter(|path| !path.as_os_str().is_empty()).ok_or_else(|| anyhow!("{SCRATCH_VARIABLE} is not set: the unit needs RuntimeDirectory="))?;
|
|
||||||
let seed = named(SEED_VARIABLE).filter(|path| !path.as_os_str().is_empty());
|
|
||||||
let seed_digest = match &seed {
|
|
||||||
Some(seed) => seed_digest(seed).ok(),
|
Some(seed) => seed_digest(seed).ok(),
|
||||||
None => Some(String::new()),
|
None => Some(String::new()),
|
||||||
};
|
};
|
||||||
Ok(Self { unit_environment, scratch, seed, keep, seed_digest })
|
spawner.keep = keep;
|
||||||
|
Ok(spawner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same, with the seed named by `seed_variable` and, if `sandbox` is given, the child run under bubblewrap with that directory as its writable home.
|
||||||
|
pub fn in_sandbox(unit_environment: impl IntoIterator<Item = (OsString, OsString)>, seed_variable: &str, sandbox: Option<PathBuf>) -> Result<Self> {
|
||||||
|
let unit_environment: Vec<(OsString, OsString)> = unit_environment.into_iter().collect();
|
||||||
|
let named = |variable: &str| unit_environment.iter().find(|(name, _)| name == variable).map(|(_, value)| PathBuf::from(value));
|
||||||
|
// systemd lists several runtime directories colon-separated; the unit names one.
|
||||||
|
let scratch = named(SCRATCH_VARIABLE).filter(|path| !path.as_os_str().is_empty()).ok_or_else(|| anyhow!("{SCRATCH_VARIABLE} is not set: the unit needs RuntimeDirectory="))?;
|
||||||
|
let seed = named(seed_variable).filter(|path| !path.as_os_str().is_empty());
|
||||||
|
Ok(Self { unit_environment, scratch, seed, sandbox, keep: None, seed_digest: None })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1136,12 +1146,50 @@ impl Spawner for ClaudeSpawner {
|
||||||
|
|
||||||
fn spawn(&self, args: &[String], token: &TokenFd, session: Option<&str>) -> Result<Box<dyn Child>> {
|
fn spawn(&self, args: &[String], token: &TokenFd, session: Option<&str>) -> Result<Box<dyn Child>> {
|
||||||
let config = FreshConfig::create(&self.scratch, self.seed.as_deref(), self.keep.clone())?;
|
let config = FreshConfig::create(&self.scratch, self.seed.as_deref(), self.keep.clone())?;
|
||||||
spawn_program(Path::new("claude"), args, token, (&self.unit_environment, session), config)
|
let Some(sandbox) = &self.sandbox else { return spawn_program(Path::new("claude"), args, token, (&self.unit_environment, session), config) };
|
||||||
|
let mut wrapped = sandbox_args(sandbox, &self.scratch);
|
||||||
|
wrapped.push("claude".into());
|
||||||
|
wrapped.extend(args.iter().cloned());
|
||||||
|
spawn_program(Path::new("bwrap"), &wrapped, token, (&self.unit_environment, session), config)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The bubblewrap arguments up to the program: the whole filesystem read-only, a private `/tmp`
|
||||||
|
/// and `/run`, the unit's scratch directory read-only with only its `claude-config` writable (she
|
||||||
|
/// cannot create, replace or link a file where the organ writes, such as the instructions file),
|
||||||
|
/// her sandbox writable, her unit's credentials (`/etc/gamecult`, the other `/var/lib`
|
||||||
|
/// directories, the lease socket under `/run`) hidden, a private process table, and the child dead
|
||||||
|
/// when the unit's process is. The network is shared: the web, `huginn` and the API are reachable,
|
||||||
|
/// and what she reaches on the host is the uid fence's (gamecult-ops `mind-fence.service`), which
|
||||||
|
/// binds the organ and this sandbox alike. The boundary is the operating system's, not a pattern
|
||||||
|
/// list (ruling `eureka-body:ruling:persona-git-personal-sandbox`).
|
||||||
|
pub(crate) fn sandbox_args(sandbox: &Path, scratch: &Path) -> Vec<String> {
|
||||||
|
let (sandbox, scratch) = (sandbox.to_string_lossy(), scratch.to_string_lossy());
|
||||||
|
let config = scratch.to_string() + "/" + CONFIG_DIR_NAME;
|
||||||
|
[
|
||||||
|
"--ro-bind", "/", "/",
|
||||||
|
"--dev", "/dev",
|
||||||
|
"--proc", "/proc",
|
||||||
|
"--tmpfs", "/tmp",
|
||||||
|
"--tmpfs", "/run",
|
||||||
|
"--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve",
|
||||||
|
"--ro-bind", &scratch, &scratch,
|
||||||
|
"--bind", &config, &config,
|
||||||
|
"--tmpfs", "/etc/gamecult",
|
||||||
|
"--tmpfs", "/var/lib",
|
||||||
|
"--bind", &sandbox, &sandbox,
|
||||||
|
"--unshare-pid",
|
||||||
|
"--die-with-parent",
|
||||||
|
"--new-session",
|
||||||
|
"--chdir", &sandbox,
|
||||||
|
"--",
|
||||||
|
]
|
||||||
|
.map(String::from)
|
||||||
|
.to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
/// The directory name of a child's configuration inside the scratch directory.
|
/// The directory name of a child's configuration inside the scratch directory.
|
||||||
pub(crate) const CONFIG_DIR_NAME: &str = "claude-config";
|
const CONFIG_DIR_NAME: &str = "claude-config";
|
||||||
|
|
||||||
/// One child's configuration directory: made empty (or as the seed) for it,
|
/// One child's configuration directory: made empty (or as the seed) for it,
|
||||||
/// owner-only, and removed when the child's handle goes. Whatever the run writes
|
/// owner-only, and removed when the child's handle goes. Whatever the run writes
|
||||||
|
|
|
||||||
|
|
@ -2026,6 +2026,57 @@ fn a_brief_the_run_claims_is_in_the_task_once_and_not_again_under_also_open() {
|
||||||
assert!(start.contains("Do the claimed thing.") && !start.contains("Also open for you"), "{start}");
|
assert!(start.contains("Do the claimed thing.") && !start.contains("Also open for you"), "{start}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The Persona's boundary: the bubblewrap wrapper `ClaudeSpawner` runs when it has a sandbox.
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod sandbox {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_sandbox_arguments_are_pinned() {
|
||||||
|
let args = sandbox_args(Path::new("/var/lib/mind-x/sandbox"), Path::new("/run/mind-x"));
|
||||||
|
let expected: Vec<String> = [
|
||||||
|
"--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp", "--tmpfs", "/run", "--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve", "--ro-bind", "/run/mind-x", "/run/mind-x", "--bind",
|
||||||
|
"/run/mind-x/claude-config", "/run/mind-x/claude-config", "--tmpfs", "/etc/gamecult", "--tmpfs", "/var/lib", "--bind", "/var/lib/mind-x/sandbox", "/var/lib/mind-x/sandbox", "--unshare-pid", "--die-with-parent", "--new-session", "--chdir", "/var/lib/mind-x/sandbox", "--",
|
||||||
|
]
|
||||||
|
.map(String::from)
|
||||||
|
.to_vec();
|
||||||
|
assert_eq!(args, expected);
|
||||||
|
// The credentials are hidden before the sandbox and the scratch are bound back, and the network is not unshared.
|
||||||
|
let at = |needle: &str| args.iter().position(|arg| arg == needle).unwrap();
|
||||||
|
assert!(at("/run") < at("/run/mind-x") && at("/var/lib") < at("/var/lib/mind-x/sandbox"));
|
||||||
|
// The scratch is read-only to her: no plain bind of it, so she cannot plant a link where the organ writes.
|
||||||
|
assert!(!args.windows(3).any(|w| w[0] == "--bind" && w[1] == "/run/mind-x"), "{args:?}");
|
||||||
|
assert!(!args.iter().any(|arg| arg == "--unshare-net" || arg == "--unshare-all"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_sandboxed_spawner_runs_bwrap_with_its_arguments_then_claude_and_the_child_sees_no_credential() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (bin, scratch, sandbox) = (dir.path().join("bin"), dir.path().join("scratch"), dir.path().join("sandbox"));
|
||||||
|
for made in [&bin, &scratch, &sandbox] {
|
||||||
|
std::fs::create_dir(made).unwrap();
|
||||||
|
}
|
||||||
|
let (argv, environment) = (dir.path().join("argv"), dir.path().join("environment"));
|
||||||
|
let fake = bin.join("bwrap");
|
||||||
|
std::fs::write(&fake, format!("#!/bin/sh\nprintf '%s\n' \"$@\" > {}\nenv > {}\n", argv.display(), environment.display())).unwrap();
|
||||||
|
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
let mut unit: Vec<(std::ffi::OsString, std::ffi::OsString)> = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "UNLISTED_VARIABLE"].iter().map(|name| ((*name).into(), format!("canary-{name}").into())).collect();
|
||||||
|
unit.push(("PATH".into(), format!("{}:/usr/bin:/bin", bin.display()).into()));
|
||||||
|
unit.push((SCRATCH_VARIABLE.into(), scratch.clone().into_os_string()));
|
||||||
|
let spawner = ClaudeSpawner::in_sandbox(unit, "MIND_PERSONA_CONFIG_SEED", Some(sandbox.clone())).unwrap();
|
||||||
|
let mut child = spawner.spawn(&["--flag".to_string(), "value".to_string()], &token_holding("tok-canary"), None).unwrap();
|
||||||
|
while !matches!(child.next(StdDuration::from_secs(20)), Read::Exited(_) | Read::Timeout) {}
|
||||||
|
let recorded: Vec<String> = std::fs::read_to_string(&argv).unwrap().lines().map(String::from).collect();
|
||||||
|
let mut expected = sandbox_args(&sandbox, &scratch);
|
||||||
|
expected.extend(["claude", "--flag", "value"].map(String::from));
|
||||||
|
assert_eq!(recorded, expected, "bwrap, its arguments, then claude and its own");
|
||||||
|
let seen = std::fs::read_to_string(&environment).unwrap();
|
||||||
|
assert!(!seen.contains("canary") && !seen.contains("UNLISTED"), "the child's environment is the allow-list: {seen}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_user_line_with_images_is_a_text_block_then_one_base64_image_block_each_and_without_them_is_the_bare_text() {
|
fn a_user_line_with_images_is_a_text_block_then_one_base64_image_block_each_and_without_them_is_the_bare_text() {
|
||||||
use super::session::user_line;
|
use super::session::user_line;
|
||||||
|
|
|
||||||
|
|
@ -56,8 +56,6 @@ pub(crate) struct Recording {
|
||||||
/// One named instance whose unit never starts.
|
/// One named instance whose unit never starts.
|
||||||
pub(crate) fail_for: RefCell<Option<Slug>>,
|
pub(crate) fail_for: RefCell<Option<Slug>>,
|
||||||
running: RefCell<Vec<(Slug, eureka_pipeline::RunSlot)>>,
|
running: RefCell<Vec<(Slug, eureka_pipeline::RunSlot)>>,
|
||||||
/// A shared order of events: a start puts `start` here, so a store that logs into the same list shows what came first.
|
|
||||||
pub(crate) log: std::rc::Rc<RefCell<Vec<&'static str>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Recording {
|
impl Recording {
|
||||||
|
|
@ -77,7 +75,6 @@ impl Launcher for Recording {
|
||||||
if self.fail.get() || self.fail_for.borrow().as_ref() == Some(instance) {
|
if self.fail.get() || self.fail_for.borrow().as_ref() == Some(instance) {
|
||||||
return Err(anyhow!("refused"));
|
return Err(anyhow!("refused"));
|
||||||
}
|
}
|
||||||
self.log.borrow_mut().push("start");
|
|
||||||
self.started.borrow_mut().push((instance.clone(), turn));
|
self.started.borrow_mut().push((instance.clone(), turn));
|
||||||
self.running.borrow_mut().push((instance.clone(), turn.slot()));
|
self.running.borrow_mut().push((instance.clone(), turn.slot()));
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
@ -127,15 +124,10 @@ impl TestMind {
|
||||||
|
|
||||||
/// Admits as `faculty`, one second after the last admission.
|
/// Admits as `faculty`, one second after the last admission.
|
||||||
pub(crate) fn put_as(&self, faculty: Faculty, documents: Vec<PipelineDocument>) -> PipelineAdmissionOutcome {
|
pub(crate) fn put_as(&self, faculty: Faculty, documents: Vec<PipelineDocument>) -> PipelineAdmissionOutcome {
|
||||||
self.put_by(faculty, "test", "test", documents)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Admits as `faculty`, by `agent` in `session`, one second after the last admission.
|
|
||||||
pub(crate) fn put_by(&self, faculty: Faculty, agent: &str, session: &str, documents: Vec<PipelineDocument>) -> PipelineAdmissionOutcome {
|
|
||||||
self.now.set(self.now.get() + Duration::seconds(1));
|
self.now.set(self.now.get() + Duration::seconds(1));
|
||||||
let batch = PipelineAdmissionBatch {
|
let batch = PipelineAdmissionBatch {
|
||||||
instance: self.instance.clone(),
|
instance: self.instance.clone(),
|
||||||
provenance: PipelineProvenance { faculty, agent: agent.into(), session: session.into(), tool: "test".into(), imported_from: None },
|
provenance: PipelineProvenance { faculty, agent: "test".into(), session: "test".into(), tool: "test".into(), imported_from: None },
|
||||||
documents,
|
documents,
|
||||||
};
|
};
|
||||||
self.mind.borrow_mut().admit(batch, self.now.get())
|
self.mind.borrow_mut().admit(batch, self.now.get())
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ use std::thread::JoinHandle;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use cultnet_rs::{CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions};
|
use cultnet_rs::{CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions};
|
||||||
use mind_body::chat_client::{self, ReplyLink, ReplyViolation, Basis, Form, ChatRefusal, MouthRefused, Refusal, REFUSAL, ACK, Chat, ChatAck, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, DirectOutcome, FetchOutcome, FETCH_RECEIPT, FETCH_REQUEST, ReceiptMode, OPEN_DIRECT_RECEIPT, OPEN_DIRECT_REQUEST, ChatPending, ChatPendingRequest, ChatRead, ChatSendReceipt, ChatSendRequest, PENDING, PENDING_REQUEST, PENDING_REQUEST_V1, PENDING_REQUEST_V4, PENDING_V1, PENDING_V2, PENDING_V4, READ, SEND_RECEIPT, SEND_REQUEST, SEND_REQUEST_V3};
|
use mind_body::chat_client::{self, ReplyLink, ReplyViolation, Basis, Form, ChatRefusal, MouthRefused, Refusal, REFUSAL, ACK, Chat, ChatAck, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, DirectOutcome, FetchOutcome, FETCH_RECEIPT, FETCH_REQUEST, ReceiptMode, OPEN_DIRECT_RECEIPT, OPEN_DIRECT_REQUEST, ChatPending, ChatPendingRequest, ChatRead, ChatSendReceipt, ChatSendRequest, PENDING, PENDING_REQUEST, PENDING_REQUEST_V1, PENDING_REQUEST_V4, PENDING_V1, PENDING_V2, PENDING_V4, READ, SEND_RECEIPT, SEND_REQUEST};
|
||||||
use mind_body::chat_rudp::{RudpChat, connection_id};
|
use mind_body::chat_rudp::{RudpChat, connection_id};
|
||||||
|
|
||||||
const ACK_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v1/gamecult.persona.chat_ack.v1.msgpack");
|
const ACK_BYTES: &[u8] = include_bytes!("fixtures/persona-chat-v1/gamecult.persona.chat_ack.v1.msgpack");
|
||||||
|
|
@ -131,7 +131,6 @@ fn serve(key: &str, bind: &str, pending_kind: &'static str, pending_bytes: &'sta
|
||||||
}
|
}
|
||||||
PENDING_REQUEST_V1 if pending_kind != PENDING && for_eureka(&chat_client::decode::<ChatPendingRequest>(&document.payload).unwrap().persona) => Some(answer(pending_kind, "eureka", pending_bytes)),
|
PENDING_REQUEST_V1 if pending_kind != PENDING && for_eureka(&chat_client::decode::<ChatPendingRequest>(&document.payload).unwrap().persona) => Some(answer(pending_kind, "eureka", pending_bytes)),
|
||||||
SEND_REQUEST if for_eureka(&chat_client::decode::<ChatSendRequest>(&document.payload).unwrap().persona) => Some(answer(SEND_RECEIPT, &document.record_key, SEND_RECEIPT_BYTES)),
|
SEND_REQUEST if for_eureka(&chat_client::decode::<ChatSendRequest>(&document.payload).unwrap().persona) => Some(answer(SEND_RECEIPT, &document.record_key, SEND_RECEIPT_BYTES)),
|
||||||
SEND_REQUEST_V3 => Some(answer(SEND_RECEIPT, &document.record_key, &chat_client::encode(&ChatSendReceipt { request_id: document.record_key.clone(), event_id: None, refusal: Some(Refusal::ResendUnknown), newer: vec![] }).unwrap())),
|
|
||||||
OPEN_DIRECT_REQUEST if for_eureka(&chat_client::decode::<ChatOpenDirectRequest>(&document.payload).unwrap().persona) => Some(answer(open.0, open.1.unwrap_or(&document.record_key), open.2)),
|
OPEN_DIRECT_REQUEST if for_eureka(&chat_client::decode::<ChatOpenDirectRequest>(&document.payload).unwrap().persona) => Some(answer(open.0, open.1.unwrap_or(&document.record_key), open.2)),
|
||||||
FETCH_REQUEST if for_eureka(&chat_client::decode::<ChatFetchRequest>(&document.payload).unwrap().persona) => Some(if open.0 == REFUSAL { answer(open.0, open.1.unwrap_or(&document.record_key), open.2) } else { answer(FETCH_RECEIPT, &document.record_key, FETCH_POSTED_BYTES) }),
|
FETCH_REQUEST if for_eureka(&chat_client::decode::<ChatFetchRequest>(&document.payload).unwrap().persona) => Some(if open.0 == REFUSAL { answer(open.0, open.1.unwrap_or(&document.record_key), open.2) } else { answer(FETCH_RECEIPT, &document.record_key, FETCH_POSTED_BYTES) }),
|
||||||
_ => None,
|
_ => None,
|
||||||
|
|
@ -210,7 +209,7 @@ fn a_request_the_mouth_does_not_answer_ends_in_an_error_not_a_hang() {
|
||||||
let mouth = mouth(KEY);
|
let mouth = mouth(KEY);
|
||||||
let chat = client(&mouth, KEY, "someone-else", Duration::from_millis(600));
|
let chat = client(&mouth, KEY, "someone-else", Duration::from_millis(600));
|
||||||
assert!(chat.pending(0).is_err(), "the mouth answers only its own Persona");
|
assert!(chat.pending(0).is_err(), "the mouth answers only its own Persona");
|
||||||
let sent = ChatSendRequest { request_id: "r".into(), persona: "someone-else".into(), room_alias: "#a:b".into(), text: "x".into(), basis: None, resend: false };
|
let sent = ChatSendRequest { request_id: "r".into(), persona: "someone-else".into(), room_alias: "#a:b".into(), text: "x".into(), basis: None };
|
||||||
assert!(chat.send(&sent).is_err());
|
assert!(chat.send(&sent).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -233,7 +232,7 @@ fn a_client_recovers_from_a_restarted_mouth_on_its_next_call() {
|
||||||
fn a_send_that_timed_out_is_not_repeated_by_the_client() {
|
fn a_send_that_timed_out_is_not_repeated_by_the_client() {
|
||||||
let mouth = mouth(KEY);
|
let mouth = mouth(KEY);
|
||||||
let chat = client(&mouth, KEY, "someone-else", Duration::from_millis(600));
|
let chat = client(&mouth, KEY, "someone-else", Duration::from_millis(600));
|
||||||
let sent = ChatSendRequest { request_id: "r-1".into(), persona: "someone-else".into(), room_alias: "#a:b".into(), text: "x".into(), basis: None, resend: false };
|
let sent = ChatSendRequest { request_id: "r-1".into(), persona: "someone-else".into(), room_alias: "#a:b".into(), text: "x".into(), basis: None };
|
||||||
assert!(chat.send(&sent).is_err());
|
assert!(chat.send(&sent).is_err());
|
||||||
chat.ack(1).unwrap();
|
chat.ack(1).unwrap();
|
||||||
let sends: Vec<_> = mouth.seen.lock().unwrap().iter().filter(|(kind, _)| kind == SEND_REQUEST).map(|(_, payload)| chat_client::decode::<ChatSendRequest>(payload).unwrap().request_id).collect();
|
let sends: Vec<_> = mouth.seen.lock().unwrap().iter().filter(|(kind, _)| kind == SEND_REQUEST).map(|(_, payload)| chat_client::decode::<ChatSendRequest>(payload).unwrap().request_id).collect();
|
||||||
|
|
@ -464,21 +463,3 @@ fn a_fetch_refusal_of_another_reason_or_naming_another_persona_is_not_heard_as_n
|
||||||
let error = client(&mouth, KEY, "eureka", Duration::from_secs(20)).fetch(&request).unwrap_err();
|
let error = client(&mouth, KEY, "eureka", Duration::from_secs(20)).fetch(&request).unwrap_err();
|
||||||
assert!(error.downcast_ref::<MouthRefused>().is_none(), "the payload names another Persona: {error}");
|
assert!(error.downcast_ref::<MouthRefused>().is_none(), "the payload names another Persona: {error}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Soul s8 pins-on-the-wire. A resend crosses the wire as the v3 kind, not the v2 one a mouth would treat as a first send, and the mouth's refusal of it,
|
|
||||||
/// `ResendUnknown`, decodes; a first send is the v2 kind.
|
|
||||||
#[test]
|
|
||||||
fn a_resend_crosses_real_rudp_as_the_v3_kind_and_the_mouths_resend_unknown_decodes() {
|
|
||||||
let mouth = mouth(KEY);
|
|
||||||
let chat = client(&mouth, KEY, "eureka", Duration::from_secs(5));
|
|
||||||
let mut request = chat_client::decode::<ChatSendRequest>(SEND_REQUEST_BYTES).unwrap();
|
|
||||||
request.resend = true;
|
|
||||||
let receipt = chat.send(&request).unwrap();
|
|
||||||
assert_eq!(receipt.refusal, Some(Refusal::ResendUnknown), "the v3 kind reached the mouth and its refusal decoded: {receipt:?}");
|
|
||||||
request.resend = false;
|
|
||||||
assert_eq!(chat.send(&request).unwrap().refusal, None, "a first send is the v2 kind");
|
|
||||||
assert_eq!(kinds_seen(&mouth), [SEND_REQUEST_V3, SEND_REQUEST]);
|
|
||||||
for refusal in Refusal::ALL {
|
|
||||||
assert_eq!(chat_client::decode::<ChatSendReceipt>(&chat_client::encode(&ChatSendReceipt { request_id: "r".into(), event_id: None, refusal: Some(refusal), newer: vec![] }).unwrap()).unwrap().refusal, Some(refusal), "{} decodes", refusal.name());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -62,37 +62,3 @@ fn the_retired_max_turns_flag_is_refused_and_its_value_is_not_echoed() {
|
||||||
assert_eq!(output.status.code(), Some(2), "{stderr}");
|
assert_eq!(output.status.code(), Some(2), "{stderr}");
|
||||||
assert!(stderr.contains("usage") && !stderr.contains("canary-turns"), "{stderr}");
|
assert!(stderr.contains("usage") && !stderr.contains("canary-turns"), "{stderr}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The harness's read-only proof at the binary: with a room fixture and a state file, `project` runs with no persona.env,
|
|
||||||
/// no mouth and the daemon's endpoint unreachable, and never needs them.
|
|
||||||
#[test]
|
|
||||||
fn project_over_a_room_fixture_and_a_state_file_needs_no_daemon_and_no_mouth() {
|
|
||||||
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/harness");
|
|
||||||
let room = fixtures.join("rooms/mind-teases.toml");
|
|
||||||
let state = fixtures.join("states/control.json");
|
|
||||||
let args = ["project", "--instance", "eureka", "--room", room.to_str().unwrap(), "--state", state.to_str().unwrap(), "--select-only"];
|
|
||||||
// Nothing listens on the discard port: a read of her stored state would fail the run.
|
|
||||||
let output = Command::new(env!("CARGO_BIN_EXE_mind-persona")).args(args).env_clear().env("HUGINN_ENDPOINT", "rudp://127.0.0.1:9").env("MIND_PERSONA_TUNING", "/nonexistent/persona-tuning.toml").output().unwrap();
|
|
||||||
assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr));
|
|
||||||
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
|
||||||
assert_eq!((report["state"].as_str(), report["persona_receipt"].is_null()), (Some("given"), true), "{report}");
|
|
||||||
assert!(report["packet"]["name"].as_str().unwrap().starts_with("Tobiah Fenn"), "{report}");
|
|
||||||
assert!(report["packet"]["stimulus"].as_str().unwrap().contains("Said to him"), "Kiko's tagged reply is for him, in his own pronouns: {report}");
|
|
||||||
// Without any endpoint at all it runs the same.
|
|
||||||
let output = Command::new(env!("CARGO_BIN_EXE_mind-persona")).args(args).env_clear().env("MIND_PERSONA_TUNING", "/nonexistent/persona-tuning.toml").output().unwrap();
|
|
||||||
assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_state_file_a_put_would_refuse_is_refused() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/harness");
|
|
||||||
let mut state: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(fixtures.join("states/control.json")).unwrap()).unwrap();
|
|
||||||
state["personaId"] = "libby".into();
|
|
||||||
let file = dir.path().join("foreign.json");
|
|
||||||
std::fs::write(&file, state.to_string()).unwrap();
|
|
||||||
let room = fixtures.join("rooms/quiet-beat.toml");
|
|
||||||
let output = Command::new(env!("CARGO_BIN_EXE_mind-persona")).args(["project", "--instance", "eureka", "--room", room.to_str().unwrap(), "--state", file.to_str().unwrap(), "--select-only"]).env_clear().output().unwrap();
|
|
||||||
assert_eq!(output.status.code(), Some(2));
|
|
||||||
assert!(text(&output.stderr).contains("refused by a put"), "{}", text(&output.stderr));
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@ mind_body: mod lease_client
|
||||||
mind_body: mod persona
|
mind_body: mod persona
|
||||||
mind_body: mod projection
|
mind_body: mod projection
|
||||||
mind_body: mod queue
|
mind_body: mod queue
|
||||||
mind_body: mod sandbox
|
|
||||||
mind_body: mod self_run
|
mind_body: mod self_run
|
||||||
mind_body: mod tempo
|
mind_body: mod tempo
|
||||||
mind_body::address: impl Addressee
|
mind_body::address: impl Addressee
|
||||||
|
|
@ -20,7 +19,7 @@ mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub e
|
||||||
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum DirectOutcome { Opened , Existing , Brake , PersonaMismatch , UnknownPersona , EmptyText , ForeignUser , NotAPerson , NoSuchUser , InvitePending , Declined , DailyLimit , SendFailed , }
|
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum DirectOutcome { Opened , Existing , Brake , PersonaMismatch , UnknownPersona , EmptyText , ForeignUser , NotAPerson , NoSuchUser , InvitePending , Declined , DailyLimit , SendFailed , }
|
||||||
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum FetchOutcome { Stored , StoredUnverified , NotAMember , BridgedRoom , TooLarge , TypeRefused , NoAttachment , HashMismatch , RateLimited , Brake , PersonaMismatch , UnknownPersona , FetchFailed , StoreFailed , }
|
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum FetchOutcome { Stored , StoredUnverified , NotAMember , BridgedRoom , TooLarge , TypeRefused , NoAttachment , HashMismatch , RateLimited , Brake , PersonaMismatch , UnknownPersona , FetchFailed , StoreFailed , }
|
||||||
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum ReceiptMode { Posted , Existing , }
|
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum ReceiptMode { Posted , Existing , }
|
||||||
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Refusal { Brake , PersonaMismatch , UnknownRoom , EmptyText , SendFailed , NotSent , UnknownPersona , RoomMoved , ResendUnknown , UnknownKind , }
|
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Refusal { Brake , PersonaMismatch , UnknownRoom , EmptyText , SendFailed , UnknownPersona , RoomMoved , UnknownKind , }
|
||||||
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum ReplyViolation { NotATriple , BadEventId , BadSenderId , ExcerptNotText , ExcerptTooLong , }
|
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum ReplyViolation { NotATriple , BadEventId , BadSenderId , ExcerptNotText , ExcerptTooLong , }
|
||||||
mind_body::chat_client: # [derive (Clone , Debug , Default , PartialEq , Eq)] pub enum ReplyLink { # [default] Absent , Quote (ReplyTo) , Dropped (ReplyViolation) , }
|
mind_body::chat_client: # [derive (Clone , Debug , Default , PartialEq , Eq)] pub enum ReplyLink { # [default] Absent , Quote (ReplyTo) , Dropped (ReplyViolation) , }
|
||||||
mind_body::chat_client: const ACK : & str
|
mind_body::chat_client: const ACK : & str
|
||||||
|
|
@ -41,7 +40,6 @@ mind_body::chat_client: const REFUSAL : & str
|
||||||
mind_body::chat_client: const REPLY_EXCERPT_CHARS : usize
|
mind_body::chat_client: const REPLY_EXCERPT_CHARS : usize
|
||||||
mind_body::chat_client: const SEND_RECEIPT : & str
|
mind_body::chat_client: const SEND_RECEIPT : & str
|
||||||
mind_body::chat_client: const SEND_REQUEST : & str
|
mind_body::chat_client: const SEND_REQUEST : & str
|
||||||
mind_body::chat_client: const SEND_REQUEST_V3 : & str
|
|
||||||
mind_body::chat_client: fn decode < T : DeserializeOwned > (bytes : & [u8]) -> Result < T >
|
mind_body::chat_client: fn decode < T : DeserializeOwned > (bytes : & [u8]) -> Result < T >
|
||||||
mind_body::chat_client: fn encode < T : Serialize > (document : & T) -> Result < Vec < u8 > >
|
mind_body::chat_client: fn encode < T : Serialize > (document : & T) -> Result < Vec < u8 > >
|
||||||
mind_body::chat_client: fn reply_warnings (pending : & ChatPending , warned : & mut std :: collections :: BTreeSet < String >) -> Vec < String >
|
mind_body::chat_client: fn reply_warnings (pending : & ChatPending , warned : & mut std :: collections :: BTreeSet < String >) -> Vec < String >
|
||||||
|
|
@ -57,7 +55,6 @@ mind_body::chat_client: impl Form: fn name (self) -> & 'static str
|
||||||
mind_body::chat_client: impl ReceiptMode
|
mind_body::chat_client: impl ReceiptMode
|
||||||
mind_body::chat_client: impl ReceiptMode: fn name (self) -> & 'static str
|
mind_body::chat_client: impl ReceiptMode: fn name (self) -> & 'static str
|
||||||
mind_body::chat_client: impl Refusal
|
mind_body::chat_client: impl Refusal
|
||||||
mind_body::chat_client: impl Refusal: const ALL : [Self ; 10]
|
|
||||||
mind_body::chat_client: impl Refusal: fn name (self) -> & 'static str
|
mind_body::chat_client: impl Refusal: fn name (self) -> & 'static str
|
||||||
mind_body::chat_client: impl ReplyLink
|
mind_body::chat_client: impl ReplyLink
|
||||||
mind_body::chat_client: impl ReplyLink: fn quote (& self) -> Option < & ReplyTo >
|
mind_body::chat_client: impl ReplyLink: fn quote (& self) -> Option < & ReplyTo >
|
||||||
|
|
@ -94,12 +91,12 @@ mind_body::chat_client: struct ChatPendingRequest # [derive (Clone , Debug , Par
|
||||||
mind_body::chat_client: struct ChatRead # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, room: String, event_id: String, at_unix_ms: u64]
|
mind_body::chat_client: struct ChatRead # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, room: String, event_id: String, at_unix_ms: u64]
|
||||||
mind_body::chat_client: struct ChatRefusal # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, refusal: Refusal]
|
mind_body::chat_client: struct ChatRefusal # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, refusal: Refusal]
|
||||||
mind_body::chat_client: struct ChatSendReceipt # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, event_id: Option < String >, refusal: Option < Refusal >, newer: Vec < String >]
|
mind_body::chat_client: struct ChatSendReceipt # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, event_id: Option < String >, refusal: Option < Refusal >, newer: Vec < String >]
|
||||||
mind_body::chat_client: struct ChatSendRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, persona: String, room_alias: String, text: String, basis: Option < SendBasis >, resend: bool]
|
mind_body::chat_client: struct ChatSendRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, persona: String, room_alias: String, text: String, basis: Option < SendBasis >]
|
||||||
mind_body::chat_client: struct ContextLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[sender: String, text: String, at_unix_ms: u64]
|
mind_body::chat_client: struct ContextLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[sender: String, text: String, at_unix_ms: u64]
|
||||||
mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub-fields[0: Refusal]
|
mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub-fields[0: Refusal]
|
||||||
mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool]
|
mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >]
|
||||||
mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64]
|
mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64]
|
||||||
mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String, reply_to: ReplyLink]
|
mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String]
|
||||||
mind_body::chat_image: impl Skip
|
mind_body::chat_image: impl Skip
|
||||||
mind_body::chat_rudp: fn connection_id (key_file_text : & str) -> u32
|
mind_body::chat_rudp: fn connection_id (key_file_text : & str) -> u32
|
||||||
mind_body::chat_rudp: impl Chat for RudpChat
|
mind_body::chat_rudp: impl Chat for RudpChat
|
||||||
|
|
@ -110,7 +107,6 @@ mind_body::chat_rudp: impl RudpChat: fn reply_defects (& self) -> usize
|
||||||
mind_body::chat_rudp: impl RudpChat: fn with_reply_link (mut self , on : bool) -> Self
|
mind_body::chat_rudp: impl RudpChat: fn with_reply_link (mut self , on : bool) -> Self
|
||||||
mind_body::chat_rudp: struct RudpChat pub-fields[]
|
mind_body::chat_rudp: struct RudpChat pub-fields[]
|
||||||
mind_body::cli: fn instance_and_endpoint (args : & [String] , env_endpoint : Option < String > , usage : & str) -> Result < (Slug , SocketAddr) >
|
mind_body::cli: fn instance_and_endpoint (args : & [String] , env_endpoint : Option < String > , usage : & str) -> Result < (Slug , SocketAddr) >
|
||||||
mind_body::cli: fn instance_and_maybe_endpoint (args : & [String] , env_endpoint : Option < String > , usage : & str) -> Result < (Slug , Option < SocketAddr >) >
|
|
||||||
mind_body::cli: fn operator_name (sudo_user : Option < String > , user : Option < String >) -> String
|
mind_body::cli: fn operator_name (sudo_user : Option < String > , user : Option < String >) -> String
|
||||||
mind_body::cli: fn run (args : & [String] , root : & Path , set_by : & str , now : DateTime < Utc > , out : & mut impl Write , stop_units : & mut dyn FnMut (StopScope < '_ >) -> Result < () > ,) -> Result < () >
|
mind_body::cli: fn run (args : & [String] , root : & Path , set_by : & str , now : DateTime < Utc > , out : & mut impl Write , stop_units : & mut dyn FnMut (StopScope < '_ >) -> Result < () > ,) -> Result < () >
|
||||||
mind_body::connector: fn render_plan (windows : & [PlanQuota] , _now_ms : u64) -> String
|
mind_body::connector: fn render_plan (windows : & [PlanQuota] , _now_ms : u64) -> String
|
||||||
|
|
@ -152,13 +148,10 @@ mind_body::control: struct SwarmWriter pub-fields[]
|
||||||
mind_body::control: struct UnsafeStore # [derive (Debug)] pub-fields[path: PathBuf, mode: u32, uid: u32]
|
mind_body::control: struct UnsafeStore # [derive (Debug)] pub-fields[path: PathBuf, mode: u32, uid: u32]
|
||||||
mind_body::heartbeat: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Outcome { Held (HeldReason) , Polled { launched : Vec < Slug > , } , }
|
mind_body::heartbeat: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Outcome { Held (HeldReason) , Polled { launched : Vec < Slug > , } , }
|
||||||
mind_body::heartbeat: const DEFAULT_BEAT_S : u32
|
mind_body::heartbeat: const DEFAULT_BEAT_S : u32
|
||||||
mind_body::heartbeat: fn own_rooms_among < 'a > (mind : & dyn MindPort , aliases : impl IntoIterator < Item = & 'a str >) -> Result < Vec < String > >
|
|
||||||
mind_body::heartbeat: fn poll (organs : & Organs , config : & Config) -> Result < Outcome >
|
mind_body::heartbeat: fn poll (organs : & Organs , config : & Config) -> Result < Outcome >
|
||||||
mind_body::heartbeat: fn woken_for (state : & HeartbeatState , slug : & str) -> Vec < String >
|
|
||||||
mind_body::heartbeat: impl Config
|
mind_body::heartbeat: impl Config
|
||||||
mind_body::heartbeat: impl Config: fn new (personas : Vec < PersonaId > , operators : Vec < String > , beat_s : u32) -> Result < Self >
|
mind_body::heartbeat: impl Config: fn new (personas : Vec < PersonaId > , operators : Vec < String > , beat_s : u32) -> Result < Self >
|
||||||
mind_body::heartbeat: impl Control for FileControl
|
mind_body::heartbeat: impl Control for FileControl
|
||||||
mind_body::heartbeat: impl Default for LineFacts
|
|
||||||
mind_body::heartbeat: impl FileStore
|
mind_body::heartbeat: impl FileStore
|
||||||
mind_body::heartbeat: impl FileStore: fn check (& self) -> Result < () >
|
mind_body::heartbeat: impl FileStore: fn check (& self) -> Result < () >
|
||||||
mind_body::heartbeat: impl FileStore: fn latest (& self) -> Result < Option < PollTrace > >
|
mind_body::heartbeat: impl FileStore: fn latest (& self) -> Result < Option < PollTrace > >
|
||||||
|
|
@ -167,23 +160,22 @@ mind_body::heartbeat: impl HeartbeatView for FileStore
|
||||||
mind_body::heartbeat: impl PersonaId
|
mind_body::heartbeat: impl PersonaId
|
||||||
mind_body::heartbeat: impl PersonaId: fn parse (spec : & str) -> Result < Self >
|
mind_body::heartbeat: impl PersonaId: fn parse (spec : & str) -> Result < Self >
|
||||||
mind_body::heartbeat: impl Row < '_ >
|
mind_body::heartbeat: impl Row < '_ >
|
||||||
mind_body::heartbeat: impl Speaker
|
|
||||||
mind_body::heartbeat: impl Store for FileStore
|
mind_body::heartbeat: impl Store for FileStore
|
||||||
mind_body::heartbeat: impl fmt :: Display for Outcome
|
mind_body::heartbeat: impl fmt :: Display for Outcome
|
||||||
mind_body::heartbeat: impl fmt :: Display for PollTrace
|
mind_body::heartbeat: impl fmt :: Display for PollTrace
|
||||||
mind_body::heartbeat: pub trait Control { fn envelope (& self) -> SwarmEffective ; fn effective (& self , instance : & Slug) -> Effective ; }
|
mind_body::heartbeat: pub trait Control { fn envelope (& self) -> SwarmEffective ; fn effective (& self , instance : & Slug) -> Effective ; }
|
||||||
mind_body::heartbeat: pub trait HeartbeatView { fn addressing (& self) -> Result < Option < Addressing > > ; fn written_at (& self) -> Option < DateTime < Utc > > { None } fn woken_for (& self , _slug : & str) -> Result < Vec < String > > { Ok (Vec :: new ()) } }
|
mind_body::heartbeat: pub trait HeartbeatView { fn addressing (& self) -> Result < Option < Addressing > > ; fn written_at (& self) -> Option < DateTime < Utc > > { None } }
|
||||||
mind_body::heartbeat: pub trait Store { fn load (& self) -> Result < Option < HeartbeatState > > ; fn save (& self , state : & HeartbeatState) -> Result < () > ; fn record (& self , trace : & PollTrace) -> Result < () > ; fn load_addressing (& self) -> Result < Option < Addressing > > ; fn save_addressing (& self , addressing : & Addressing) -> Result < () > ; }
|
mind_body::heartbeat: pub trait Store { fn load (& self) -> Result < Option < HeartbeatState > > ; fn save (& self , state : & HeartbeatState) -> Result < () > ; fn record (& self , trace : & PollTrace) -> Result < () > ; fn load_addressing (& self) -> Result < Option < Addressing > > ; fn save_addressing (& self , addressing : & Addressing) -> Result < () > ; }
|
||||||
mind_body::heartbeat: struct Addressing # [derive (Clone , Debug , Default , PartialEq , Eq , DatabaseEntry)] pub-fields[minds: Vec < Addressee >]
|
mind_body::heartbeat: struct Addressing # [derive (Clone , Debug , Default , PartialEq , Eq , DatabaseEntry)] pub-fields[minds: Vec < Addressee >]
|
||||||
mind_body::heartbeat: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[personas: Vec < PersonaId >, operators: Vec < String >, beat_s: u32]
|
mind_body::heartbeat: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[personas: Vec < PersonaId >, operators: Vec < String >, beat_s: u32]
|
||||||
mind_body::heartbeat: struct FileControl pub-fields[]
|
mind_body::heartbeat: struct FileControl pub-fields[]
|
||||||
mind_body::heartbeat: struct FileStore pub-fields[]
|
mind_body::heartbeat: struct FileStore pub-fields[]
|
||||||
mind_body::heartbeat: struct HeartbeatState # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[last_beat_at: DateTime < Utc >, handled_mentions: Vec < String >, last_turn_at: BTreeMap < String , DateTime < Utc > >, retired_slot_3: BTreeMap < String , u32 >]
|
mind_body::heartbeat: struct HeartbeatState # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[last_beat_at: DateTime < Utc >, handled_mentions: Vec < String >, last_turn_at: BTreeMap < String , DateTime < Utc > >]
|
||||||
mind_body::heartbeat: struct InstanceTrace # [derive (Clone , Debug , PartialEq , Eq , serde :: Serialize , serde :: Deserialize)] pub-fields[instance: String, vote_beat_s: Option < u32 >, urgency_permille: u16, addressed: bool, busy: bool, released: bool, idle_s: i64, score: String, note: String]
|
mind_body::heartbeat: struct InstanceTrace # [derive (Clone , Debug , PartialEq , Eq , serde :: Serialize , serde :: Deserialize)] pub-fields[instance: String, vote_beat_s: Option < u32 >, urgency_permille: u16, addressed: bool, busy: bool, released: bool, idle_s: i64, score: String, note: String]
|
||||||
mind_body::heartbeat: struct Organs< 'a > pub-fields[seats: & 'a [Seat < 'a >], control: & 'a dyn Control, launcher: & 'a dyn Launcher, clock: & 'a dyn Clock, store: & 'a dyn Store]
|
mind_body::heartbeat: struct Organs< 'a > pub-fields[seats: & 'a [Seat < 'a >], control: & 'a dyn Control, launcher: & 'a dyn Launcher, clock: & 'a dyn Clock, store: & 'a dyn Store]
|
||||||
mind_body::heartbeat: struct PersonaId # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[slug: Slug, public_name: String, handle: String, matrix_id: String, huginn: SocketAddr]
|
mind_body::heartbeat: struct PersonaId # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[slug: Slug, public_name: String, handle: String, matrix_id: String, huginn: SocketAddr]
|
||||||
mind_body::heartbeat: struct PollTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[at: DateTime < Utc >, tempo_s: u32, instances: Vec < InstanceTrace >, launches: Vec < String >]
|
mind_body::heartbeat: struct PollTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[at: DateTime < Utc >, tempo_s: u32, instances: Vec < InstanceTrace >, launches: Vec < String >]
|
||||||
mind_body::heartbeat: struct Seat< 'a > pub-fields[who: PersonaId, mind: & 'a dyn MindPort, chat: & 'a dyn Chat, trace: & 'a dyn TraceView]
|
mind_body::heartbeat: struct Seat< 'a > pub-fields[who: PersonaId, mind: & 'a dyn MindPort, chat: & 'a dyn Chat]
|
||||||
mind_body::launch: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum StopScope < 'a > { Mind (& 'a Slug) , Swarm , }
|
mind_body::launch: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum StopScope < 'a > { Mind (& 'a Slug) , Swarm , }
|
||||||
mind_body::launch: impl Clock for SystemClock
|
mind_body::launch: impl Clock for SystemClock
|
||||||
mind_body::launch: impl Default for SystemdLauncher
|
mind_body::launch: impl Default for SystemdLauncher
|
||||||
|
|
@ -218,209 +210,72 @@ mind_body::lease_client: struct LeaseRequest # [derive (Clone , Debug , PartialE
|
||||||
mind_body::lease_client: struct SocketLender pub-fields[]
|
mind_body::lease_client: struct SocketLender pub-fields[]
|
||||||
mind_body::lease_client: struct TokenFd pub-fields[]
|
mind_body::lease_client: struct TokenFd pub-fields[]
|
||||||
mind_body::lease_client::socket: impl Lease for Granted
|
mind_body::lease_client::socket: impl Lease for Granted
|
||||||
mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , Drained { wakes : usize , acked_through : Option < u64 > } , Failed (String) , }
|
mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , NoOrgan , }
|
||||||
mind_body::persona: const AGENT : & str
|
mind_body::persona: const AGENT : & str
|
||||||
mind_body::persona: const ENV_MINDS : & str
|
mind_body::persona: const ENV_MINDS : & str
|
||||||
mind_body::persona: const ENV_MODEL : & str
|
mind_body::persona: const ENV_MODEL : & str
|
||||||
mind_body::persona: const ENV_OPERATOR : & str
|
mind_body::persona: const ENV_OPERATOR : & str
|
||||||
mind_body::persona: const ENV_REVIEW_ROOM : & str
|
|
||||||
mind_body::persona: const ENV_ROOMS : & str
|
mind_body::persona: const ENV_ROOMS : & str
|
||||||
mind_body::persona: const ENV_SELF_SENDER : & str
|
mind_body::persona: const ENV_SELF_SENDER : & str
|
||||||
mind_body::persona: fn carry < C : Chat > (control : & impl ControlSource , swarm : & impl ControlSource , instance : & Slug , build : impl FnOnce () -> Result < Start < C > >) -> Outcome
|
mind_body::persona: fn carry (control : & impl ControlSource , swarm : & impl ControlSource , instance : & Slug) -> Outcome
|
||||||
mind_body::persona: fn trace_lines (trace : & dyn TraceView , last : usize) -> Result < Vec < String > >
|
|
||||||
mind_body::persona: impl Config
|
mind_body::persona: impl Config
|
||||||
mind_body::persona: impl Config: fn from_args (args : & [String] , usage : & str) -> Result < (Self , Vec < String >) >
|
mind_body::persona: impl Config: fn from_args (args : & [String] , usage : & str) -> Result < (Self , Vec < String >) >
|
||||||
mind_body::persona: impl Config: fn from_args_and_env (args : & [String] , lookup : impl Fn (& str) -> Option < String > , usage : & str) -> Result < (Self , Vec < String >) >
|
mind_body::persona: impl Config: fn from_args_and_env (args : & [String] , lookup : impl Fn (& str) -> Option < String > , usage : & str) -> Result < (Self , Vec < String >) >
|
||||||
mind_body::persona: impl Conversation
|
mind_body::persona: impl Conversation
|
||||||
mind_body::persona: impl FileTrace
|
mind_body::persona: impl FileTrace
|
||||||
mind_body::persona: impl FileTrace: fn new (path : impl Into < PathBuf >) -> Self
|
mind_body::persona: impl FileTrace: fn new (path : impl Into < PathBuf >) -> Self
|
||||||
mind_body::persona: impl PersonaStore for HuginnPersonaSource
|
|
||||||
mind_body::persona: impl Sender
|
mind_body::persona: impl Sender
|
||||||
mind_body::persona: impl Trace for FileTrace
|
mind_body::persona: impl Trace for FileTrace
|
||||||
mind_body::persona: impl TraceSnapshot
|
|
||||||
mind_body::persona: impl TraceSnapshot: fn new (path : impl Into < PathBuf >) -> Self
|
|
||||||
mind_body::persona: impl TraceView for FileTrace
|
|
||||||
mind_body::persona: impl TraceView for TraceSnapshot
|
|
||||||
mind_body::persona: impl fmt :: Display for Outcome
|
mind_body::persona: impl fmt :: Display for Outcome
|
||||||
mind_body::persona: pub trait Trace : TraceView { fn record (& self , key : & str , record : & Value) -> Result < () > ; }
|
mind_body::persona: pub trait Trace { fn record (& self , trace : & TurnTrace) -> Result < () > ; }
|
||||||
mind_body::persona: pub trait TraceView { fn records (& self) -> Result < Vec < Value > > ; }
|
mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String]
|
||||||
mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String, review_room: Option < String >]
|
|
||||||
mind_body::persona: struct FileTrace pub-fields[]
|
mind_body::persona: struct FileTrace pub-fields[]
|
||||||
mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, agent: Box < dyn Steps >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, session: PathBuf, box_socket: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >]
|
mind_body::persona: struct TraceItem # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[provenance: String, room: String, text: String]
|
||||||
mind_body::persona: struct TraceSnapshot pub-fields[]
|
mind_body::persona: struct TurnTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[run: String, turn: u32, at: DateTime < Utc >, inputs: Vec < TraceItem >, outputs: Vec < TraceItem >, outcome: String]
|
||||||
mind_body::persona: struct TurnRecord # [derive (Clone , Debug , PartialEq , DatabaseEntry)] pub-fields[value: Value]
|
|
||||||
mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , }
|
|
||||||
mind_body::projection: # [derive (Debug , PartialEq , Eq)] pub enum Put { Committed , Stale , Refused (String) , }
|
|
||||||
mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value >
|
mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value >
|
||||||
mind_body::projection: impl HuginnPersonaSource
|
mind_body::projection: impl HuginnPersonaSource
|
||||||
mind_body::projection: impl HuginnPersonaSource: fn new (client : HuginnClient) -> Self
|
mind_body::projection: impl HuginnPersonaSource: fn new (client : HuginnClient) -> Self
|
||||||
mind_body::projection: impl PersonaSource for HuginnPersonaSource
|
mind_body::projection: impl PersonaSource for HuginnPersonaSource
|
||||||
mind_body::projection: impl< T : Chat > MouthReader for T
|
mind_body::projection: impl< T : Chat > MouthReader for T
|
||||||
mind_body::projection: mod agent
|
|
||||||
mind_body::projection: mod harness
|
|
||||||
mind_body::projection: pub trait MouthReader { fn pending (& self) -> Result < ChatPending > ; }
|
mind_body::projection: pub trait MouthReader { fn pending (& self) -> Result < ChatPending > ; }
|
||||||
mind_body::projection: pub trait PersonaSource { fn persona (& self) -> Result < (Value , String) > ; }
|
mind_body::projection: pub trait PersonaSource { fn persona (& self) -> Result < (Value , String) > ; }
|
||||||
mind_body::projection: pub trait PersonaStore : PersonaSource { fn put (& self , state : & Value , expected_updated_at : Option < & str > , session : & str) -> Result < Put > ; }
|
mind_body::projection: pub use narrate :: { Answer , Failed , KitModel , Model , Spent , connector_key } ;
|
||||||
mind_body::projection: pub use domain :: { DomainFacts , DomainSource , HttpForge , MindDomain } ;
|
|
||||||
mind_body::projection: pub use narrate :: { Answer , Failed , KitModel , Model , Spent , StepRequest , Stepped , ToolCall , connector_key } ;
|
|
||||||
mind_body::projection: pub use read :: { LiveReads , ReadFailure , ReadFixture , ReadRequest , ReadSource } ;
|
|
||||||
mind_body::projection: pub use select :: TurnKind ;
|
mind_body::projection: pub use select :: TurnKind ;
|
||||||
mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ;
|
mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ;
|
||||||
mind_body::projection: struct HuginnPersonaSource pub-fields[]
|
mind_body::projection: struct HuginnPersonaSource pub-fields[]
|
||||||
mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >, domain: Option < & 'a dyn DomainSource >, reads: Option < & 'a dyn ReadSource >]
|
mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >]
|
||||||
mind_body::projection: struct Request # [derive (Clone)] pub-fields[instance: String, kind: TurnKind, state: Option < Value >, rooms: Vec < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >, woken_for: Vec < String >, told: Vec < Value >, tools: Vec < String >, last_wake: Option < DateTime < Utc > >, records: Vec < Value >]
|
mind_body::projection: struct Request pub-fields[instance: String, kind: TurnKind, state: Option < Value >, room: Option < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf]
|
||||||
mind_body::projection::agent: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize)] # [serde (rename_all = "snake_case")] pub enum Status { Ok , Refused , Error , Unknown , NotSent , Cap , }
|
|
||||||
mind_body::projection::agent: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cap { ToolCalls , ModelCalls , WakeSpend , DaySpend , }
|
|
||||||
mind_body::projection::agent: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Ended { EndTurn , Cap (Cap) , Failed (Failed) , }
|
|
||||||
mind_body::projection::agent: fn instructions (name : & str) -> String
|
|
||||||
mind_body::projection::agent: fn step (agent : & Agent < '_ > , wake : & Wake < '_ >) -> Result < Turn >
|
|
||||||
mind_body::projection::agent: impl Cap
|
|
||||||
mind_body::projection::agent: impl FileSession
|
|
||||||
mind_body::projection::agent: impl FileSession: fn discard (& self) -> Result < () >
|
|
||||||
mind_body::projection::agent: impl FileSession: fn load (& self) -> Result < Option < Session > >
|
|
||||||
mind_body::projection::agent: impl FileSession: fn new (path : impl Into < PathBuf >) -> Self
|
|
||||||
mind_body::projection::agent: impl FileSession: fn save (& self , session : & Session) -> Result < () >
|
|
||||||
mind_body::projection::agent: impl Ledger for TraceLedger < '_ >
|
|
||||||
mind_body::projection::agent: impl Receipt
|
|
||||||
mind_body::projection::agent: impl Receipt: fn fields (& self) -> & Map < String , Value >
|
|
||||||
mind_body::projection::agent: impl Receipt: fn json (& self) -> Value
|
|
||||||
mind_body::projection::agent: impl Receipt: fn new (tool : impl Into < String > , status : Status , fields : Value) -> Self
|
|
||||||
mind_body::projection::agent: impl Receipt: fn status (& self) -> Status
|
|
||||||
mind_body::projection::agent: impl Receipt: fn tool (& self) -> & str
|
|
||||||
mind_body::projection::agent: impl Run < '_ >
|
|
||||||
mind_body::projection::agent: impl Steps for KitModel
|
|
||||||
mind_body::projection::agent: impl TraceLedger < 'a >: fn new (trace : & 'a dyn Trace , stem : impl Into < String >) -> Self
|
|
||||||
mind_body::projection::agent: impl< 'a > TraceLedger < 'a >
|
|
||||||
mind_body::projection::agent: impl< T : Steps + ? Sized > Steps for std :: rc :: Rc < T >
|
|
||||||
mind_body::projection::agent: pub trait Executor { fn definitions (& self) -> Vec < ToolDefinition > ; fn run (& self , call : & ToolCall) -> Receipt ; }
|
|
||||||
mind_body::projection::agent: pub trait Ledger { fn rows (& self) -> Result < Vec < Value > > ; fn append (& self , row : Value) -> Result < u64 > ; }
|
|
||||||
mind_body::projection::agent: pub trait Steps { fn step (& self , request : StepRequest < '_ >) -> std :: result :: Result < Stepped , Failed > ; }
|
|
||||||
mind_body::projection::agent: struct Agent< 'a > pub-fields[model: & 'a dyn Steps, session: & 'a FileSession, executors: & 'a [& 'a dyn Executor], ledger: & 'a dyn Ledger, bounds: & 'a AgentTuning, clock: & 'a dyn Fn () -> DateTime < Utc >]
|
|
||||||
mind_body::projection::agent: struct FileSession pub-fields[]
|
|
||||||
mind_body::projection::agent: struct Receipt # [derive (Clone , Debug , PartialEq)] pub-fields[]
|
|
||||||
mind_body::projection::agent: struct Session # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[items: Vec < InputItem >, digest: String, retention: CacheRetention, created_at: DateTime < Utc >, last_call_at: DateTime < Utc >, last_usage: Option < Spent >]
|
|
||||||
mind_body::projection::agent: struct TraceLedger< 'a > pub-fields[]
|
|
||||||
mind_body::projection::agent: struct Turn # [derive (Clone , Debug , PartialEq)] pub-fields[ended: Ended, text: String, receipts: Vec < Receipt >, model_calls: usize, tool_calls: usize, usd: f64]
|
|
||||||
mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, instructions: & 'a str, input: & 'a str, fresh: & 'a str]
|
|
||||||
mind_body::projection::agent::read: impl Executor for Read < '_ >
|
|
||||||
mind_body::projection::agent::read: struct Read< 'a > pub-fields[source: Option < & 'a dyn ReadSource >, since: DateTime < Utc >]
|
|
||||||
mind_body::projection::agent::request_tool: impl Executor for RequestTool
|
|
||||||
mind_body::projection::agent::request_tool: struct RequestTool pub-fields[]
|
|
||||||
mind_body::projection::agent::say: impl Executor for Say < '_ >
|
|
||||||
mind_body::projection::agent::say: impl Mouth < '_ >
|
|
||||||
mind_body::projection::agent::say: impl Say < '_ >
|
|
||||||
mind_body::projection::agent::say: struct Say< 'a > pub-fields[]
|
|
||||||
mind_body::projection::agent::shell: impl Executor for Shell
|
|
||||||
mind_body::projection::agent::shell: struct Shell pub-fields[socket: PathBuf]
|
|
||||||
mind_body::projection::commit: impl Commit < '_ >
|
|
||||||
mind_body::projection::commit: impl Heard
|
|
||||||
mind_body::projection::domain: impl DomainSource for DomainFacts
|
|
||||||
mind_body::projection::domain: impl DomainSource for MindDomain
|
|
||||||
mind_body::projection::domain: impl ForgeGet for HttpForge
|
|
||||||
mind_body::projection::domain: impl HttpForge
|
|
||||||
mind_body::projection::domain: impl HttpForge: fn new (base_url : & str) -> Self
|
|
||||||
mind_body::projection::domain: impl MindDomain
|
|
||||||
mind_body::projection::domain: impl MindDomain: fn new (client : HuginnClient , forge : HttpForge) -> Self
|
|
||||||
mind_body::projection::domain: impl Names
|
|
||||||
mind_body::projection::domain: pub trait DomainSource { fn read (& self , since : DateTime < Utc > , now : DateTime < Utc >) -> Result < DomainFacts > ; fn stewarded (& self) -> Result < Vec < String > > { Ok (Vec :: new ()) } }
|
|
||||||
mind_body::projection::domain: struct DomainFacts # [derive (Clone , Debug , Default , PartialEq , Eq , Serialize , Deserialize)] pub-fields[]
|
|
||||||
mind_body::projection::domain: struct HttpForge pub-fields[]
|
|
||||||
mind_body::projection::domain: struct MindDomain pub-fields[]
|
|
||||||
mind_body::projection::harness: fn batch (harness : & Harness , plan_path : & Path) -> Result < String >
|
|
||||||
mind_body::projection::harness: fn fixture_request (harness : & Harness , fixture : & Fixture , state : Option < Value > , seed : u64 , renders : Option < usize > , through : Through) -> Request
|
|
||||||
mind_body::projection::harness: fn state_file (path : & Path , instance : & str) -> Result < Value >
|
|
||||||
mind_body::projection::harness: impl Fixture
|
|
||||||
mind_body::projection::harness: impl Fixture: fn addressee (& self) -> Option < & dyn HeartbeatView >
|
|
||||||
mind_body::projection::harness: impl Fixture: fn domain (& self) -> Option < & dyn DomainSource >
|
|
||||||
mind_body::projection::harness: impl Fixture: fn load (path : & Path) -> Result < Self >
|
|
||||||
mind_body::projection::harness: impl Fixture: fn parse (text : & str) -> Result < Self >
|
|
||||||
mind_body::projection::harness: impl Fixture: fn reads (& self) -> Option < & dyn ReadSource >
|
|
||||||
mind_body::projection::harness: impl HeartbeatView for Fixture
|
|
||||||
mind_body::projection::harness: impl Line
|
|
||||||
mind_body::projection::harness: impl MouthReader for Fixture
|
|
||||||
mind_body::projection::harness: pub use super :: simulate :: simulate ;
|
|
||||||
mind_body::projection::harness: struct Fixture # [derive (Clone , Debug)] pub-fields[her: String, names: Vec < String >, kind: TurnKind, now: DateTime < Utc >, here: Option < String >, operators: Vec < String >, minds: Vec < String >, last_heard: Vec < (String , u64) >]
|
|
||||||
mind_body::projection::harness: struct Harness< 'a > pub-fields[instance: String, persona: Option < & 'a dyn PersonaSource >, model: Option < & 'a dyn Model >, tuning: PathBuf]
|
|
||||||
mind_body::projection::harness: struct Message # [derive (Clone , Debug , Deserialize)] pub-fields[from: String, name: String, room: String, ago: Option < String >, round: Option < usize >, says: String, new: bool, tag: bool, mentions: Vec < String >, dm: bool, to: Option < String >, follow_up: bool, reply_to: Option < usize >]
|
|
||||||
mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String >
|
mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String >
|
||||||
mind_body::projection::narrate: impl Failed
|
mind_body::projection::narrate: impl Failed
|
||||||
mind_body::projection::narrate: impl KitModel
|
mind_body::projection::narrate: impl KitModel
|
||||||
mind_body::projection::narrate: impl KitModel: fn open (endpoint : SocketAddr , connection_key : String , caller : & str , timeout : Duration) -> Result < Self >
|
mind_body::projection::narrate: impl KitModel: fn open (endpoint : SocketAddr , connection_key : String , caller : & str , timeout : Duration) -> Result < Self >
|
||||||
mind_body::projection::narrate: impl KitModel: fn step (& self , request : StepRequest < '_ >) -> std :: result :: Result < Stepped , Failed >
|
|
||||||
mind_body::projection::narrate: impl Model for KitModel
|
mind_body::projection::narrate: impl Model for KitModel
|
||||||
mind_body::projection::narrate: impl std :: fmt :: Display for Failed
|
mind_body::projection::narrate: impl std :: fmt :: Display for Failed
|
||||||
mind_body::projection::narrate: impl< T : Model + ? Sized > Model for std :: rc :: Rc < T >
|
mind_body::projection::narrate: pub trait Model { fn ask (& self , request_id : & str , model : & str , prompt : & str) -> std :: result :: Result < Answer , Failed > ; }
|
||||||
mind_body::projection::narrate: pub trait Model { fn ask (& self , request_id : & str , model : & str , prompt : & str , schema : Option < & str >) -> std :: result :: Result < Answer , Failed > ; }
|
|
||||||
mind_body::projection::narrate: struct Answer # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[text: String, usage: Option < Spent >]
|
mind_body::projection::narrate: struct Answer # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[text: String, usage: Option < Spent >]
|
||||||
mind_body::projection::narrate: struct Failed # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[reason: String, outage: bool, usage: Option < Spent >]
|
mind_body::projection::narrate: struct Failed # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[reason: String, usage: Option < Spent >]
|
||||||
mind_body::projection::narrate: struct KitModel pub-fields[]
|
mind_body::projection::narrate: struct KitModel pub-fields[]
|
||||||
mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >]
|
mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >]
|
||||||
mind_body::projection::narrate: struct StepRequest< 'a > pub-fields[request_id: & 'a str, conversation_id: & 'a str, model: & 'a str, instructions: & 'a str, tools: & 'a [ToolDefinition], input: Vec < InputItem >, retention: Option < CacheRetention >, schema: Option < & 'a str >]
|
mind_body::projection::select: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize)] # [serde (rename_all = "snake_case")] pub enum TurnKind { Chat , Beat , FollowUp , Reflection , }
|
||||||
mind_body::projection::narrate: struct Stepped # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[items: Vec < InputItem >, text: String, calls: Vec < ToolCall >, stop: StopReason, usage: Spent]
|
|
||||||
mind_body::projection::narrate: struct ToolCall # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[call_id: String, name: String, arguments: String]
|
|
||||||
mind_body::projection::outcome: impl Outcome
|
|
||||||
mind_body::projection::outcome: impl Part
|
|
||||||
mind_body::projection::outcome::form: impl EventPhrase
|
|
||||||
mind_body::projection::outcome::form: impl Form < '_ >
|
|
||||||
mind_body::projection::outcome::form: impl Name
|
|
||||||
mind_body::projection::outcome::form: impl ReadName
|
|
||||||
mind_body::projection::outcome::form: impl Words
|
|
||||||
mind_body::projection::outcome::form: impl std :: fmt :: Debug for Words
|
|
||||||
mind_body::projection::read: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (rename_all = "snake_case")] pub enum ReadFailure { NotFound , Private , TooLarge , Failed , }
|
|
||||||
mind_body::projection::read: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "kind" , content = "target" , rename_all = "snake_case" , deny_unknown_fields)] pub enum ReadRequest { Mind (String) , Campaign (String) , Repo (String) , Web (String) , }
|
|
||||||
mind_body::projection::read: impl LiveReads
|
|
||||||
mind_body::projection::read: impl LiveReads: fn new (client : HuginnClient , forge : Option < HttpForge >) -> Self
|
|
||||||
mind_body::projection::read: impl ReadFailure
|
|
||||||
mind_body::projection::read: impl ReadFixture
|
|
||||||
mind_body::projection::read: impl ReadRequest
|
|
||||||
mind_body::projection::read: impl ReadRequest: fn from_target (kind : & str , target : & str) -> Result < Self , String >
|
|
||||||
mind_body::projection::read: impl ReadSource for LiveReads
|
|
||||||
mind_body::projection::read: impl ReadSource for ReadFixture
|
|
||||||
mind_body::projection::read: pub trait ReadSource { fn read (& self , request : & ReadRequest , since : DateTime < Utc >) -> Result < String , ReadFailure > ; }
|
|
||||||
mind_body::projection::read: struct LiveReads pub-fields[]
|
|
||||||
mind_body::projection::read: struct ReadFixture # [derive (Clone , Debug , Default , PartialEq , Eq , Deserialize)] pub-fields[]
|
|
||||||
mind_body::projection::select: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum TurnKind { Chat , Beat , FollowUp , Reflection , }
|
|
||||||
mind_body::projection::select: impl Addressed < '_ >
|
mind_body::projection::select: impl Addressed < '_ >
|
||||||
mind_body::projection::select: impl Context
|
|
||||||
mind_body::projection::select: impl Draw
|
mind_body::projection::select: impl Draw
|
||||||
mind_body::projection::select: impl Lens
|
mind_body::projection::select: impl Lens
|
||||||
mind_body::projection::select: impl Lines
|
mind_body::projection::select: impl Lines
|
||||||
mind_body::projection::select: impl Packet
|
|
||||||
mind_body::projection::select: impl People < '_ >
|
mind_body::projection::select: impl People < '_ >
|
||||||
mind_body::projection::select: impl RoomKind
|
|
||||||
mind_body::projection::select: impl Section
|
|
||||||
mind_body::projection::select: impl std :: fmt :: Display for Who
|
|
||||||
mind_body::projection::select: impl< 'a > Inputs < 'a >
|
|
||||||
mind_body::projection::simulate: fn simulate (harness : & Harness , plan_path : & Path) -> Result < String >
|
|
||||||
mind_body::projection::simulate: impl HeartbeatView for Names < '_ >
|
|
||||||
mind_body::projection::simulate: impl MouthReader for View < '_ >
|
|
||||||
mind_body::projection::simulate: impl ReadSource for CastReads < '_ >
|
|
||||||
mind_body::projection::tuning: const TUNING_FILE : & str
|
mind_body::projection::tuning: const TUNING_FILE : & str
|
||||||
mind_body::projection::tuning: const TUNING_ROOT : & str
|
mind_body::projection::tuning: const TUNING_ROOT : & str
|
||||||
mind_body::projection::tuning: fn load (path : & Path) -> Result < Loaded >
|
mind_body::projection::tuning: fn load (path : & Path) -> Result < Loaded >
|
||||||
mind_body::projection::tuning: impl AgentTuning
|
|
||||||
mind_body::projection::tuning: impl Default for AgentTuning
|
|
||||||
mind_body::projection::tuning: impl Default for CacheTtl
|
|
||||||
mind_body::projection::tuning: impl Default for InterpreterTuning
|
|
||||||
mind_body::projection::tuning: impl Default for LensWeights
|
mind_body::projection::tuning: impl Default for LensWeights
|
||||||
mind_body::projection::tuning: impl Default for PersonaTuning
|
|
||||||
mind_body::projection::tuning: impl Default for PoolCaps
|
mind_body::projection::tuning: impl Default for PoolCaps
|
||||||
mind_body::projection::tuning: impl Default for ProjectorTuning
|
mind_body::projection::tuning: impl Default for ProjectorTuning
|
||||||
mind_body::projection::tuning: impl Default for SelectTuning
|
mind_body::projection::tuning: impl Default for SelectTuning
|
||||||
mind_body::projection::tuning: impl Default for Tuning
|
|
||||||
mind_body::projection::tuning: impl Price
|
|
||||||
mind_body::projection::tuning: impl Tuning
|
mind_body::projection::tuning: impl Tuning
|
||||||
mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >]
|
|
||||||
mind_body::projection::tuning: struct CacheTtl # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[short: u64, long: u64]
|
|
||||||
mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String]
|
|
||||||
mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64]
|
mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64]
|
||||||
mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String]
|
mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String]
|
||||||
mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize]
|
mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[memories_about_present: usize, other_memories: usize, needs: usize, incubation: usize, stance: usize, value: usize, said: usize]
|
||||||
mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[memories_about_present: usize, other_memories: usize, needs: usize, incubation: usize, stance: usize, value: usize]
|
|
||||||
mind_body::projection::tuning: struct Price # [derive (Clone , Copy , Debug , PartialEq , Serialize , Deserialize)] pub-fields[input: f64, output: f64, cache_read: f64, cache_write_short: f64, cache_write_long: f64]
|
|
||||||
mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize]
|
mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize]
|
||||||
mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, notes_bytes: usize, here_bytes: usize, outcome_bytes: usize, domain_bytes: usize, exchange_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, body_bytes: usize, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps]
|
mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, context_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, memory_tau_h: f64, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, caps: PoolCaps]
|
||||||
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, agent: AgentTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >]
|
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , Default , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, select: SelectTuning, lens: LensWeights]
|
||||||
mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held >
|
mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held >
|
||||||
mind_body::queue: impl Held
|
mind_body::queue: impl Held
|
||||||
mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool
|
mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool
|
||||||
|
|
@ -432,9 +287,6 @@ mind_body::queue: impl< 'a > HuginnMind < 'a >
|
||||||
mind_body::queue: pub trait MindPort { fn instance (& self) -> & Slug ; fn query (& self , selection : & Selection) -> Result < PipelineSelectionPage > ; fn query_near (& self , _selection : & Selection , _text : & str , _top_k : u32) -> Result < PipelineSelectionPage > { bail ! ("this mind port has no semantic index") } fn stewarded_activity (& self , _repos : & [OrgRepo] , _after : Option < u64 >) -> Result < RepoActivity > { bail ! ("this mind port has no forge to read") } fn roots_touched (& self) -> Result < Vec < RootTouched > > { bail ! ("this mind port has no roots to read") } fn admit (& self , agent : & str , session : & str , documents : Vec < PipelineDocument >) -> Result < PipelineAdmissionOutcome > ; }
|
mind_body::queue: pub trait MindPort { fn instance (& self) -> & Slug ; fn query (& self , selection : & Selection) -> Result < PipelineSelectionPage > ; fn query_near (& self , _selection : & Selection , _text : & str , _top_k : u32) -> Result < PipelineSelectionPage > { bail ! ("this mind port has no semantic index") } fn stewarded_activity (& self , _repos : & [OrgRepo] , _after : Option < u64 >) -> Result < RepoActivity > { bail ! ("this mind port has no forge to read") } fn roots_touched (& self) -> Result < Vec < RootTouched > > { bail ! ("this mind port has no roots to read") } fn admit (& self , agent : & str , session : & str , documents : Vec < PipelineDocument >) -> Result < PipelineAdmissionOutcome > ; }
|
||||||
mind_body::queue: struct Held # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[]
|
mind_body::queue: struct Held # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[]
|
||||||
mind_body::queue: struct HuginnMind< 'a > pub-fields[]
|
mind_body::queue: struct HuginnMind< 'a > pub-fields[]
|
||||||
mind_body::sandbox: const COMMONS_RW : [& str ; 2]
|
|
||||||
mind_body::sandbox: fn serve_box (mut input : impl Read , mut output : impl Write , paths : & BoxPaths < '_ >) -> std :: io :: Result < () >
|
|
||||||
mind_body::sandbox: struct BoxPaths< 'a > pub-fields[home: & 'a Path, scratch: & 'a Path, extra_rw: & 'a [& 'a Path]]
|
|
||||||
mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq , PartialOrd , Ord)] pub enum Stop { Interrupt , Terminate , Kill , }
|
mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq , PartialOrd , Ord)] pub enum Stop { Interrupt , Terminate , Kill , }
|
||||||
mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cause { Own , FlushRequested , Signalled (Stop) , Unstoppable , }
|
mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cause { Own , FlushRequested , Signalled (Stop) , Unstoppable , }
|
||||||
mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Read { Line (String) , Timeout , Eof , Exited (Option < i32 >) , }
|
mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Read { Line (String) , Timeout , Eof , Exited (Option < i32 >) , }
|
||||||
|
|
@ -468,6 +320,7 @@ mind_body::self_run: fn start_message (instance : & Slug , run : & PipelineRef ,
|
||||||
mind_body::self_run: fn writes_hour_cache (line : & str) -> Option < bool >
|
mind_body::self_run: fn writes_hour_cache (line : & str) -> Option < bool >
|
||||||
mind_body::self_run: impl Child for ClaudeProcess
|
mind_body::self_run: impl Child for ClaudeProcess
|
||||||
mind_body::self_run: impl ClaudeSpawner
|
mind_body::self_run: impl ClaudeSpawner
|
||||||
|
mind_body::self_run: impl ClaudeSpawner: fn in_sandbox (unit_environment : impl IntoIterator < Item = (OsString , OsString) > , seed_variable : & str , sandbox : Option < PathBuf >) -> Result < Self >
|
||||||
mind_body::self_run: impl ClaudeSpawner: fn new (unit_environment : impl IntoIterator < Item = (OsString , OsString) >) -> Result < Self >
|
mind_body::self_run: impl ClaudeSpawner: fn new (unit_environment : impl IntoIterator < Item = (OsString , OsString) >) -> Result < Self >
|
||||||
mind_body::self_run: impl Drop for FreshConfig
|
mind_body::self_run: impl Drop for FreshConfig
|
||||||
mind_body::self_run: impl FreshConfig
|
mind_body::self_run: impl FreshConfig
|
||||||
|
|
|
||||||
|
|
@ -137,7 +137,7 @@ Nothing that acts for a Persona writes her Mind. Since C1 the host enforces that
|
||||||
| Heartbeat (`mind-heartbeat.service`; `heartbeat.rs`, `tempo.rs`, `bin/mind-heartbeat.rs`) | Huginn `mind-body`. The one process deciding which Persona wakes and when. Sole writer of `heartbeat.cc`. | Swarm envelope and each Persona's brake (`read_effective`); each Persona's pending chat from Bifrost's mouth (`chat.pending`, read only, never acked, at most 16 pages); the unit table through `Launcher::alive`; `stewardships_of` on her Mind; `HEARTBEAT_PERSONAS`, `MIND_PERSONA_OPERATOR`, `HEARTBEAT_POLL_S` (20), `HEARTBEAT_BEAT_S` (1800), `BIFROST_CHAT_ENDPOINT`, `BIFROST_CHAT_KEY_FILE`, `STATE_DIRECTORY`. It holds no connector key. | `systemctl start mind-persona@<i>` through `SystemdLauncher`; `heartbeat.cc` (state, addressing table, poll traces). No run, no brief, no Self-run launch. | Off the beat: the operator, or another Mind of the roster, naming her wakes her once per message (`handled_mentions`, 64 kept). On the beat: when `beat_s` has passed since `last_beat_at`, `tempo::pick` over idle, released Minds by wait since the heartbeat last woke each, bent by a member addressing her. Busy is systemd's: an active unit is busy and a start is a no-op. | Her Mind (a Persona wake is a unit start); `heartbeat.cc` by anything but the heartbeat; the brakes. | `heartbeat.cc` under the unit's `STATE_DIRECTORY`, world-readable: Personas read the addressing table through `HeartbeatView`. `mind-heartbeat timeline` prints the latest poll. | C2 deleted the claimable-brief and Self-run branch, tempo votes and the PID fallback (`tally`, `fallback_beat`), the urgency pulse, `sleep.rs` (no night wake until C4) and `attachment.rs`. It kept `tempo::pick` and `score`. `vote_beat_s` in `InstanceTrace` is retired and always none, kept so old trace records decode. A `heartbeat.cc` holding an older document is refused by name and never migrated. | `heartbeat/tests.rs`: `a_mind_whose_self_holds_briefs_gets_a_persona_wake_and_no_self_run`, `no_poll_admits_anything_to_any_mind_whatever_it_wakes`, the mention and beat tests. |
|
| Heartbeat (`mind-heartbeat.service`; `heartbeat.rs`, `tempo.rs`, `bin/mind-heartbeat.rs`) | Huginn `mind-body`. The one process deciding which Persona wakes and when. Sole writer of `heartbeat.cc`. | Swarm envelope and each Persona's brake (`read_effective`); each Persona's pending chat from Bifrost's mouth (`chat.pending`, read only, never acked, at most 16 pages); the unit table through `Launcher::alive`; `stewardships_of` on her Mind; `HEARTBEAT_PERSONAS`, `MIND_PERSONA_OPERATOR`, `HEARTBEAT_POLL_S` (20), `HEARTBEAT_BEAT_S` (1800), `BIFROST_CHAT_ENDPOINT`, `BIFROST_CHAT_KEY_FILE`, `STATE_DIRECTORY`. It holds no connector key. | `systemctl start mind-persona@<i>` through `SystemdLauncher`; `heartbeat.cc` (state, addressing table, poll traces). No run, no brief, no Self-run launch. | Off the beat: the operator, or another Mind of the roster, naming her wakes her once per message (`handled_mentions`, 64 kept). On the beat: when `beat_s` has passed since `last_beat_at`, `tempo::pick` over idle, released Minds by wait since the heartbeat last woke each, bent by a member addressing her. Busy is systemd's: an active unit is busy and a start is a no-op. | Her Mind (a Persona wake is a unit start); `heartbeat.cc` by anything but the heartbeat; the brakes. | `heartbeat.cc` under the unit's `STATE_DIRECTORY`, world-readable: Personas read the addressing table through `HeartbeatView`. `mind-heartbeat timeline` prints the latest poll. | C2 deleted the claimable-brief and Self-run branch, tempo votes and the PID fallback (`tally`, `fallback_beat`), the urgency pulse, `sleep.rs` (no night wake until C4) and `attachment.rs`. It kept `tempo::pick` and `score`. `vote_beat_s` in `InstanceTrace` is retired and always none, kept so old trace records decode. A `heartbeat.cc` holding an older document is refused by name and never migrated. | `heartbeat/tests.rs`: `a_mind_whose_self_holds_briefs_gets_a_persona_wake_and_no_self_run`, `no_poll_admits_anything_to_any_mind_whatever_it_wakes`, the mention and beat tests. |
|
||||||
| Self-run actuator (`mind-self@<i>`; `self_run.rs`, `bin/mind-self-run.rs`) | Huginn `mind-body`. Carries the one in-force Self run of its instance. | The run document (the grant), the lease socket, the Mind, the clock. | One `claude` child, its flush, its stop. | Request prefix, session id (UUIDv5 of the run id), kept transcript. | Nothing launches it. `launch::open_and_launch`, the work queue and the repetition breaker are gone (tag `parked/self-run-launch`). No organ opens a Self run, so `mind-self-run` with no open run exits 3. | The run slot in the Mind; `/var/lib/gamecult/minds/<i>/` state. | Left in place on purpose (C2 keep list): C3b's Interpreter reuses its spawn and sandbox and `lease_client`. `inbox` still reads briefs admitted by agent `mind-persona`; nothing admits them now. | `tests/self_run.rs` (ignored lane: the real binary against the real daemon with a fake `claude`); `self_run/tests.rs`. |
|
| Self-run actuator (`mind-self@<i>`; `self_run.rs`, `bin/mind-self-run.rs`) | Huginn `mind-body`. Carries the one in-force Self run of its instance. | The run document (the grant), the lease socket, the Mind, the clock. | One `claude` child, its flush, its stop. | Request prefix, session id (UUIDv5 of the run id), kept transcript. | Nothing launches it. `launch::open_and_launch`, the work queue and the repetition breaker are gone (tag `parked/self-run-launch`). No organ opens a Self run, so `mind-self-run` with no open run exits 3. | The run slot in the Mind; `/var/lib/gamecult/minds/<i>/` state. | Left in place on purpose (C2 keep list): C3b's Interpreter reuses its spawn and sandbox and `lease_client`. `inbox` still reads briefs admitted by agent `mind-persona`; nothing admits them now. | `tests/self_run.rs` (ignored lane: the real binary against the real daemon with a fake `claude`); `self_run/tests.rs`. |
|
||||||
| Persona state (`gamecult.persona_state.v0`, one per mind, `personaId` = instance) | The Persona. No organ of Huginn writes it today. Target writers (ruling `persona-only-state-writers-self-and-life`): her commit step (C3c), and Self and Life on Starfire through `mind-persona edit`. | `PersonaGet`, `PersonaPut` on the daemon. | A receipt per put. | None stored. | The Projector, the Persona stage and the Interpreter never put. A raw `huginn persona put` is detected and recorded `unexplained`, not sanctioned. | The Mind store; reached by `PersonaGet` and `PersonaPut` at the persona door (C1, live), the only listener a Persona uid can reach. | `huginn-mind/src/persona.rs` keeps the document and its CAS. C2 removed the organ that was its only writer. | `huginn-mind` persona tests; `serve.rs` tests that the persona door answers her persona and refuses `Admit`. |
|
| Persona state (`gamecult.persona_state.v0`, one per mind, `personaId` = instance) | The Persona. No organ of Huginn writes it today. Target writers (ruling `persona-only-state-writers-self-and-life`): her commit step (C3c), and Self and Life on Starfire through `mind-persona edit`. | `PersonaGet`, `PersonaPut` on the daemon. | A receipt per put. | None stored. | The Projector, the Persona stage and the Interpreter never put. A raw `huginn persona put` is detected and recorded `unexplained`, not sanctioned. | The Mind store; reached by `PersonaGet` and `PersonaPut` at the persona door (C1, live), the only listener a Persona uid can reach. | `huginn-mind/src/persona.rs` keeps the document and its CAS. C2 removed the organ that was its only writer. | `huginn-mind` persona tests; `serve.rs` tests that the persona door answers her persona and refuses `Admit`. |
|
||||||
| Persona turn trace (`eureka.persona.turn_record.v1`, `FileTrace`: the turn record itself, the shape `outcome_of` reads) | The Persona organ, when C3 lands. | Nothing writes it today. | None. | None. | Any Mind writer; any model. | The unit's state directory. | Kept for C3c (the record gains `outside_put` and `tuning_changed`). Deltas are read from it over ssh (`persona-only-deltas-from-trace`). | `persona/tests.rs` `the_trace_store_keeps_each_record_under_its_key_and_lists_them_oldest_first`. |
|
| Persona turn trace (`eureka.persona.turn_trace.v1`, `FileTrace`) | The Persona organ, when C3 lands. | Nothing writes it today. | None. | None. | Any Mind writer; any model. | The unit's state directory. | Kept for C3c (trace v2 with `outside_put` and `tuning_changed`). Deltas are read from it over ssh (`persona-only-deltas-from-trace`). | `persona/tests.rs` `the_trace_store_keeps_each_turn_under_its_run_and_turn`. |
|
||||||
| Brake and the stop on hold | Operator. `mind-control brake hold` writes the brake, then stops the instance's units. | The operator's word. | `control.cc`; a blocking `systemctl stop`. | `read_effective` is the one reader. | Every organ of hers. | `/etc/gamecult/minds/<i>/`, `swarm.cc`. | `StopScope` still names three templates: `mind-self@`, `mind-persona@` and `mind-stream@`. The stream organ is parked; its unit name stays on the stop list so a host that still has it installed is stopped. | `tests/cli.rs` and the `launch.rs` stop tests (they spell `mind-stream@`). |
|
| Brake and the stop on hold | Operator. `mind-control brake hold` writes the brake, then stops the instance's units. | The operator's word. | `control.cc`; a blocking `systemctl stop`. | `read_effective` is the one reader. | Every organ of hers. | `/etc/gamecult/minds/<i>/`, `swarm.cc`. | `StopScope` still names three templates: `mind-self@`, `mind-persona@` and `mind-stream@`. The stream organ is parked; its unit name stays on the stop list so a host that still has it installed is stopped. | `tests/cli.rs` and the `launch.rs` stop tests (they spell `mind-stream@`). |
|
||||||
| Parked and deleted organs | Tags on the forge, not main. | n/a | n/a | n/a | Main must not regrow them without a ruling. | n/a | `parked/divergence-stream` holds `stream.rs` and `bin/mind-stream` (ruling `persona-only-divergence-parked`; return condition: measured narrations converge, judged by the eval of the design map's section 3.4; its Projector code is reused by C3a). `parked/self-run-launch` holds `open_and_launch`, the work queue and its breaker (a future spend owner may restore Self runs on address). `sleep.rs` and `attachment.rs` are deleted, not parked: consolidation returns in C4 as a retarget onto `thoughtMemory`. | The C2 negative greps: `start_self_run`, `WORK_QUESTION`, `WAKE_ASK`, `TURN_INSTRUCTION`, `Pulse`, `tempo_vote` absent from `crates/mind-body/src`. |
|
| Parked and deleted organs | Tags on the forge, not main. | n/a | n/a | n/a | Main must not regrow them without a ruling. | n/a | `parked/divergence-stream` holds `stream.rs` and `bin/mind-stream` (ruling `persona-only-divergence-parked`; return condition: measured narrations converge, judged by the eval of the design map's section 3.4; its Projector code is reused by C3a). `parked/self-run-launch` holds `open_and_launch`, the work queue and its breaker (a future spend owner may restore Self runs on address). `sleep.rs` and `attachment.rs` are deleted, not parked: consolidation returns in C4 as a retarget onto `thoughtMemory`. | The C2 negative greps: `start_self_run`, `WORK_QUESTION`, `WAKE_ASK`, `TURN_INSTRUCTION`, `Pulse`, `tempo_vote` absent from `crates/mind-body/src`. |
|
||||||
|
|
||||||
|
|
@ -607,7 +607,7 @@ pipeline kinds are in Huginn `docs/eureka-substrate-map.md`.
|
||||||
| Connector request and transcript items | Request: `(caller_runtime_id, request_id)`, the replay key the daemon already keeps (`replay.cc`). Items: UserText, AssistantText, ToolCall, ToolResult, plus `ReasoningState { provider, model, opaque }` (ruling `connector-opaque-state-item`). Contract ids become provider-neutral `gamecult.model.*.v3` (follow-up `connector-contract-untyped`); the connector serves Ghostlight too, so not `eureka.*`. | Invocation expires at `expires_at_unix_ms`; replay record per key; restart-era `Indeterminate`. The caller stores the transcript and replays it verbatim; foreign-tagged reasoning state inside an in-flight tool exchange is refused typed; completed-turn foreign state is settled per provider in the connector cut (follow-up `connector-reasoning-state-cheap-providers`). | The connector produces, reads or refuses reasoning bytes; callers never branch on provider. |
|
| Connector request and transcript items | Request: `(caller_runtime_id, request_id)`, the replay key the daemon already keeps (`replay.cc`). Items: UserText, AssistantText, ToolCall, ToolResult, plus `ReasoningState { provider, model, opaque }` (ruling `connector-opaque-state-item`). Contract ids become provider-neutral `gamecult.model.*.v3` (follow-up `connector-contract-untyped`); the connector serves Ghostlight too, so not `eureka.*`. | Invocation expires at `expires_at_unix_ms`; replay record per key; restart-era `Indeterminate`. The caller stores the transcript and replays it verbatim; foreign-tagged reasoning state inside an in-flight tool exchange is refused typed; completed-turn foreign state is settled per provider in the connector cut (follow-up `connector-reasoning-state-cheap-providers`). | The connector produces, reads or refuses reasoning bytes; callers never branch on provider. |
|
||||||
| Connector spend ledger | The reservation lives in the replay record itself (cut connector-spend, F33): integer micro-USD, windowed per caller (ruling `connector-spend-caller-window-ceiling`). | Reserve before the provider runs, settle to actual; refusals `CostBound` (the invocation's own `max_cost_micro_usd`) and `SpendCeiling` (the caller's window); a ledger that cannot be written refuses the request. | The kit's `ProviderCall::charge` is the one billing owner; a backend reports usage or `None` (bills the reservation). The root caller config sets the ceiling. |
|
| Connector spend ledger | The reservation lives in the replay record itself (cut connector-spend, F33): integer micro-USD, windowed per caller (ruling `connector-spend-caller-window-ceiling`). | Reserve before the provider runs, settle to actual; refusals `CostBound` (the invocation's own `max_cost_micro_usd`) and `SpendCeiling` (the caller's window); a ledger that cannot be written refuses the request. | The kit's `ProviderCall::charge` is the one billing owner; a backend reports usage or `None` (bills the reservation). The root caller config sets the ceiling. |
|
||||||
| Claude connector backend (B4a, landed `200933f`; the Persona does not use this backend, it borrows a lease like the Self) | `ClaudeCodeBackend` in `crates/claude-connector`, provider tag `claude-code`: one `claude -p` child per call in its own process group, tool-less, system prompt in a private temp file; reasoning state is a named-MessagePack `ClaudeCodeHandle { session_id, instance, prefix_sha256 }`; usage is `model_usage_since_last_result` summed over models, in list-price units from B4b's price table (ruling `claude-code-plan-quota-fuse-2`). | A handle resumes (always `--fork-session`) only when it decodes, names this instance, its session file exists and its digest matches the request's instructions, model and earlier items; anything else re-seeds from the caller's transcript (ruling `claude-code-handle-reseeds`). The CLI's session store under `config_dir` is a cache; the caller's transcript is the truth. A refusal at the door with explicitly empty usage bills zero; unknown usage, a crash or a deadline bills the reservation. | The backend owns the argv, env, process and stream mapping. It never reads `total_cost_usd`, never forwards `ANTHROPIC_API_KEY`, never retries, never spawns twice per execute. Forbidden: `--bare`, `--fallback-model`, `--mcp-config` and `--dangerously-skip-permissions` (B4d changes the MCP line, by spec). Her organs hold none of it: the subscription token lives in the connector's own environment. |
|
| Claude connector backend (B4a, landed `200933f`; the Persona does not use this backend, it borrows a lease like the Self) | `ClaudeCodeBackend` in `crates/claude-connector`, provider tag `claude-code`: one `claude -p` child per call in its own process group, tool-less, system prompt in a private temp file; reasoning state is a named-MessagePack `ClaudeCodeHandle { session_id, instance, prefix_sha256 }`; usage is `model_usage_since_last_result` summed over models, in list-price units from B4b's price table (ruling `claude-code-plan-quota-fuse-2`). | A handle resumes (always `--fork-session`) only when it decodes, names this instance, its session file exists and its digest matches the request's instructions, model and earlier items; anything else re-seeds from the caller's transcript (ruling `claude-code-handle-reseeds`). The CLI's session store under `config_dir` is a cache; the caller's transcript is the truth. A refusal at the door with explicitly empty usage bills zero; unknown usage, a crash or a deadline bills the reservation. | The backend owns the argv, env, process and stream mapping. It never reads `total_cost_usd`, never forwards `ANTHROPIC_API_KEY`, never retries, never spawns twice per execute. Forbidden: `--bare`, `--fallback-model`, `--mcp-config` and `--dangerously-skip-permissions` (B4d changes the MCP line, by spec). Her organs hold none of it: the subscription token lives in the connector's own environment. |
|
||||||
| Persona turn traces | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** `FileTrace` exists; nothing writes it until C3c. **Empty: question `persona-trace-retention`.** Candidate: per turn, the request digest, the transcript items and the typed output, keyed by the turn's run. | Empty: how long they are kept, whether Discord-sourced content may enter a training export (F14). | Empty: who may export them. Unconfirmed 2026-11-02: `FileTrace` exists in `persona.rs`; whether they are the retention answer is not checked against the question's state. |
|
| Persona turn traces | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** `FileTrace` exists; nothing writes it until C3c. **Empty: question `persona-trace-retention`.** Candidate: per turn, the request digest, the transcript items and the typed output, keyed by the turn's run. | Empty: how long they are kept, whether Discord-sourced content may enter a training export (F14). | Empty: who may export them. Unconfirmed 2026-11-02: `FileTrace`/`TurnTrace` exist in `persona.rs`; whether they are the retention answer is not checked against the question's state. |
|
||||||
| Persona state | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No organ writes it; target writers are her commit step, Self and Life (`persona-only-state-writers-self-and-life`). `gamecult.persona_state.v0`, one per mind, `personaId` = instance (cut-huginn-persona-state r2, eureka-substrate). | Replaced whole under CAS with a receipt; she may rewrite any field (`identity-write-all-visible`). | The Persona organ is the only writer. |
|
| Persona state | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No organ writes it; target writers are her commit step, Self and Life (`persona-only-state-writers-self-and-life`). `gamecult.persona_state.v0`, one per mind, `personaId` = instance (cut-huginn-persona-state r2, eureka-substrate). | Replaced whole under CAS with a receipt; she may rewrite any field (`identity-write-all-visible`). | The Persona organ is the only writer. |
|
||||||
| Persona session | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No `claude` session runs in `mind-persona@<i>`; the organ is inert. The three-stage turn replaces it (C3). Process `claude` under bwrap in `mind-persona@<i>`; id uuid5(run, `p<n>`); one conversation per process | Ends at cache TTL, near the 4 h cap minus `ROTATE_MARGIN_S`, at the context ceiling's flush, or when another conversation's delivery is the oldest unanswered; next process rehydrates from the mind | The Persona organ (lifetime, input, acks); the mind is truth; heartbeat only starts units |
|
| Persona session | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No `claude` session runs in `mind-persona@<i>`; the organ is inert. The three-stage turn replaces it (C3). Process `claude` under bwrap in `mind-persona@<i>`; id uuid5(run, `p<n>`); one conversation per process | Ends at cache TTL, near the 4 h cap minus `ROTATE_MARGIN_S`, at the context ceiling's flush, or when another conversation's delivery is the oldest unanswered; next process rehydrates from the mind | The Persona organ (lifetime, input, acks); the mind is truth; heartbeat only starts units |
|
||||||
| Persona sandbox | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Nothing writes it now; C3b decides the Interpreter's sandbox. `/var/lib/mind-<i>/sandbox` | Kept between processes; the only place her tools write (besides the fresh config dir) | Her; nobody else reads it. Not a source of truth for anything. |
|
| Persona sandbox | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Nothing writes it now; C3b decides the Interpreter's sandbox. `/var/lib/mind-<i>/sandbox` | Kept between processes; the only place her tools write (besides the fresh config dir) | Her; nobody else reads it. Not a source of truth for anything. |
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -56,9 +56,6 @@
|
||||||
"affect": {
|
"affect": {
|
||||||
"$ref": "#/definitions/personaAffect"
|
"$ref": "#/definitions/personaAffect"
|
||||||
},
|
},
|
||||||
"embodiment": {
|
|
||||||
"$ref": "#/definitions/embodiment"
|
|
||||||
},
|
|
||||||
"updatedAt": {
|
"updatedAt": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "date-time"
|
"format": "date-time"
|
||||||
|
|
@ -1022,65 +1019,6 @@
|
||||||
"socialBiases",
|
"socialBiases",
|
||||||
"doctrineStances"
|
"doctrineStances"
|
||||||
]
|
]
|
||||||
},
|
|
||||||
"embodiment": {
|
|
||||||
"type": "object",
|
|
||||||
"description": "What she is: her senses and actuators, each one she has, as she has it now. Written by Self and Life puts, never by her turn's commit: it is a fact about what exists, not a feeling. An absence records nothing about her.",
|
|
||||||
"additionalProperties": false,
|
|
||||||
"properties": {
|
|
||||||
"senses": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"$ref": "#/definitions/embodimentEntry"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"actuators": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"$ref": "#/definitions/embodimentEntry"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"embodimentEntry": {
|
|
||||||
"type": "object",
|
|
||||||
"description": "One sense or actuator. summary: how it works and what it is like, in close third person. lacks: what it is not, in her terms. builtOn: when she made it.",
|
|
||||||
"additionalProperties": false,
|
|
||||||
"properties": {
|
|
||||||
"id": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"status": {
|
|
||||||
"$ref": "#/definitions/thoughtStatus"
|
|
||||||
},
|
|
||||||
"label": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"summary": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"lacks": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"builtOn": {
|
|
||||||
"type": "string",
|
|
||||||
"format": "date-time"
|
|
||||||
},
|
|
||||||
"updatedAt": {
|
|
||||||
"type": "string",
|
|
||||||
"format": "date-time"
|
|
||||||
},
|
|
||||||
"extensions": {
|
|
||||||
"$ref": "#/definitions/extensions"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"id",
|
|
||||||
"status",
|
|
||||||
"label",
|
|
||||||
"summary",
|
|
||||||
"updatedAt"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue