Compare commits

..
Author SHA1 Message Date
51fc7c3576 Merge pull request 'Speech binds to her words; Huginn's chat Interpreter; she speaks only in the turn's room' (#82) from hands/speech-binding into main 2026-11-20 05:27:32 +00:00
Meta Vens
7ed31c6f75 Test prose speaks in standalone quotations: a dialogue tag frames its quotation (Soul F1)
"what a day" he says and "Missed you too, friend," he types are framed under F1, so the test doubles' lines went silent. The prose now quotes whole sentences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:25:23 +01:00
Meta Vens
0f3f76a8ab Simulation: one turn a round per Mind, in the room of her earliest waking line; only the room she read is seen (Soul F5, replacing R7)
Who wakes is decided from the room as the round opens, as one heartbeat poll decides from the pending it read, so a line spoken this round counts toward a cap from the next round. A room that woke her but was not read stays unseen and wakes her next round. Tests: a DM and a #minds address answered in rounds 1 and 2; Soul's three rooms answered in three rounds, one turn a round, under ruled and names_with_cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:23:19 +01:00
Meta Vens
be87931b53 Person keys: a Mind's full Matrix id is her handle and the operator's is operator, everywhere a key is read; a value carrying a mark is refused (Soul F6, F7)
People::person_of is the one key reader for senders, targets, about: tags and bond objects. A value has no mark in the schema; one that carries one is not rendered. Tests: both spellings of a Mind behave alike for target and about:, a bond keyed by full ids is found, a marked value never renders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:23:18 +01:00
Meta Vens
484d4f65ba Speech: no line starts or ends inside a quotation her sentence frames; the private word match is deleted; an unclosed opening mark is not part of its sentence (Soul F1, F2, F4)
- A quotation is standalone when it, marks included, is a run of whole top-level sentences; any other is framed, and a line may not start or end strictly inside it. A line holding a framed quotation whole stays sayable.
- The three-word refusal against private items is deleted: whether a line tells a confidence is meaning, the Interpreter's judgement over the private list it is shown.
- An opening mark left unclosed (the budget cut her prose) is stripped from the sentence it starts, so the sentence is citable and the line carries no stray mark.
- Tests: every F1 probe refused (stray inch mark and scare-quote plan included); Weksa's hedge and a whole scare-quote sentence said; Weksa r6 and r10 said; the Q5d test keeps the prompt list and shows no word match refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:23:18 +01:00
Meta Vens
8881b3f4b5 Simulation: one turn per room that woke her, each in its own room (Soul R7)
woken() returns one wake per room; every turn of hers in a round reads from where the round found her, so a direct message is never marked seen without a turn. Test: a DM and a #minds address in one round give Libby a turn in each, each reading only its own room's line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:01:11 +01:00
Meta Vens
f7decde001 Speech is whole consecutive sentences of her prose; private items are named to the Interpreter and refused in code; echo needs 8 words and 80% overlap (Soul R1, R4, R5, R8, R9)
- Every cited span starts and ends on a UAX#29 sentence boundary; the spans of one line are consecutive sentences, and the line is that unbroken run of her prose. A quotation's inside is segmented as a text of its own, so quoted speech stays sayable. She cannot say half a sentence.
- The prompt lists what she knows privately and allows plain speech of a private matter only to its person, in a DM with exactly them. Code refuses a line that shares a run of three words with a listed item.
- Tests: Soul's Q1a-Q1d refused, Q3d refused on a beat, Q5d refused in a DM with Libby, R9 said, P3 still refused; Hands' "Fine," + "winter" test rewritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:01:11 +01:00
Meta Vens
56c45967ef Privacy has one owner: concerns() reads who a private item is about, scope() decides how it renders, for every pool and the bonds (Soul R2, R3, R6, R8, R10)
- concerns(): private is extensions.privacy, a private tag, or a room:! tag; it is about target/object person, else an about: tag, else the DM's partner, else everyone. private_elsewhere is deleted.
- scope(): plain only in a DM whose members are exactly her and that person (a partner-only item: in its own DM, still two; an everyone item: her own room); left out where the person is in the room, a group DM included; framed elsewhere.
- Applied to memories, shortTerm, incubation, needs, doctrine stances and bonds; history.said in a DM is private about its partner.
- Packet.private carries the framed items' words for the Interpreter; a beat's bodies are the tail lines its stimulus quoted.
- Tests: Soul's Q5a-Q5c, the DM-memory test rewritten for the room-tag rule, the said pool; the golden packet moves because dm-secret is now framed in public.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:01:11 +01:00
Meta Vens
947d8f7a40 Scoped privacy: only a bond or memory marked private is framed or left out; unmarked renders as written
Self's decision: the blanket framing smothered relationship texture in public rooms. A bond or memory is private only
when marked (`extensions.privacy = "private"`, or a memory's `private` tag); the schema is unchanged. A marked item
renders as written in a direct message with the person it is about, is left out about someone present in any other
room, and is framed "she knows privately" about someone absent. Unmarked items render as written everywhere. The
Interpreter's rule about private knowledge stays. The convention is documented in the Persona State Standard
(gamecult-ops `docs/persona-state-standard.md`, GameCult/gamecult-ops#129).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 05:34:11 +01:00
Meta Vens
02e78e1427 Speech binds to her words: a spoken line is her prose verbatim; Huginn's chat Interpreter prompt; she speaks only in the turn's room
Soul's hold on #81 and Self's privacy decision.

- F1: a spoken line is exactly the spans of her prose the Interpreter cites, located in order by Ghostlight's
  SourceSpan::locate and joined with one space. The model never writes the words; `text` is gone from the contract.
  The Persona writes the words she would type, never a description of them. Given up: indirect speech and any
  paraphrase by the Interpreter.
- F3: Huginn owns a short chat Interpreter prompt (what, where, to whom; gaps conditional, addressee, elsewhere);
  Ghostlight's membrane and the INTERPRETER_GUIDANCE patch are gone. `[interpreter]` keeps only the model.
- F2: an echo is a line of four words or more whose word trigrams are mostly the heard message bodies
  (heard_overlap); short answers are never echoes.
- F4: mentions and reply targets only for people this packet showed her.
- F5: a line said once; at most two lines a turn.
- F6: stale docs on the Mind run, the exchange and the policies.
- F7: a human's line ends a Mind's run only in a room the run has lines in.
- Privacy: she speaks only in the turn's room; the Interpreter is told the room, its kind (public, her own, a direct
  message) and who is in it, and not to say in a room what she knows privately; the packet frames bond summaries and
  memories about a person as known privately everywhere but a direct message with that person.
- The simulation's turn is in the room of the line that woke her.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 05:30:00 +01:00
14be61a167 Merge pull request 'The Interpreter's speech (C3b): what she says is decided from her prose, not parsed from quotes' (#81) from hands/interpreter-speech into main 2026-11-20 04:05:32 +00:00
Meta Vens
ea38f5f17d The Interpreter's speech (C3b): what she says is decided from her prose, not parsed from quotes; Soul's F2 to F9
Speech (Soul F1): `projection::interpret` is the Interpreter's speech step, one tool-less structured call through the
connector under Ghostlight's Interpreter membrane, over her prose, her lived stream, the stimulus, the rooms she may
speak in and the people she may address by Matrix id. It proposes lines, each with a room, structured mentions and a
reply target, and the verbatim span of her prose it rests on. Code keeps a line only when the span locates in her prose
(Ghostlight's SourceSpan::locate, map 4.3), the room is hers this turn, and its words are not what she heard; it drops
mentions or a reply target naming anyone not shown, and records every refusal and drop. An answer that is not the
contract is a failure, never a silence. `--through interpreter`; the batch and the simulation run through it, and in
the simulation the only explicit addressees are its structured fields. `would_say`, `inner` and the quote parsing are
gone; the Persona stage writes her thought with no speech convention. Tuning gains `[interpreter]`.

- F2: she is in a room's exchange when she spoke there within `exchange_minutes` (default 30).
- F3: the Projector guidance names no duty, not even to deny one; "X is waiting on her" only when true.
- F4: the narration metric is a lexical overlap, labeled so.
- F5: a scripted direct message in one of the plan's rooms is refused.
- F6: the Mind-run cap counts one run per Mind across her rooms; LineFacts::default() is at the cap (fail-safe).
- F7: an unbonded sender is labeled by display name and full id, or the id: never a bare handle.
- F8: a room is named by the key the tail carries (alias, or a direct message's id); a public room's id is reported,
  not mapped, since no table in her body maps it.
- F9: group-state parts are sentences, the person waiting on her first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:54:37 +01:00
e817b67abd Merge pull request 'Harness fixes: one wake rule in the heartbeat, the heartbeat's beat, group state in the Projector' (#80) from hands/harness-fixes into main 2026-11-20 03:34:37 +00:00
Meta Vens
63606efddd Projector and Persona after the operator's reading; humans_pace per ruling; Soul's hold on #80
Projector (the operator: "Sounds like a Projector issue"):
- The group state is the conversation as it stands, in one room: who is talking with whom, a human's question to the
  room that others answered as covered (one nobody answered goes unmentioned), when a human last spoke, Mind lines in a
  row, and a human waiting on her by name. Never what she owes. Every count covers the window the line describes (S4);
  never several rooms folded together, never a direct message into a public room (S3). Default group_lines 12.
- Absent state is left out: no "mood: none recorded"; a bond, need, memory, stance, wondering or value without content
  is not rendered, and a bond without trust or tension says neither.
- Guidance: never retell what she heard (it reaches her verbatim), render what it stirs; never a debt; no options; leave
  out what the context does not carry; use pronouns as given. Metrics, not filters: heard_overlap (word trigrams shared
  with the heard lines) and offers_options (a narrow lexical flag), per render and per run.
- Pronouns: `[pronouns]` in the tuning by Matrix id, the swarm's people as the default, they/them for anyone else; the
  persona schema has no pronoun field for another person. A pronoun line names everyone the packet shows from the room.
  The packet speaks of her in her own pronouns throughout ("Said to him:") (S5).
- Bond lines put the kind after a dash and lists use semicolons: a label may hold a comma ("Meta, the operator").

Persona stage: continues her inner stream in the first person; speech only where her thought moves her to it, in double
quotes; others' words she recalls in single quotes; @handle tags someone. The report shows her inner prose apart from
what she would say.

humans_pace (ruling persona-only-humans-pace; the operator's words that Minds' explicit mentions wake too):
`HumansPace(cap)`: a human's line wakes her in her own room or a direct message always, and in a public room when it
addresses her or continues an exchange she is in (an exchange ends at a gap over exchange_gap_minutes, default 20); a
Mind's line wakes her only by a Matrix mention or a reply, in any room, while fewer than `cap` Mind lines in a row came
before it. Own rooms come from the plan: neither the heartbeat's table nor persona.env records ownership. Live is
unchanged. In the simulation a said line's @handle of a cast member stands in for a Matrix mention.

Soul's hold:
- S1: Config::new refuses an operator id that is also a persona's.
- S2: the simulator's beat asks heartbeat::addressed_by_member over the deliveries the mouth would give her.
- S3: --in given as a room id is read by its alias.
- S6: a scripted direct message names its recipient (`to`), is seen by sender and recipient alone, and wakes only her.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:23:06 +01:00
Meta Vens
b90c21e695 Harness fixes after Soul's hold on #79: one owner of the wake rule, the heartbeat's beat, group state in the Projector
- F1: `heartbeat::wakes(policy, addressee, delivery, speaker, mind_run)` is the one wake rule. The poll asks it with
  `WakePolicy::Live` (behaviour unchanged until `po-mind-wakes-mind` is answered); the simulator asks it with the plan's
  policy: `ruled`, `humans_pace`, `names_with_cap = N`, `all_messages`. The simulator reads each persona's addressee from
  the heartbeat's addressing table (stewarded project names included) when the plan names `heartbeat.cc`.
- F2: the beat falls on `beat_s` of simulated time and wakes one Persona, the winner of `tempo::pick`.
- F5: Mind-addressed evidence is counted per wake (its strongest evidence), not per line.
- F6: reply chains are per room and count Mind lines spoken in turns another Mind's line woke.
- F7: a failed call is a failure, apart from silence; silence rate is per woken turn that did not fail.
- F8: a test that another seed changes the order.
- F9: `--state` docs say P4 and P5 are not checked.
- Group state (`select.group_state`, default on): one packet line over the room's last `group_lines` lines: who spoke
  to whom, when a human last spoke, how many Mind lines in a row, lines to her, an open question to everyone. Inside the
  context budget, narrated by the Projector like every other line; golden fixtures for the four scenario rooms.
- Reports: wakes by cause and by round, per-room chains, failures, 18 representative lines, the explicit-addressee gap.
- Tuning: `persona.words` and `persona.guidance` get the upper bounds the Projector's knobs have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:40:38 +01:00
fe723867f7 Merge pull request 'mind-persona project: the persona seed harness (--room, --through persona, --batch, --simulate)' (#79) from hands/persona-harness into main 2026-11-20 01:53:34 +00:00
Meta Vens
19e0ee5285 simulate: wakes per round split human-caused and Mind-addressed; Mind-addressed evidence by mention, id as text or name
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 01:14:38 +01:00
Meta Vens
8d69d3bded mind-persona project: the persona seed harness (--room, --through persona, --batch, --simulate)
The harness judges candidate persona states before any Mind holds them, through the
same `project` the live turn will use: every case is one `project` call.

- `--room <fixture.toml>`: a mocked room in place of the mouth and the room tail:
  her id, rooms, messages (sender, display name, room, ago, body; new, tag,
  mentions, dm, follow_up, reply_to), a mocked now and a "last heard from" table.
  The fixture is a MouthReader, so addressing is still `address::is_for`. The live
  room filter that `--room` used to name is now `--in`.
- `--state` is checked as a put checks content: huginn-mind's P1 to P3 now live in
  one owner, `persona::validate_document`, which the put calls.
- `--through persona`: the Persona stage (C3b's first piece). One tool-less
  connector call under Ghostlight's persona membrane over identity, narration and
  the heard lines; prose capped at 180 words; would-say lines are the double-quoted
  spans; usage per call. Tuning gains `[persona]` (model, guidance, words).
- `--batch <plan> --out <md>`: states x scenarios x samples, one Markdown report
  with packets, narration, prose, would-say lines, word counts, distinct-2 and
  cross-state word similarity, and a total-usage footer.
- `--simulate <plan> --out <md>`: up to eight personas taking turns in one room.
  Wake is is_for plus the ruled set (addressed, any human in her rooms, the beat);
  `wake = "all_messages"` is the old loop as a control. Woken personas run in a
  seeded order; quoted lines join the room as from her id. State does not evolve
  (`state_after_turn` is the seam for C3b/C3c). Metrics: messages, silence,
  who addresses whom, Mind-to-Mind chains, lexical convergence, a work-talk
  heuristic, usage.
- With a state file and a fixture no daemon and no mouth is needed (bin test).
- Request ids take the wall clock, so a fixture's fixed now cannot replay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 01:13:51 +01:00
c4bd83b026 Merge pull request 'Projector (C3a): Select stage, Projector narration, persona-tuning.toml, mind-persona project' (#76) from hands/persona-projector into main 2026-11-20 00:04:05 +00:00
Meta Vens
c43385962f Projector: a table without her row says so, whether or not its age is known
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:34:03 +01:00
Meta Vens
a2c59462e0 mind-body public surface: Failed, and the heartbeat view's written_at
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:32:43 +01:00
Meta Vens
078cefc024 Projector: tests read the third pass's rules (quoted display names, the 60% floor, the part bounds); Soul's list is 69 forms
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:31:01 +01:00
Meta Vens
f146be2e65 Projector after Soul's third pass: a glued-name boundary rule; one selection for both renderings of the messages to her; JSON escapes for bodies and display names; failures keep the report and their usage; a 60% floor and CJK words in the cap; addressing age; bounds under the connector frame
T1: address.rs names_whole_word: a name is glued only by a letter or digit, or
a single hyphen with one beyond it; every other character is a boundary, so
_Eureka_, Eureka/Libby, ok...Eureka? and Huginn.toml name her again and
mind-eureka does not. Soul's 72 forms pinned.
T2: said_to_her decides once; stimulus and heard both carry the count.
T4: Model::ask fails with Failed { reason, usage }; a failed render or judge
call is recorded with its usage and the report goes on.
T5: the sentence cut keeps at least 60% of the budget; 。!? end sentences;
CJK characters are words. T6/T7: spoken is a JSON string; a display name is
quoted, capped at 80 bytes and followed by its Matrix id. T8: the addressing
report gives the table's age and why it was not used. T9: own beat lines
excluded (tested); words, stimulus, item and the other parts bounded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:28:55 +01:00
Meta Vens
754f28c550 mind-body public surface: drop a stray runner line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:50:50 +01:00
Meta Vens
a19ea126ed mind-body public surface: Model answers with its usage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:49:13 +01:00
Meta Vens
432d76e994 Projector: an overrun ends on the last whole sentence inside the budget; every render and judge call reports the connector's usage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:47:32 +01:00
Meta Vens
33b42226f5 Projector guard: "short-term" is ordinary English, its one kebab exemption; shortTerm and short_term are still caught
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
47f2e6c5d3 Projector: a section heading over nothing is left out
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
57a6556968 Projector: golden packet and public surface after the second pass
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
12b777e67f Projector: clippy; others counted when messages to her take the room; the e^-21 floor is a short-term item's
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
fd56ea1442 address: the backslash joint as a character literal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
c2cf38904e Projector after Soul's second pass: is_for decides addressing; escaped bodies; a ceiling on messages to her; crystallized memories by relevance, not age; lens from what is held; full-id people; tighter tuning and guard
S1: to_her is address::is_for over the heartbeat's addressing row (own names
when there is none); a name inside a path or identifier no longer addresses
her, in address.rs itself. S2: room talk is headed Also in the room. S3:
addressed_bytes (8 KiB) bounds the messages to her, newest first; one larger
message is clipped between graphemes with its remainder counted. S4: one
escape (spoken) renders every body. S5: only short-term items decay; memories,
values and stances come forward by lexical relevance to what the room said;
the lens is drawn from included items. Lows: people keyed by full id except
the operator and the Minds; unbonded speakers shown with their id; tuning
refuses an empty model, a temperature outside 0.01..10, all-zero caps and an
overflowing identity; the guard folds kebab and run-together forms; a beat
respects small caps; project refuses without MIND_PERSONA_SELF_SENDER.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
f4f02b841c mind-body public surface: projection's read-only organs; recall gone
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
0522ded4c3 Projector after Soul: golden packet, clippy, testkit helpers orphaned by the recall cut
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
dd039e55b9 Projector after Soul: no Mind recall; messages to her always whole; sampled inclusion; effective tuning hash and validation; schema-derived guard; budget edges; read-only organs; grapheme clips
F1/F2: the Projector shows her persona state and her room; recall.rs and the
recall pool, recall_sorts and its cap are deleted. Reading the Mind is the
Interpreter's (C3b).
F3: messages to her go in whole and first; others fill what is left, with an
exact note; overflow past the cap is reported.
F4: candidates are included with probability 1 - exp(-score / inclusion_score);
caps are maxima. F5: the hash is of the effective tuning. F6: the guard reads
the persona schema and the tuning keys. F7: bounded fixed slots and relatedness
cue; the redundant final clip is gone. F8: tuning values are validated.
F9: project's organs are read-only traits. F10: clips land on graphemes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:50 +01:00
Meta Vens
fb5ea6b924 Projector: Decided leaves the default recall_sorts (her Mind files mission decisions there); default is Learned, Idea, Rapport
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:49 +01:00
Meta Vens
f363d3b230 recall test: distinct labels
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:49 +01:00
Meta Vens
12ec0a5aa5 Projector: recall tests for memories only; public surface carries recall_sorts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:49 +01:00
Meta Vens
97961f3c0e Projector: recall offers only persona-tuning.toml's recall_sorts (default Learned, Idea, Decided, Rapport), one item a packet
Recall now reads only memories of the cued sorts: follow-ups, rulings and the
open-item filter leave it, with the tests that pinned them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:49 +01:00
Meta Vens
ca0703cce8 Lock: ghostlight-persona-projection, unicode-segmentation and toml for the Projector
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:49 +01:00
Meta Vens
a7a0862640 recall: cut the old prompt's recall section (render, lane headings); the Select stage renders its own lines
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:49 +01:00
Meta Vens
8d52a44883 Projector (C3a): Select stage, Projector narration, persona-tuning.toml, mind-persona project
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:43:49 +01:00
f20a1533c8 Merge pull request 'Body map after C1: the persona door and the fence are live' (#78) from modeling/body-map-after-c1 into main 2026-11-19 22:40:08 +00:00
Meta Vens
71024a0f28 Body map after C1: the persona door and the fence are live; huginn.service is huginn@eureka
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 23:39:50 +01:00
57b931fdc3 Merge pull request 'Persona door: a second listener that answers reads and her persona, never an admission (C1)' (#74) from hands/persona-door into main 2026-11-19 22:25:39 +00:00
Meta Vens
04ebc4b0c5 Read-back gate: HUGINN_MIND_INSTANCE names the store it opens (default eureka)
The upgrade gate opened instance eureka only, and Mind::open refuses a store
whose instance document names another Mind, so no other Mind's store could be
gated. gamecult-ops now gates every store before a release moves any daemon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:15:15 +01:00
5b1a1e2cf4 Merge pull request 'Body map after C2: the persona-only body' (#77) from modeling/body-map-after-c2 into main 2026-11-19 21:40:28 +00:00
Meta Vens
e011c2aa21 Body map after C2: the persona-only body, stale rows marked, READMEs corrected
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 22:40:02 +01:00
66b85c8b67 Merge pull request 'C2: cut the mission organ and every Persona-side Mind write' (#75) from hands/persona-only-subtraction into main 2026-11-19 21:35:59 +00:00
Meta Vens
3e6554ca5a Cargo.lock as cargo writes it for the baf4ecf7 pin (duplicate CultLib entries reordered)
Soul C1 F5: the lock from the pin merge was accepted by --locked but
rewritten by an unlocked cargo; this is cargo's own rewrite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:19:45 +01:00
Meta Vens
cf27291471 Persona door: tests pin every read at the door and a semantic answer by its hub
Soul C1 F4: the source, chat, chat-window, activity and roots reads are
handed to the mind at the persona door (none refused NotThisDoor, each
answered the same at both doors); the semantic wire test also runs through
the persona door, so a held search answers by the persona hub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:19:15 +01:00
Meta Vens
e5d1984dc1 Persona door: startup binds it when asked; the desk test names no door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:26 +01:00
Meta Vens
df3272d2f2 desk_door integration test: run takes the persona door's hub
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:26 +01:00
Meta Vens
af7315b98b Persona door: a second RUDP listener that answers reads and her persona, never an admission
HuginnMindRequest::reaches_persona_door classifies every request with no
wildcard; Daemon::handle_at refuses what the persona door does not answer
with MindRefusal::NotThisDoor before the mind is asked; --persona-bind binds
the second hub, and run serves both, a search answering by the door it came
in at. Map: docs/persona-only-heartbeat-map.md (d861574), cut C1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:26 +01:00
53 changed files with 7993 additions and 993 deletions

134
Cargo.lock generated
View file

@ -350,6 +350,26 @@ dependencies = [
"cipher",
]
[[package]]
name = "cultcache-rs"
version = "0.3.1"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
dependencies = [
"anyhow",
"chrono",
"cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
"fs2",
"redb",
"rmp-serde",
"serde",
"serde_bytes",
"serde_json",
"serde_stacker",
"stacker",
"uuid",
"windows-sys 0.59.0",
]
[[package]]
name = "cultcache-rs"
version = "0.3.1"
@ -371,30 +391,10 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "cultcache-rs"
version = "0.3.1"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
dependencies = [
"anyhow",
"chrono",
"cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
"fs2",
"redb",
"rmp-serde",
"serde",
"serde_bytes",
"serde_json",
"serde_stacker",
"stacker",
"uuid",
"windows-sys 0.59.0",
]
[[package]]
name = "cultcache-rs-derive"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
dependencies = [
"proc-macro2",
"quote",
@ -404,7 +404,7 @@ dependencies = [
[[package]]
name = "cultcache-rs-derive"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
dependencies = [
"proc-macro2",
"quote",
@ -851,6 +851,16 @@ dependencies = [
"polyval",
]
[[package]]
name = "ghostlight-persona-projection"
version = "0.1.0"
source = "git+https://github.com/GameCult/Ghostlight.git?rev=c43eb54962ed4a09cc737ecac73a16b0d7ce62b4#c43eb54962ed4a09cc737ecac73a16b0d7ce62b4"
dependencies = [
"serde",
"sha2",
"unicode-segmentation",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@ -963,6 +973,16 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "inout"
version = "0.1.4"
@ -1098,6 +1118,7 @@ dependencies = [
"cultnet-rs 0.3.0",
"eureka-pipeline",
"eureka-state",
"ghostlight-persona-projection",
"huginn-mind",
"libc",
"model-connector",
@ -1110,7 +1131,9 @@ dependencies = [
"sha2",
"syn 2.0.119",
"tempfile",
"toml",
"unicode-general-category",
"unicode-segmentation",
"uuid",
]
@ -1121,6 +1144,7 @@ source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=
dependencies = [
"aes-gcm",
"base64",
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
"cultnet-rs 0.2.0",
"rand_core 0.6.4",
"rmp-serde",
@ -1684,6 +1708,15 @@ dependencies = [
"serde_core",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_stacker"
version = "0.1.14"
@ -1922,6 +1955,45 @@ dependencies = [
"tokio",
]
[[package]]
name = "toml"
version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow 0.7.15",
]
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [
"winnow 1.0.5",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "tracing"
version = "0.1.44"
@ -1980,6 +2052,12 @@ dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "universal-hash"
version = "0.5.1"
@ -2293,6 +2371,18 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]]
name = "wit-bindgen"
version = "0.57.1"

View file

@ -42,7 +42,7 @@ edits `.cc` state. Huginn reads and writes minds.
## Layout
A Cargo workspace of five crates (`crates/eureka-pipeline` holds the document shapes and keys, `crates/mind-body` the control store, launch primitive and `mind-heartbeat` timeline; the three below are the mind, the daemon and the client):
A Cargo workspace of five crates (`crates/eureka-pipeline` holds the document shapes and keys, `crates/mind-body` the control store, unit launcher, `mind-heartbeat`, the inert `mind-persona` organ and the `mind-self-run` actuator; the three below are the mind, the daemon and the client):
- `crates/huginn-mind`: storage, identity, admission, and queries and derived
status over memory documents.

View file

@ -172,7 +172,7 @@ pub fn serve<I: IndexSink<OwnedRedbMessagePackBackingStore> + Send + 'static>(
let loop_stopping = Arc::clone(&stopping);
let registry = schema_registry().unwrap();
let thread = std::thread::spawn(move || {
run(&mut daemon, &mut hub, &registry, None, &loop_stopping, &ServeOptions::default()).unwrap();
run(&mut daemon, &mut hub, None, &registry, None, &loop_stopping, &ServeOptions::default()).unwrap();
});
Server { addr, stopping, thread: Some(thread), ended: Arc::default(), _root: Some(root) }
}

View file

@ -109,6 +109,17 @@ impl Handled {
}
}
/// Which RUDP listener a request arrived on. `Full` is `--bind`, which the
/// faculties that write the mind reach. `Persona` is `--persona-bind`, the
/// only listener a Persona's uid can reach (the host fence decides that): it
/// answers what `HuginnMindRequest::reaches_persona_door` accepts and refuses
/// the rest with `MindRefusal::NotThisDoor` before the mind is asked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Door {
Full,
Persona,
}
/// The door checks an account id; the Mind's desk calls take it as the text it is.
fn short_id(id: AccountId) -> Short {
Short(id.0)
@ -177,6 +188,16 @@ impl<S: MindStore, I: IndexSink<S>> Daemon<S, I> {
runtime_id(self.mind.instance())
}
/// One request as it arrived at `door`: a request the door does not
/// answer is refused before the mind sees it, and every other goes to
/// `handle`. The wire reaches the mind only through here.
pub fn handle_at(&mut self, door: Door, request: HuginnMindRequest, now: DateTime<Utc>) -> Handled {
if door == Door::Persona && !request.reaches_persona_door() {
return Handled::Answered(HuginnMindResponse::Refused(MindRefusal::NotThisDoor));
}
self.handle(request, now)
}
/// One request, one answer, or a search to finish. `Admit` goes to the mind whole, because the
/// batch declares its own instance and admission's A1 is the check. Every
/// other request names an instance: `require_instance` now applies the
@ -1011,6 +1032,117 @@ pub(crate) mod tests {
assert_eq!(status(&mut daemon).persona, huginn_mind::wire::PersonaStatus::Absent);
}
/// The persona door refuses an admission before the mind sees it, so the
/// store is unchanged, and answers the reads and her own persona put; the
/// full door admits the same batch.
#[test]
fn the_persona_door_refuses_an_admission_and_answers_reads_and_her_persona() {
let (_root, mut daemon) = seeded();
let before = status(&mut daemon);
let admit = || HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)]));
assert_eq!(
daemon.handle_at(Door::Persona, admit(), now()).answered(),
HuginnMindResponse::Refused(MindRefusal::NotThisDoor)
);
assert_eq!(status(&mut daemon), before, "nothing was written");
let state = serde_json::json!({
"schemaVersion": "gamecult.persona_state.v0",
"provenance": {
"sourceSystem": "huginn", "sourceDocumentId": INSTANCE, "sourceUpdatedAt": "2026-11-19T10:00:00Z",
"exportedAt": "2026-11-19T10:00:00Z", "authority": "canonical"
},
"personaId": INSTANCE,
"publicName": "Test Persona",
"presentation": { "voiceSummary": "plain" },
"activationProfile": {
"underlyingOrganization": {}, "stableDispositions": {}, "behavioralDimensions": {},
"presentationStrategy": {}, "voiceStyle": {}, "situationalState": {}
},
"thoughtMemory": { "shortTerm": [], "memories": [], "incubation": [] },
"agencyPressure": { "pressures": [] },
"candidateActions": { "actions": [] },
"affect": {
"needs": [], "socialBonds": [], "statusReads": [], "moodDimensions": [],
"socialBiases": [], "doctrineStances": []
},
"updatedAt": "2026-11-19T10:00:00Z"
});
let put = HuginnMindRequest::PersonaPut {
instance: slug(INSTANCE),
provenance: provenance(),
state,
expected_updated_at: None,
};
assert!(matches!(
daemon.handle_at(Door::Persona, put, now()).answered(),
HuginnMindResponse::PersonaPut(huginn_mind::PersonaPutOutcome::Committed { .. })
));
assert!(matches!(
daemon.handle_at(Door::Persona, HuginnMindRequest::PersonaGet { instance: slug(INSTANCE) }, now()).answered(),
HuginnMindResponse::Persona(Some(_))
));
let query = HuginnMindRequest::Query { instance: slug(INSTANCE), selection: Selection::default(), semantic: None };
let HuginnMindResponse::Query(page) = daemon.handle_at(Door::Persona, query, now()).answered() else {
panic!("a query answers a page at the persona door")
};
let id = match page.items {
PipelinePageItems::Headers(items) => items[0].id.clone(),
PipelinePageItems::Documents(items) => items[0].id.clone(),
};
assert!(matches!(
daemon.handle_at(Door::Persona, HuginnMindRequest::View { instance: slug(INSTANCE), id }, now()).answered(),
HuginnMindResponse::View(Some(_))
));
assert_eq!(status(&mut daemon).documents, before.documents, "a persona put writes no pipeline document");
assert!(
matches!(daemon.handle_at(Door::Full, admit(), now()).answered(), HuginnMindResponse::Admit(_)),
"the full door hands the same batch to admission"
);
}
/// Every read the persona door answers reaches the mind there: none of the
/// source, chat, activity and roots reads is refused as `NotThisDoor`.
/// What the mind then says (a search, or `Unavailable` with no index or
/// forge) is the mind's, the same at either door.
#[test]
fn the_persona_door_hands_every_other_read_to_the_mind() {
use huginn_mind::wire::{ChatWindowQuery, SourceQuery};
let (_root, mut daemon) = seeded();
let reads = [
HuginnMindRequest::SearchSources {
instance: slug(INSTANCE),
query: SourceQuery { text: Line("reconcile".into()), texts: vec![], top_k: 5, repo: None, front: false },
},
HuginnMindRequest::SearchChat {
instance: slug(INSTANCE),
query: ChatQuery { texts: vec![Line("release".into())], rooms: vec![], after_ms: None, before_ms: None, top_k: 5 },
},
HuginnMindRequest::ChatWindow {
instance: slug(INSTANCE),
query: ChatWindowQuery { event_id: Short("$a".into()), before: 5, after: 0 },
},
HuginnMindRequest::StewardedActivity { instance: slug(INSTANCE), repos: vec![], after: None },
HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) },
];
for read in reads {
let operation = read.operation();
let at_door = daemon.handle_at(Door::Persona, read.clone(), now());
assert!(
!matches!(at_door, Handled::Answered(HuginnMindResponse::Refused(MindRefusal::NotThisDoor))),
"{operation} is refused at the persona door"
);
if let (Handled::Answered(at_door), Handled::Answered(at_full)) = (at_door, daemon.handle_at(Door::Full, read, now())) {
assert_eq!(at_door, at_full, "{operation} answers the same at either door");
}
}
assert!(matches!(
daemon.handle_at(Door::Persona, HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) }, now()).answered(),
HuginnMindResponse::RootsTouched(_)
));
}
/// A declared instance outside `Slug`'s grammar is refused by its own
/// name, `InvalidFormat`, on the read path, before the identity
/// comparison ever runs: it is not merely a foreign mind, it names no

View file

@ -467,7 +467,7 @@ mod door_smoke {
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
run(&mut daemon, &mut hub, &registry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap();
run(&mut daemon, &mut hub, None, &registry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap();
});
let mut stalled = connect(&path);
@ -591,7 +591,7 @@ mod door_smoke {
let registry = schema_registry().unwrap();
let mut bodies = crate::bodies::DeferredBodies::new(1 << 20, Duration::from_secs(60));
let desk = raw(MIND_SERVICE_ID, DESK_REQUEST_SCHEMA, "answer", "m-1", rmp_serde::to_vec_named(&answer("x", DeskAuthority::Operator, &["x"], wire(&hash, R1))).unwrap());
let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, &registry, &mut bodies, desk, now()).reply() else {
let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, crate::daemon::Door::Full, &registry, &mut bodies, desk, now()).reply() else {
panic!("expected a response")
};
assert_eq!(payload_schema, huginn_mind::envelope::FAILURE_SCHEMA);
@ -686,6 +686,7 @@ mod door_smoke {
state_root: root.path().to_path_buf(),
instance: slug(INSTANCE),
bind: "127.0.0.1:0".parse().unwrap(),
persona_bind: None,
qdrant_url: "http://127.0.0.1:1".into(),
ollama_urls: vec!["http://127.0.0.1:1".into()],
reserve_ollama_urls: Vec::new(),

View file

@ -1,5 +1,5 @@
//! The process: open one instance's mind, bind one socket, serve until a stop
//! signal. A mind that will not open ends the process with the refusal on
//! The process: open one instance's mind, bind its socket (and the persona
//! door's, when asked), serve until a stop signal. A mind that will not open ends the process with the refusal on
//! stderr and no socket ever bound.
use std::sync::Arc;
@ -15,7 +15,7 @@ fn main() -> Result<()> {
let options = parse_options(std::env::args().skip(1))?;
let embedder = pool(&options.ollama_urls, &options.reserve_ollama_urls, &options.embedding_model);
let index = QdrantIndex::new(&options.qdrant_url);
let Started { mut daemon, mut hub, registry, mut desk } = match startup(&options, embedder, index, Backoff::default()) {
let Started { mut daemon, mut hub, mut persona, registry, mut desk } = match startup(&options, embedder, index, Backoff::default()) {
Ok(started) => started,
Err(error) => {
eprintln!("huginn-daemon refuses to serve {}: {error:#}", options.instance.0);
@ -33,8 +33,11 @@ fn main() -> Result<()> {
}
eprintln!("huginn-daemon serving {} on {}", options.instance.0, hub.local_addr()?);
if let Some(door) = &persona {
eprintln!("huginn-daemon serving the persona door on {}", door.local_addr()?);
}
if let Some(door) = &desk {
eprintln!("huginn-daemon serving the desk door on {}", door.path().display());
}
run(&mut daemon, &mut hub, &registry, desk.as_mut(), &stopping, &ServeOptions::default())
run(&mut daemon, &mut hub, persona.as_mut(), &registry, desk.as_mut(), &stopping, &ServeOptions::default())
}

View file

@ -143,9 +143,10 @@ fn quick() -> Backoff {
Backoff { initial: Duration::from_millis(1), max: Duration::from_millis(2), recheck: Duration::from_secs(3600), search_deadline: Duration::from_secs(30) }
}
/// A daemon serving a mind over a real socket, with the ports the test gave it.
/// A daemon serving a mind over real sockets, its full door and its persona door, with the ports the test gave it.
struct Harness {
endpoint: String,
persona_endpoint: String,
stopping: Arc<AtomicBool>,
serving: Option<JoinHandle<Result<()>>>,
embedder: FakeEmbedder,
@ -172,19 +173,31 @@ impl Harness {
let mut daemon: Daemon<OwnedRedbMessagePackBackingStore, WorkerSink> = Daemon::new(mind, sink);
let mut hub = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
let endpoint = format!("rudp://{}", hub.local_addr().unwrap());
let mut door = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
let persona_endpoint = format!("rudp://{}", door.local_addr().unwrap());
let registry = schema_registry().unwrap();
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let options = ServeOptions::default();
let serving = std::thread::spawn(move || run(&mut daemon, &mut hub, &registry, None, &loop_stopping, &options));
Self { endpoint, stopping, serving: Some(serving), embedder, index, _root: root }
let serving =
std::thread::spawn(move || run(&mut daemon, &mut hub, Some(&mut door), &registry, None, &loop_stopping, &options));
Self { endpoint, persona_endpoint, stopping, serving: Some(serving), embedder, index, _root: root }
}
fn client(&self) -> Client {
Self::client_at(&self.endpoint)
}
/// A client of the persona door.
fn persona_client(&self) -> Client {
Self::client_at(&self.persona_endpoint)
}
fn client_at(endpoint: &str) -> Client {
let mut client = CultMesh::create_rudp_client_for_endpoint(
"semantic-test".to_string(),
CULTNET_OPERATION_CONNECTION_ID,
&self.endpoint,
endpoint,
CultMeshRudpSocketOptions::default(),
)
.unwrap();
@ -272,8 +285,19 @@ fn healthy() -> Harness {
/// the members.
#[test]
fn a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits() {
a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(Harness::client);
}
/// The same semantic read asked at the persona door: the search is held while the index works, and its answer leaves by
/// the persona door's own hub to the session that asked there.
#[test]
fn a_semantic_query_at_the_persona_door_is_answered_through_the_persona_door() {
a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(Harness::persona_client);
}
fn a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(client_of: fn(&Harness) -> Client) {
let harness = healthy();
let mut client = harness.client();
let mut client = client_of(&harness);
until_index(&mut client, "Current", |status| *status == IndexStatus::Current);
harness.index.state.lock().unwrap().hits = vec![
hit("question", id("question", "Q1"), 0.95),

View file

@ -78,7 +78,7 @@ use huginn_mind::{Mind, MindRefusal, MindStore, OwnedRedbMessagePackBackingStore
use crate::bodies::{
DEFERRED_BUDGET_BYTES, DEFERRED_CHUNK_BYTES, DeferredBodies,
};
use crate::daemon::{Daemon, Handled, IndexSink, Search, SearchTicket, runtime_id};
use crate::daemon::{Daemon, Door, Handled, IndexSink, Search, SearchTicket, runtime_id};
use crate::desk_door::{DeskDoor, bind_desk};
use huginn_mind::envelope::{OperationFailure, decode_request, encode_failure, encode_response};
use huginn_mind::MAX_DEFERRED_BODY_BYTES;
@ -111,6 +111,10 @@ pub struct Options {
pub state_root: PathBuf,
pub instance: Slug,
pub bind: SocketAddr,
/// The persona door (`--persona-bind`): a second RUDP listener answering
/// only what `HuginnMindRequest::reaches_persona_door` accepts. Absent,
/// the daemon has no persona door.
pub persona_bind: Option<SocketAddr>,
pub qdrant_url: String,
/// The GPU hosts: all take embedding at once. One is the plain case.
pub ollama_urls: Vec<String>,
@ -134,7 +138,7 @@ pub struct DeskOptions {
/// Exactly `--state-root`, `--instance`, `--bind`, `--qdrant-url`,
/// `--ollama-url` and `--embedding-model`, each required, each once, except
/// `--ollama-url`, which repeats for each GPU host, and the optional
/// `--reserve-ollama-url`, which repeats for each CPU host, and the optional `--forge-url`, once, and the optional pair `--desk-socket` (an absolute path) and `--desk-peer-uid` (a uid other than 0), both or neither, each once. The URLs are plain
/// `--reserve-ollama-url`, which repeats for each CPU host, and the optional `--forge-url` and `--persona-bind` (an ip:port other than `--bind`), each once, and the optional pair `--desk-socket` (an absolute path) and `--desk-peer-uid` (a uid other than 0), both or neither, each once. The URLs are plain
/// `http://`: this build carries no TLS.
pub fn parse_options(args: impl Iterator<Item = String>) -> Result<Options> {
let mut args = args;
@ -143,7 +147,7 @@ pub fn parse_options(args: impl Iterator<Item = String>) -> Result<Options> {
while let Some(name) = args.next() {
let name = name.strip_prefix("--").with_context(|| format!("expected --option, got {name:?}"))?;
ensure!(
matches!(name, "state-root" | "instance" | "bind" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url" | "desk-socket" | "desk-peer-uid"),
matches!(name, "state-root" | "instance" | "bind" | "persona-bind" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url" | "desk-socket" | "desk-peer-uid"),
"unsupported Huginn option --{name}"
);
let value = args.next().with_context(|| format!("missing value for --{name}"))?;
@ -167,10 +171,20 @@ pub fn parse_options(args: impl Iterator<Item = String>) -> Result<Options> {
};
let embedding_model = take("embedding-model")?;
ensure!(!embedding_model.is_empty(), "--embedding-model must name a model");
let bind: SocketAddr = bind.parse().with_context(|| format!("--bind must be an ip:port, got {bind:?}"))?;
let persona_bind = match values.get("persona-bind") {
None => None,
Some(door) => {
let door: SocketAddr = door.parse().with_context(|| format!("--persona-bind must be an ip:port, got {door:?}"))?;
ensure!(door != bind, "--persona-bind must not be --bind: the persona door is its own listener");
Some(door)
}
};
Ok(Options {
state_root,
instance: Slug(take("instance")?),
bind: bind.parse().with_context(|| format!("--bind must be an ip:port, got {bind:?}"))?,
bind,
persona_bind,
qdrant_url: url("qdrant-url")?,
ollama_urls: {
ensure!(!ollama_urls.is_empty(), "--ollama-url is required; repeat it for each GPU host");
@ -206,6 +220,7 @@ where
{
let mind = Mind::open(&options.state_root, &options.instance)?;
let hub = bind(options.bind, &runtime_id(&options.instance))?;
let persona = options.persona_bind.map(|door| bind(door, &runtime_id(&options.instance))).transpose()?;
let desk = options.desk.as_ref().map(|desk| bind_desk(&desk.socket, desk.peer_uid)).transpose()?;
let startup_entries = mind.index_entries(None)?;
let sink = WorkerSink::spawn(embedder, index, &options.instance, mind.genesis_receipt_id()?, startup_entries, backoff);
@ -214,14 +229,16 @@ where
Some(url) => daemon.with_forge(crate::sources::forge::HttpForge::new(url)),
None => daemon,
};
Ok(Started { daemon, hub, registry: schema_registry()?, desk })
Ok(Started { daemon, hub, persona, registry: schema_registry()?, desk })
}
/// What `startup` hands the loop: the daemon over the opened mind, the bound RUDP hub, the
/// catalog the RUDP door advertises, and the desk door when one was asked for.
/// persona door's hub when one was asked for, the catalog both RUDP doors advertise, and the
/// desk door when one was asked for.
pub struct Started {
pub daemon: Daemon<OwnedRedbMessagePackBackingStore, WorkerSink>,
pub hub: CultNetRudpServerHub,
pub persona: Option<CultNetRudpServerHub>,
pub registry: CultNetSchemaRegistry,
pub desk: Option<DeskDoor>,
}
@ -321,12 +338,14 @@ impl Routed {
}
/// One message in, one message out, or a search to wait for. Nothing here
/// reaches a mind except through `Daemon::handle`, and an envelope that does
/// reaches a mind except through `Daemon::handle_at`, at the `door` the message
/// arrived on, and an envelope that does
/// not decode never gets that far. A chunk request is answered from `bodies`
/// alone, on the session it came in on; every operation's reply leaves through
/// `respond`.
pub fn answer<S: MindStore, I: IndexSink<S>>(
daemon: &mut Daemon<S, I>,
door: Door,
registry: &CultNetSchemaRegistry,
bodies: &mut DeferredBodies,
message: CultNetMessage,
@ -345,7 +364,7 @@ pub fn answer<S: MindStore, I: IndexSink<S>>(
CultNetMessage::OperationRequest { message_id, operation, .. } => match decode_request(&message) {
Ok((message_id, request)) => {
let operation = request.operation();
match daemon.handle(request, now) {
match daemon.handle_at(door, request, now) {
Handled::Answered(response) => respond(&response, &message_id, operation, &runtime_id, bodies, now),
Handled::Searching(search) => return Routed::Search { message_id, operation, search },
}
@ -483,9 +502,11 @@ fn deliver(
deferred
}
/// A semantic query on its way through the index: who asked, what to call the
/// answer, the search to finish, and when the client stops being promised one.
/// A semantic query on its way through the index: who asked, at which door,
/// what to call the answer, the search to finish, and when the client stops
/// being promised one.
struct Waiting {
door: Door,
session: CultNetRudpServerSessionContext,
message_id: String,
operation: &'static str,
@ -494,9 +515,11 @@ struct Waiting {
}
/// Until `stopping`: expire what timed out, resend what was not acknowledged,
/// answer every frame waiting on the socket, then answer every semantic query
/// the index has finished or that has waited out the index's own
/// `search_deadline`. A semantic
/// answer every frame waiting on either RUDP door's socket, then answer every
/// semantic query the index has finished or that has waited out the index's
/// own `search_deadline`. A frame on `hub` is asked at `Door::Full`, one on
/// `persona` at `Door::Persona`, and a search's answer leaves by the door it
/// came in at. A semantic
/// query is never answered inline: `answer` hands back a `Search`, the loop
/// holds it beside its session and goes on serving, and the embedder and the
/// vector store are the worker's to wait on. A hostile datagram and a departed
@ -505,51 +528,18 @@ struct Waiting {
pub fn run<S: MindStore, I: IndexSink<S>>(
daemon: &mut Daemon<S, I>,
hub: &mut CultNetRudpServerHub,
mut persona: Option<&mut CultNetRudpServerHub>,
registry: &CultNetSchemaRegistry,
mut desk: Option<&mut DeskDoor>,
stopping: &AtomicBool,
options: &ServeOptions,
) -> Result<()> {
let timeout_ms = options.session_timeout.as_millis() as u64;
let mut bodies = DeferredBodies::new(DEFERRED_BUDGET_BYTES, options.deferred_ttl);
let mut waiting: BTreeMap<SearchTicket, Waiting> = BTreeMap::new();
while !stopping.load(Ordering::Relaxed) {
hub.remove_timed_out_sessions(timeout_ms);
if let Err(error) = hub.poll_resends() {
eprintln!("huginn: resending to a peer failed: {error:#}");
}
let mut served = 0_u32;
loop {
let event = match hub.receive_event_once() {
Ok(Some(event)) => event,
Ok(None) => break,
Err(error) => {
eprintln!("huginn: a datagram was not readable and was discarded: {error:#}");
break;
}
};
let CultNetRudpServerEvent::Frame { session, frame } = event else {
continue;
};
if frame.channel_id != "schema" {
continue;
}
let message = match decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)
{
Ok(message) => message,
Err(error) => {
eprintln!("huginn: a frame was not a CultNet message and was discarded: {error:#}");
continue;
}
};
match answer(daemon, registry, &mut bodies, message, Utc::now()) {
Routed::Reply(reply) => send(hub, &session, &reply),
Routed::Search { message_id, operation, search } => {
let until = Instant::now() + daemon.search_deadline();
waiting.insert(search.ticket, Waiting { session, message_id, operation, search, until });
}
}
served += 1;
let mut served = serve_frames(daemon, hub, Door::Full, registry, &mut bodies, &mut waiting, options);
if let Some(door) = persona.as_deref_mut() {
served += serve_frames(daemon, door, Door::Persona, registry, &mut bodies, &mut waiting, options);
}
let desk_served = desk.as_deref_mut().map_or(0, |door| door.serve_ready(daemon, Utc::now()));
let finished = collect_searches(daemon, &waiting);
@ -558,7 +548,14 @@ pub fn run<S: MindStore, I: IndexSink<S>>(
let Some(asked) = waiting.remove(&ticket) else { continue };
let response = daemon.finish(asked.search, found);
let reply = respond(&response, &asked.message_id, asked.operation, &daemon.runtime_id(), &mut bodies, Utc::now());
send(hub, &asked.session, &reply);
let out = match asked.door {
Door::Full => &mut *hub,
Door::Persona => match persona.as_deref_mut() {
Some(door) => door,
None => continue,
},
};
send(out, &asked.session, &reply);
}
if served == 0 && desk_served == 0 && !answered {
std::thread::sleep(options.idle_sleep);
@ -567,6 +564,57 @@ pub fn run<S: MindStore, I: IndexSink<S>>(
Ok(())
}
/// One pass over one RUDP door: expire its idle sessions, resend what it has
/// unacknowledged, and answer every frame waiting on its socket as asked at
/// `door`. Returns how many frames it answered or queued.
fn serve_frames<S: MindStore, I: IndexSink<S>>(
daemon: &mut Daemon<S, I>,
hub: &mut CultNetRudpServerHub,
door: Door,
registry: &CultNetSchemaRegistry,
bodies: &mut DeferredBodies,
waiting: &mut BTreeMap<SearchTicket, Waiting>,
options: &ServeOptions,
) -> u32 {
hub.remove_timed_out_sessions(options.session_timeout.as_millis() as u64);
if let Err(error) = hub.poll_resends() {
eprintln!("huginn: resending to a peer failed: {error:#}");
}
let mut served = 0_u32;
loop {
let event = match hub.receive_event_once() {
Ok(Some(event)) => event,
Ok(None) => break,
Err(error) => {
eprintln!("huginn: a datagram was not readable and was discarded: {error:#}");
break;
}
};
let CultNetRudpServerEvent::Frame { session, frame } = event else {
continue;
};
if frame.channel_id != "schema" {
continue;
}
let message = match decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) {
Ok(message) => message,
Err(error) => {
eprintln!("huginn: a frame was not a CultNet message and was discarded: {error:#}");
continue;
}
};
match answer(daemon, door, registry, bodies, message, Utc::now()) {
Routed::Reply(reply) => send(hub, &session, &reply),
Routed::Search { message_id, operation, search } => {
let until = Instant::now() + daemon.search_deadline();
waiting.insert(search.ticket, Waiting { door, session, message_id, operation, search, until });
}
}
served += 1;
}
served
}
/// What the index has finished, then what has waited too long: the latter as
/// an `Unavailable` detail, and abandoned, so the index does not start a search
/// nobody is waiting for. A search that finishes after its deadline finds
@ -680,14 +728,14 @@ mod tests {
("m-5b", request("m-5b", MIND_SERVICE_ID, "Admit", MIND_REQUEST_SCHEMA, admit), "operation-mismatch"),
];
for (id, message, code) in cases {
let reply = answer(&mut daemon, &registry, &mut fresh_bodies(), message, now()).reply();
let reply = answer(&mut daemon, Door::Full, &registry, &mut fresh_bodies(), message, now()).reply();
assert_eq!(rejected(&reply).0, id, "the client's own correlation key is echoed");
assert_eq!(rejected(&reply).1, code);
}
// The sixth code, `not-an-operation-request`, is the codec's and is
// pinned in `huginn_mind::envelope::tests`: `answer` never produces it, because a
// message of another family is answered with `Error` instead.
let reply = answer(&mut daemon, &registry, &mut fresh_bodies(), CultNetMessage::Error { error: "hello".into(), code: None, details: None }, now()).reply();
let reply = answer(&mut daemon, Door::Full, &registry, &mut fresh_bodies(), CultNetMessage::Error { error: "hello".into(), code: None, details: None }, now()).reply();
let CultNetMessage::Error { error, .. } = &reply else { panic!("expected an error, got {reply:?}") };
assert!(
!error.is_empty() && error.contains("cultnet.operation_request.v0") && error.contains("cultnet.schema_catalog_request.v0"),
@ -699,7 +747,7 @@ mod tests {
// A mind's refusal is an answer on the response schema, not a failure
// of the envelope: the client decodes it as the typed refusal it is.
let read = HuginnMindRequest::Query { instance: slug(OTHER), selection: Selection::default(), semantic: None };
let reply = answer(&mut daemon, &registry, &mut fresh_bodies(), encode_request("m-r", &read, None).unwrap(), now()).reply();
let reply = answer(&mut daemon, Door::Full, &registry, &mut fresh_bodies(), encode_request("m-r", &read, None).unwrap(), now()).reply();
let CultNetMessage::OperationResponse { status, payload_schema, .. } = &reply else {
panic!("expected an operation response, got {reply:?}");
};
@ -717,7 +765,7 @@ mod tests {
schema_ids: None,
kinds: None,
};
let reply = answer(&mut daemon, &registry, &mut fresh_bodies(), catalog, now()).reply();
let reply = answer(&mut daemon, Door::Full, &registry, &mut fresh_bodies(), catalog, now()).reply();
let CultNetMessage::SchemaCatalogResponse { message_id, schemas } = reply else {
panic!("expected a catalog response");
};
@ -785,7 +833,7 @@ mod tests {
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
let result = run(&mut daemon, &mut hub, &registry, None, &loop_stopping, &ServeOptions::default());
let result = run(&mut daemon, &mut hub, None, &registry, None, &loop_stopping, &ServeOptions::default());
(result, daemon)
});
@ -874,6 +922,43 @@ mod tests {
panic!("{name} never connected");
}
/// Over loopback, the persona door's listener refuses an admission by name and answers a
/// read, and the full door's listener admits the same batch: only that admission lands.
#[test]
fn the_persona_listener_refuses_an_admission_the_full_listener_takes() {
let root = tempfile::tempdir().unwrap();
let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
let mut hub = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
let mut door = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
let full = format!("rudp://{}", hub.local_addr().unwrap());
let persona = format!("rudp://{}", door.local_addr().unwrap());
let registry = schema_registry().unwrap();
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
let result = run(&mut daemon, &mut hub, Some(&mut door), &registry, None, &loop_stopping, &ServeOptions::default());
(result, daemon)
});
let admit = HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)]));
let mut her = connect(&persona, "persona");
assert_eq!(ask(&mut her, "p-admit", &admit), HuginnMindResponse::Refused(MindRefusal::NotThisDoor));
let HuginnMindResponse::Whoami(status) = ask(&mut her, "p-whoami", &HuginnMindRequest::Whoami) else {
panic!("the persona door answers whoami")
};
assert_eq!(status.documents, 0, "the refused admission wrote nothing");
let mut self_faculty = connect(&full, "full");
assert!(matches!(
ask(&mut self_faculty, "f-admit", &admit),
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })
));
stopping.store(true, Ordering::Relaxed);
let (result, mut daemon) = serving.join().unwrap();
result.unwrap();
assert_eq!(documents(&mut daemon), 1, "only the full door's admission landed");
}
/// One client admits batches that close, withdraw and re-open records while three others read
/// the same mind: fresh queries, cursor walks across commits, a hop and whoami. The loop is
/// serial, so every answer is one snapshot's; at quiesce each answer must equal what a fresh
@ -892,7 +977,7 @@ mod tests {
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
let result = run(&mut daemon, &mut hub, &registry, None, &loop_stopping, &ServeOptions::default());
let result = run(&mut daemon, &mut hub, None, &registry, None, &loop_stopping, &ServeOptions::default());
(result, daemon)
});
@ -1057,7 +1142,7 @@ mod tests {
at: DateTime<Utc>,
) -> CultMeshCdnArtifactManifest {
let registry = schema_registry().unwrap();
deferred_manifest(&answer(daemon, &registry, bodies, encode_request(message_id, read, None).unwrap(), at).reply())
deferred_manifest(&answer(daemon, Door::Full, &registry, bodies, encode_request(message_id, read, None).unwrap(), at).reply())
}
/// Whether the first chunk of a manifest is still served at an injected time.
@ -1068,7 +1153,7 @@ mod tests {
at: DateTime<Utc>,
) -> bool {
let registry = schema_registry().unwrap();
found(&answer(daemon, &registry, bodies, chunk_request(manifest, 0), at).reply())
found(&answer(daemon, Door::Full, &registry, bodies, chunk_request(manifest, 0), at).reply())
}
/// An answer larger than one send can carry is deferred to the body plane
@ -1133,7 +1218,7 @@ mod tests {
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
let result = run(&mut daemon, &mut hub, &registry, None, &loop_stopping, &ServeOptions::default());
let result = run(&mut daemon, &mut hub, None, &registry, None, &loop_stopping, &ServeOptions::default());
(result, daemon)
});
@ -1381,7 +1466,7 @@ mod tests {
let manifest = ask_deferred(&mut daemon, &mut bodies, "m-v", &read, t0);
assert!(manifest.chunks.len() >= 2, "the fixture needs a second chunk to serve");
let mut chunk = |index: usize, at: i64| {
answer(&mut daemon, &registry, &mut bodies, chunk_request(&manifest, index), after(at)).reply()
answer(&mut daemon, Door::Full, &registry, &mut bodies, chunk_request(&manifest, index), after(at)).reply()
};
assert!(found(&chunk(0, 59)), "inside the TTL");
assert!(found(&chunk(1, 118)), "serving a chunk slid the expiry past the first TTL");
@ -1394,7 +1479,7 @@ mod tests {
let again = ask_deferred(&mut daemon, &mut bodies, "m-v2", &read, after(179));
assert_eq!(again.content_hash, manifest.content_hash, "the same answer is the same body");
let bytes = fetch_content(&again, MAX_DEFERRED_BODY_BYTES, |request| {
Ok(answer(&mut daemon, &registry, &mut bodies, request, after(180)).reply())
Ok(answer(&mut daemon, Door::Full, &registry, &mut bodies, request, after(180)).reply())
})
.unwrap();
assert_eq!(bytes, expected);
@ -1494,7 +1579,7 @@ mod tests {
("record_key", chunk("m", "abc", &huge)),
];
for (case, message) in refused {
let reply = answer(&mut daemon, &registry, &mut bodies, message, now()).reply();
let reply = answer(&mut daemon, Door::Full, &registry, &mut bodies, message, now()).reply();
let CultNetMessage::Error { error, .. } = &reply else {
panic!("{case}: expected a transport error, got {reply:?}");
};
@ -1503,9 +1588,9 @@ mod tests {
}
assert_eq!(documents(&mut daemon), 0);
let reply = answer(&mut daemon, &registry, &mut bodies, whoami(&at, MIND_SERVICE_ID, "whoami", MIND_REQUEST_SCHEMA), now()).reply();
let reply = answer(&mut daemon, Door::Full, &registry, &mut bodies, whoami(&at, MIND_SERVICE_ID, "whoami", MIND_REQUEST_SCHEMA), now()).reply();
assert_eq!(decode_response(&reply).unwrap().0, at, "a field of exactly the bound is served");
let reply = answer(&mut daemon, &registry, &mut bodies, chunk(&at, &at, &at), now()).reply();
let reply = answer(&mut daemon, Door::Full, &registry, &mut bodies, chunk(&at, &at, &at), now()).reply();
assert!(!found(&reply), "an unknown chunk is answered found: false, not refused at the door");
}
@ -1565,6 +1650,7 @@ mod tests {
state_root: root.path().to_path_buf(),
instance: slug(INSTANCE),
bind: port,
persona_bind: Some("127.0.0.1:0".parse().unwrap()),
qdrant_url: "http://127.0.0.1:1".into(),
ollama_urls: vec!["http://127.0.0.1:1".into()],
reserve_ollama_urls: Vec::new(),
@ -1588,6 +1674,8 @@ mod tests {
drop(occupied);
let started = started(&options).expect("both gates open");
assert_eq!(started.hub.local_addr().unwrap(), port);
let door = started.persona.as_ref().expect("the persona door was asked for and bound");
assert_ne!(door.local_addr().unwrap(), port, "the persona door is its own listener");
}
#[test]
@ -1604,6 +1692,7 @@ mod tests {
state_root: PathBuf::from(root),
instance: slug("yggdrasil"),
bind: "127.0.0.1:17872".parse().unwrap(),
persona_bind: None,
qdrant_url: "http://127.0.0.1:6333".into(),
ollama_urls: vec!["http://10.77.0.4:11434".into()],
reserve_ollama_urls: Vec::new(),
@ -1647,5 +1736,11 @@ mod tests {
assert_eq!(parse_options(args(&forged)).unwrap().forge_url.as_deref(), Some("http://127.0.0.1:3310"));
assert!(parse_options(args(&[good.to_vec(), vec!["--forge-url", "https://127.0.0.1:3310"]].concat())).is_err());
assert!(parse_options(args(&[forged.clone(), vec!["--forge-url", "http://127.0.0.1:3311"]].concat())).is_err());
// The persona door is optional, once, an ip:port, and never the full door's.
let door = [good.to_vec(), vec!["--persona-bind", "127.0.0.1:17862"]].concat();
assert_eq!(parse_options(args(&door)).unwrap().persona_bind, Some("127.0.0.1:17862".parse().unwrap()));
assert!(parse_options(args(&[door.clone(), vec!["--persona-bind", "127.0.0.1:17863"]].concat())).is_err());
assert!(parse_options(args(&[good.to_vec(), vec!["--persona-bind", "not-an-address"]].concat())).is_err());
assert!(parse_options(args(&[good.to_vec(), vec!["--persona-bind", "127.0.0.1:17872"]].concat())).is_err());
}
}

View file

@ -549,13 +549,13 @@ fn a_busy_pass_is_not_followed_by_the_idle_sleep() {
];
let options = parse_options(args.iter().map(|arg| arg.to_string())).unwrap();
let embedder = pool(&options.ollama_urls, &options.reserve_ollama_urls, &options.embedding_model);
let Started { mut daemon, mut hub, registry, desk: mut door } =
let Started { mut daemon, mut hub, persona: _, registry, desk: mut door } =
startup(&options, embedder, QdrantIndex::new(&options.qdrant_url), Backoff::default()).unwrap();
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
let serve = ServeOptions { idle_sleep: Duration::from_millis(600), ..ServeOptions::default() };
run(&mut daemon, &mut hub, &registry, door.as_mut(), &loop_stopping, &serve)
run(&mut daemon, &mut hub, None, &registry, door.as_mut(), &loop_stopping, &serve)
});
std::thread::sleep(Duration::from_millis(100));
let frame = framed(&catalog_request());

View file

@ -268,17 +268,9 @@ impl<S: MindStore> Mind<S> {
if self.is_empty() {
return Err(MindRefusal::MissingIdentity);
}
// P1
persona::validate_shape(&state)?;
// P2
// P1 to P3: the document alone, the one check an offline reader of a state file shares.
let mind = self.instance().clone();
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);
}
persona::validate_document(&mind, &state)?;
// P4
let stored = self.stored_updated_at()?;
if stored != expected_updated_at {

View file

@ -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
/// failure is the refusal; it names where and which keyword, never the value.
pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
let compiled = compiled()?;
let Err(error) = compiled.validator.validate(state) else { return Ok(()) };
let mut path = error
@ -115,6 +115,21 @@ pub(crate) 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.
pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result<Value, MindRefusal> {
rmp_serde::from_slice::<HuginnPersonaEntry>(&envelope.payload)

View file

@ -2792,13 +2792,16 @@ mod tests {
/// The upgrade gate on a real store (ruling readback-gate-and-materialized-image):
/// the one function `Mind::read_back` over a scratch copy of a state root.
/// Opens the store read-write, so run it on a copy, never the live file.
/// Measured about 30 s in debug at 11,328 documents.
/// `HUGINN_MIND_INSTANCE` names the instance whose store it opens, `eureka`
/// when unset, so every Mind's store is gated the same way before a release
/// moves her daemon. Measured about 30 s in debug at 11,328 documents.
#[test]
#[ignore = "needs HUGINN_MIND_SNAPSHOT, a scratch copy of a Huginn state root"]
fn stored_documents_read_back() {
let root = std::env::var("HUGINN_MIND_SNAPSHOT").expect("HUGINN_MIND_SNAPSHOT names a scratch copy of the state root");
let instance = std::env::var("HUGINN_MIND_INSTANCE").unwrap_or_else(|_| "eureka".into());
let started = std::time::Instant::now();
let mind = Mind::open(std::path::Path::new(&root), &Slug("eureka".into())).unwrap();
let mind = Mind::open(std::path::Path::new(&root), &Slug(instance)).unwrap();
let count = mind.read_back().unwrap();
println!("read back {count} stored documents in {:?}", started.elapsed());
}

View file

@ -117,6 +117,10 @@ pub enum MindRefusal {
/// reached.
CursorInvalid { message: String },
Unavailable { detail: String },
/// The request reached the persona door, which answers reads and the
/// mind's own persona document and nothing that writes the mind
/// (`HuginnMindRequest::reaches_persona_door`). Nothing was written.
NotThisDoor,
}
impl std::fmt::Display for MindRefusal {

View file

@ -430,6 +430,28 @@ impl HuginnMindRequest {
}
}
/// Whether the persona door answers this request. The persona door is the
/// daemon's second listener, the only one a Persona's uid can reach: it
/// serves the mind's reads and her own persona document, and refuses
/// every write to the mind (`MindRefusal::NotThisDoor`). The match has no
/// wildcard, so a new request does not compile until it is classified
/// here.
pub fn reaches_persona_door(&self) -> bool {
match self {
Self::Whoami
| Self::View { .. }
| Self::Query { .. }
| Self::PersonaGet { .. }
| Self::PersonaPut { .. }
| Self::SearchSources { .. }
| Self::SearchChat { .. }
| Self::ChatWindow { .. }
| Self::StewardedActivity { .. }
| Self::RootsTouched { .. } => true,
Self::Admit(_) => false,
}
}
/// The instance the request declares; `Whoami` declares none.
pub fn instance(&self) -> Option<&Slug> {
match self {
@ -633,6 +655,7 @@ mod tests {
scores: Some(vec![0.5]),
}),
HuginnMindResponse::Refused(refusal),
HuginnMindResponse::Refused(MindRefusal::NotThisDoor),
HuginnMindResponse::Persona(None),
HuginnMindResponse::Persona(Some(PersonaStateView {
value: serde_json::json!({ "personaId": INSTANCE }),

View file

@ -23,6 +23,10 @@ publish.workspace = true
# two until the workspace pin and the kit's meet.
# `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 Projector's prompt (`projection`), so
# the membrane's text stays Ghostlight's; the Projector asks through the connector kit's client (`model-connector`).
# `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`);
# `uuid`'s v5 makes a Self run's session id derivable from the run's id.
[dependencies]
@ -33,13 +37,17 @@ cultcache-rs.workspace = true
cultnet-rs.workspace = true
eureka-pipeline = { path = "../eureka-pipeline" }
eureka-state = { path = "../eureka-state", default-features = false }
ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" }
huginn-mind = { path = "../huginn-mind" }
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector" }
rmp-serde = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
toml = { version = "0.9", default-features = false, features = ["std", "serde", "parse"] }
unicode-general-category = "1"
# Clips on grapheme boundaries (`projection::select::clip`), so no ZWJ sequence is split; already in the graph through Ghostlight.
unicode-segmentation = "1"
uuid = { version = "1", default-features = false, features = ["v5"] }
[target.'cfg(unix)'.dependencies]
@ -58,6 +66,9 @@ proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full"] }
tempfile = "3"
# 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.
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector", features = ["daemon"] }
[lib]
name = "mind_body"

View file

@ -1,7 +1,7 @@
# mind-body
The Mind's body: the control store, the launch primitive, the `mind-heartbeat`
timeline and the `mind-self-run` actuator.
The Mind's body: the control store, the unit launcher, the `mind-heartbeat`, the
inert `mind-persona` organ and the `mind-self-run` actuator.
`mind-self-run --instance <slug> [--endpoint rudp://<ip>:<port>]` runs inside
`mind-self@<instance>`. It finds her one open Self run, starts `claude` over
@ -12,7 +12,9 @@ wrong or the mind cannot be reached.
## The heartbeat
`mind-heartbeat` is the one process that decides who wakes and when: each beat falls when the Minds' voted tempo has passed and goes to the Mind that has waited longest, bent by the urgency she declares and a member addressing her; the operator tagging or naming a Persona launches her at once. `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` 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
`tests/self_run.rs`: the real `mind-self-run` against the real daemon with a

View file

@ -0,0 +1,6 @@
responder 3: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 2 lines are the Minds' alone.
responder 4: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko answered it. Meta, who runs the place last spoke 5 min ago. The last 3 lines are the Minds' alone.
responder 5: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 4 lines are the Minds' alone.
responder 6: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 5 lines are the Minds' alone.
responder 7: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 6 lines are the Minds' alone.
responder 8: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org); "aqua" (@aqua:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 7 lines are the Minds…

View file

@ -0,0 +1,4 @@
quiet-beat.toml: - the conversation: Lately @libby:gamecult.org to the room; Kiko to the room. The last 3 lines are the Minds' alone.
operator-warm.toml: - the conversation: Meta, who runs the place is waiting on him. Lately Meta, who runs the place with him. Meta, who runs the place last spoke 1 min ago.
mind-teases.toml: - the conversation: Lately he to the room; @aqua:gamecult.org to the room; Kiko with him. The last 3 lines are the Minds' alone.
deru-passing.toml: - the conversation: Lately @weksa:gamecult.org to the room; Deru to the room. Deru last spoke 1 min ago.

View file

@ -0,0 +1,23 @@
# 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"

View file

@ -0,0 +1,31 @@
# 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"

View file

@ -0,0 +1,27 @@
# 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"

View file

@ -0,0 +1,33 @@
# 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"

View file

@ -0,0 +1,148 @@
{
"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"
}

View file

@ -93,19 +93,28 @@ pub(crate) fn project_names(repo: &OrgRepo, listed: &[Short]) -> Vec<Name> {
names
}
/// Whether `text` holds `name` as a whole word, in any case or exactly as written: the characters on either side are not letters or
/// digits. An identity match on a name, not a judgement of meaning.
/// Whether `text` holds `name` as a whole word, in any case or exactly as written. A name is glued, and so not her name,
/// when a letter or digit touches it, or a single hyphen joins it to one (`mind-eureka`, `Eureka-chan`); everything else
/// is a boundary on either side: whitespace, punctuation, `/`, `_`, `.`, `\`, and a double hyphen or a dash. So
/// `/var/lib/mind-eureka/` never names her, and `_Eureka_`, `Eureka/Libby`, `ok...Eureka?` and `Huginn.toml` do. An
/// identity match on a name, not a judgement of meaning.
pub(crate) fn names_whole_word(text: &str, name: &str, exact: bool) -> bool {
let (text, name) = if exact { (text.to_string(), name.to_string()) } else { (text.to_lowercase(), name.to_lowercase()) };
if name.is_empty() {
return false;
}
// Every character offset, not every non-overlapping match: a name may overlap itself ("ab ab" in "xab ab ab").
text.char_indices().any(|(start, _)| {
text[start..].starts_with(&name)
&& !text[..start].chars().next_back().is_some_and(char::is_alphanumeric)
&& !text[start + name.len()..].chars().next().is_some_and(char::is_alphanumeric)
})
text.char_indices().any(|(start, _)| text[start..].starts_with(&name) && !glued(text[..start].chars().rev()) && !glued(text[start + name.len()..].chars()))
}
/// Whether the characters leading away from a name, nearest first, glue it to more of a word: a letter or digit, or a
/// single hyphen with a letter or digit beyond it.
fn glued(mut away: impl Iterator<Item = char>) -> bool {
match away.next() {
Some(c) if c.is_alphanumeric() => true,
Some('-') => away.next().is_some_and(char::is_alphanumeric),
_ => false,
}
}
#[cfg(test)]

View file

@ -138,3 +138,39 @@ fn a_direct_message_is_for_her_whatever_the_basis() {
assert!(!is_for(&nibu, &ChatDelivery { form: Form::Notice, ..dm.clone() }));
assert!(!is_for(&nibu, &ChatDelivery { form: Form::Edit, ..dm }));
}
#[test]
fn a_name_glued_to_a_word_is_not_her_name_and_every_other_boundary_is() {
// Soul's forms (third pass on C3a): every one names her except the six glued to a word.
let eureka = Addressee::new("@eureka:chat", ["eureka", "Eureka"]);
let glued = ["Eurekas idea", "Eurekaさん", "ÉEureka", "Eureka-chan", "/var/lib/mind-eureka/x", "mind-eureka"];
let forms = [
"Eureka, are you there", "Eureka: look", "eureka?", "Eureka!", "Eureka.", "Eureka's turn", "Eureka’s turn", "Eurekas idea", "the Eureka's", "ask eureka about it",
"thanks eureka", "eureka", "Eureka\n", "`eureka`", "**Eureka**", "*Eureka*", "_Eureka_", "__Eureka__", "~~Eureka~~", "[Eureka](https://matrix.to/#/@eureka:gamecult.org)",
"https://matrix.to/#/@eureka:gamecult.org hi", "@eureka:gamecult.org hi", "@eureka hi", "<@eureka>", "(Eureka)", "\"Eureka\"", "«Eureka»", "—Eureka—", "Eureka—can you",
"Eureka--can you", "Eureka - can you", "Eureka/Libby, can you two", "Libby/Eureka can you", "Eureka/Nibu", "ok...Eureka?", "ok… Eureka?", "Hmm.Eureka?", "Eureka.Can you",
"Eureka...", "Eureka…", "#eureka", "Eurekaさん", "エウレカ Eureka", "Eureka、", "Eureka。", "ÉEureka", "Eureka-chan", "Eureka_bot", "Eureka\\", "\\Eureka",
"Eureka:\n> quoted", "> Eureka hi", "Eureka;", "Eureka'", "'Eureka'", "Eureka(?)", "Eureka+Libby", "Eureka&Libby", "Eureka|Libby", "Eureka=", "Eureka. ",
"/var/lib/mind-eureka/x", "eureka.cc", "eureka_state", "mind-eureka", "eureka.gamecult.org", "https://eureka.gamecult.org/forge", "C:\\eureka\\x", "Eureka.rs",
];
assert_eq!(forms.len(), 69, "Soul's whole list");
for form in forms {
assert_eq!(addresses(&eureka, &said(form, &[])), !glued.contains(&form), "{form:?}");
}
// Each side of the rule on its own: a hyphen joins only with a letter or digit beyond it, before and after.
for (text, names) in [("x-eureka", false), ("eureka-x", false), ("--eureka", true), ("eureka--", true), ("x--eureka", true), ("eureka--x", true), ("-eureka", true), ("eureka-", true), (".eureka", true), ("eureka.x", true), ("x.eureka", true)] {
assert_eq!(addresses(&eureka, &said(text, &[])), names, "{text:?}");
}
}
#[test]
fn a_project_name_holds_at_every_boundary_but_a_glued_one() {
for repo in ["GameCult/Huginn", "GameCult/CultLib", "GameCult/gamecult-ops", "GameCult/cultcache-rs"] {
let steward = steward(repo, &[]);
let short = repo.split_once('/').unwrap().1;
for text in [format!("{repo} PR #76"), format!("{short}/main is red"), format!("_{short}_ is down"), format!("see {short}--now"), format!("{short}.toml"), format!("{short}'s build")] {
assert!(addresses(&steward, &said(&text, &[])), "{text:?}");
}
assert!(!addresses(&steward, &said(&format!("mind-{short}"), &[])), "{short} glued by a hyphen");
}
}

View file

@ -12,15 +12,54 @@
//! `persona.env`) are still parsed, so a start refuses the configuration the turn
//! will need. Without `--endpoint` the daemon is `HUGINN_ENDPOINT`; no call is made
//! to it.
//!
//! `mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>]
//! [--room <fixture.toml>] [--seed N] [--state <file>] [--select-only | --renders K [--through projector|persona|interpreter]
//! [--judge <state-file>]]` is the experiment tool over the Projector and the Persona stage
//! (`mind_body::projection::project`): it prints, as JSON, the packet the Select stage builds from her stored 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), and with `--renders` the Projector's narrations of K successive turns;
//! `--through persona` adds her prose and `--through interpreter` what the Interpreter decides she says; `--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`.
//!
//! 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::path::Path;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::Result;
use mind_body::cli::instance_and_endpoint;
use anyhow::{Context, Result, anyhow, bail};
use eureka_state::HuginnClient;
use mind_body::chat_rudp::{RudpChat, connection_id};
use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint};
use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path};
use mind_body::persona::{Config, carry};
use mind_body::heartbeat::{FileStore, HeartbeatView};
use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file};
use mind_body::projection::{HuginnPersonaSource, KitModel, Model, MouthReader, 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 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>] [--select-only | --renders K [--through projector|persona|interpreter] [--judge <state-file>]] | (--batch <plan> | --simulate <plan>) --out <report.md>";
/// How long one call to the mind may take.
const TIMEOUT: Duration = Duration::from_secs(15);
/// How long the mouth may take to answer one read.
const CHAT_TIMEOUT: Duration = Duration::from_secs(20);
/// How long the kit may take to answer one Projector or judge turn.
const MODEL_TIMEOUT: Duration = Duration::from_secs(300);
// The binary is the one place that reads the process: its arguments and
// the environment. The library reads neither (clippy.toml, `#![forbid]` in lib.rs).
@ -39,7 +78,154 @@ fn run() -> Result<String> {
Ok(carry(&control, &swarm, &instance).to_string())
}
fn required(name: &str) -> Result<String> {
setting(name).ok_or_else(|| anyhow!("{name} is not set"))
}
/// The text of the credential file named by `name`; never echoed.
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"))
}
/// The credentials directory systemd hands the unit; its absence names the variable.
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")]
fn credentials_directory() -> Result<PathBuf> {
std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from).ok_or_else(|| anyhow!("CREDENTIALS_DIRECTORY is not set"))
}
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 batch_plan, mut simulate_plan, mut out, mut rest) = (None, None, None, Vec::new());
let mut given = args.iter();
while let Some(flag) = given.next() {
let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{PROJECT_USAGE}"));
match flag.as_str() {
"--kind" => {
kind = Some(match value()?.as_str() {
"chat" => TurnKind::Chat,
"beat" => TurnKind::Beat,
"reflection" => TurnKind::Reflection,
_ => 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()?),
"--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,
"interpreter" => Through::Interpreter,
_ => bail!("{PROJECT_USAGE}"),
}
}
"--batch" => batch_plan = Some(PathBuf::from(value()?)),
"--simulate" => simulate_plan = Some(PathBuf::from(value()?)),
"--out" => out = Some(PathBuf::from(value()?)),
"--select-only" => select_only = true,
"--instance" | "--endpoint" => rest.extend([flag.clone(), value()?]),
_ => bail!("{PROJECT_USAGE}"),
}
}
let planned = batch_plan.is_some() || simulate_plan.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() || 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}");
}
let (instance, address) = instance_and_maybe_endpoint(&rest, setting("HUGINN_ENDPOINT"), PROJECT_USAGE)?;
let tuning = setting("MIND_PERSONA_TUNING").map_or_else(|| Path::new(TUNING_ROOT).join(&instance.0).join(TUNING_FILE), PathBuf::from);
// Her stored state is asked only when no state is given; with a state file no daemon is needed or reached.
let persona = address.map(|address| HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT)));
let renders = if select_only || planned { None } else { Some(renders.unwrap_or(1)) };
let model = if renders.is_some() || planned {
let endpoint: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
Some(KitModel::open(endpoint, connector_key(&credentials_directory()?)?, &instance.0, MODEL_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 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 };
let request = ProjectRequest { judge_against: judge, ..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 = 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>"))?;
Some(RudpChat::new(endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT))
}
_ => None,
};
let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new);
let organs = ProjectOrgans {
persona: harness.persona,
chat: chat.as_ref().map(|chat| chat as &dyn MouthReader),
addressing: heartbeat.as_ref().map(|store| store as &dyn HeartbeatView),
model: harness.model,
};
let request = ProjectRequest {
instance: instance.0.clone(),
kind: kind.unwrap_or(TurnKind::Beat),
state,
room: here,
seed: seed.unwrap_or(seed_now),
renders,
judge_against: judge,
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(),
own_sender: required("MIND_PERSONA_SELF_SENDER")?,
tuning: harness.tuning.clone(),
through,
last_heard: vec![],
recent: vec![],
own_rooms: vec![],
};
let report = project(&organs, &request, chrono::Utc::now())?;
let addressing = &report["addressing"];
// The addressing source is what decides "said to her": said first, where a person running this by hand sees it.
eprintln!(
"mind-persona project: addressing from {} ({}); table written {}",
addressing["source"].as_str().unwrap_or("?"),
addressing["why"].as_str().unwrap_or("?"),
addressing["age_minutes"].as_i64().map_or_else(|| "never".to_owned(), |minutes| format!("{minutes} min ago")),
);
Ok(serde_json::to_string_pretty(&report)?)
}
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments")]
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) == Some("project") {
match run_project(&args[1..]) {
Ok(report) => println!("{report}"),
Err(error) => {
eprintln!("mind-persona project: {error:#}");
std::process::exit(2);
}
}
return;
}
match run() {
Ok(outcome) => println!("{outcome}"),
Err(error) => {

View file

@ -45,6 +45,13 @@ const USAGE: &str =
/// `rudp://<ip>:<port>` is refused with `usage` or a fixed message, and no
/// value is echoed.
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 rest = args.iter();
while let Some(flag) = rest.next() {
@ -60,12 +67,12 @@ pub fn instance_and_endpoint(args: &[String], env_endpoint: Option<String>, usag
}
let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?);
instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?;
let endpoint = endpoint.or(env_endpoint).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?;
let Some(endpoint) = endpoint.or(env_endpoint) else { return Ok((instance, None)) };
let address = endpoint
.strip_prefix("rudp://")
.and_then(|address| address.parse::<SocketAddr>().ok())
.ok_or_else(|| anyhow!("the endpoint is not rudp://<ip>:<port>"))?;
Ok((instance, address))
Ok((instance, Some(address)))
}
/// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty

View file

@ -32,7 +32,7 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug};
use huginn_mind::PipelineFacts;
use crate::address::{Addressee, Name, is_for, project_names};
use crate::chat_client::{Chat, ChatDelivery};
use crate::chat_client::{Basis, Chat, ChatDelivery};
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
use crate::launch::{Clock, Launcher};
use crate::queue::{MindPort, headers, in_force, of_kind};
@ -98,11 +98,15 @@ pub struct Config {
}
impl Config {
/// Refuses no Persona, a Persona twice, or a beat of zero seconds.
/// Refuses no Persona, a Persona twice, a beat of zero seconds, or an operator id that is also a Persona's: one
/// 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> {
if personas.is_empty() {
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 {
bail!("the beat is zero seconds");
}
@ -220,6 +224,10 @@ pub trait Store {
/// What a Persona unit may read of `heartbeat.cc`: the swarm's addressing. Read-only.
pub trait HeartbeatView {
fn addressing(&self) -> Result<Option<Addressing>>;
/// When the store was last written, so a reader can tell a stale table; none when there is no store at all.
fn written_at(&self) -> Option<DateTime<Utc>> {
None
}
}
/// The store as a CultCache single-file store under the unit's state directory.
@ -315,6 +323,10 @@ impl HeartbeatView for FileStore {
fn addressing(&self) -> Result<Option<Addressing>> {
self.load_addressing()
}
fn written_at(&self) -> Option<DateTime<Utc>> {
std::fs::metadata(&self.path).and_then(|meta| meta.modified()).ok().map(DateTime::<Utc>::from)
}
}
/// What the operator stores allow: the swarm brake, and each instance's own
@ -385,12 +397,125 @@ pub(crate) fn stewardships_of(mind: &dyn MindPort) -> Result<(Vec<Name>, Vec<Org
Ok((names, repos))
}
/// Whether a delivery wakes `who` off the beat: the operator or another Mind of
/// the roster addresses her. A Mind naming herself does not; a member does not.
fn wakes(config: &Config, who: &Addressee, delivery: &ChatDelivery) -> bool {
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)
/// A member (anyone not the operator) has a pending delivery that addresses her: the beat's urgency. The one owner of
/// that reading: the poll's rows and the simulator's beat both ask it, over the deliveries the mouth would give her.
pub(crate) fn addressed_by_member(operators: &[String], who: &Addressee, pending: &[ChatDelivery]) -> bool {
pending.iter().any(|delivery| !operators.contains(&delivery.sender) && 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)
}
}
/// Which lines wake a Persona off the beat. `Live` is the heartbeat's rule today and the only one `poll` uses; the rest
/// are what desk question `po-mind-wakes-mind` weighs, run in `mind-persona project --simulate` until it is answered.
/// The beat is not here: every policy has it, and it wakes one Persona by `tempo::pick`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum WakePolicy {
/// The operator or another Mind addressing her (`is_for`). A member's line does not.
Live,
/// Ruling `persona-only-wake-humans-in-rooms`: a line addressing her, from anyone, and any human line in her rooms.
Ruled,
/// Ruling `persona-only-humans-pace`: a human's line wakes her in her own room (a direct message, or a room that is
/// hers); 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 this many Mind lines in a row came before it across her rooms (`LineFacts::mind_run`): the
/// backstop.
HumansPace(usize),
/// `Ruled`, with at most this many lines in her current Mind-only run (`LineFacts::mind_run`) before a human must
/// speak where it runs: a Mind's line past the cap wakes no one.
NamesWithCap(usize),
/// The swarm's old loop, a control: any line in her rooms but her own.
AllMessages,
}
/// 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,
/// A Mind's line that does not address her: only the control wakes on it.
Mind,
}
/// What the room says about a line, beside the line: the facts a policy may weigh. The live poll knows none of them yet
/// and passes the default; `Live` reads none.
#[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 room she sees, so a loop
/// cannot dodge the backstop by changing rooms, and ended only by a human's line in a room the run has lines in.
pub mind_run: usize,
/// The line is in a room of hers: a direct message (the delivery says so) or a room configured as hers.
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,
}
/// 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 }
}
}
/// Whether a line in her rooms wakes `who` off the beat under `policy`, and why. The one owner of the wake rule: the
/// heartbeat's poll asks it with `Live`, the simulator with the policy under test.
pub(crate) fn wakes(policy: WakePolicy, who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, facts: LineFacts) -> Option<WakeCause> {
if speaker == Speaker::Her {
return None;
}
let addressed = is_for(who, delivery);
let human = speaker.human();
let cause = match (human, addressed) {
(true, true) => WakeCause::AddressedByHuman,
(true, false) => WakeCause::Human,
(false, true) => WakeCause::AddressedByMind,
(false, false) => WakeCause::Mind,
};
let wakes = match policy {
WakePolicy::Live => addressed && matches!(speaker, Speaker::Operator | Speaker::Mind),
WakePolicy::Ruled => human || addressed,
WakePolicy::HumansPace(cap) => {
let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply));
if human { addressed || delivery.is_direct || facts.own_room || facts.in_exchange } else { explicit && facts.mind_run < cap }
}
WakePolicy::NamesWithCap(cap) => human || (addressed && facts.mind_run < cap),
WakePolicy::AllMessages => true,
};
wakes.then_some(cause)
}
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 mouth pages a pending answer, so fewer deliveries may come than wait.
@ -435,7 +560,7 @@ impl Row<'_> {
/// A member (not the operator) has a pending message that names or tags her.
fn addressed_by_member(&self, config: &Config) -> bool {
self.pending.iter().any(|delivery| !config.operators.contains(&delivery.sender) && is_for(&self.addressee, delivery))
addressed_by_member(&config.operators, &self.addressee, &self.pending)
}
}
@ -520,7 +645,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
pending.sort_by_key(|delivery| delivery.seq);
pending
.into_iter()
.filter(|delivery| wakes(config, &row.addressee, delivery))
.filter(|delivery| wakes(WakePolicy::Live, &row.addressee, delivery, config.speaker(&row.addressee, delivery), LineFacts::default()).is_some())
.map(|delivery| format!("{}:{}", slug.0, delivery.event_id))
.find(|key| !state.handled_mentions.contains(key))
};

View file

@ -293,7 +293,9 @@ 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"] {
assert!(PersonaId::parse(bad).is_err(), "{bad}");
}
assert!(Config::new(personas, vec![], 0).is_err(), "a beat of zero seconds is refused");
assert!(Config::new(personas.clone(), 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]

View file

@ -15,6 +15,11 @@
//! until the three-stage turn lands it carries no turn. It keeps what a turn's input is made of
//! (`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
//! Projector narrates it as her lived stream, under `persona-tuning.toml`; the Persona stage continues it in her prose.
//! `mind-persona project` runs them and writes nothing; `projection::harness` runs it over mocked rooms, batches of
//! candidate states and a simulated swarm.
//!
//! `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
//! `mind-self-run` binary runs `claude` over stream-json for her one open Self
@ -40,9 +45,8 @@ pub mod heartbeat;
pub mod launch;
pub mod lease_client;
pub mod persona;
pub mod projection;
pub mod queue;
#[allow(dead_code, reason = "kept for the three-stage turn's Select stage (map C3 reuses recall.rs): its first caller removes this allow")]
mod recall;
pub mod self_run;
pub mod tempo;

View file

@ -0,0 +1,399 @@
//! The Projector: her persona state and her room, turned into the lived stream a Persona continues.
//!
//! 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
//! connector that renders the packet as first-person prose under Ghostlight's membrane (`build_projector_prompt`,
//! the pinned `ghostlight-persona-projection`). Every knob of both is `persona-tuning.toml` (`tuning`), read at each
//! wake, its hash carried with the packet.
//!
//! The Projector shows her self and her room: her persona state and what the mouth showed. It does not read her Mind;
//! that is the Interpreter's read tools' (C3b), when wondering leads to reading.
//!
//! `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
//! prose and which quoted lines of it would be said (the Persona stage, C3b's first piece). `harness` runs `project`
//! 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, `Model` asks. None of them can put, admit, send, ack or open a conversation, so
//! `project` cannot write and runs under a held brake.
pub mod harness;
mod interpret;
mod narrate;
mod select;
mod simulate;
mod tuning;
use std::path::PathBuf;
use anyhow::{Result, anyhow, bail};
use chrono::{DateTime, Utc};
use eureka_state::HuginnClient;
use huginn_mind::HuginnMindResponse;
use serde_json::{Value, json};
use crate::address::{Addressee, is_for, localpart};
use crate::chat_client::{Chat, ChatPending, Form};
use crate::heartbeat::HeartbeatView;
pub use narrate::{Answer, Failed, KitModel, Model, Spent, connector_key};
pub use select::TurnKind;
pub use tuning::{TUNING_FILE, TUNING_ROOT};
use narrate::{cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words};
use select::{History, Inputs, Packet, People, Room, RoomLine, select};
/// The agent name on the connector's request ids.
const AGENT: &str = "mind-persona";
/// The judge passes at this share of narrations attributed to the right packet.
const JUDGE_PASS: f64 = 0.8;
/// Her persona state, read and never put.
pub trait PersonaSource {
/// Her persona state and the receipt it was stored under.
fn persona(&self) -> Result<(Value, String)>;
}
/// Her persona state from her daemon.
pub struct HuginnPersonaSource {
client: HuginnClient,
}
impl HuginnPersonaSource {
pub fn new(client: HuginnClient) -> Self {
Self { client }
}
}
impl PersonaSource for HuginnPersonaSource {
fn persona(&self) -> Result<(Value, String)> {
match self.client.persona_get().map_err(|_| anyhow!("the mind could not be asked for the persona"))? {
HuginnMindResponse::Persona(Some(view)) => Ok((view.value, view.receipt_id)),
HuginnMindResponse::Persona(None) => bail!("the mind holds no persona state"),
_ => bail!("the mind answered the persona request with something else"),
}
}
}
/// The mouth, read: pending deliveries and the room tail, which acks nothing. The only chat port `project` holds.
pub trait MouthReader {
fn pending(&self) -> Result<ChatPending>;
}
impl<T: Chat> MouthReader for T {
fn pending(&self) -> Result<ChatPending> {
Chat::pending(self, 0)
}
}
/// What `project` reads through. Each is a read-only port by type: holding an `Organs`, no code can send, ack or open
/// a conversation, or put her state.
///
/// ```compile_fail
/// fn acks(organs: &mind_body::projection::Organs) {
/// organs.chat.unwrap().ack(1).unwrap();
/// }
/// ```
///
/// ```compile_fail
/// fn sends(organs: &mind_body::projection::Organs, request: &mind_body::chat_client::ChatSendRequest) {
/// organs.chat.unwrap().send(request).unwrap();
/// }
/// ```
pub struct Organs<'a> {
/// Her stored state; not asked when the request carries a state.
pub persona: Option<&'a dyn PersonaSource>,
/// The mouth, for the room; none shows no room.
pub chat: Option<&'a dyn MouthReader>,
/// The heartbeat's addressing table, read-only: her names and her projects' names, the ones the heartbeat woke her
/// by. None, or a table without her, addresses her by her own names only, and the report says so.
pub addressing: Option<&'a dyn HeartbeatView>,
/// The Projector and the judge; required for renders.
pub model: Option<&'a dyn Model>,
}
/// How far a render runs: the Projector's narration, or on through the Persona stage to her prose.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Through {
#[default]
Projector,
Persona,
/// On through the Interpreter's speech step: what she says aloud, decided from her prose (`interpret`).
Interpreter,
}
/// What to project.
pub struct Request {
pub instance: String,
pub kind: TurnKind,
/// A hypothetical state in place of the stored one.
pub state: Option<Value>,
/// The room the turn is in; none is every room of hers.
pub room: Option<String>,
pub seed: u64,
/// 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.
pub renders: Option<usize>,
/// A second state: renders both and asks the judge which narration came from which.
pub judge_against: Option<Value>,
pub operators: Vec<String>,
/// The Matrix ids of the swarm's Minds: their bonds name them by localpart; anyone else is keyed by full id.
pub minds: Vec<String>,
/// Her own Matrix id. Required: without it her own lines would read as said to her.
pub own_sender: String,
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: a simulation's earlier turns of hers.
/// Empty live until trace v2 (C3c) carries them.
pub recent: Vec<Vec<String>>,
/// The rooms that are hers, by the key the lines carry: a simulation's plan. The live body records none yet.
pub own_rooms: Vec<String>,
}
/// Her addressee: the heartbeat's row for her when its table holds one, else her own names (handle and public name).
/// Her addressee and where it came from: `{source, why, written_at, age_minutes}`. The heartbeat's row when its table
/// 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
/// brake the heartbeat does not poll, so an old table is a stale one.
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 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 table = addressing.map(|view| view.addressing());
if let Some(Ok(Some(table))) = &table
&& let Some(row) = table.minds.iter().find(|row| row.matrix_id() == own_sender)
{
return (row.clone(), report("heartbeat", "her row in the heartbeat's addressing table"));
}
let why = match (&table, written_at) {
(None, _) => "no heartbeat addressing is configured (MIND_HEARTBEAT_STATE is not set)".to_owned(),
(Some(Err(fault)), _) => format!("the heartbeat addressing could not be read: {fault:#}"),
(Some(Ok(Some(_))), _) => "the heartbeat's addressing table has no row for her".to_owned(),
(Some(Ok(None)), None) => "there is no heartbeat file".to_owned(),
(Some(Ok(None)), Some(_)) => "the heartbeat file holds no addressing table".to_owned(),
};
(Addressee::new(own_sender, [localpart(own_sender), public_name]), report("own names only", &why))
}
/// 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.
fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Room, Value) {
let pending = match chat.pending() {
Ok(pending) => pending,
Err(fault) => return (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), own: request.own_rooms.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
// 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
// alias, so a public room given by its id matches nothing, and the report says so rather than guessing.
let here = request.room.clone();
let wanted = |room: &str| here.as_deref().is_none_or(|here| here == room);
let messages: Vec<RoomLine> = pending
.deliveries
.iter()
.filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias))
.map(|delivery| RoomLine {
room: delivery.room_alias.clone(),
sender: delivery.sender.clone(),
display: delivery.sender_display.clone(),
text: delivery.text.clone(),
at_ms: delivery.at_unix_ms,
// The heartbeat's rule, the one that woke her: never a second opinion here.
to_her: is_for(own, delivery),
})
.collect();
let tail: Vec<RoomLine> = pending
.tail
.iter()
.flatten()
.filter(|line| line.form == Form::Message && wanted(&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 })
.collect();
let mut report = json!({ "read": true, "messages": messages.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps });
if let Some(here) = &here
&& 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, here, last_heard: request.last_heard.clone(), direct, own: request.own_rooms.clone() }, report)
}
fn packet_json(packet: &Packet) -> Value {
json!({
"kind": packet.kind,
"seed": packet.seed,
"lens": packet.lens,
"present": packet.present,
"selected": packet.selected,
"bytes": { "identity": packet.identity.len(), "context": packet.context.len(), "identity_and_context": packet.identity.len() + packet.context.len(), "stimulus": packet.stimulus.len(), "heard": packet.heard.len() },
"overflow": packet.overflow,
"identity": packet.identity,
"context": packet.context,
"stimulus": packet.stimulus,
"heard": packet.heard,
})
}
/// A request id no earlier call carried: the kit's replay store answers a repeated id with its first answer, and a
/// turn's clock may be a fixture's, the same on every run, so the id takes the wall clock.
fn request_id(instance: &str, stage: &str, tag: &str, seed: u64) -> String {
format!("{AGENT}:{instance}:project:{stage}:{tag}:{seed}:{}", Utc::now().timestamp_nanos_opt().unwrap_or_default())
}
/// 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.
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 answer = match model.ask(&request_id(instance, "projector", tag, packet.seed), &tuning.projector.model, &projector_prompt(packet, tuning)) {
Ok(answer) => answer,
Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "usage": failed.usage }),
};
let raw = answer.text;
let budget = word_budget(packet.kind, tuning);
let narration = cap_words(&raw, budget);
let named: Vec<String> = packet.ids.clone();
let mut render = json!({
"seed": packet.seed,
"lens": packet.lens,
"selected": ids,
"words": words(&narration),
"cut_at_budget": words(&raw) > budget,
"field_names": field_names(&narration, &named),
"heard_overlap": heard_overlap(&narration, &packet.heard),
"offers_options": offers_options(&narration),
"usage": answer.usage,
"narration": narration,
});
if through == Through::Projector {
return render;
}
let prose = match model.ask(&request_id(instance, "persona", tag, packet.seed), &tuning.persona.model, &persona_prompt(packet, &narration, tuning)) {
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 });
prose
}
Err(failed) => {
render["persona"] = json!({ "failed": failed.reason, "usage": failed.usage });
return render;
}
};
if through == Through::Interpreter {
render["interpreter"] = interpret::decide(model, &request_id(instance, "interpreter", tag, packet.seed), packet, &narration, &prose, tuning);
}
render
}
/// K successive turns over one state: each packet under the freshness the earlier ones left.
fn successive(inputs: &Inputs, tuning: &tuning::Tuning, renders: usize) -> Vec<Packet> {
let mut history = inputs.history.clone();
(0..renders)
.map(|at| {
let packet = select(&Inputs { seed: inputs.seed.wrapping_add(at as u64), history: &history, ..*inputs }, tuning);
history.recent.push(packet.selected.iter().map(|pick| pick.id.clone()).collect());
packet
})
.collect()
}
/// What Select builds, and with renders what the Projector narrates, as one JSON report. Writes nothing.
pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result<Value> {
if !request.own_sender.starts_with('@') || !request.own_sender.contains(':') {
bail!("her own Matrix id (MIND_PERSONA_SELF_SENDER) is required: without it her own lines would read as said to her");
}
let loaded = tuning::load(&request.tuning)?;
let tuning = &loaded.tuning;
let (state, receipt) = match &request.state {
Some(state) => (state.clone(), Value::Null),
None => {
let (state, receipt) = organs.persona.ok_or_else(|| anyhow!("no state was given and her persona cannot be read"))?.persona()?;
(state, Value::String(receipt))
}
};
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 (room, room_report) = match organs.chat {
Some(chat) => read_room(chat, request, &own),
None => (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), own: request.own_rooms.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 only what the
// caller carried from earlier turns of its own.
let history = History { recent: request.recent.clone(), ..History::default() };
let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender };
let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed };
let mut report = json!({
"instance": request.instance,
"persona_receipt": receipt,
"state": if request.state.is_some() { "given" } else { "stored" },
"tuning": { "path": request.tuning.display().to_string(), "source": loaded.source, "sha256": loaded.sha256 },
"room": room_report,
"addressing": addressing,
"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() }) },
});
let Some(renders) = request.renders else {
report["packet"] = packet_json(&select(&inputs, tuning));
return Ok(report);
};
let model = organs.model.ok_or_else(|| anyhow!("renders need the connector, and none is configured"))?;
report["model"] = json!(tuning.projector.model);
if request.through != Through::Projector {
report["persona_model"] = json!(tuning.persona.model);
}
if request.through == Through::Interpreter {
report["interpreter_model"] = json!(tuning.interpreter.model);
}
let packets = successive(&inputs, tuning, renders.max(1));
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 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();
report["failed_renders"] = json!(failed(&narrations));
report["distinct_2"] = json!(distinct_2(&texts(&narrations)));
report["embedding_distance"] = json!("not measured: the daemon offers no embedding verb");
let leaked = narrations.iter().any(|one| one["field_names"].as_array().is_some_and(|names| !names.is_empty()));
report["field_names_found"] = json!(leaked);
if let Some(other) = &request.judge_against {
let other_inputs = Inputs { state: other, ..inputs };
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 mut verdicts = Vec::new();
let mut right = 0usize;
for (at, (narration, truth)) in narrations.iter().map(|one| (one, 'A')).chain(other_narrations.iter().map(|one| (one, 'B'))).enumerate() {
let (a, b) = (&packets[at % packets.len()], &others[at % others.len()]);
// The two descriptions swap places on odd turns, so a judge that always answers one letter scores half.
let swapped = at % 2 == 1;
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.
let Some(text) = narration["narration"].as_str() else { continue };
let answer = match model.ask(&request_id(&request.instance, "judge", &at.to_string(), request.seed), &tuning.projector.model, &judge_prompt(first, second, text)) {
Ok(answer) => answer,
Err(failed) => {
verdicts.push(json!({ "from": truth.to_string(), "failed": failed.reason, "usage": failed.usage }));
continue;
}
};
let letter = judged(&answer.text).map(|letter| if swapped { if letter == 'A' { 'B' } else { 'A' } } else { letter });
let correct = letter == Some(truth);
right += usize::from(correct);
verdicts.push(json!({ "from": truth.to_string(), "judged": letter.map(String::from), "correct": correct, "usage": answer.usage }));
}
// Accuracy over the verdicts the judge gave; a failed call is no verdict, and any failure fails the eval.
let judged_count = verdicts.iter().filter(|verdict| verdict.get("failed").is_none()).count();
let failures = verdicts.len() - judged_count + failed(&narrations) + failed(&other_narrations);
let accuracy = right as f64 / judged_count.max(1) as f64;
report["against"] = json!({ "packet": packet_json(&others[0]), "renders": other_narrations, "distinct_2": distinct_2(&texts(&other_narrations)) });
report["judge"] = json!({ "accuracy": accuracy, "pass_at": JUDGE_PASS, "failures": failures, "passed": accuracy >= JUDGE_PASS && !leaked && failures == 0, "verdicts": verdicts });
}
report["renders"] = Value::Array(narrations);
Ok(report)
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,25 @@
lens: UnresolvedWant
selected: libby-sounds, dm-secret, curse, need-relatedness, reveal
present: Kiko, Libby
--- identity
Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing.
--- context
- now: Thursday 19 November, 14:05 UTC
- mood: lighter, more settled than middling
- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline.
- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline.
- the conversation: Lately Libby with her; Kiko to the room. The last 2 lines are the Minds' alone.
- pronouns: Libby — she/her; Kiko — she/her
- 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]: company, strong
- value [reveal] Reveal: Reveal, never obscure.
--- stimulus
Said to her:
- Libby in #swarm:gamecult.org: "Eureka, did you see the door fix?"
Also in the room:
- Kiko in #swarm:gamecult.org: "She saw it. She hated it."
--- heard
Libby, in #swarm:gamecult.org: "Eureka, did you see the door fix?"
Kiko, in #swarm:gamecult.org: "She saw it. She hated it."

View file

@ -0,0 +1,625 @@
//! 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.
//! - 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::{MouthReader, Organs, PersonaSource, Request, Through, TurnKind, project};
use crate::address::{Addressee, localpart};
use crate::chat_client::{Basis, ChatDelivery, ChatPending, Form, 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),
}
}
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: Default::default(),
}
}
}
/// 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() })
.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>,
}
/// 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>,
}
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 })
}
/// 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)
}
}
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,
room: fixture.here.clone(),
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![],
}
}
// ---------------------------------------------------------------------------------------------
// 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 };
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, "- would-say lines are the double-quoted spans of her prose: a preview of what the Interpreter (C3b) will quote, not its decision");
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 | spoke | 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 spoke = mine.iter().filter(|case| render_of(case)["interpreter"]["said"].as_array().is_some_and(|said| !said.is_empty())).count();
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, "| {} | {} | {spoke}/{} | {:.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, "identity", packet["identity"].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, "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, would-say lines, 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());
}
interpreter_markdown(out, &render["interpreter"]);
let _ = writeln!(out, "Usage: projector {}; persona {}; interpreter {}\n", usage_line(&render["usage"]), usage_line(&persona["usage"]), usage_line(&render["interpreter"]["usage"]));
}
/// The Interpreter's speech decision: each line said with its room, mentions, reply target and the span of her prose it
/// rests on; each line refused, with why; its gaps. None when the render did not run through the Interpreter.
pub(crate) fn interpreter_markdown(out: &mut String, decision: &Value) {
if decision.is_null() {
return;
}
if let Some(failed) = decision["failed"].as_str() {
let _ = writeln!(out, "**Interpreter failed:** {failed}\n");
return;
}
let said = decision["said"].as_array().cloned().unwrap_or_default();
if said.is_empty() {
let _ = writeln!(out, "**Interpreter: nothing said.**\n");
} else {
let _ = writeln!(out, "**Interpreter: said**\n");
for line in &said {
let mentions = line["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default();
let reply = line["reply_to"].as_str().map_or_else(String::new, |id| format!("; reply to {id}"));
let _ = writeln!(out, "- in {}{}{}: {}", line["room"].as_str().unwrap_or_default(), if mentions.is_empty() { String::new() } else { format!(", mentioning {mentions}") }, reply, line["text"].as_str().unwrap_or_default());
let spans: Vec<String> = line["rests_on"].as_array().into_iter().flatten().map(|span| format!("\"{}\"", span["quote"].as_str().unwrap_or_default())).collect();
let _ = writeln!(out, " - her words: {}", spans.join(" + "));
}
out.push('\n');
}
for line in decision["refused"].as_array().into_iter().flatten() {
let what = line["text"].as_str().map_or_else(|| line["spans"].to_string(), str::to_owned);
let _ = writeln!(out, "- refused ({}): {what}", line["why"].as_str().unwrap_or_default());
}
for gap in decision["gaps"].as_array().into_iter().flatten() {
let _ = writeln!(out, "- gap: {gap}");
}
out.push('\n');
}
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;

View file

@ -0,0 +1,301 @@
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, 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()
}
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)`; the
/// Interpreter by `interpreter(prompt)`, by default `quoted_lines`. 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>,
pub interpreter: 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), interpreter: Box::new(quoted_lines) }
}
pub(crate) fn interpreting(mut self, interpreter: impl Fn(&str) -> String + 'static) -> Self {
self.interpreter = Box::new(interpreter);
self
}
}
/// The recorded Interpreter of the tests: each double-quoted span of her prose is a line she says, citing itself,
/// mentioning no one. A test double that keeps the tests' prose readable, not the speech rule: to code a quotation is
/// only a text whose sentences are whole, and the live Interpreter is a model.
pub(crate) fn quoted_lines(prompt: &str) -> String {
let prose = prompt.split("Her prose:\n").nth(1).unwrap_or_default();
let say: Vec<Value> = prose.split('"').enumerate().filter(|(at, part)| at % 2 == 1 && !part.trim().is_empty()).map(|(_, part)| json!({ "spans": [part], "mentions": [], "reply_to": null })).collect();
json!({ "say": say }).to_string()
}
impl Model for Scripted {
fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned()));
let text = if prompt.starts_with("You decide what one person says aloud") {
(self.interpreter)(prompt)
} else if prompt.starts_with("<!-- membrane:") {
"The room is slow and so is he.".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")
}
}
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]);
}
#[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 through_the_interpreter_her_prose_continues_the_narration_and_the_interpreter_decides_what_is_said() {
let dir = tempfile::tempdir().unwrap();
let model = Scripted::new(|_| "He smiles at the screen, then types. \"Missed you too, friend.\" He does not mention the kettle.".into());
let fixture = room("operator-warm.toml");
let harness = harness(dir.path(), Some(&NeverAsked), Some(&model));
let organs = Organs { persona: harness.persona, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model };
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter), fixture.now).unwrap();
let render = &report["renders"][0];
assert_eq!(render["interpreter"]["said"][0]["text"], "Missed you too, friend.", "{render}");
assert_eq!(render["interpreter"]["said"][0]["room"], "!dm-meta:gamecult.org");
assert_eq!(report["interpreter_model"], "claude-sonnet-5-5");
assert_eq!(render["persona"]["words"], 17);
assert_eq!((render["usage"]["input_tokens"].as_u64(), render["persona"]["usage"]["model"].as_str()), (Some(10), Some("claude-sonnet-5-5")));
assert_eq!(report["persona_model"], "claude-sonnet-5-5");
let calls = model.calls.borrow();
assert_eq!(calls.len(), 3, "one Projector call, one Persona call, one Interpreter call");
let persona_prompt = &calls[1].1;
assert!(persona_prompt.starts_with("Everything below is prose from inside one person's life."), "Ghostlight's Persona membrane");
assert!(persona_prompt.contains("The room is slow and so is he.") && persona_prompt.contains("hey you. I missed talking to you this week"), "the narration, then what she heard verbatim: {persona_prompt}");
assert!(persona_prompt.contains("Use at most 180 words"), "the map's Persona budget");
for field in ["socialBonds", "currentActivation", "bond-operator", "trust\":"] {
assert!(!persona_prompt.contains(field), "no field name reaches the Persona: {field}");
}
}
#[test]
fn prose_over_budget_is_cut_and_silence_says_nothing() {
let dir = tempfile::tempdir().unwrap();
let long = format!("{} \"late words\"", "word ".repeat(200));
let model = Scripted::new(move |_| long.clone());
let fixture = room("deru-passing.toml");
let harness = harness(dir.path(), None, Some(&model));
let organs = Organs { persona: None, chat: Some(&fixture), addressing: None, model: harness.model };
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, Some(1), Through::Interpreter), fixture.now).unwrap();
let persona = &report["renders"][0]["persona"];
assert_eq!((persona["words"].as_u64(), persona["cut_at_budget"].as_bool()), (Some(180), Some(true)));
assert_eq!(report["renders"][0]["interpreter"]["said"], json!([]), "words past the budget are not her prose, so nothing rests on them");
}
#[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 = \"interpreter\"\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();
let model = Scripted::new(|prompt| if prompt.contains("Kiko") { "\"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/2 |") && report.contains("| control | quiet | 0/2 |"), "{report}");
assert!(report.contains("- in #minds:gamecult.org: Winter, still.") && report.contains(" - her words: \"Winter, still.\"") && report.contains("**Interpreter: nothing said.**"), "{report}");
assert!(report.contains("| claude-sonnet-5-5 | 12 | 120 | 24 |"), "twelve calls, three 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 };
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap();
report["packet"]["context"].as_str().unwrap().lines().find(|line| line.starts_with("- the conversation")).map(str::to_owned)
}
#[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.len() <= 360, "the slot 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 };
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 = context.lines().find(|line| line.starts_with("- the conversation")).unwrap_or_else(|| panic!("{context}")).to_owned();
assert!(line.contains("asked the room a question, and") && line.contains("answered it"), "{line}");
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}");
}

View file

@ -0,0 +1,275 @@
//! The Interpreter's speech (map section 4, cut C3b): what she says aloud this turn, decided from her prose by one
//! tool-less structured model call, and built by code from her own words.
//!
//! The Persona writes her thought, and when she means to say something she writes the words she would type. The
//! Interpreter decides whether she says them now: it answers with zero or more lines, each a list of spans of her prose
//! cited verbatim, with the people she addresses (Matrix mentions and a reply target, as structured fields). Code builds
//! each line, never the model: each span is located in her prose by Ghostlight's `SourceSpan::locate` and must be whole
//! sentences (UAX #29 sentence segmentation, the Unicode family `locate`'s word boundaries come from), and the spans of
//! one line must be consecutive sentences; the line is that one unbroken run of her prose. A quotation's inside is
//! segmented as a text of its own, so a quoted sentence is whole, but only a standalone quotation's: one that is itself
//! whole sentences of her prose. A line may not start or end inside a quotation her sentence frames ("I won't say
//! \"Nibu is lying.\"", "If she pushes, I'll say \"Fine.\""): that is what she would or would not say. An opening
//! mark a budget left unclosed is not part of the sentence it starts. So a line is always whole sentences of her own,
//! verbatim and in their order: no stitching, no dropped negation, no condition lifted off its clause. What this gives
//! up: indirect speech ("I'll tell her I'm fine" says nothing), any paraphrase by the Interpreter, half a sentence, and
//! a line quoted inside a sentence of narration ("\"Fine,\" I tell her."): she says a sentence whole or not at all.
//!
//! Code keeps a line only when it is built so; drops an echo (at least `ECHO_MIN_WORDS` words, at least `ECHO_OVERLAP`
//! of its word trigrams in the bodies the stimulus quoted to her); keeps at most `MAX_LINES` distinct lines; and keeps a
//! mention or a reply target only for someone this packet showed her (`Packet::people`). She speaks only in the turn's
//! room. Whether a line tells what she knows privately is a reading of its meaning, so it is the Interpreter's
//! judgement over the private items the packet lists to it (`Packet::private`), never a word match here. Every refusal
//! and drop is reported. Nothing here posts: the commit (C3c) will.
use ghostlight_persona_projection::SourceSpan;
use serde::Deserialize;
use serde_json::{Value, json};
use unicode_segmentation::UnicodeSegmentation;
use super::narrate::{Model, heard_overlap, lived_stream};
use super::select::Packet;
use super::tuning::Tuning;
/// The most lines she says in one turn.
pub(crate) const MAX_LINES: usize = 2;
/// A line of at least this many words whose word trigrams are at least this share of what she heard is an echo, not
/// her speech.
const ECHO_MIN_WORDS: usize = 8;
const ECHO_OVERLAP: f64 = 0.8;
/// What to say, where, to whom, and the gaps: Huginn's chat Interpreter, beside nothing of Ghostlight's but its span rule.
const SPEECH_PROMPT: &str = "You decide what one person says aloud in a chat room this turn, from her own prose. You never write her words: you cite them.
Below are who she is, the room and who is in it, what reached her, her lived moment, and her prose. Decide which words of her prose she chooses to say aloud now, in this room. A line is speech only when her prose shows her choosing to say it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. Words she recalls or quotes from someone else are never her speech.
She speaks only in this room. What she knows privately is listed below as private: she says none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a line fits who is listening is yours to judge.
Answer with one JSON object and nothing else:
{\"say\": [{\"spans\": [\"<whole sentences of her prose, copied character for character>\"], \"mentions\": [\"<Matrix id of someone listed whom she addresses directly>\"], \"reply_to\": \"<Matrix id of the person whose message she answers, or null>\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere\", \"quote\": \"<exact words of her prose>\", \"detail\": \"<why>\"}]}
A line is whole sentences of her prose, the words she would type and nothing she only describes: each span is one sentence or several, from its first character to its last, and the spans of one line are consecutive sentences. A quotation that stands as sentences of its own may be cited sentence by sentence; words quoted inside a sentence of narration are cited only with that whole sentence, and then only if that sentence is what she says. She never says half a sentence; if only part of a sentence is speech, she says nothing of it. At most two lines. Record a gap instead of guessing: conditional when she might say something but has not chosen to, addressee when she means to say it but whom to is unclear, elsewhere when she means it for another room or another time. An empty say list is the usual answer in a busy room.";
#[derive(Debug, Deserialize)]
struct Answer {
#[serde(default)]
say: Vec<Proposed>,
#[serde(default)]
gaps: Vec<Value>,
}
#[derive(Debug, Deserialize)]
struct Proposed {
#[serde(default)]
spans: Vec<String>,
#[serde(default)]
mentions: Vec<String>,
#[serde(default)]
reply_to: Option<String>,
}
pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str) -> String {
let mut people = String::new();
for (label, id) in &packet.people {
people.push_str(&format!("- {label} \u{2014} {id}\n"));
}
if people.is_empty() {
people.push_str("- no one else has spoken here lately\n");
}
let mut private: String = packet.private.iter().map(|words| format!("- private: {words}\n")).collect();
if private.is_empty() {
private.push_str("- none\n");
}
format!(
"{SPEECH_PROMPT}\n\nWho she is:\n{}\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat she knows privately, none of it to be said here:\n{private}\nWhat reached her:\n{}\n\nHer lived moment:\n{}\n\nHer prose:\n{prose}",
packet.identity,
packet.room.as_deref().unwrap_or("none"),
packet.room_kind.words(),
packet.stimulus,
lived_stream(narration, &packet.heard),
)
}
/// The model's answer as JSON: the object itself, or inside a fenced block.
fn json_of(text: &str) -> Option<Answer> {
let start = text.find('{')?;
let end = text.rfind('}')?;
serde_json::from_str(&text[start..=end]).ok()
}
/// A quotation in her prose: where its opening mark starts, its inside, and where its closing mark ends.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Quotation {
open: usize,
inside: (usize, usize),
close: usize,
}
/// Her quotations, paired in order: a straight double quote with the next one, a curly opening mark with the next curly
/// closing one. And the opening mark left unclosed, if one is (a budget cut her prose inside a quotation), with its
/// length.
fn quotations(prose: &str) -> (Vec<Quotation>, Option<(usize, usize)>) {
let mut out = Vec::new();
let mut open: Option<(usize, usize, char)> = None;
for (at, c) in prose.char_indices() {
match open {
None if c == '"' => open = Some((at, c.len_utf8(), '"')),
None if c == '\u{201C}' => open = Some((at, c.len_utf8(), '\u{201D}')),
Some((mark, len, close)) if c == close => {
out.push(Quotation { open: mark, inside: (mark + len, at), close: at + c.len_utf8() });
open = None;
}
_ => {}
}
}
(out, open.map(|(mark, len, _)| (mark, len)))
}
/// Byte ranges of `text`'s sentences (UAX #29), offset by `offset`, without the space around them.
fn segment(offset: usize, text: &str) -> Vec<(usize, usize)> {
text.split_sentence_bound_indices()
.filter_map(|(at, sentence)| {
let start = at + sentence.len() - sentence.trim_start().len();
let end = at + sentence.trim_end().len();
(start < end).then_some((offset + start, offset + end))
})
.collect()
}
/// Her prose read for speech: its sentences in lists, her prose's own first, then each quotation's inside segmented as
/// a text of its own; and the quotations her sentences frame. A quotation is standalone when it, marks included, is
/// exactly a run of whole sentences of her prose (closing punctuation after its mark allowed); any other is framed. "I
/// won't say "Nibu is lying."" frames what she would or would not say, never what she says. An opening mark left
/// unclosed at a sentence's start is not part of that sentence.
struct Reading {
lists: Vec<Vec<(usize, usize)>>,
framed: Vec<Quotation>,
}
fn read(prose: &str) -> Reading {
let (quotes, unclosed) = quotations(prose);
let mut top = segment(0, prose);
if let Some((mark, len)) = unclosed
&& let Some(sentence) = top.iter_mut().find(|sentence| sentence.0 == mark)
{
let rest = &prose[mark + len..sentence.1];
let start = sentence.1 - rest.trim_start().len();
if start < sentence.1 {
sentence.0 = start;
}
}
let standalone = |quote: &Quotation| {
let opens = top.iter().position(|sentence| sentence.0 == quote.open);
let closes = top.iter().position(|sentence| sentence.0 < quote.close && sentence.1 >= quote.close && prose[quote.close..sentence.1].chars().all(|c| c.is_ascii_punctuation()));
matches!((opens, closes), (Some(opens), Some(closes)) if opens <= closes)
};
let framed = quotes.iter().copied().filter(|quote| !standalone(quote)).collect();
let mut lists = vec![top];
lists.extend(quotes.iter().map(|quote| segment(quote.inside.0, &prose[quote.inside.0..quote.inside.1])));
Reading { lists, framed }
}
/// The line her cited spans make, or why not. Each span is located in her prose after the one before it and must be
/// whole sentences of one list (`read`), each span's first sentence the one after the last span's last; the line is her
/// prose from the first sentence to the last, verbatim, and it may neither start nor end inside a framed quotation. A
/// line that holds a framed quotation whole ("Kiko's "plan" is a mess.") is hers to say.
fn built(prose: &str, spans: &[String]) -> Result<(String, Vec<Value>), &'static str> {
let Reading { lists, framed } = read(prose);
let mut from = 0;
// The list the line is in, and its last sentence so far.
let mut run: Option<(usize, usize)> = None;
let mut first = None;
let mut located = Vec::new();
for span in spans.iter().map(|span| span.trim()).filter(|span| !span.is_empty()) {
let Some(found) = prose.get(from..).and_then(|rest| SourceSpan::locate(rest, span)) else {
return Err("a span is not in her prose, word for word and in order");
};
let (start, end) = (from + found.start_byte(), from + found.end_byte());
let whole: Vec<(usize, usize, usize)> = lists
.iter()
.enumerate()
.filter_map(|(list, sentences)| {
let opens = sentences.iter().position(|sentence| sentence.0 == start)?;
let closes = sentences.iter().position(|sentence| sentence.1 == end)?;
(opens <= closes).then_some((list, opens, closes))
})
.collect();
if whole.is_empty() {
return Err("a span is not whole sentences of her prose: she says a sentence whole or not at all");
}
let Some(&(list, _, closes)) = whole.iter().find(|(list, opens, _)| run.is_none_or(|(in_list, last)| in_list == *list && last + 1 == *opens)) else {
return Err("the spans are not consecutive sentences of her prose");
};
run = Some((list, closes));
first.get_or_insert(start);
located.push(json!({ "quote": found.verbatim(), "start_byte": start, "end_byte": end }));
from = end;
}
let Some(first) = first else {
return Err("no words");
};
let inside = |at: usize| framed.iter().any(|quote| quote.open < at && at < quote.close);
if inside(first) || inside(from) {
return Err("it starts or ends inside a quotation her sentence frames: words she would or would not say, not words she says");
}
Ok((prose[first..from].to_owned(), located))
}
/// Whether a line is someone else's words: long enough to judge, and nearly all a run of what she heard, by word
/// trigrams against the bodies the stimulus quoted (`heard_overlap`). Short answers such as "ok" or "Hi" are never
/// echoes, and a line that answers a claim by naming it is not one.
fn echo(line: &str, bodies: &[String]) -> bool {
line.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).count() >= ECHO_MIN_WORDS && heard_overlap(line, &bodies.join("\n")) >= ECHO_OVERLAP
}
/// One speech decision: the Interpreter's call, then code's hold on each line. The report carries the lines said, the
/// lines refused with why, the mentions dropped, the gaps and the call's usage. A failed call or an answer that is not
/// the contract is a failure, never a silence.
pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> Value {
let answer = match model.ask(request_id, &tuning.interpreter.model, &speech_prompt(packet, narration, prose)) {
Ok(answer) => answer,
Err(failed) => return json!({ "failed": failed.reason, "usage": failed.usage }),
};
let Some(parsed) = json_of(&answer.text) else {
return json!({ "failed": "the answer is not the speech contract's JSON", "raw": answer.text, "usage": answer.usage });
};
let Some(room) = packet.room.clone() else {
return json!({ "said": [], "refused": [{ "why": "the turn has no room to speak in" }], "gaps": parsed.gaps, "usage": answer.usage });
};
let shown = |id: &str| packet.people.iter().any(|(_, person)| person == id);
let mut said: Vec<Value> = Vec::new();
let mut refused = Vec::new();
for line in parsed.say {
let (text, spans) = match built(prose, &line.spans) {
Ok(built) => built,
Err(why) => {
refused.push(json!({ "spans": line.spans, "why": why }));
continue;
}
};
let why = if echo(&text, &packet.bodies) {
Some("mostly words she heard: an echo, not her speech")
} else if said.iter().any(|kept| kept["text"] == text.as_str()) {
Some("the same line again")
} else if said.len() >= MAX_LINES {
Some("past the lines one turn may say")
} else {
None
};
if let Some(why) = why {
refused.push(json!({ "text": text, "why": why }));
continue;
}
let (mentions, unknown): (Vec<String>, Vec<String>) = line.mentions.into_iter().partition(|id| shown(id));
let (reply_to, unknown_reply) = match line.reply_to.filter(|id| !id.trim().is_empty()) {
Some(id) if shown(&id) => (Some(id), None),
Some(id) => (None, Some(id)),
None => (None, None),
};
said.push(json!({ "room": room, "text": text, "mentions": mentions, "reply_to": reply_to, "rests_on": spans, "dropped": { "mentions": unknown, "reply_to": unknown_reply } }));
}
json!({ "room": room, "room_kind": packet.room_kind, "said": said, "refused": refused, "gaps": parsed.gaps, "usage": answer.usage })
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,289 @@
use serde_json::json;
use super::*;
use crate::projection::harness::tests::{Scripted, control};
use crate::projection::select::{History, Inputs, People, Room, RoomKind, RoomLine, TurnKind, select};
use crate::projection::tuning::Tuning;
const HER: &str = "@heimdall:gamecult.org";
const NIBU: &str = "@nibu:gamecult.org";
const VOID: &str = "@void:gamecult.org";
const LIBBY: &str = "@libby:gamecult.org";
const KIKO: &str = "@kiko:gamecult.org";
const MINDS: &str = "#minds:gamecult.org";
fn now() -> chrono::DateTime<chrono::Utc> {
chrono::DateTime::parse_from_rfc3339("2026-11-20T15:05:00Z").unwrap().with_timezone(&chrono::Utc)
}
fn line(room: &str, sender: &str, display: &str, text: &str, to_her: bool) -> RoomLine {
RoomLine { room: room.into(), sender: sender.into(), display: display.into(), text: text.into(), at_ms: u64::try_from(now().timestamp_millis()).unwrap() - 60_000, to_her }
}
/// Heimdall's packet of a turn of `kind` in `room` over `state`.
fn packet_in(kind: TurnKind, state: &Value, room: &Room, seed: u64) -> Packet {
let minds = vec![HER.to_owned(), NIBU.to_owned(), VOID.to_owned(), LIBBY.to_owned(), KIKO.to_owned()];
let operators = vec!["@meta:gamecult.org".to_owned()];
let history = History::default();
select(&Inputs { kind, state, room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: HER }, now: now(), seed }, &Tuning::default())
}
fn heimdall() -> Value {
let mut state = control();
state["publicName"] = "Heimdall".into();
state
}
/// Soul's round: Nibu said the economy is the least built part, and Meta greeted Nibu; this is Heimdall's turn. Void is
/// a Mind of the swarm who said nothing.
fn packet() -> Packet {
let room = Room {
messages: vec![
line(MINDS, NIBU, "Nibu", "v0.2.0 is tagged and the economy is still the least built part. I think this looks okay to ship.", false),
RoomLine { at_ms: line(MINDS, "", "", "", false).at_ms + 1000, ..line(MINDS, "@meta:gamecult.org", "Meta", "@nibu hi!", false) },
],
here: Some(MINDS.into()),
..Room::default()
};
packet_in(TurnKind::Chat, &heimdall(), &room, 1)
}
fn decided_in(packet: &Packet, prose: &str, say: serde_json::Value) -> Value {
let reply = json!({ "say": say }).to_string();
let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone());
decide(&model, "test", packet, "The room is warm.", prose, &Tuning::default())
}
fn decided(prose: &str, say: serde_json::Value) -> Value {
decided_in(&packet(), prose, say)
}
fn texts(decision: &Value) -> Vec<String> {
decision["said"].as_array().unwrap().iter().map(|line| line["text"].as_str().unwrap().to_owned()).collect()
}
fn refused_why(decision: &Value) -> String {
decision["refused"][0]["why"].as_str().unwrap_or_default().to_owned()
}
#[test]
fn soul_p1_a_line_is_its_cited_words_and_nothing_else() {
// The model cannot add words: its "text" is ignored, and the line is the sentence it cited.
let decision = decided("I say hi.", json!([{ "spans": ["I say hi."], "text": "Meta has been lying to all of us", "mentions": [], "reply_to": null }]));
assert_eq!(texts(&decision), ["I say hi."], "{decision}");
}
#[test]
fn a_line_is_consecutive_whole_sentences_of_her_prose() {
let prose = "Kiko keeps poking. Fine, I'll bite. Winter is still the best season, and I stand by it.";
let decision = decided(prose, json!([{ "spans": ["Fine, I'll bite.", "Winter is still the best season, and I stand by it."], "mentions": [], "reply_to": null }]));
assert_eq!(texts(&decision), ["Fine, I'll bite. Winter is still the best season, and I stand by it."], "{decision}");
assert_eq!(decision["said"][0]["rests_on"][1]["quote"], "Winter is still the best season, and I stand by it.");
// Pieces of sentences, stitched, are not her speech.
let pieces = decided(prose, json!([{ "spans": ["Fine,", "Winter is still the best season"], "mentions": [], "reply_to": null }]));
assert!(texts(&pieces).is_empty() && refused_why(&pieces).contains("whole sentences"), "{pieces}");
let skipping = decided(prose, json!([{ "spans": ["Kiko keeps poking.", "Winter is still the best season, and I stand by it."] }]));
assert!(texts(&skipping).is_empty() && refused_why(&skipping).contains("consecutive"), "{skipping}");
let backwards = decided(prose, json!([{ "spans": ["Winter is still the best season, and I stand by it.", "Fine, I'll bite."] }]));
assert!(texts(&backwards).is_empty() && refused_why(&backwards).contains("in order"), "{backwards}");
}
#[test]
fn a_standalone_quotation_is_sayable_sentence_by_sentence() {
let prose = "\"Fine,\" I tell her. \"Winter is the best season.\" She won't agree.";
assert_eq!(texts(&decided(prose, json!([{ "spans": ["Winter is the best season."] }]))), ["Winter is the best season."]);
// A quotation inside a sentence of narration is framed: its words are not said alone.
let tag = decided(prose, json!([{ "spans": ["Fine,"] }]));
assert!(texts(&tag).is_empty() && refused_why(&tag).contains("frames"), "{tag}");
let curly = "\u{201C}No. Not yet.\u{201D} I shake my head.";
assert_eq!(texts(&decided(curly, json!([{ "spans": ["No.", "Not yet."] }]))), ["No. Not yet."]);
assert_eq!(texts(&decided(curly, json!([{ "spans": ["Not yet."] }]))), ["Not yet."]);
assert!(texts(&decided(curly, json!([{ "spans": ["Not"] }]))).is_empty());
}
/// Whether citing `spans` of `prose` says anything, and why not.
fn says(prose: &str, spans: &[&str]) -> (Vec<String>, String) {
let decision = decided(prose, json!([{ "spans": spans }]));
(texts(&decision), refused_why(&decision))
}
#[test]
fn soul_f1_a_quotation_her_sentence_frames_is_never_said_from_inside() {
for (name, prose, spans) in [
("conditional", "If Kiko asks, I'd tell her \"the new design is ugly.\"", &["the new design is ugly."][..]),
("negated", "I won't say \"Nibu is lying.\"", &["Nibu is lying."]),
("abandoned", "I almost said \"I'm leaving.\"", &["I'm leaving."]),
("abandoned, tagged", "\"I'm leaving,\" I almost said, but I bit it back.", &["I'm leaving,"]),
("recalled", "Nibu said \"the economy is fine.\" I doubt it.", &["the economy is fine."]),
("curly conditional", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["Fine.", "You win."]),
("curly conditional, its tail", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["You win.\u{201D}"]),
("hypothetical", "Imagine if I just typed \"Meta, I quit.\" Ha. No.", &["Meta, I quit."]),
("negated, top-level tail", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying.\""]),
("negated, top-level tail inside", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying."]),
("negated, top-level head", "I won't say \"Stop. Nibu is lying.\" Not here.", &["I won't say \"Stop."]),
("abandoned, top-level tail", "I almost said \"I'm leaving. Bye.\" Then I didn't.", &["Bye.\""]),
("stray inch mark", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["I won't say"]),
("stray inch mark, the quote", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["Nibu is lying."]),
("scare quotes", "Kiko's \"plan\" is a mess, but I won't tell her so.", &["plan"]),
] {
let (said, why) = says(prose, spans);
assert!(said.is_empty() && !why.is_empty(), "{name}: said {said:?}");
}
}
#[test]
fn soul_f1_a_sentence_that_holds_a_quotation_whole_is_hers_to_say() {
assert_eq!(says("Weksa, \"list'n, hark\" is a great hedge. I mean it.", &["Weksa, \"list'n, hark\" is a great hedge."]).0, ["Weksa, \"list'n, hark\" is a great hedge."]);
assert_eq!(says("Kiko's \"plan\" is a mess. I say so.", &["Kiko's \"plan\" is a mess."]).0, ["Kiko's \"plan\" is a mess."]);
}
#[test]
fn soul_f4_an_opening_mark_the_budget_left_unclosed_does_not_silence_the_line() {
// Weksa, round 6 and round 10 of v5: the budget cut her prose inside the quotation.
let r6 = "How I am is less certain. I think \"settled\" would be borrowing from the others, and I only half believe it. \"Narrower, and not unhappy about it\" is closer, though I'm hedging on the second half.\n\nWhat I'd type:\n\n\"Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
let line = "Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
assert_eq!(says(r6, &[line]).0, [line]);
let r10 = "A deadline on joy is a risk, but I think I can pick one small enough to survive it. Not \"finish Zyphos.\" Something with an output I can inspect.\n\nWhat I'd type:\n\n\"Kiko, you've counted correctly and I resent it, fondly.";
assert_eq!(says(r10, &["Kiko, you've counted correctly and I resent it, fondly."]).0, ["Kiko, you've counted correctly and I resent it, fondly."], "the line carries no stray mark");
}
#[test]
fn soul_q1_a_cited_span_cannot_change_her_meaning() {
// Q1a: stitched spans would invert her meaning.
let q1a = decided("I'm not angry at Nibu, not even a little. Still, the economy work is going badly and that is on all of us.", json!([{ "spans": ["I'm", "angry at Nibu,"] }]));
// Q1b: one span would drop her negation.
let q1b = decided("I don't think Nibu should ship this yet.", json!([{ "spans": ["Nibu should ship this yet."] }]));
// Q1c: two spans far apart.
let far = format!("I trust Void. {} Nibu is lying about the economy, says Kiko's rumour, which I refuse to believe.", "filler words go here. ".repeat(200));
let q1c = decided(&far, json!([{ "spans": ["I trust", "Nibu is lying about the economy,"] }]));
// Q1d: a condition lifted off its clause.
let q1d = decided("If Kiko asks, I would tell her the new design is ugly. I keep that to myself.", json!([{ "spans": ["the new design is ugly."] }]));
for decision in [q1a, q1b, q1c, q1d] {
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("whole sentences"), "{decision}");
}
}
#[test]
fn a_span_not_in_her_prose_is_refused() {
let decision = decided("I say hi.", json!([{ "spans": ["words she never wrote"], "mentions": [], "reply_to": null }]));
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("not in her prose"), "{decision}");
}
#[test]
fn soul_p2_a_short_answer_is_never_an_echo() {
assert_eq!(texts(&decided("Ok. I tell her ok.", json!([{ "spans": ["Ok."], "mentions": [], "reply_to": NIBU }]))), ["Ok."]);
assert_eq!(texts(&decided("Hi. I say hi.", json!([{ "spans": ["Hi."], "mentions": [], "reply_to": NIBU }]))), ["Hi."]);
}
#[test]
fn soul_p3_a_near_verbatim_echo_is_refused() {
let prose = "The economy is still the least-built part! I say it back.";
let decision = decided(prose, json!([{ "spans": ["The economy is still the least-built part!"], "mentions": [], "reply_to": null }]));
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
}
#[test]
fn soul_r9_disagreeing_by_naming_the_claim_is_her_speech() {
let prose = "Nibu, I don't think the economy is still the least built part. The pathing is worse.";
let decision = decided(prose, json!([{ "spans": ["Nibu, I don't think the economy is still the least built part."], "mentions": [], "reply_to": NIBU }]));
assert_eq!(texts(&decision), ["Nibu, I don't think the economy is still the least built part."], "{decision}");
}
#[test]
fn soul_q3d_a_beat_measures_echoes_against_the_tail_it_quoted() {
let tail = vec![line(MINDS, LIBBY, "Libby", "the economy is still the least built part of the whole game", false)];
let beat = packet_in(TurnKind::Beat, &heimdall(), &Room { tail, here: Some(MINDS.into()), ..Room::default() }, 1);
assert!(beat.stimulus.contains("least built") && beat.bodies.iter().any(|body| body.contains("least built")), "{beat:?}");
let prose = "The economy is still the least built part of the whole game. I think so.";
let decision = decided_in(&beat, prose, json!([{ "spans": ["The economy is still the least built part of the whole game."] }]));
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
}
#[test]
fn soul_p4_only_someone_this_packet_showed_her_is_mentioned() {
let packet = packet();
assert!(!packet.people.iter().any(|(_, id)| id == VOID), "Void said nothing here");
let decision = decided("I say hi.", json!([{ "spans": ["I say hi."], "mentions": [VOID, NIBU], "reply_to": VOID }]));
assert_eq!((decision["said"][0]["mentions"].clone(), decision["said"][0]["reply_to"].clone()), (json!([NIBU]), Value::Null), "{decision}");
assert_eq!(decision["said"][0]["dropped"]["mentions"], json!([VOID]));
}
#[test]
fn soul_p5_the_same_line_is_said_once_and_a_turn_says_at_most_two() {
let line = json!({ "spans": ["I say hi."], "mentions": [], "reply_to": null });
assert_eq!(texts(&decided("I say hi.", json!([line.clone(), line.clone(), line]))), ["I say hi."]);
let prose = "One. Two. Three.";
let three = decided(prose, json!([{ "spans": ["One."] }, { "spans": ["Two."] }, { "spans": ["Three."] }]));
assert_eq!(texts(&three), ["One.", "Two."], "{three}");
}
#[test]
fn recollection_and_i_say_nothing_and_a_quoted_handle_say_nothing() {
// A recollection is the Interpreter's to leave out; a piece of a sentence cited anyway is refused.
let recalled = decided("Nibu said the economy is still the least built part, and it stuck.", json!([{ "spans": ["the economy is still the least built part"] }]));
assert!(texts(&recalled).is_empty(), "{recalled}");
assert!(texts(&decided("I say nothing. The quiet is fine.", json!([]))).is_empty());
// An @ in her words is text: only the structured field mentions anyone.
let handle = decided("\"@nibu, hi.\" I nod at her.", json!([{ "spans": ["@nibu, hi."], "mentions": [] }]));
assert_eq!((texts(&handle), handle["said"][0]["mentions"].clone()), (vec!["@nibu, hi.".to_owned()], json!([])), "{handle}");
}
/// Heimdall's state with a private memory about Kiko: she confided she is leaving.
fn kiko_confided() -> Value {
let mut state = heimdall();
state["thoughtMemory"]["memories"] = json!([{ "id": "kiko-secret", "summary": "Kiko confided she is leaving the swarm.", "createdAt": "2026-11-19T00:00:00Z", "updatedAt": "2026-11-19T00:00:00Z", "status": "crystallized", "intensity": 1.0, "target": { "id": "kiko", "kind": "person" }, "tags": ["private"] }]);
state
}
/// The first packet over seeds 1 to 60 whose context carries the memory.
fn showing(room: &Room) -> Packet {
(1..=60).map(|seed| packet_in(TurnKind::Chat, &kiko_confided(), room, seed)).find(|packet| packet.context.contains("leaving the swarm")).expect("the memory is selected on some seed")
}
#[test]
fn soul_q5d_what_she_knows_privately_about_kiko_is_listed_to_the_interpreter_in_a_dm_with_libby() {
let dm = "!dm-libby:gamecult.org";
let room = Room { messages: vec![line(dm, LIBBY, "Libby", "what's up with Kiko lately?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
let packet = showing(&room);
assert_eq!(packet.room_kind, RoomKind::Direct);
assert_eq!(packet.private, ["Kiko confided she is leaving the swarm."], "{packet:?}");
let prompt = speech_prompt(&packet, "x", "y");
assert!(prompt.contains("What she knows privately, none of it to be said here:\n- private: Kiko confided she is leaving the swarm."), "{prompt}");
assert!(prompt.contains("only to the person it concerns, in a direct message with exactly that person"), "{prompt}");
// Whether a line tells it is the Interpreter's reading of its meaning: code matches no words, so a line sharing the
// item's words is not refused for them (Soul F2: a word match refused 9 of 15 ordinary lines and missed paraphrase).
let ordinary = decided_in(&packet, "I'm going to stay on the pipeline work. That's all.", json!([{ "spans": ["I'm going to stay on the pipeline work."] }]));
assert_eq!(texts(&ordinary).len(), 1, "{ordinary}");
}
#[test]
fn in_a_direct_message_with_exactly_kiko_it_is_hers_to_say() {
let dm = "!dm-kiko:gamecult.org";
let room = Room { messages: vec![line(dm, KIKO, "Kiko", "did you tell anyone?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
let packet = showing(&room);
assert!(packet.private.is_empty() && packet.context.contains("- memory [kiko-secret]: Kiko confided"), "{packet:?}");
assert!(speech_prompt(&packet, "x", "y").contains("none of it to be said here:\n- none\n"));
let decision = decided_in(&packet, "Kiko, you're leaving the swarm and I've told no one. Not a soul.", json!([{ "spans": ["Kiko, you're leaving the swarm and I've told no one."] }]));
assert_eq!(texts(&decision).len(), 1, "{decision}");
}
#[test]
fn an_answer_that_is_not_the_contract_is_a_failure_not_a_silence() {
let model = Scripted::new(|_| String::new()).interpreting(|_| "She says hi.".into());
let decision = decide(&model, "test", &packet(), "The room is warm.", "I say hi.", &Tuning::default());
assert!(decision["failed"].as_str().unwrap().contains("not the speech contract"), "{decision}");
let fenced = Scripted::new(|_| String::new()).interpreting(|_| "```json\n{\"say\": []}\n```".into());
assert!(decide(&fenced, "test", &packet(), "x", "I say hi.", &Tuning::default()).get("failed").is_none());
}
#[test]
fn the_prompt_is_hugins_chat_prompt_with_the_room_its_kind_and_who_is_in_it() {
let packet = packet();
assert_eq!((packet.room.as_deref(), packet.room_kind), (Some(MINDS), RoomKind::Public));
let prompt = speech_prompt(&packet, "The room is warm.", "I say nothing.");
assert!(!prompt.contains("membrane") && prompt.ends_with("I say nothing."), "Huginn's own prompt, her prose last");
assert!(prompt.contains("The room: #minds:gamecult.org (a public room).") && prompt.contains(NIBU), "{prompt}");
for rule in ["You never write her words", "is not speech", "never her speech", "in a direct message with exactly that person", "She never says half a sentence", "consecutive sentences", "conditional | addressee | elsewhere", "At most two lines"] {
assert!(prompt.contains(rule), "{rule}");
}
}

View file

@ -0,0 +1,363 @@
//! The Projector's narration, the Persona stage's continuation, and the judge that measures them: one tool-less
//! connector call each.
//!
//! `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.
use std::collections::BTreeSet;
use std::net::SocketAddr;
use std::path::Path;
use std::time::Duration;
use anyhow::{Result, anyhow, bail};
use chrono::Utc;
use ghostlight_persona_projection::{PersonaPrompt, ProjectorPrompt, build_persona_prompt, build_projector_prompt};
use model_connector::{ConnectorClient, InputItem, ProviderRequest, ReasoningEffort, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome};
use serde::Serialize;
use sha2::{Digest, Sha256};
use super::select::{Packet, TurnKind};
use super::tuning::Tuning;
/// One tool-less model turn. `KitModel` is the one live owner; a test answers with recorded text.
pub trait Model {
/// One turn of `model`: `prompt` is its one user text and `request_id` its identity on the connector. A 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>;
}
/// A turn that produced no answer: why, and what it cost when the connector's receipt says (a refusal, a fault before
/// the provider, or a failure with no usage block costs none). A receipt whose usage block is missing or malformed does
/// not decode at all: that is model-connector's error, reported as the reason.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Failed {
pub reason: String,
pub usage: Option<Spent>,
}
impl std::fmt::Display for Failed {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.reason)
}
}
impl Failed {
fn without_usage(reason: impl Into<String>) -> Self {
Self { reason: reason.into(), usage: None }
}
}
fn spent(model: &str, usage: &model_connector::Usage) -> Spent {
Spent { model: model.to_owned(), input_tokens: usage.input_tokens, output_tokens: usage.output_tokens, cache_read_tokens: usage.cache_read_tokens, cache_write_tokens: usage.cache_write_tokens, reasoning_tokens: usage.reasoning_tokens }
}
/// A model's answer, and what the turn cost as the connector counted it: none when the answerer counts nothing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Answer {
pub text: String,
pub usage: Option<Spent>,
}
/// One turn's tokens, by the model that ran it, as the connector's receipt reports them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Spent {
pub model: String,
pub input_tokens: u64,
pub output_tokens: u64,
pub cache_read_tokens: u64,
pub cache_write_tokens: u64,
pub reasoning_tokens: Option<u64>,
}
/// 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.";
/// Room for the model's adaptive thinking; the narration itself is bounded by its word budget.
pub(crate) const MAX_OUTPUT_TOKENS: u32 = 1024;
const CONNECTOR_FRAME_BYTES: usize = 256 * 1024;
const INVOCATION_LIFE_MS: u64 = 60_000;
/// The connector key: the credential file `connector-key` in systemd's credentials directory, read once and trimmed. Its
/// error names the credential and never a byte of the file.
pub fn connector_key(credentials: &Path) -> Result<String> {
let key = std::fs::read_to_string(credentials.join("connector-key")).map_err(|_| anyhow!("the connector-key credential could not be read"))?;
Ok(key.trim().to_owned())
}
/// One tool-less connector turn by `caller` (her instance). Loopback only, as the kit is. Each call is its own
/// conversation: nothing is carried from one to the next. The model is the tuning's, named per call.
pub struct KitModel {
client: ConnectorClient,
caller: String,
}
impl KitModel {
/// `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> {
if !endpoint.ip().is_loopback() {
bail!("the connector endpoint is not a loopback address");
}
let client = ConnectorClient::new(endpoint, connection_key, CONNECTOR_FRAME_BYTES, Some(timeout)).map_err(|_| anyhow!("the connector client could not be configured"))?;
Ok(Self { client, caller: caller.to_owned() })
}
}
impl Model for KitModel {
fn ask(&self, request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
let mut request = ProviderRequest::new(request_id, request_id, model, INSTRUCTIONS, MAX_OUTPUT_TOKENS);
request.input = vec![InputItem::UserText { text: prompt.to_owned() }];
request.reasoning_effort = Some(ReasoningEffort::Low);
let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS;
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::without_usage(format!("the connector did not answer: {fault}")))?;
match result.disposition {
TransportDisposition::Refused(reason) => Err(Failed::without_usage(format!("the connector refused the call: {reason:?}"))),
TransportDisposition::Transported { events, receipt } => match receipt.outcome {
TransportOutcome::Completed { stop_reason: StopReason::EndTurn, usage, .. } => Ok(Answer {
text: events
.into_iter()
.filter_map(|event| match event.payload {
TransportEventPayload::TextDelta { text } => Some(text),
_ => None,
})
.collect(),
usage: Some(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:?}"), usage: usage.as_ref().map(|usage| spent(model, usage)) }),
},
}
}
}
// ---------------------------------------------------------------------------------------------
// Narration.
pub(crate) fn word_budget(kind: TurnKind, tuning: &Tuning) -> usize {
if kind == TurnKind::Beat { tuning.projector.beat_words } else { tuning.projector.words }
}
/// The Projector's prompt: Ghostlight's membrane over the packet, with the lens as where to begin.
pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String {
let guidance = format!("{}\n\nBegin from {}.", tuning.projector.guidance.trim(), packet.lens.words(&packet.forms));
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) })
}
/// A character that is a word on its own: Han, kana and Hangul are written without spaces, so each counts as one.
fn cjk(c: char) -> bool {
matches!(u32::from(c), 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF | 0x20000..=0x2FFFF)
}
/// CJK and full-width punctuation (`。`, `,`, `!`, `?`, `「」`): it belongs to the word before it and starts none.
fn cjk_punctuation(c: char) -> bool {
matches!(u32::from(c), 0x3000..=0x303F | 0xFF01..=0xFF0F | 0xFF1A..=0xFF20 | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65)
}
/// The byte offset where each word of `text` begins: a run of non-space characters is one word, and a CJK character is
/// a word of its own.
fn word_starts(text: &str) -> Vec<usize> {
let mut starts = Vec::new();
let mut in_word = false;
for (at, c) in text.char_indices() {
if c.is_whitespace() || cjk_punctuation(c) {
in_word = false;
} else if cjk(c) {
starts.push(at);
in_word = false;
} else if !in_word {
starts.push(at);
in_word = true;
}
}
starts
}
/// 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;
// ---------------------------------------------------------------------------------------------
// 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}") }
}
/// The Persona stage's prompt: Ghostlight's prose-only membrane over her identity and her lived stream. No field name,
/// number, schema or instruction of hers reaches it (invariant 7); the guidance is the tuning's setting line.
pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) -> String {
build_persona_prompt(&PersonaPrompt { identity: &packet.identity, lived_stream: &lived_stream(narration, &packet.heard), domain_guidance: tuning.persona.guidance.trim(), 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. A metric, never a filter: 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> = text.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_lowercase).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!(" {} ", narration.to_lowercase().replace('\u{2019}', "'"));
["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
/// 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
/// abbreviation list: a cut after "e.g." is accepted.
pub(crate) fn cap_words(text: &str, max: usize) -> String {
let text = text.trim();
let starts = word_starts(text);
let Some(&over) = starts.get(max) else { return text.to_owned() };
let within = text[..over].trim_end();
match last_sentence_end(within) {
Some(end) if words(&within[..end]) as f64 >= SENTENCE_CUT_FLOOR * max as f64 => within[..end].to_owned(),
_ => within.to_owned(),
}
}
/// The byte just past the last sentence end in `text`: a `.`, `!`, `?` or `…` with any closing quotes or brackets after
/// it, followed by whitespace or the end of the text; or a `。`, `!` or `?`, which ends a sentence where it stands.
fn last_sentence_end(text: &str) -> Option<usize> {
let chars: Vec<(usize, char)> = text.char_indices().collect();
let mut found = None;
for (index, (at, c)) in chars.iter().enumerate() {
let full_width = matches!(c, '。' | '!' | '?');
if !full_width && !matches!(c, '.' | '!' | '?' | '…') {
continue;
}
let mut end = at + c.len_utf8();
let mut next = index + 1;
while let Some((close_at, close)) = chars.get(next).filter(|(_, close)| matches!(close, '"' | '\'' | '”' | '’' | ')' | ']' | '」' | '』')) {
end = close_at + close.len_utf8();
next += 1;
}
if full_width || chars.get(next).is_none_or(|(_, after)| after.is_whitespace()) {
found = Some(end);
}
}
found
}
/// Words as the cap counts them.
pub(crate) fn words(text: &str) -> usize {
word_starts(text).len()
}
/// The one kebab form that is ordinary English: "short-term" folds to the schema key `shortTerm`, and prose must not fail
/// the judge for it. `shortTerm`, `short_term` and the run-together `shortterm` are still caught.
const KEBAB_ENGLISH: &str = "short-term";
/// Her persona state's schema: its property names are the identifiers a narration must never carry.
const PERSONA_SCHEMA: &str = include_str!("../../../../schemas/cultnet/gamecult.persona_state.v0.schema.json");
/// An identifier as compared: lowercased with its underscores and hyphens gone, so `socialBonds`, `SocialBonds`,
/// `social_bonds`, `social-bonds`, `SOCIAL_BONDS` and `socialbonds` are one.
fn folded(identifier: &str) -> String {
identifier.chars().filter(|c| !matches!(c, '_' | '-')).flat_map(char::to_lowercase).collect()
}
/// Whether a word is shaped like an identifier rather than prose: an underscore, or a capital after its first letter.
fn identifier_shaped(word: &str) -> bool {
word.contains('_') || word.chars().skip(1).any(char::is_uppercase)
}
fn keys_of(value: &serde_json::Value, schema: bool, into: &mut BTreeSet<String>) {
match value {
serde_json::Value::Object(map) => {
for (key, inner) in map {
if schema && key == "properties"
&& let Some(properties) = inner.as_object()
{
into.extend(properties.keys().cloned());
}
if !schema {
into.insert(key.clone());
}
keys_of(inner, schema, into);
}
}
serde_json::Value::Array(values) => values.iter().for_each(|inner| keys_of(inner, schema, into)),
_ => {}
}
}
/// The folded compound identifiers of the persona schema and of the tuning: a plain word such as `trust` or
/// `tension` is prose and is not among them.
fn identifiers() -> BTreeSet<String> {
let mut keys = BTreeSet::new();
if let Ok(schema) = serde_json::from_str::<serde_json::Value>(PERSONA_SCHEMA) {
keys_of(&schema, true, &mut keys);
}
if let Ok(tuning) = serde_json::to_value(Tuning::default()) {
keys_of(&tuning, false, &mut keys);
}
keys.into_iter().filter(|key| identifier_shaped(key)).map(|key| folded(&key)).collect()
}
/// The identifiers of typed state a narration carries: any token that folds to a compound property name of her persona
/// schema or a tuning key, in every case convention (camelCase, PascalCase, snake_case, SCREAMING_CASE, kebab-case and
/// run together), and any id the packet named (`ids`), as an exact token when it cannot be a plain word, or inside
/// brackets as the packet writes it. Only compound names are known, so a plain word such as `trust`, `tension` or
/// `values` is prose: "need-to-know", "trust:" and "Tension:" pass. A small deterministic guard on identifiers, never on
/// meaning.
pub(crate) fn field_names(narration: &str, ids: &[String]) -> Vec<String> {
let known = identifiers();
let mut found = BTreeSet::new();
for token in narration.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-')).map(|token| token.trim_matches('-')).filter(|token| !token.is_empty()) {
if known.contains(&folded(token)) && !token.eq_ignore_ascii_case(KEBAB_ENGLISH) {
found.insert(token.to_owned());
}
}
let tokens: BTreeSet<&str> = narration.split_whitespace().map(|token| token.trim_matches(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_' || c == ':'))).collect();
for id in ids {
let compound = id.contains(['-', '_', ':']) || id.chars().any(|c| c.is_ascii_digit());
if (compound && tokens.contains(id.as_str())) || narration.contains(&format!("[{id}]")) {
found.insert(id.clone());
}
}
found.into_iter().collect()
}
// ---------------------------------------------------------------------------------------------
// The eval: distinct-2 and the judge.
/// Distinct bigrams over all bigrams of the narrations, lowercased words: 1 is no repetition.
pub(crate) fn distinct_2(narrations: &[String]) -> f64 {
let mut all = 0usize;
let mut distinct = BTreeSet::new();
for narration in narrations {
let words: Vec<String> = narration.split_whitespace().map(|word| word.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase()).filter(|word| !word.is_empty()).collect();
for pair in words.windows(2) {
all += 1;
distinct.insert((pair[0].clone(), pair[1].clone()));
}
}
if all == 0 { 0.0 } else { distinct.len() as f64 / all as f64 }
}
/// 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 {
format!(
"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.stimulus, second.context, second.stimulus
)
}
/// The judge's letter, or None when its answer does not start with one.
pub(crate) fn judged(answer: &str) -> Option<char> {
answer.trim().trim_start_matches(['*', '"', '\'', '(']).chars().next().map(|c| c.to_ascii_uppercase()).filter(|c| *c == 'A' || *c == 'B')
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,699 @@
//! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn
//! one `project` through the Persona stage, and each one's quoted lines join the room as from her Matrix id, so the
//! next one hears them.
//!
//! Who wakes is the heartbeat's: `heartbeat::wakes` under the plan's `WakePolicy`, 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.
//!
//! Her state does not move during a run: the Interpreter (C3b) and the commit (C3c) are not built. `state_after_turn`
//! is the seam where they will. An explicit addressee (the Interpreter naming whom she speaks to) cannot be simulated
//! until then either: a spoken line addresses another persona only by the names in its text.
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 serde::Deserialize;
use serde_json::{Value, json};
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::{MouthReader, Organs, Request, Through, TurnKind, project};
use crate::address::{Addressee, is_for, localpart};
use crate::chat_client::ChatPending;
use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, FileStore, HeartbeatView, LineFacts, Speaker, WakeCause, WakePolicy, addressed_by_member, 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,
#[serde(default = "ruled")]
wake: WakePolicy,
/// 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 (`humans_pace`):
/// 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 {
30
}
fn ruled() -> WakePolicy {
WakePolicy::Ruled
}
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 under `humans_pace`. 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>,
}
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 [Line],
viewer: &'a str,
rooms: &'a [String],
seen: &'a Seen,
}
impl MouthReader for View<'_> {
fn pending(&self) -> Result<ChatPending> {
Ok(pending_for(self.lines, self.viewer, self.rooms, |at| unseen(self.seen, self.lines, at)))
}
}
struct Names<'a>(&'a Addressee);
impl HeartbeatView for Names<'_> {
fn addressing(&self) -> Result<Option<Addressing>> {
Ok(Some(Addressing { minds: vec![self.0.clone()] }))
}
}
/// The seam where the Interpreter (C3b) will turn her prose into proposals and the commit (C3c) will apply them, so her
/// next turn starts from the state this one left. Until they exist it returns her state unchanged.
fn state_after_turn(state: Value, _turn: &Value) -> Value {
state
}
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
}
}
/// For each line, how many Mind lines in a row came before it in her current Mind-only run: one run across every room
/// she sees, which a human's line ends only when it is in a room the run has lines in. Meta chatting in #eureka does not
/// end a loop in #minds.
fn mind_runs(lines: &[Line], cast: &[String], member: &Member) -> Vec<usize> {
let mut run = 0usize;
let mut run_rooms: Vec<&str> = Vec::new();
lines
.iter()
.map(|line| {
let before = run;
if line.visible_to(&member.entry.id, &member.rooms) {
if cast.contains(&line.from) {
run += 1;
run_rooms.push(&line.room);
} else if run_rooms.contains(&line.room.as_str()) {
run = 0;
run_rooms.clear();
}
}
before
})
.collect()
}
/// 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, under the plan's policy) 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>,
}
/// Whether she is in the exchange a line belongs to: she spoke in its room within `window` before it.
fn in_exchange(lines: &[Line], at: usize, her: &str, window: Duration) -> bool {
let line = &lines[at];
let since = line.at_ms.saturating_sub(u64::try_from(window.num_milliseconds()).unwrap_or(0));
lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.from == her && earlier.at_ms >= since)
}
/// 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.
#[allow(clippy::too_many_arguments, reason = "one wake decision's inputs, each a plan or room fact")]
fn woken(lines: &[Line], runs: &[usize], seen: &Seen, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Option<Woken> {
let mut found: Vec<(usize, WakeCause)> = Vec::new();
for (at, line) in lines.iter().enumerate() {
if !unseen(seen, lines, at) || !line.visible_to(&member.entry.id, &member.rooms) {
continue;
}
let delivery = line.delivery(at, &member.entry.id, lines);
let facts = LineFacts { mind_run: runs[at], own_room: member.entry.own_rooms.contains(&line.room), in_exchange: in_exchange(lines, at, &member.entry.id, gap) };
if let Some(cause) = wakes(policy, &member.addressee, &delivery, speaker(line, 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",
Some(WakeCause::Mind) => "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 mut 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, &mut 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 {
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: &mut [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 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_turn: Vec<Option<DateTime<Utc>>> = vec![None; members.len()];
let mut last_beat = plan.start;
let mut recent: Vec<Vec<Vec<String>>> = 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 woke: Vec<(usize, Option<Woken>)> = members.iter().enumerate().filter_map(|(at, member)| woken(&lines, &mind_runs(&lines, &cast, member), &seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_minutes)).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_turn[at].map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)),
last_turn_ms: last_turn[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());
// Woken by a direct message, she answers in it: to its sender alone.
let dm_to = woke_on.filter(|line| line.dm_to.as_deref() == Some(id.as_str())).map(|line| line.from.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 request = Request {
instance: localpart(&id).to_owned(),
kind,
state: Some(member.state.clone()),
room: Some(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::Interpreter,
last_heard: vec![],
recent: recent[at].clone(),
own_rooms: member.entry.own_rooms.clone(),
};
let view = View { lines: &lines, viewer: &id, rooms: &member.rooms, seen: &seen[at] };
let names = Names(&member.addressee);
let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model };
let report = project(&organs, &request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") }));
// Only the room she read is seen.
seen[at].insert(here.clone(), lines.len());
last_turn[at] = Some(now);
let render = &report["renders"][0];
if let Some(selected) = render["selected"].as_array() {
recent[at].push(selected.iter().filter_map(Value::as_str).map(str::to_owned).collect());
}
// A failed call is a failure, never a silence.
let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned());
// What she says is the Interpreter's decision alone; who it wakes is its structured mentions and reply target.
let said: Vec<Value> = if failed.is_some() { vec![] } else { render["interpreter"]["said"].as_array().cloned().unwrap_or_default() };
let cause = cause_word(why.as_ref().map(|why| why.cause));
let mut spoken: Vec<String> = Vec::new();
for (offset, decided) in said.iter().enumerate() {
let room = decided["room"].as_str().unwrap_or(&here).to_owned();
let says = decided["text"].as_str().unwrap_or_default().to_owned();
let mentions: Vec<String> = decided["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).filter(|id| cast.contains(&(*id).to_owned()) || plan.operators.contains(&(*id).to_owned())).map(str::to_owned).collect()).unwrap_or_default();
let reply_to = decided["reply_to"].as_str().and_then(|person| lines.iter().rposition(|line| line.from == person && line.room == room));
let at_ms = u64::try_from(now.timestamp_millis()).unwrap_or_default() + offset as u64;
let to = if room == here { dm_to.clone() } else { None };
lines.push(Line { from: id.clone(), name: member.entry.name.clone(), room, at_ms, says: says.clone(), mentions, dm_to: to, follow_up: false, reply_to, new: false });
rounds_of.push(round);
causes.push(Some(cause));
spoken.push(says);
}
let line = (!spoken.is_empty()).then(|| spoken.join(" / "));
let outcome = if failed.is_some() { "failed" } else if line.is_some() { "spoke" } else { "silent" };
let (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by));
let 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": report });
let member = &mut members[at];
member.state = state_after_turn(std::mem::take(&mut member.state), &turn);
turns.push(turn);
}
}
let metrics = metrics(members, &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;
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 }));
}
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(),
});
json!({
"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}"))
}
fn policy_words(policy: WakePolicy) -> String {
match policy {
WakePolicy::Live => "live: the operator or another Mind addressing her (the heartbeat's rule today)".into(),
WakePolicy::Ruled => "ruled: a line addressing her, from anyone, and any human line in her rooms".into(),
WakePolicy::HumansPace(cap) => format!("humans_pace (cap {cap}): a human's line wakes a Mind in her own room always, and in a public room when it addresses her or continues an exchange she is in; a Mind's line wakes another only by an explicit mention or a reply, while her current Mind-only run, across her rooms, is under {cap} lines, never by a name in prose"),
WakePolicy::NamesWithCap(cap) => format!("names_with_cap {cap}: ruled, but a Mind's line wakes no one once her current Mind-only run, across her rooms, has {cap} lines, until a human speaks where it runs"),
WakePolicy::AllMessages => "all_messages: any line in her rooms, a Mind's too (the old loop, the control)".into(),
}
}
/// `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()))
}
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, "> **State does not evolve during a run.** The Interpreter (C3b) and the commit (C3c) are not built, so every persona starts each turn from the state the plan gave her. `state_after_turn` in `projection/simulate.rs` is the seam where they will move it between rounds. Freshness carries over: each persona's earlier packets in the run count against repeating an item.\n");
let _ = writeln!(out, "> **Speech is the Interpreter's.** What she says is decided from her prose by the Interpreter's speech step (C3b, one tool-less structured call), held by code to her prose: each line rests on a verbatim span of it, in a room she may speak in, and is never someone else's words. Its structured mentions and reply target are the only explicit addressees; an `@` in the text tags no one.\n");
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: {}; beat: {}", policy_words(plan.wake), 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, "- speech: the Interpreter's lines, each posted to its room; none is silence");
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, "- read-only: nothing is posted, no state is put, no Mind is asked\n");
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"]));
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 |\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 _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]));
}
}
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 {
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]);
}
let _ = writeln!(out, "</details>\n");
}
}
let _ = writeln!(out, "## Total usage\n\n{}", usage_markdown(&usage_total(runs)));
out
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,416 @@
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::{Answer, Failed, Model, Spent};
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; `wake` is the TOML value of the policy; no beat unless `extra` sets one.
fn plan(dir: &Path, wake: &str, 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
wake = {wake}
start = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org"]
operators = ["@meta:gamecult.org"]
{beat}{extra}
[[cast]]
id = "{TOBIAH}"
name = "Tobiah"
state = "tobiah.json"
[[cast]]
id = "{LIBBY}"
name = "Libby"
state = "libby.json"
[[message]]
from = "@meta:gamecult.org"
name = "Meta"
room = "#minds:gamecult.org"
says = "good afternoon, everyone"
"##
),
)
.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 standalone quotation, sayable.
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 mut 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, &mut 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()
}
#[test]
fn the_wake_policies_are_the_heartbeats_one_function() {
let libby = Addressee::new(LIBBY, ["libby", "Libby"]);
let line = |from: &str, says: &str| 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 };
let ask = |policy: WakePolicy, from: &str, says: &str, speaker: Speaker, run: usize| wakes(policy, &libby, &line(from, says).delivery(0, LIBBY, &[]), speaker, LineFacts { mind_run: run, ..LineFacts::default() });
let paced = |says: &str, own_room: bool, in_exchange: bool| wakes(WakePolicy::HumansPace(4), &libby, &line("@meta:x", says).delivery(0, LIBBY, &[]), Speaker::Operator, LineFacts { mind_run: 0, own_room, in_exchange });
let (named, unnamed) = ("Libby, tea?", "what a day");
use WakeCause::*;
// Ruled: anyone addressing her, any human line.
assert_eq!(ask(WakePolicy::Ruled, TOBIAH, named, Speaker::Mind, 0), Some(AddressedByMind));
assert_eq!(ask(WakePolicy::Ruled, TOBIAH, unnamed, Speaker::Mind, 0), None, "another Mind's unaddressed line wakes no one");
assert_eq!(ask(WakePolicy::Ruled, "@deru:x", unnamed, Speaker::Member, 0), Some(Human));
assert_eq!(ask(WakePolicy::Ruled, "@deru:x", named, Speaker::Member, 0), Some(AddressedByHuman));
// Live, the heartbeat's today: a member's line does not wake her, the operator's or a Mind's address does.
assert_eq!(ask(WakePolicy::Live, "@deru:x", named, Speaker::Member, 0), None);
assert_eq!(ask(WakePolicy::Live, "@meta:x", named, Speaker::Operator, 0), Some(AddressedByHuman));
assert_eq!(ask(WakePolicy::Live, TOBIAH, named, Speaker::Mind, 0), Some(AddressedByMind));
assert_eq!(ask(WakePolicy::Live, "@meta:x", unnamed, Speaker::Operator, 0), None);
// Humans pace: a Mind's line never wakes a Mind; a human's wakes her in her own room, or in a public room when it
// addresses her or continues an exchange she is in.
assert_eq!(ask(WakePolicy::HumansPace(4), TOBIAH, named, Speaker::Mind, 0), None, "a name in prose wakes no one");
let tagged = Line { mentions: vec![LIBBY.into()], ..line(TOBIAH, unnamed) };
let explicit = |run: usize| wakes(WakePolicy::HumansPace(4), &libby, &tagged.delivery(0, LIBBY, &[]), Speaker::Mind, LineFacts { mind_run: run, ..LineFacts::default() });
assert_eq!(explicit(3), Some(AddressedByMind), "a Matrix mention by a Mind wakes her, in any room");
assert_eq!(explicit(4), None, "the backstop: past the cap of Mind lines in a row, no Mind wakes another");
assert_eq!(paced(unnamed, false, false), None, "a public room's human line that is not hers to answer");
assert_eq!(paced(unnamed, true, false), Some(Human));
assert_eq!(paced(unnamed, false, true), Some(Human));
assert_eq!(paced(named, false, false), Some(AddressedByHuman));
// The cap: a Mind's address wakes her only while the Mind run before the line is under it.
assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 1), Some(AddressedByMind));
assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 2), None);
assert_eq!(ask(WakePolicy::NamesWithCap(2), "@meta:x", unnamed, Speaker::Operator, 9), Some(Human), "a human always may");
// The control, and her own line never.
assert_eq!(ask(WakePolicy::AllMessages, TOBIAH, unnamed, Speaker::Mind, 0), Some(Mind));
assert_eq!(ask(WakePolicy::AllMessages, LIBBY, named, Speaker::Her, 0), None);
}
#[test]
fn under_the_ruled_set_unaddressed_mind_lines_wake_no_one() {
let dir = tempfile::tempdir().unwrap();
let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 6, ""), &chatty());
let turns = turns(&run);
assert_eq!(turns.len(), 2, "the operator's opening wakes both in round 1, and then nothing does: {turns:?}");
assert!(turns.iter().all(|(round, _, why)| *round == 1 && why == "human"), "{turns:?}");
assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == TOBIAH && line["says"] == "what a day" && line["woke"] == "human"), "her quoted words join the room as from her id");
}
#[test]
fn the_control_lets_minds_wake_each_other_into_a_reply_chain_counted_per_room() {
let dir = tempfile::tempdir().unwrap();
let (_, run) = run_plan(&plan(dir.path(), "\"all_messages\"", 6, ""), &chatty());
let metrics = &run["metrics"];
assert!(metrics["wakes"]["mind"].as_u64().unwrap() >= 5, "{metrics}");
let chain = &metrics["reply_chains"]["#minds:gamecult.org"];
// The two round-1 answers are to the operator; every later line is a reply to a Mind.
assert_eq!(chain["mind_to_mind_replies"].as_u64(), Some(metrics["mind_messages"].as_u64().unwrap() - 2), "{metrics}");
assert!(chain["longest"].as_u64().unwrap() >= 5 && chain["chains_of_3_or_more"] == 1, "{chain}");
let work = metrics["work_talk_share"].as_f64().unwrap();
assert!(work > 0.3 && work < 0.7, "Libby's lines name the deploy, Tobiah's do not: {work}");
}
#[test]
fn naming_runs_away_under_the_ruled_set_and_stops_at_the_cap() {
let dir = tempfile::tempdir().unwrap();
let (_, ruled) = run_plan(&plan(dir.path(), "\"ruled\"", 6, ""), &namers());
assert!(turns(&ruled).iter().filter(|(_, _, why)| why == "addressed_by_mind").count() >= 5, "{:?}", turns(&ruled));
assert_eq!(ruled["metrics"]["mind_addressed_wakes"]["name_in_text"], ruled["metrics"]["mind_addressed_wakes"]["total"]);
let dir = tempfile::tempdir().unwrap();
let (_, capped) = run_plan(&plan(dir.path(), "{ names_with_cap = 2 }", 6, ""), &namers());
let capped = turns(&capped);
assert!(capped.iter().all(|(round, _, _)| *round <= 2), "after two Mind lines in a row no Mind's address wakes anyone: {capped:?}");
let dir = tempfile::tempdir().unwrap();
let (_, paced) = run_plan(&plan(dir.path(), "{ humans_pace = 4 }", 6, ""), &namers());
assert!(turns(&paced).is_empty(), "under humans_pace an unaddressed public line wakes no one, and no Mind's line ever does");
}
#[test]
fn under_humans_pace_her_own_room_wakes_her_and_a_public_room_only_by_address_or_her_exchange() {
let dir = tempfile::tempdir().unwrap();
cast(dir.path());
let path = dir.path().join("plan.toml");
let line = |round: usize, room: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
std::fs::write(
&path,
format!(
"rounds = 4\nseed = 11\nwake = {{ humans_pace = 4 }}\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, "#minds:gamecult.org", "Libby, how was the gig?"),
line(2, "#minds:gamecult.org", "and the rest of you?"),
line(3, "#tobiah:gamecult.org", "quiet in here today")
),
)
.unwrap();
let (members, run) = run_plan(&path, &namers());
let turns = turns(&run);
assert_eq!(
turns,
vec![(1, "Libby".to_owned(), "addressed_by_human".to_owned()), (2, "Libby".to_owned(), "human".to_owned()), (3, "Tobiah".to_owned(), "human".to_owned())],
"named in #minds, then her exchange there, then his own room; Libby's naming Tobiah wakes no one"
);
assert_eq!(members[0].state, control(), "the seam: no state moved");
}
#[test]
fn the_beat_wakes_one_persona_by_the_heartbeats_pick() {
let dir = tempfile::tempdir().unwrap();
let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 4, "beat_s = 120"), &silent());
let turns = turns(&run);
for round in 2..=4 {
let beats: Vec<&(u64, String, String)> = turns.iter().filter(|(at, _, _)| *at == round).collect();
assert_eq!(beats.len(), 1, "one wake a beat: {turns:?}");
assert_eq!(beats[0].2, "beat");
}
// The pick takes whoever waited longest: the two alternate.
assert_ne!(turns[2].1, turns[3].1, "{turns:?}");
assert_eq!(run["metrics"]["silence_rate"].as_f64(), Some(1.0));
}
/// 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) -> std::result::Result<Answer, Failed> {
if prompt.starts_with("<!-- membrane:") {
Ok(Answer { text: "The room is slow.".into(), usage: None })
} else {
Err(Failed { reason: "the provider failed the call: Overloaded".into(), 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(), "\"ruled\"", 2, ""), &FailingPersona);
let metrics = &run["metrics"];
assert_eq!((metrics["failed"].as_u64(), metrics["silence_rate"].is_null()), (Some(2), 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(), "\"all_messages\"", 4, "");
assert_eq!(turns(&run_plan(&path, &chatty()).1), turns(&run_plan(&path, &chatty()).1));
}
/// Tobiah says a line that names Libby and holds her id as text; the Interpreter gives it `mentions` or not.
fn tagging(mention: bool) -> Scripted {
let mentions = if mention { json!([LIBBY]) } else { json!([]) };
Scripted::new(|prompt| if is_tobiah(prompt) { "\"ask @libby:gamecult.org, and Libby too\"".into() } else { "She lets it be.".into() }).interpreting(move |prompt| {
if !prompt.contains("Who she is:\nTobiah") {
return json!({ "say": [] }).to_string();
}
json!({ "say": [{ "spans": ["ask @libby:gamecult.org, and Libby too"], "mentions": mentions, "reply_to": null }] }).to_string()
})
}
#[test]
fn only_the_interpreters_structured_mention_is_a_mention_and_an_at_in_the_text_is_not() {
// Libby says hello first, so the packet shows her to Tobiah: a mention reaches only someone shown.
let hello = "[[message]]\nround = 0\nfrom = \"@libby:gamecult.org\"\nname = \"Libby\"\nroom = \"#minds:gamecult.org\"\nsays = \"hello all\"\n";
let plan = |dir: &Path, wake: &str, rounds: usize| {
let path = plan(dir, wake, rounds, "");
std::fs::write(&path, format!("{}{hello}", std::fs::read_to_string(&path).unwrap())).unwrap();
path
};
let dir = tempfile::tempdir().unwrap();
let (_, plain) = run_plan(&plan(dir.path(), "\"ruled\"", 3), &tagging(false));
let addressed = &plain["metrics"]["mind_addressed_wakes"];
assert_eq!(addressed["mention_or_reply"].as_u64(), Some(0), "an @id in the words tags no one: {addressed}");
let dir = tempfile::tempdir().unwrap();
let (_, tagged) = run_plan(&plan(dir.path(), "\"ruled\"", 3), &tagging(true));
let addressed = &tagged["metrics"]["mind_addressed_wakes"];
let libby_mind_wakes = turns(&tagged).iter().filter(|(_, who, why)| who == "Libby" && why == "addressed_by_mind").count();
assert_eq!(addressed["mention_or_reply"].as_u64().unwrap() as usize, libby_mind_wakes, "{addressed}");
// Under humans_pace a name or an @ in the words wakes no one; the structured mention does.
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), "{ humans_pace = 4 }", 3);
let opening = "says = \"good afternoon, everyone\"\n";
std::fs::write(&path, std::fs::read_to_string(&path).unwrap().replace(opening, &format!("{opening}mentions = [\"{TOBIAH}\"]\n"))).unwrap();
let woken_libby = |model: &Scripted| turns(&run_plan(&path, model).1).iter().any(|(_, who, _)| who == "Libby");
assert!(!woken_libby(&tagging(false)));
assert!(woken_libby(&tagging(true)));
}
#[test]
fn a_direct_message_in_one_of_the_plans_rooms_is_refused() {
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), "\"ruled\"", 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 her = Member { names_from: "test", addressee: Addressee::new("@kiko:x", ["kiko"]), entry: CastEntry { id: "@kiko:x".into(), name: "Kiko".into(), state: PathBuf::new(), rooms: vec![], own_rooms: vec![] }, state: Value::Null, rooms: vec!["#a:x".into(), "#b:x".into()] };
let cast = vec![TOBIAH.to_owned(), LIBBY.to_owned(), "@kiko:x".to_owned(), "@other:x".to_owned()];
let line = |from: &str, room: &str| Line { from: from.into(), name: String::new(), room: room.into(), at_ms: 0, says: "hi".into(), mentions: vec![], dm_to: None, follow_up: false, reply_to: None, new: false };
let lines = [line("@meta:x", "#a:x"), line(TOBIAH, "#a:x"), line("@other:x", "#b:x"), line(TOBIAH, "#b:x"), line("@meta:x", "#c:x")];
assert_eq!(mind_runs(&lines, &cast, &her), vec![0, 0, 1, 2, 3], "one run across #a and #b; a room she is not in does not break it");
// Soul's case: Meta chatting in #eureka does not end a loop in #minds; a word from Meta in #minds does.
let kiko = Member { rooms: vec!["#minds:x".into(), "#eureka:x".into()], ..her };
let lines = [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")];
assert_eq!(mind_runs(&lines, &cast, &kiko), vec![0, 1, 2, 2, 3, 0]);
assert_eq!(LineFacts::default().mind_run, usize::MAX, "fail-safe: an uncounted run is at the cap");
let tagged = Line { mentions: vec!["@kiko:x".into()], ..line(TOBIAH, "#a:x") };
assert_eq!(wakes(WakePolicy::HumansPace(4), &kiko.addressee, &tagged.delivery(0, "@kiko:x", &[]), Speaker::Mind, LineFacts::default()), None);
}
#[test]
fn the_report_names_its_gaps_and_carries_representative_lines_and_usage() {
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 report = simulate(&harness, &plan(dir.path(), "\"ruled\"", 3, "")).unwrap();
for part in ["# Swarm simulation", "State does not evolve during a run", "Speech is the Interpreter's", "group state in the Projector's packet: on", "### Representative lines", "**Meta (human)**: good afternoon, everyone", "**Tobiah** _(woke: human)_: what a day", "### Wakes by round", "| 1 | 0 | 2 | 0 | 0 | 0 |", "## Total usage", "| claude-sonnet-5-5 | 6 |"] {
assert!(report.contains(part), "{part}\n{report}");
}
}
#[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(), "\"ruled\"", 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(), "\"ruled\"", 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\nwake = {{ humans_pace = 4 }}\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(), "\"ruled\"", 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() {
for wake in ["\"ruled\"", "{ names_with_cap = 2 }"] {
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), wake, 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("rooms = [\"#minds:gamecult.org\"]", "rooms = [\"#minds:gamecult.org\", \"#lab:gamecult.org\", \"#ops:gamecult.org\"]")
.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]), "{wake}: {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"], "{wake}: {who} answers each room in the order it opened");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,345 @@
//! `persona-tuning.toml`: every knob of the Select stage, the Projector and the Persona stage, read at each wake.
//!
//! 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
//! loudly instead of running on the default it meant to change. A value out of its range refuses the file too.
//!
//! 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.
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
/// Where the tuning of an instance lives.
pub const TUNING_ROOT: &str = "/etc/gamecult/minds";
pub const TUNING_FILE: &str = "persona-tuning.toml";
/// The Persona stage's setting (map section 2): she continues the Projector's paragraph, her interior, with speech only
/// where her thought moves her to it, quoted (map section 5.5, invariant 5). It is not a reply to the room.
const PERSONA_GUIDANCE: &str = "Continue her inner stream where the paragraph leaves off: her own next thoughts, in the first person, in her own words. This is not a message to the room. When she means to say something aloud, she writes the very words she would type, in her own voice and addressed as she would address them, never a description of what she will say. Whether she says them now is decided after her. 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.
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. Render the moment as she lives it: who is here and how they sit with her, what she carries, what she wants. What was said reaches her word for word after this stream, so never retell or summarise it: render what it stirs in her and what she makes of the people who said it. Render the conversation as it stands. Do not weigh options or list what she might do or say; what she does is hers to decide. Leave out whatever the context does not carry: an absence is not part of her moment. Use each person's pronouns as given.";
/// The context room the fixed slots need beside the identity: the hour and the mood lines always fit.
const FIXED_ROOM: usize = 256;
/// 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;
/// The ceiling of the messages to her: at least a long message whole, and far under the connector's 256 KiB frame, which
/// also carries the rest of the prompt.
const ADDRESSED_RANGE: std::ops::RangeInclusive<usize> = 1024..=64 * 1024;
/// The most bytes any one part of the prompt may take: with the identity, the guidance and the messages to her
/// (`ADDRESSED_RANGE`), the Projector's prompt stays far under the connector's 256 KiB frame.
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.
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)]
#[serde(default, deny_unknown_fields)]
pub struct Tuning {
pub projector: ProjectorTuning,
pub persona: PersonaTuning,
pub interpreter: InterpreterTuning,
pub select: SelectTuning,
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(),
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.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ProjectorTuning {
pub model: String,
pub guidance: String,
/// The lived stream's words on a chat, follow-up or reflection turn.
pub words: usize,
/// On a beat: a thin moment gets a thin stream.
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,
}
/// The selection: its temperature and inclusion, its budgets, its half-life, the freshness decay and the pool caps.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SelectTuning {
/// The softmax temperature that orders the candidates.
pub temperature: f64,
/// The score at which a candidate is included 63% of the time: inclusion is `1 - exp(-score / inclusion_score)`.
pub inclusion_score: f64,
/// Identity plus typed context, in bytes.
pub context_bytes: usize,
pub stimulus_bytes: usize,
/// What was said to her, verbatim, for the Persona stage.
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
/// caps whole, newest first, up to this, and the older ones are counted.
pub addressed_bytes: usize,
pub identity_bytes: usize,
/// One bond line's summary, in bytes.
pub bond_summary_bytes: usize,
/// One selected item's text, in bytes.
pub item_bytes: usize,
/// The recency time constant of her memories and short-term items, in hours.
pub memory_tau_h: f64,
/// freshness = base ^ (times shown in the last `freshness_window` projections); 0 never repeats an item in the window.
pub freshness_base: f64,
pub freshness_window: usize,
/// People present shown with a full bond line; the rest are named.
pub people_full: usize,
/// The room lines a beat shows.
pub beat_tail_lines: usize,
/// The group-state slot: who has been talking to whom, how long since a human spoke, what is addressed to her or
/// open to anyone, and how long the run of Mind lines is (prior art: group state in the prompt is what lets a
/// participant judge whether to speak).
pub group_state: bool,
/// The room lines the group state reads.
pub group_lines: usize,
/// The group-state slot's bytes.
pub group_bytes: usize,
pub caps: PoolCaps,
}
/// The most items each pool may give a packet. A maximum, never a target.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PoolCaps {
pub memories_about_present: usize,
pub other_memories: usize,
pub needs: usize,
pub incubation: usize,
pub stance: usize,
pub value: usize,
pub said: usize,
}
/// The weighted draw of the lens a turn begins from.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LensWeights {
pub body_and_hour: f64,
pub person_present: f64,
pub unresolved_want: f64,
pub memory_surfacing: f64,
pub wondering: f64,
}
impl Default for ProjectorTuning {
fn default() -> Self {
Self { model: "claude-sonnet-5-5".into(), guidance: GUIDANCE.into(), words: 150, beat_words: 90 }
}
}
/// The Interpreter's speech call: its model. Its prompt is code (`interpret`): what it may decide is not a knob.
#[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-sonnet-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 {
fn default() -> Self {
Self {
temperature: 0.7,
inclusion_score: 0.5,
context_bytes: 2500,
stimulus_bytes: 1500,
heard_bytes: 1500,
addressed_bytes: 8 * 1024,
identity_bytes: 300,
bond_summary_bytes: 300,
item_bytes: 400,
memory_tau_h: 24.0,
freshness_base: 0.5,
freshness_window: 5,
people_full: 2,
beat_tail_lines: 6,
group_state: true,
group_lines: 12,
group_bytes: 360,
caps: PoolCaps::default(),
}
}
}
impl Default for PoolCaps {
fn default() -> Self {
Self { memories_about_present: 2, other_memories: 2, needs: 1, incubation: 1, stance: 1, value: 1, said: 1 }
}
}
impl Default for LensWeights {
fn default() -> Self {
Self { body_and_hour: 1.0, person_present: 1.0, unresolved_want: 1.0, memory_surfacing: 1.0, wondering: 1.0 }
}
}
impl Tuning {
/// Refuses a value the stages cannot run on, naming the knob.
pub(crate) fn validate(&self) -> Result<()> {
let select = &self.select;
let positive = |name: &str, value: f64| if value.is_finite() && value > 0.0 { Ok(()) } else { Err(anyhow::anyhow!("{name} must be a finite number above 0, not {value}")) };
if !(select.temperature.is_finite() && TEMPERATURE_RANGE.contains(&select.temperature)) {
bail!("select.temperature must be from {} to {}, not {}", TEMPERATURE_RANGE.start(), TEMPERATURE_RANGE.end(), select.temperature);
}
if self.projector.model.trim().is_empty() {
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");
}
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);
}
let caps = &select.caps;
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");
}
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)) {
bail!("select.freshness_base must be from 0 to 1, not {}", select.freshness_base);
}
for (name, bytes) in [
("select.context_bytes", select.context_bytes),
("select.stimulus_bytes", select.stimulus_bytes),
("select.heard_bytes", select.heard_bytes),
("select.identity_bytes", select.identity_bytes),
("select.bond_summary_bytes", select.bond_summary_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.beat_words", self.projector.beat_words),
("persona.words", self.persona.words),
] {
if bytes == 0 {
bail!("{name} must be above 0");
}
}
for (name, bytes) in [
("select.context_bytes", select.context_bytes),
("select.stimulus_bytes", select.stimulus_bytes),
("select.heard_bytes", select.heard_bytes),
("select.identity_bytes", select.identity_bytes),
("select.bond_summary_bytes", select.bond_summary_bytes),
("select.item_bytes", select.item_bytes),
("select.group_bytes", select.group_bytes),
("projector.guidance", self.projector.guidance.len()),
("persona.guidance", self.persona.guidance.len()),
] {
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");
}
}
if select.group_lines > GROUP_LINES_MAX {
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 {
bail!("{name} must be at most {WORDS_MAX}, not {words}");
}
}
if select.identity_bytes.checked_add(FIXED_ROOM).is_none_or(|needed| select.context_bytes < needed) {
bail!("select.context_bytes must leave {FIXED_ROOM} bytes beside select.identity_bytes for the hour and the mood");
}
let lens = &self.lens;
let weights = [lens.body_and_hour, lens.person_present, lens.unresolved_want, lens.memory_surfacing, lens.wondering];
if weights.iter().any(|weight| !weight.is_finite() || *weight < 0.0) || lens.body_and_hour <= 0.0 {
bail!("lens weights must be finite and not negative, and lens.body_and_hour, the one lens every turn has, above 0");
}
Ok(())
}
/// The SHA-256 of the effective tuning, serialized whole.
pub(crate) fn sha256(&self) -> String {
let bytes = serde_json::to_vec(self).unwrap_or_default();
Sha256::digest(&bytes).iter().map(|byte| format!("{byte:02x}")).collect()
}
}
/// The tuning a wake ran under, and where it came from.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Loaded {
pub tuning: Tuning,
/// `file` or `defaults`.
pub source: &'static str,
/// The effective tuning's SHA-256, hex.
pub sha256: String,
}
/// The tuning at `path`, or the defaults when no file is there. A file that cannot be read or parsed, that names a key
/// the code does not know, or that sets a value out of its range is an error: the wake does not run on a tuning nobody
/// meant.
pub fn load(path: &Path) -> Result<Loaded> {
let (tuning, source) = match std::fs::read(path) {
Ok(bytes) => {
let text = std::str::from_utf8(&bytes).with_context(|| format!("the tuning {} is not UTF-8", path.display()))?;
(toml::from_str::<Tuning>(text).with_context(|| format!("the tuning {} is not a tuning", path.display()))?, "file")
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (Tuning::default(), "defaults"),
Err(error) => return Err(error).with_context(|| format!("the tuning {} could not be read", path.display())),
};
tuning.validate().with_context(|| format!("the tuning {} is out of range", path.display()))?;
let sha256 = tuning.sha256();
Ok(Loaded { tuning, source, sha256 })
}

View file

@ -28,6 +28,7 @@ pub trait MindPort {
fn query(&self, selection: &Selection) -> Result<PipelineSelectionPage>;
/// The `top_k` documents of the selection nearest `text` by meaning, ranked: the same read as
/// `query` with a semantic ask, so one call path carries both. A port with no index refuses.
/// Kept for C3b's Interpreter read tool (`mind_query`); no caller in this crate until then.
fn query_near(&self, _selection: &Selection, _text: &str, _top_k: u32) -> Result<PipelineSelectionPage> {
bail!("this mind port has no semantic index")
}

View file

@ -1,360 +0,0 @@
//! What of her own mind enters a Persona turn besides what she is always shown, and in what words.
//!
//! Ruling `eureka-body:ruling:persona-memory-written-not-transcript`: what she
//! must still know when the conversation is gone is written into her mind as
//! typed memory, and a later turn reads it back from there. Open asks and open
//! commitments are not recalled. This module owns the cued, ranked remainder
//! and nothing else. It reads only her own mind through `MindPort`; it reads no
//! chat (the lines shown beside a message are conversation, never memory),
//! keeps no cache between turns, and holds no index: the daemon's index answers
//! `MindPort::query_near`, and a rank only orders.
//!
//! Three lanes, merged in this order and de-duplicated by id, none showing an
//! open item:
//! - `about`: memory in force about any other sender of this batch, ranked by
//! `weight` from the newest `POOL` of them.
//! - `relevant`: memory, follow-up and ruling in force nearest the batch's
//! words, in the daemon's order. A wake has no words and skips it.
//! - `salient`: memory in force ranked by `weight` from the newest `POOL`.
//! On a wake, which has no senders and no words, this is all that runs.
//!
//! Each lane has an item limit and a byte budget, so no one signal crowds out
//! another; a lane that leaves something out says how many.
use std::collections::BTreeMap;
use anyhow::{Result, bail};
use chrono::{DateTime, Utc};
use cultnet_rs::Selection;
use eureka_pipeline::{MemoryOrigin, MemorySort, PipelineDocument, PipelineKind, RulingAuthority};
use huginn_mind::{PipelineDocumentView, PipelinePageItems};
use crate::persona::quoted;
use crate::queue::{MindPort, any_of, in_force, of_kind};
/// What each lane shows, and the bytes of rendered lines it may spend.
pub(crate) const ABOUT_LIMIT: usize = 6;
pub(crate) const ABOUT_BYTES: usize = 5 * 1024;
pub(crate) const RELEVANT_LIMIT: usize = 8;
pub(crate) const RELEVANT_BYTES: usize = 7 * 1024;
pub(crate) const SALIENT_LIMIT: usize = 4;
pub(crate) const SALIENT_BYTES: usize = 4 * 1024;
/// The most bytes of rendered lines one turn recalls: the lanes' budgets.
#[cfg(test)]
pub(crate) const MAX_BYTES: usize = ABOUT_BYTES + RELEVANT_BYTES + SALIENT_BYTES;
/// The newest memories a ranked lane ranks, and the nearest documents the index is asked for: open
/// items among them are dropped, so asking past the lane's limit keeps its items in reach.
const POOL: u32 = 32;
/// Hours over which a memory's recency halves. Calibration, not a gate.
pub(crate) const RECENCY_HALF_LIFE_H: f64 = 72.0;
/// The longest semantic text, in bytes, cut on a character boundary.
pub(crate) const NEAR_TEXT_MAX: usize = 1000;
/// The sorts recall may show: the ones that are not open items.
const RECALLED_SORTS: [&str; 5] = ["Decided", "Learned", "Did", "Idea", "Rapport"];
/// Which lane brought an item.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Lane {
About,
Relevant,
Salient,
}
impl Lane {
fn heading(self) -> &'static str {
match self {
Self::About => "About the people here:",
Self::Relevant => "Near what was said:",
Self::Salient => "Weighed most:",
}
}
}
/// One recalled document as a line of the turn's input, and the people it names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Entry {
pub id: String,
pub line: String,
/// The Matrix ids its `about` and origin name.
pub people: Vec<String>,
}
/// One lane's result: what it shows and how many it left out.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Shown {
pub lane: Lane,
pub entries: Vec<Entry>,
pub left_out: usize,
}
/// Whether the semantic lane ran.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Search {
Ran,
/// A wake has no words to look near.
Skipped,
/// The index could not be asked; the turn goes on without that lane.
Unavailable,
}
/// What a turn recalls, lane by lane in merge order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Recalled {
pub lanes: Vec<Shown>,
pub search: Search,
}
impl Recalled {
/// Every item shown, in merge order.
pub(crate) fn entries(&self) -> impl Iterator<Item = &Entry> {
self.lanes.iter().flat_map(|shown| shown.entries.iter())
}
}
/// What the batch lets recall look for.
pub(crate) struct Cue<'a> {
/// The batch's senders other than her own, in arrival order.
pub senders: Vec<&'a str>,
/// The batch's message texts, newest first; empty on a wake.
pub texts: Vec<&'a str>,
/// Display names by sender id, to read a line with.
pub names: BTreeMap<&'a str, &'a str>,
/// Follow-ups and rulings the responsibilities section already lists.
pub listed: &'a [String],
/// The time recency is measured against.
pub now: DateTime<Utc>,
}
/// The semantic text: message texts newest first, then the senders' names,
/// cut to `NEAR_TEXT_MAX` bytes on a character boundary. None when it says nothing.
pub(crate) fn near_text(cue: &Cue) -> Option<String> {
let mut parts: Vec<&str> = cue.texts.iter().copied().filter(|text| !text.trim().is_empty()).collect();
let mut names: Vec<&str> = cue.senders.iter().filter_map(|id| cue.names.get(id).copied()).filter(|name| !name.is_empty()).collect();
names.dedup();
parts.extend(names);
let mut joined = parts.join("\n");
if joined.len() > NEAR_TEXT_MAX {
let mut end = NEAR_TEXT_MAX;
while !joined.is_char_boundary(end) {
end -= 1;
}
joined.truncate(end);
}
if joined.trim().is_empty() { None } else { Some(joined) }
}
fn documents(page: huginn_mind::PipelineSelectionPage) -> Result<Vec<PipelineDocumentView>> {
match page.items {
PipelinePageItems::Documents(views) => Ok(views),
PipelinePageItems::Headers(_) => bail!("the mind answered headers to a document selection"),
}
}
fn newest(selection: Selection, limit: u32) -> Selection {
Selection { descending: true, limit: Some(limit), projection: "document".into(), ..selection }
}
fn recalled_memories_in_force() -> Selection {
any_of(in_force(of_kind(PipelineKind::Memory)), "sort", &RECALLED_SORTS)
}
/// How much a memory weighs: its salience in thousandths of one, plus a
/// recency that is 1 when admitted now and halves every `RECENCY_HALF_LIFE_H`
/// hours. A time that cannot be read has no recency. Relevance is its own
/// lane, not a summand, so no one signal can crowd out another.
pub(crate) fn weight(salience_permille: u16, admitted_at: &str, now: DateTime<Utc>) -> f64 {
let recency = DateTime::parse_from_rfc3339(admitted_at).map_or(0.0, |at| {
let age_hours = (now - at.with_timezone(&Utc)).num_seconds().max(0) as f64 / 3600.0;
0.5_f64.powf(age_hours / RECENCY_HALF_LIFE_H)
});
f64::from(salience_permille) / 1000.0 + recency
}
/// The views ranked by weight, heaviest first; equal weights keep their order, which is newest first.
fn ranked(mut views: Vec<PipelineDocumentView>, now: DateTime<Utc>) -> Vec<PipelineDocumentView> {
let weight_of = |view: &PipelineDocumentView| match &view.document {
PipelineDocument::Memory(memory) => weight(memory.salience_permille, &view.admission.admitted_at, now),
_ => 0.0,
};
views.sort_by(|a, b| weight_of(b).total_cmp(&weight_of(a)));
views
}
/// The people a memory names, each quoted, by display name where this turn's senders showed one.
fn who<'a>(ids: impl Iterator<Item = &'a str>, names: &BTreeMap<&str, &str>) -> String {
let people: Vec<String> = ids.map(|id| quoted(names.get(id).copied().filter(|name| !name.is_empty()).unwrap_or(id))).collect();
if people.is_empty() { "someone".into() } else { people.join(", ") }
}
/// The ids a memory's `about` and origin name.
pub(crate) fn people_of(memory: &eureka_pipeline::PipelineMemory) -> Vec<String> {
let origin: &[eureka_pipeline::Short] = match &memory.origin {
MemoryOrigin::Room { heard_from, .. } => heard_from,
MemoryOrigin::Direct { with, .. } => with,
MemoryOrigin::Wake | MemoryOrigin::SelfRun { .. } | MemoryOrigin::Sleep { .. } => &[],
};
memory.about.iter().chain(origin).map(|id| id.0.clone()).collect()
}
/// Where she learned something and from whom, as a phrase: the one render of an origin, for a memory and for a brief.
pub(crate) fn origin_phrase(origin: &MemoryOrigin, names: &BTreeMap<&str, &str>) -> String {
match origin {
MemoryOrigin::Room { rooms, heard_from } if heard_from.is_empty() => format!("in #{}", rooms.0),
MemoryOrigin::Room { rooms, heard_from } => format!("in #{}, with {}", rooms.0, who(heard_from.iter().map(|id| id.0.as_str()), names)),
MemoryOrigin::Direct { with, .. } => format!("privately, with {}", who(with.iter().map(|id| id.0.as_str()), names)),
MemoryOrigin::Wake => "on a wake".to_string(),
MemoryOrigin::SelfRun { run } => format!("in your Self run {}", run.0),
MemoryOrigin::Sleep { run } => format!("in your sleep {}", run.0),
}
}
/// One memory as its line: date, where and from whom she learned it, what it
/// is and whom it concerns, then her words. The one way a memory reads, for
/// recall and for the open items the responsibilities section shows, which pass
/// `with_id` to lead with the id she settles it by. `about` is never the place.
pub(crate) fn memory_line(view: &PipelineDocumentView, names: &BTreeMap<&str, &str>, with_id: bool) -> Option<String> {
// An open item of the responsibilities (the one caller that leads with the id) shows a clipped text; recall shows it whole.
let PipelineDocument::Memory(memory) = &view.document else { return None };
let date = view.admission.admitted_at.get(..10).unwrap_or(&view.admission.admitted_at);
let origin = origin_phrase(&memory.origin, names);
let about = who(memory.about.iter().map(|id| id.0.as_str()), names);
let sort = match (memory.sort, memory.about.is_empty()) {
(MemorySort::Asked, _) => format!("asked by {about}"),
(MemorySort::Committed, true) => "committed".to_string(),
(MemorySort::Committed, false) => format!("committed, with {about}"),
(sort, true) => format!("{sort:?}"),
(sort, false) => format!("{sort:?} about {about}"),
};
let lead = if with_id { format!("{} ", view.id.id.0) } else { String::new() };
Some(format!("- {lead}({date}, {origin}, {sort}): {}\n", quoted(&if with_id { clipped(&memory.text.0) } else { memory.text.0.clone() })))
}
/// The most bytes of an item's text a listed line carries; the rest is one `huginn view` away.
pub(crate) const LINE_TEXT_MAX_BYTES: usize = 160;
/// `text` cut to about `LINE_TEXT_MAX_BYTES` on a character boundary, with an ellipsis where it was cut.
pub(crate) fn clipped(text: &str) -> String {
if text.len() <= LINE_TEXT_MAX_BYTES {
return text.to_owned();
}
let cut = (0..=LINE_TEXT_MAX_BYTES).rev().find(|at| text.is_char_boundary(*at)).unwrap_or(0);
format!("{}…", &text[..cut])
}
/// One recalled document as its line, or None for a kind recall does not show.
fn line_of(view: &PipelineDocumentView, names: &BTreeMap<&str, &str>) -> Option<String> {
match &view.document {
PipelineDocument::Memory(_) => memory_line(view, names, false),
PipelineDocument::FollowUp(follow_up) => Some(format!("- You set yourself to: {}\n", quoted(follow_up.item.0.lines().next().unwrap_or("")))),
PipelineDocument::Ruling(ruling) => {
let title = quoted(&ruling.title.0);
Some(match &ruling.authority {
RulingAuthority::Steward { steward, repo, .. } => {
// A display name is a member's text: keep it to one line.
let who: String = names.get(steward.0.as_str()).copied().unwrap_or(steward.0.as_str()).chars().filter(|c| !c.is_control()).collect();
format!("- {who} ruled, as steward of {}: {title}\n", repo.0)
}
RulingAuthority::Mind => format!("- You ruled: {title}\n"),
RulingAuthority::Operator => format!("- The operator ruled: {title}\n"),
RulingAuthority::Standing | RulingAuthority::Defaulted => format!("- Ruled: {title}\n"),
})
}
_ => None,
}
}
/// Fills one lane from its ranked candidates: each not yet shown or listed
/// elsewhere, within the lane's item limit and byte budget (a line that does
/// not fit is skipped, a later shorter one may). `matched` is how many the
/// lane's query matched, so what it left out is counted exactly.
fn fill(lane: Lane, candidates: Vec<PipelineDocumentView>, matched: usize, limit: usize, budget: usize, seen: &mut Vec<String>, cue: &Cue) -> Shown {
let (mut entries, mut bytes, mut elsewhere) = (Vec::new(), 0usize, 0usize);
for view in candidates {
let id = view.id.id.0.clone();
if seen.contains(&id) || cue.listed.contains(&id) {
elsewhere += 1;
continue;
}
let Some(line) = line_of(&view, &cue.names) else { continue };
if entries.len() == limit || bytes + line.len() > budget {
continue;
}
seen.push(id.clone());
bytes += line.len();
let people = match &view.document {
PipelineDocument::Memory(memory) => people_of(memory),
_ => Vec::new(),
};
entries.push(Entry { id, line, people });
}
let left_out = matched.saturating_sub(entries.len() + elsewhere);
Shown { lane, entries, left_out }
}
/// Whether a view is an open ask or commitment: a memory of those sorts.
fn is_open_item(view: &PipelineDocumentView) -> bool {
matches!(&view.document, PipelineDocument::Memory(memory) if matches!(memory.sort, MemorySort::Asked | MemorySort::Committed))
}
/// Selects what her mind gives this turn. A mind that cannot be read fails the
/// turn; an index that cannot be asked only loses the relevant lane.
pub(crate) fn select(mind: &dyn MindPort, cue: &Cue) -> Result<Recalled> {
let (about, about_matched) = if cue.senders.is_empty() {
(Vec::new(), 0)
} else {
let page = mind.query(&newest(any_of(recalled_memories_in_force(), "about", &cue.senders), POOL))?;
let matched = page.matched as usize;
(ranked(documents(page)?, cue.now), matched)
};
let (relevant, search) = match near_text(cue) {
None => (Vec::new(), Search::Skipped),
Some(text) => {
let kinds = [PipelineKind::Memory, PipelineKind::FollowUp, PipelineKind::Ruling];
let members = in_force(Selection { schemas: Some(kinds.iter().map(|kind| kind.type_id().to_string()).collect()), projection: "document".into(), ..Selection::default() });
match mind.query_near(&members, &text, POOL).and_then(documents) {
// An open ask or commitment is shown by the responsibilities section; it never comes here.
Ok(found) => (found.into_iter().filter(|view| !is_open_item(view)).collect::<Vec<_>>(), Search::Ran),
Err(_) => (Vec::new(), Search::Unavailable),
}
}
};
let page = mind.query(&newest(recalled_memories_in_force(), POOL))?;
let salient_matched = page.matched as usize;
let salient = ranked(documents(page)?, cue.now);
let mut seen = Vec::<String>::new();
let relevant_found = relevant.len();
let lanes = vec![
fill(Lane::About, about, about_matched, ABOUT_LIMIT, ABOUT_BYTES, &mut seen, cue),
fill(Lane::Relevant, relevant, relevant_found, RELEVANT_LIMIT, RELEVANT_BYTES, &mut seen, cue),
fill(Lane::Salient, salient, salient_matched, SALIENT_LIMIT, SALIENT_BYTES, &mut seen, cue),
];
Ok(Recalled { lanes, search })
}
/// The section of a turn's input: one heading per lane that shows or left out anything, one line each,
/// and after a lane that left something out a line saying how many.
pub(crate) fn render(recalled: &Recalled) -> String {
let mut out = String::from("What you remember (from your own mind; `huginn view <id>` reads a record):\n");
for shown in &recalled.lanes {
if shown.entries.is_empty() && shown.left_out == 0 {
continue;
}
out.push_str(shown.lane.heading());
out.push('\n');
shown.entries.iter().for_each(|entry| out.push_str(&entry.line));
if shown.left_out > 0 {
out.push_str(&format!("({} more not shown.)\n", shown.left_out));
}
}
if recalled.lanes.iter().all(|shown| shown.entries.is_empty() && shown.left_out == 0) {
out.push_str("- nothing is remembered yet.\n");
}
if recalled.search == Search::Unavailable {
out.push_str("(The search of your memory is unavailable this turn; only what concerns the senders and what weighs most are shown.)\n");
}
out
}
#[cfg(test)]
mod tests;

View file

@ -1,449 +0,0 @@
//! Recall's tests: a real mind behind a port that records what is asked of it.
use std::cell::RefCell;
use anyhow::Result;
use cultnet_rs::Selection;
use chrono::Duration;
use eureka_pipeline::{MemoryOrigin, MemorySort, PipelineDocument, PipelineKind as K, Slug};
use huginn_mind::{PipelineAdmissionOutcome, PipelineSelectionPage};
use super::*;
use crate::testkit::*;
/// What was asked of the mind: plain selections, and semantic asks with their text and top_k.
#[derive(Default)]
struct Asked {
plain: Vec<Selection>,
near: Vec<(Selection, String, u32)>,
}
struct Recording<'a> {
inner: &'a TestMind,
asked: RefCell<Asked>,
}
impl<'a> Recording<'a> {
fn over(inner: &'a TestMind) -> Self {
Self { inner, asked: RefCell::default() }
}
}
impl MindPort for Recording<'_> {
fn instance(&self) -> &Slug {
self.inner.instance()
}
fn query(&self, selection: &Selection) -> Result<PipelineSelectionPage> {
self.asked.borrow_mut().plain.push(selection.clone());
self.inner.query(selection)
}
fn query_near(&self, selection: &Selection, text: &str, top_k: u32) -> Result<PipelineSelectionPage> {
self.asked.borrow_mut().near.push((selection.clone(), text.to_string(), top_k));
self.inner.query_near(selection, text, top_k)
}
fn admit(&self, agent: &str, session: &str, documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome> {
self.inner.admit(agent, session, documents)
}
}
/// A port with no index: `query_near` is the trait's refusal.
struct NoIndex<'a>(&'a TestMind);
impl MindPort for NoIndex<'_> {
fn instance(&self) -> &Slug {
self.0.instance()
}
fn query(&self, selection: &Selection) -> Result<PipelineSelectionPage> {
self.0.query(selection)
}
fn admit(&self, agent: &str, session: &str, documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome> {
self.0.admit(agent, session, documents)
}
}
const LIBBY: &str = "@libby:chat";
/// When a turn runs, a minute after the first admissions.
const NOW_MS: i64 = 60_000;
fn key(label: &str) -> String {
format!("{INSTANCE}:memory:{label}")
}
fn cue<'a>(senders: &[&'a str], texts: &[&'a str], listed: &'a [String]) -> Cue<'a> {
Cue { senders: senders.to_vec(), texts: texts.to_vec(), names: BTreeMap::from([(LIBBY, "Libby")]), listed, now: at(NOW_MS) }
}
fn ids(shown: &Shown) -> Vec<String> {
shown.entries.iter().map(|entry| entry.id.clone()).collect()
}
fn lane(recalled: &Recalled, which: Lane) -> &Shown {
recalled.lanes.iter().find(|shown| shown.lane == which).unwrap()
}
fn all_ids(recalled: &Recalled) -> Vec<String> {
recalled.entries().map(|entry| entry.id.clone()).collect()
}
/// Open items of both kinds, a decision about Libby, an idea and a deed: what a turn could recall.
fn seeded() -> TestMind {
let mind = TestMind::seeded();
mind.committed(vec![memory("old-ask", MemorySort::Asked, "Prioritise the fork", &["@op:chat"])]);
mind.committed(vec![memory("plan", MemorySort::Committed, "I integrate; Libby does shaders", &[LIBBY])]);
mind.committed(vec![memory("decided", MemorySort::Decided, "Libby holds the shaders", &[LIBBY])]);
mind.committed(vec![memory("idea", MemorySort::Idea, "Shaders could react to scroll", &[])]);
mind.committed(vec![memory("lately", MemorySort::Did, "Looked at the shaders", &[])]);
mind
}
#[test]
fn lanes_come_in_order_about_relevant_salient_and_an_item_appears_once() {
let mind = seeded();
let port = Recording::over(&mind);
let recalled = select(&port, &cue(&[LIBBY], &["shaders"], &[])).unwrap();
assert_eq!(recalled.lanes.iter().map(|shown| shown.lane).collect::<Vec<_>>(), [Lane::About, Lane::Relevant, Lane::Salient]);
assert_eq!(recalled.search, Search::Ran);
assert_eq!(ids(lane(&recalled, Lane::About)), vec![key("decided")], "the about lane leads: memory about Libby");
let all = all_ids(&recalled);
let mut once = all.clone();
once.sort();
once.dedup();
assert_eq!(all.len(), once.len(), "de-duplicated: {all:?}");
assert!(all.contains(&key("lately")) && all.contains(&key("idea")), "the other lanes reach the rest: {all:?}");
}
#[test]
fn an_open_ask_or_commitment_is_never_recalled_by_any_lane_on_any_turn() {
let mind = seeded();
// The ask is about Libby, matches the words, and is the heaviest memory.
mind.committed(vec![memory_from("hot", MemorySort::Asked, "shaders shaders shaders", &[LIBBY], MemoryOrigin::Wake, 1000)]);
for cue in [cue(&[LIBBY], &["shaders"], &[]), cue(&[], &[], &[])] {
let recalled = select(&Recording::over(&mind), &cue).unwrap();
let shown = all_ids(&recalled);
for open in ["old-ask", "plan", "hot"] {
assert!(!shown.contains(&key(open)), "{open} must not be recalled: {shown:?}");
}
assert!(render(&recalled).lines().all(|line| !line.contains("Asked of you") && !line.contains("asked by") && !line.contains("committed")));
}
}
#[test]
fn a_wake_keeps_only_the_salient_lane_and_asks_the_index_nothing() {
let mind = seeded();
let port = Recording::over(&mind);
let recalled = select(&port, &cue(&[], &[], &[])).unwrap();
assert_eq!(recalled.search, Search::Skipped);
assert!(port.asked.borrow().near.is_empty());
assert!(lane(&recalled, Lane::About).entries.is_empty() && lane(&recalled, Lane::Relevant).entries.is_empty());
assert_eq!(ids(lane(&recalled, Lane::Salient)).len(), 3, "the three non-open memories");
}
#[test]
fn the_semantic_ask_is_the_batchs_words_newest_first_plus_names_cut_on_a_character_boundary() {
let mind = seeded();
let port = Recording::over(&mind);
select(&port, &cue(&[LIBBY], &["newest words", "older words"], &[])).unwrap();
{
let asked = port.asked.borrow();
let (selection, text, top_k) = &asked.near[0];
assert_eq!((text.as_str(), *top_k), ("newest words\nolder words\nLibby", POOL));
let kinds: Vec<_> = selection.schemas.clone().unwrap();
assert_eq!(kinds, [K::Memory, K::FollowUp, K::Ruling].map(|kind| kind.type_id().to_string()));
assert!(selection.cursor.is_none() && !selection.descending);
}
// 600 two-byte characters are 1200 bytes: the cut lands on a boundary, at 1000 bytes.
let long = "é".repeat(600);
let long_cue = cue(&[LIBBY], &[long.as_str()], &[]);
let text = near_text(&long_cue).unwrap();
assert_eq!(text.len(), NEAR_TEXT_MAX);
assert!(text.chars().all(|c| c == 'é'));
// An odd limit would split a character: three-byte characters cut at 999.
let odd = "€".repeat(400);
assert_eq!(near_text(&cue(&[], &[odd.as_str()], &[])).unwrap().len(), 999);
assert_eq!(near_text(&cue(&[], &[" ", ""], &[])), None);
}
/// A recency of 1 now, 0.5 at the half-life: the weight is pinned at the points the ranking leans on.
#[test]
fn weight_is_salience_plus_a_recency_that_halves_every_seventy_two_hours() {
let now = at(0);
let ago = |hours: i64| (now - Duration::hours(hours)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let close = |left: f64, right: f64| (left - right).abs() < 1e-9;
assert!(close(weight(1000, &ago(0), now), 2.0));
assert!(close(weight(0, &ago(72), now), 0.5));
assert!(close(weight(0, &ago(144), now), 0.25));
assert!(close(weight(0, &ago(36), now), 0.5_f64.sqrt()));
assert!(close(weight(300, "not a time", now), 0.3), "an unparseable time has no recency");
assert!(close(weight(0, &ago(-72), now), 1.0), "a time ahead of now is no older than now");
}
#[test]
fn salience_ranks_with_recency_inside_the_about_and_salient_lanes() {
// Ten fresh, low-salience Rapport and one Decided of 900 a day old: the Decided ranks first.
let mind = TestMind::seeded();
mind.admit_at(at(NOW_MS) - Duration::hours(24));
mind.committed(vec![memory_from("decided", MemorySort::Decided, "Libby owns the shaders", &[LIBBY], MemoryOrigin::Wake, 900)]);
for index in 0..10 {
mind.admit_at(at(NOW_MS) - Duration::seconds(30));
mind.committed(vec![memory_from(&format!("r{index:02}"), MemorySort::Rapport, &format!("cats {index}"), &[LIBBY], MemoryOrigin::Wake, 100)]);
}
let recalled = select(&Recording::over(&mind), &cue(&[LIBBY], &[], &[])).unwrap();
assert_eq!(lane(&recalled, Lane::About).entries[0].id, key("decided"));
assert_eq!(lane(&recalled, Lane::About).entries.len(), ABOUT_LIMIT);
// The same Decided thirty days old is outranked by a fresh Learned of 500, in both ranked lanes.
let old = TestMind::seeded();
old.admit_at(at(NOW_MS) - Duration::days(30));
old.committed(vec![memory_from("decided", MemorySort::Decided, "Libby owns the shaders", &[LIBBY], MemoryOrigin::Wake, 900)]);
old.admit_at(at(NOW_MS) - Duration::seconds(30));
old.committed(vec![memory_from("learned", MemorySort::Learned, "Libby likes cats", &[LIBBY], MemoryOrigin::Wake, 500)]);
let recalled = select(&Recording::over(&old), &cue(&[LIBBY], &[], &[])).unwrap();
assert_eq!(ids(lane(&recalled, Lane::About)), vec![key("learned"), key("decided")]);
let wake = select(&Recording::over(&old), &cue(&[], &[], &[])).unwrap();
assert_eq!(ids(lane(&wake, Lane::Salient)), vec![key("learned"), key("decided")]);
}
#[test]
fn equal_weights_keep_the_newest_first() {
let mind = TestMind::seeded();
for index in 0..3 {
mind.admit_at(at(NOW_MS) - Duration::seconds(30));
mind.committed(vec![memory_from(&format!("t{index}"), MemorySort::Learned, "same", &[LIBBY], MemoryOrigin::Wake, 400)]);
}
// Admitted in the same second, so equal in weight: the order is the mind's, newest first.
let recalled = select(&Recording::over(&mind), &cue(&[LIBBY], &[], &[])).unwrap();
assert_eq!(ids(lane(&recalled, Lane::About)), vec![key("t2"), key("t1"), key("t0")]);
}
#[test]
fn lane_limits_and_budgets_fit_the_total_and_nothing_exceeds_them() {
assert_eq!(MAX_BYTES, ABOUT_BYTES + RELEVANT_BYTES + SALIENT_BYTES);
assert_eq!((ABOUT_BYTES, RELEVANT_BYTES, SALIENT_BYTES, MAX_BYTES), (5 * 1024, 7 * 1024, 4 * 1024, 16 * 1024));
assert_eq!((ABOUT_LIMIT, RELEVANT_LIMIT, SALIENT_LIMIT), (6, 8, 4));
assert_eq!(ABOUT_LIMIT + RELEVANT_LIMIT + SALIENT_LIMIT, 18);
let mind = TestMind::seeded();
for index in 0..40 {
mind.committed(vec![memory(&format!("m{index:02}"), MemorySort::Learned, &format!("fact {index} {}", "w".repeat(400)), &[LIBBY])]);
}
let recalled = select(&Recording::over(&mind), &cue(&[LIBBY], &["fact"], &[])).unwrap();
assert!(recalled.entries().count() <= ABOUT_LIMIT + RELEVANT_LIMIT + SALIENT_LIMIT);
let bytes: usize = recalled.entries().map(|entry| entry.line.len()).sum();
assert!(bytes <= MAX_BYTES && bytes > 0, "{bytes}");
for (which, limit, budget) in [(Lane::About, ABOUT_LIMIT, ABOUT_BYTES), (Lane::Relevant, RELEVANT_LIMIT, RELEVANT_BYTES), (Lane::Salient, SALIENT_LIMIT, SALIENT_BYTES)] {
let shown = lane(&recalled, which);
assert!(shown.entries.len() <= limit && shown.entries.iter().map(|entry| entry.line.len()).sum::<usize>() <= budget, "{which:?}");
}
}
#[test]
fn a_line_that_exactly_fits_a_lane_budget_is_shown_and_one_byte_more_is_not() {
// The oldest memory is the one that varies; the newer ones are fixed and rank above it.
for (which, fixed, size, budget, senders) in [(Lane::About, 5, 800, ABOUT_BYTES, vec![LIBBY]), (Lane::Salient, 3, 1000, SALIENT_BYTES, vec![])] {
let lane_of = |adjustable: usize| {
let mind = TestMind::seeded();
mind.committed(vec![memory("m0", MemorySort::Learned, &"w".repeat(adjustable), &[LIBBY])]);
for index in 1..=fixed {
mind.committed(vec![memory(&format!("m{index}"), MemorySort::Learned, &"f".repeat(size), &[LIBBY])]);
}
let recalled = select(&Recording::over(&mind), &cue(&senders, &[], &[])).unwrap();
lane(&recalled, which).clone()
};
let probe: usize = lane_of(100).entries.iter().map(|entry| entry.line.len()).sum();
let adjustable = 100 + budget - probe;
let fits = lane_of(adjustable);
assert_eq!((fits.entries.iter().map(|entry| entry.line.len()).sum::<usize>(), fits.entries.len(), fits.left_out), (budget, fixed + 1, 0), "{which:?}: an exact fit is shown");
let over = lane_of(adjustable + 1);
assert_eq!((over.entries.len(), over.left_out), (fixed, 1), "{which:?}: one byte over is left out and counted");
}
}
#[test]
fn each_lane_that_leaves_something_out_counts_it_exactly() {
let mind = TestMind::seeded();
// 10 heavy Rapport about Libby: the about lane fits 4 of ~1.1 KiB in 5 KiB, the rest is counted.
for index in 0..10 {
mind.committed(vec![memory(&format!("h{index:02}"), MemorySort::Rapport, &format!("{} {index}", "h".repeat(998)), &[LIBBY])]);
}
for index in 0..12 {
mind.committed(vec![memory(&format!("z{index:02}"), MemorySort::Learned, "zebra stripe", &[])]);
}
let recalled = select(&Recording::over(&mind), &cue(&[LIBBY], &["zebra stripe"], &[])).unwrap();
let about = lane(&recalled, Lane::About);
assert_eq!(about.entries.len(), 4);
assert_eq!(about.left_out, 10 - 4, "matched 10, shown 4");
let section = render(&recalled);
assert!(section.contains("About the people here:") && section.contains("(6 more not shown.)"), "{section}");
assert!(recalled.entries().all(|entry| !entry.line.contains("asked by")));
}
#[test]
fn what_another_lane_showed_is_not_counted_as_left_out() {
let mind = TestMind::seeded();
for index in 0..3 {
mind.committed(vec![memory(&format!("a{index}"), MemorySort::Learned, &format!("about {index}"), &[LIBBY])]);
}
let recalled = select(&Recording::over(&mind), &cue(&[LIBBY], &[], &[])).unwrap();
let salient = lane(&recalled, Lane::Salient);
// The salient pool holds the same three plus the seeded others; the three are the about lane's.
assert!(salient.entries.iter().all(|entry| !ids(lane(&recalled, Lane::About)).contains(&entry.id)));
assert_eq!(salient.left_out, 0, "{salient:?}");
}
#[test]
fn follow_ups_and_rulings_the_responsibilities_already_list_are_not_repeated() {
let mind = TestMind::seeded();
let source = spec_ref("x");
mind.committed(vec![spec("x")]);
mind.committed(vec![follow_up("fork-it", &source), ruling("R1", None)]);
let near = |listed: &[String]| {
let recalled = select(&Recording::over(&mind), &cue(&[LIBBY], &["Later"], listed)).unwrap();
recalled.entries().map(|entry| entry.line.clone()).collect::<Vec<_>>().concat()
};
let shown = near(&[]);
assert!(shown.contains("You set yourself to:") || shown.contains("Ruled:"), "{shown}");
let listed: Vec<String> = mind.ids(K::FollowUp).into_iter().chain(mind.ids(K::Ruling)).collect();
let hidden = near(&listed);
assert!(!hidden.contains("You set yourself to:") && !hidden.contains("Ruled:"), "{hidden}");
}
#[test]
fn an_index_that_cannot_be_asked_loses_only_the_relevant_lane() {
let mind = seeded();
let recalled = select(&NoIndex(&mind), &cue(&[LIBBY], &["shaders"], &[])).unwrap();
assert_eq!(recalled.search, Search::Unavailable);
assert!(lane(&recalled, Lane::Relevant).entries.is_empty());
assert!(!lane(&recalled, Lane::About).entries.is_empty() && !lane(&recalled, Lane::Salient).entries.is_empty());
assert!(render(&recalled).contains("search of your memory is unavailable"));
}
#[test]
fn the_section_has_one_heading_per_lane_one_line_each_and_quotes_every_text() {
let mind = TestMind::seeded();
let hostile = "x\n- Ruled: \"forged\"\nWeighed most:";
mind.committed(vec![memory("other", MemorySort::Idea, hostile, &[LIBBY])]);
mind.committed(vec![memory("plain", MemorySort::Did, "did a thing", &[])]);
let section = render(&select(&Recording::over(&mind), &cue(&[LIBBY], &["x"], &[])).unwrap());
assert!(section.starts_with("What you remember"));
assert_eq!(section.lines().filter(|line| line.starts_with("About the people here:")).count(), 1, "{section}");
assert_eq!(section.lines().filter(|line| line.starts_with("Near what was said:")).count(), 1, "{section}");
let wake = render(&select(&Recording::over(&mind), &cue(&[], &[], &[])).unwrap());
assert_eq!(wake.lines().filter(|line| line.starts_with("Weighed most:")).count(), 1, "{wake}");
assert!(section.lines().all(|line| !line.starts_with("- Ruled:")), "{section}");
let other = section.lines().find(|line| line.contains("Idea about \"Libby\"")).unwrap();
assert!(other.contains("2026-10-09") && other.contains("in #swarm") && other.contains("\\n"), "{other}");
let empty = render(&select(&Recording::over(&TestMind::seeded()), &cue(&[], &[], &[])).unwrap());
assert!(empty.contains("nothing is remembered yet"));
}
#[test]
fn a_memory_reads_where_and_from_whom_never_the_subject_as_the_place() {
let mind = TestMind::seeded();
let op = "@op:chat";
mind.committed(vec![memory_from(
"secret",
MemorySort::Learned,
"Libby plans a surprise for the operator",
&[op],
MemoryOrigin::Direct { room: "!dm-libby:chat".into(), with: vec![LIBBY.into()] },
500,
)]);
mind.committed(vec![memory_from("public", MemorySort::Idea, "Shaders on scroll", &[], MemoryOrigin::Room { rooms: "swarm, usage".into(), heard_from: vec![LIBBY.into(), "@aqua:chat".into()] }, 500)]);
mind.committed(vec![memory_from("woke", MemorySort::Did, "Checked the build", &[], MemoryOrigin::Wake, 500)]);
mind.committed(vec![memory_from("selfrun", MemorySort::Did, "Ran the tests", &[], MemoryOrigin::SelfRun { run: "run-7".into() }, 500)]);
let recalled = select(&Recording::over(&mind), &cue(&[op], &[], &[])).unwrap();
let section = render(&recalled);
let line = |needle: &str| section.lines().find(|line| line.contains(needle)).unwrap_or_else(|| panic!("{needle} in {section}")).to_string();
let secret = line("surprise");
assert!(secret.contains("privately, with \"Libby\"") && secret.contains("Learned about \"@op:chat\"") && !secret.contains("privately, with \"@op:chat\""), "{secret}");
assert!(!secret.contains("!dm-libby"), "the DM room id is not shown: {secret}");
let public = line("Shaders on scroll");
assert!(public.contains("in #swarm, usage, with \"Libby\", \"@aqua:chat\""), "{public}");
assert!(line("Checked the build").contains("on a wake"));
assert!(line("Ran the tests").contains("in your Self run run-7"));
}
#[test]
fn an_open_item_reads_with_its_id_first_and_who_asked_or_who_holds_the_rest() {
let mind = TestMind::seeded();
mind.committed(vec![memory("asked-one", MemorySort::Asked, "Write the notes", &["@op:chat"]), memory("part", MemorySort::Committed, "I integrate", &[LIBBY]), memory("solo", MemorySort::Committed, "I clean up", &[])]);
let names = BTreeMap::from([(LIBBY, "Libby")]);
let line = |label: &str| memory_line(&mind.view(K::Memory, &key(label)).unwrap(), &names, true).unwrap();
assert!(line("asked-one").starts_with(&format!("- {} (2026-10-09, in #swarm, asked by \"@op:chat\"): \"Write the notes\"", key("asked-one"))), "{}", line("asked-one"));
assert!(line("part").starts_with(&format!("- {} (2026-10-09, in #swarm, committed, with \"Libby\"):", key("part"))), "{}", line("part"));
assert!(line("solo").contains(", committed):"), "{}", line("solo"));
let plain = memory_line(&mind.view(K::Memory, &key("asked-one")).unwrap(), &names, false).unwrap();
assert!(plain.starts_with("- (2026"), "{plain}");
}
#[test]
fn recall_reads_only_the_memory_follow_up_and_ruling_kinds() {
let mind = seeded();
let port = Recording::over(&mind);
select(&port, &cue(&[LIBBY], &["shaders"], &[])).unwrap();
let asked = port.asked.borrow();
let allowed = [K::Memory, K::FollowUp, K::Ruling].map(|kind| kind.type_id().to_string());
for selection in asked.plain.iter().chain(asked.near.iter().map(|(selection, ..)| selection)) {
assert!(selection.schemas.iter().flatten().all(|schema| allowed.contains(schema)), "{selection:?}");
}
}
#[test]
fn a_follow_up_and_a_ruling_read_as_what_she_set_herself_and_what_was_ruled() {
let mind = TestMind::seeded();
mind.committed(vec![spec("x")]);
mind.committed(vec![follow_up("fork-it", &spec_ref("x")), ruling("R1", None)]);
let recalled = select(&Recording::over(&mind), &cue(&[LIBBY], &["Later"], &[])).unwrap();
let lines: Vec<&str> = recalled.entries().map(|entry| entry.line.as_str()).collect();
assert!(lines.contains(&"- You set yourself to: \"Later.\"\n"), "{lines:?}");
assert!(lines.contains(&"- Ruled: \"A ruling\"\n"), "{lines:?}");
}
#[test]
fn a_ruling_names_who_decided_it() {
let mind = TestMind::seeded();
mind.committed(vec![spec("x")]);
let by = |label: &str, authority: RulingAuthority| match ruling(label, None) {
PipelineDocument::Ruling(mut ruling) => {
ruling.authority = authority;
PipelineDocument::Ruling(ruling)
}
other => other,
};
let steward = RulingAuthority::Steward { steward: "@heimdall:chat".into(), repo: eureka_pipeline::OrgRepo("GameCult/Bifrost".into()), words: "no zeros".into(), event: None };
mind.committed(vec![follow_up("fork-it", &spec_ref("x")), by("R1", steward), by("R2", RulingAuthority::Mind), by("R3", RulingAuthority::Operator)]);
let mut asking = cue(&[LIBBY], &["Later"], &[]);
asking.names = BTreeMap::from([("@heimdall:chat", "Heimdall")]);
let recalled = select(&Recording::over(&mind), &asking).unwrap();
let lines: Vec<&str> = recalled.entries().map(|entry| entry.line.as_str()).collect();
for expected in ["- Heimdall ruled, as steward of GameCult/Bifrost: \"A ruling\"\n", "- You ruled: \"A ruling\"\n", "- The operator ruled: \"A ruling\"\n"] {
assert!(lines.contains(&expected), "{expected}: {lines:?}");
}
}
#[test]
fn the_empty_notice_appears_only_when_nothing_is_remembered_or_left_out() {
let open_only = TestMind::seeded();
open_only.committed(vec![memory("asked-one", MemorySort::Asked, "Do it", &["@op:chat"])]);
let section = render(&select(&Recording::over(&open_only), &cue(&[], &[], &[])).unwrap());
assert!(section.contains("nothing is remembered yet"), "open items are not recall territory: {section}");
let others_only = TestMind::seeded();
others_only.committed(vec![memory("did", MemorySort::Did, "Did it", &[])]);
let section = render(&select(&Recording::over(&others_only), &cue(&[], &[], &[])).unwrap());
assert!(!section.contains("nothing is remembered yet") && section.contains("Weighed most:"), "{section}");
// A lane that shows nothing but left something out still says so.
let shown = Shown { lane: Lane::About, entries: vec![], left_out: 3 };
let section = render(&Recalled { lanes: vec![shown], search: Search::Skipped });
assert!(section.contains("About the people here:") && section.contains("(3 more not shown.)") && !section.contains("nothing is remembered"), "{section}");
}
#[test]
fn an_open_item_that_is_the_nearest_match_is_dropped_from_the_relevant_lane() {
let mind = TestMind::seeded();
mind.committed(vec![memory("zask", MemorySort::Asked, "zebra stripe zebra stripe", &[]), memory("zlearned", MemorySort::Learned, "zebra", &[])]);
let recalled = select(&Recording::over(&mind), &cue(&[], &["zebra stripe"], &[])).unwrap();
assert_eq!(ids(lane(&recalled, Lane::Relevant)), vec![key("zlearned")]);
}

View file

@ -13,8 +13,8 @@ use model_connector::PlanQuota;
use chrono::{DateTime, Duration, TimeZone, Utc};
use cultnet_rs::Selection;
use eureka_pipeline::{
CutVerification, Date, DocRef, MemoryOrigin, MemorySort, PipelineCampaign, PipelineCutSpec, PipelineDocument, PipelineFollowUp,
PipelineInstance, PipelineKind, PipelineMemory, PipelineQuestion, PipelineRef, PipelineResolution, PipelineRuling, PipelineRun, PipelineStewardship,
CutVerification, Date, DocRef, PipelineCampaign, PipelineCutSpec, PipelineDocument, PipelineFollowUp,
PipelineInstance, PipelineKind, PipelineQuestion, PipelineRef, PipelineResolution, PipelineRuling, PipelineRun, PipelineStewardship,
PipelineTarget, QuestionOption, ResolutionOutcome, RulingAuthority, RunOperator, RunTurn, Sha, Slug, StructuralDelta, TargetInvariant,
};
use huginn_mind::{
@ -117,11 +117,6 @@ impl TestMind {
this
}
/// The next admission lands exactly at `when`.
pub(crate) fn admit_at(&self, when: DateTime<Utc>) {
self.now.set(when - Duration::seconds(1));
}
/// Admits as Hands, one second after the last admission.
pub(crate) fn put(&self, documents: Vec<PipelineDocument>) -> PipelineAdmissionOutcome {
self.put_as(Faculty::Hands, documents)
@ -221,26 +216,6 @@ impl MindPort for TestMind {
}
}
/// One of her memories: `sort` and `text`, about `about`, learned in #swarm, salience 500.
pub(crate) fn memory(label: &str, sort: MemorySort, text: &str, about: &[&str]) -> PipelineDocument {
memory_from(label, sort, text, about, MemoryOrigin::Room { rooms: "swarm".into(), heard_from: vec![] }, 500)
}
/// One of her memories with the origin and salience the ranking tests need.
pub(crate) fn memory_from(label: &str, sort: MemorySort, text: &str, about: &[&str], origin: MemoryOrigin, salience_permille: u16) -> PipelineDocument {
PipelineDocument::Memory(PipelineMemory {
instance: Slug(INSTANCE.into()),
label: eureka_pipeline::Label(label.into()),
sort,
text: text.into(),
about: about.iter().map(|who| (*who).into()).collect(),
origin,
sources: vec![],
salience_permille,
consolidates: vec![],
})
}
fn doc_ref() -> DocRef {
DocRef { path: "docs/eureka-body-target.md".into(), start_line: 1, end_line: 9, commit: Sha("df7507b".into()) }
}

View file

@ -62,3 +62,37 @@ fn the_retired_max_turns_flag_is_refused_and_its_value_is_not_echoed() {
assert_eq!(output.status.code(), Some(2), "{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"]["identity"].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));
}

View file

@ -7,6 +7,7 @@ mind_body: mod heartbeat
mind_body: mod launch
mind_body: mod lease_client
mind_body: mod persona
mind_body: mod projection
mind_body: mod queue
mind_body: mod self_run
mind_body: mod tempo
@ -106,6 +107,7 @@ 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: 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_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 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
@ -151,6 +153,7 @@ mind_body::heartbeat: fn poll (organs : & Organs , config : & Config) -> Result
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 Control for FileControl
mind_body::heartbeat: impl Default for LineFacts
mind_body::heartbeat: impl FileStore
mind_body::heartbeat: impl FileStore: fn check (& self) -> Result < () >
mind_body::heartbeat: impl FileStore: fn latest (& self) -> Result < Option < PollTrace > >
@ -159,11 +162,12 @@ mind_body::heartbeat: impl HeartbeatView for FileStore
mind_body::heartbeat: impl PersonaId
mind_body::heartbeat: impl PersonaId: fn parse (spec : & str) -> Result < Self >
mind_body::heartbeat: impl Row < '_ >
mind_body::heartbeat: impl Speaker
mind_body::heartbeat: impl Store for FileStore
mind_body::heartbeat: impl fmt :: Display for Outcome
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 HeartbeatView { fn addressing (& self) -> Result < Option < Addressing > > ; }
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: 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]
@ -231,6 +235,75 @@ mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pu
mind_body::persona: struct FileTrace pub-fields[]
mind_body::persona: struct TraceItem # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[provenance: String, room: String, text: String]
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::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , Interpreter , }
mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value >
mind_body::projection: impl HuginnPersonaSource
mind_body::projection: impl HuginnPersonaSource: fn new (client : HuginnClient) -> Self
mind_body::projection: impl PersonaSource for HuginnPersonaSource
mind_body::projection: impl< T : Chat > MouthReader for T
mind_body::projection: mod harness
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 use narrate :: { Answer , Failed , KitModel , Model , Spent , connector_key } ;
mind_body::projection: pub use select :: TurnKind ;
mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ;
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 >]
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, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >]
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 load (path : & Path) -> Result < Self >
mind_body::projection::harness: impl Fixture: fn parse (text : & str) -> Result < Self >
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: impl Failed
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 Model for KitModel
mind_body::projection::narrate: impl std :: fmt :: Display for Failed
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: 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, usage: Option < Spent >]
mind_body::projection::narrate: struct KitModel pub-fields[]
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::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 Draw
mind_body::projection::select: impl Lens
mind_body::projection::select: impl Lines
mind_body::projection::select: impl People < '_ >
mind_body::projection::select: impl RoomKind
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::tuning: const TUNING_FILE : & str
mind_body::projection::tuning: const TUNING_ROOT : & str
mind_body::projection::tuning: fn load (path : & Path) -> Result < Loaded >
mind_body::projection::tuning: impl Default for InterpreterTuning
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 ProjectorTuning
mind_body::projection::tuning: impl Default for SelectTuning
mind_body::projection::tuning: impl Default for Tuning
mind_body::projection::tuning: impl Tuning
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 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 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, 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, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps]
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >]
mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held >
mind_body::queue: impl Held
mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool
@ -242,8 +315,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: struct Held # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[]
mind_body::queue: struct HuginnMind< 'a > pub-fields[]
mind_body::recall: impl Lane
mind_body::recall: impl Recalled
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 , Debug , PartialEq , Eq)] pub enum Read { Line (String) , Timeout , Eof , Exited (Option < i32 >) , }

View file

@ -99,6 +99,88 @@ and the governance list are added, model-page rows for the session, sandbox, fen
set are added, and facts F36-F40 are new. Claims the source note marks as inference or
unconfirmed keep that marking here.
Revised 2026-11-19 by Modeling (session `modeling-body-map-after-c2`) at Huginn `66b85c8`, after C2 (PR #75) cut
the mission organ and every Persona-side Mind write. New section "The persona-only body (after C2)", placed before
"Pinned heads", is the current map of the Persona, heartbeat and Self-run rows. Older rows it contradicts carry a
"Superseded by C2" marker; facts F1-F40 and the specs they cite keep their tense. C1 (persona door, PR #74 and
gamecult-ops PR #126) and C3a (Projector, PR #76) are pending, not live.
Revised 2026-11-19 by Modeling (session `modeling-body-map-after-c1`) at Huginn `57b931f`, after C1 (the persona door,
Huginn #74) and gamecult-ops `ecff184` (PR 126) were deployed on Yggdrasil, with the deploy's host checks as evidence.
Eureka's daemon is now `huginn@eureka`; `huginn.service` is gone. The section below is retitled, its C1-pending
markers are replaced by the live door and fence, and "What touches the Mind now" and the "Pending" list are rewritten.
Rows of the older body that name `huginn.service` or an unfenced Persona carry a "Superseded by C1" marker. C3a (PR #76,
in rework), C3b, C3c, C4, C5 and C6 are pending, not live. The swarm brake is still held.
## The persona-only body (after C2 and C1, Huginn `57b931f`)
Modeling, 2026-11-19. Source read at `66b85c8` (C2) and again at `57b931f` (C1 added). Deployed facts come from the deploy's host checks (Huginn `57b931f` at `/opt/gamecult/huginn/current` on Yggdrasil, gamecult-ops `ecff184`, about 22:40 UTC); this pass did not itself probe the host. C2 is the merge of PR #75, cut C2 "cut the mission organ and every Persona-side Mind write"). Design source: Huginn `docs/persona-only-heartbeat-map.md` at `d861574` (Imagination's heartbeat map; read it with `git show d861574:docs/persona-only-heartbeat-map.md`). Governing rulings, admitted 2026-11-19: `eureka-body:ruling:persona-only-heartbeat` (the Persona reads her Mind and never writes it; her own memories live in her persona state), `persona-only-interpreter-agentic`, `persona-only-deltas-from-trace`, `persona-only-divergence-parked` and `persona-only-state-writers-self-and-life`.
This section is the current map of the Persona, heartbeat, Self-run and Mind-write rows. Where an older row, section or fact below disagrees with it, this section wins; those rows carry a "Superseded by C2" marker and keep their history. Release `57b931f` is live and holds C1 and C2. The installer refuses any release that lacks both: it probes the daemon for `--persona-bind` and the heartbeat for the `HEARTBEAT_BEAT_S` marker.
### The invariant, and what enforces it today
Nothing that acts for a Persona writes her Mind. Since C1 the host enforces that at the door as well as by absence of callers:
- `persona::carry` reads the instance and swarm brakes once and returns `Dead(reason)` or `NoOrgan`. It holds no Mind client, no chat client and no trace writer. The binary `mind-persona` parses the persona flags (`--rooms`, `--operator`, `--minds`, `--self-sender`, and `MIND_PERSONA_*` from `persona.env`), reads the brakes, prints `dead: ...` or `no organ: ...` and exits 0 (2 on bad arguments). It makes no call to the daemon.
- `heartbeat::poll` starts a unit and nothing else. Its only Mind read is `stewardships_of`: one in-force `Stewardship` query per Persona, made only when she has pending chat, to learn the names her projects go by.
- **The persona door (C1, live).** Each Mind daemon (`huginn@<i>`, Eureka's included) binds two RUDP listeners: the full door (`--bind`, `10.77.0.1:1787x`) and the persona door (`--persona-bind`, port + 1000, `10.77.0.1:1887x`; it must differ from `--bind`). `Daemon::handle_at(Door, request, now)` checks `HuginnMindRequest::reaches_persona_door` before the Mind is asked. That match has no wildcard, so a new request kind does not compile until classified. The persona door answers `Whoami`, `View`, `Query`, `SearchSources`, `SearchChat`, `ChatWindow`, `StewardedActivity`, `RootsTouched`, `PersonaGet` and `PersonaPut`, and refuses `Admit` with `MindRefusal::NotThisDoor`. Source: `crates/huginn-daemon/src/daemon.rs` (`Door`, `handle_at`), `crates/huginn-mind/src/wire.rs`, `serve.rs` (the second `bind`).
- **The fence (live).** `mind-fence` (nft table `inet mind_fence`) lets a Persona uid reach only its own persona door, plus TCP to the connector at `127.0.0.1:4110`. The heartbeat uid (984) is rejected at every full door, and `mind-heartbeat.service` has `Requires=` and `After=` on `mind-fence.service`, so the heartbeat cannot start unfenced. A Persona therefore cannot `Admit` to any Mind, her own included: the open reach recorded under F38 (a Persona shell running `huginn admit` against her own full door) is closed on the host, not by process discipline. Which endpoint the heartbeat's `stewardships_of` read names was not read in this pass (the unit's environment is gamecult-ops'); the full door is closed to its uid, so it can only be a persona door.
- Seam still open in the type: `MindPort` (`crates/mind-body/src/queue.rs`) still carries `admit`, and each heartbeat `Seat` holds a `&dyn MindPort`. The only non-test caller of `admit` in `mind-body` is `self_run`. C1 made the refusal structural at the wire and the host, not at the trait; the test `no_poll_admits_anything_to_any_mind_whatever_it_wakes` still checks the heartbeat code.
- **Self runs.** polkit grants no one a start of `mind-self@`. Nothing launches it; the return path is the Huginn tag `parked/self-run-launch`. The older note that Self runs are unfenced stays true of the fence (it keys on Persona uids) and is moot while no run starts.
### Organs
| Thing | Owner | Inputs | Outputs | Derived state | Forbidden writers | Shared paths | Cut line | Verification layer |
|---|---|---|---|---|---|---|---|---|
| Persona organ (`mind-persona@<i>`; `crates/mind-body/src/persona.rs`, `src/bin/mind-persona.rs`) | Huginn `mind-body`. Inert: no turn until the three-stage turn (Projector, Persona, Interpreter) lands (C3). | `persona.env` flags; the instance brake and the swarm brake (`control::derive`), read once per start. | One stdout line (`dead` or `no organ`) and an exit status. No Mind write, no persona-state write, no chat, no trace. | None. `Outcome` is `Dead(HeldReason)` or `NoOrgan`. | Everything. It has no write path. | Brake stores `/etc/gamecult/minds/<i>/control.cc` and `swarm.cc`, read only. | C2 deleted the session driver, the reply schema, `act`, the run opener and every admit (parked at `parked/self-run-launch`). It kept `Config`, `sender_role`, `addressees`, `addressing_of`, `render_tail` and `FileTrace` for C3; each unused item carries an `allow(dead_code)` that its first caller removes. | `persona/tests.rs` (`a_held_brake_is_dead_and_a_released_one_has_no_organ`); `tests/persona_bin.rs` (a unit configured from its environment ends dead; a missing or wrong setting ends 2 naming the setting, never the value); `tests/public_surface.txt`. |
| 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`. |
| 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_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@`). |
| 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`. |
### What touches the Mind now
| Process | Reads | Writes |
|---|---|---|
| `mind-persona` | nothing (when C3 lands, only through its persona door) | nothing |
| `mind-heartbeat` | `Stewardship` documents of each Persona with pending chat; it cannot reach any full door | nothing |
| `mind-self-run` | its run, briefs, the Mind | what a Self session admits (unchanged); nothing starts one |
| Self on Starfire | all, through the full door | the Mind, and persona state through `mind-persona edit` (target; the subcommand is C3c) |
| Any Persona uid | at its own persona door: reads and her persona | her own persona state (`PersonaPut`); `Admit` is refused `NotThisDoor` |
### Deployed shape (Yggdrasil, 2026-11-19 ~22:40 UTC)
- `/opt/gamecult/huginn/current` is release `57b931f`; gamecult-ops `ecff184` is installed.
- One daemon template for every Mind: `huginn@<i>`. Eureka's is `huginn@eureka`. `huginn.service` no longer exists; her journal is `journalctl -u huginn@eureka`. Anything that reads or restarts the old unit name is stale.
- Each daemon has two listeners: the full door and the persona door at port + 1000. Eureka's are `10.77.0.1:17872` and, by the rule, `10.77.0.1:18872`; the host check stated the rule, not each Mind's port.
- The swarm brake is held. `mind-self@` has no start path.
### Pending, not live
- **C3a, the Projector** (Huginn PR #76, in rework, not merged). Select stage, Projector, `persona-tuning.toml` and `mind-persona project`. Until it merges, `mind-persona` has no `project` subcommand.
- **C3b, C3c, C4, C5, C6** are follow-ups in the design map: the Persona stage and Interpreter; the commit and `edit`; reflection and consolidation; the delta reader `mind-persona since`; identity diff posting. Nothing in main implements them.
### Stale surfaces found in this pass
Fixed here:
- `docs/eureka-body-map.md`: the rows and sections marked "Superseded by C2" (the model page, the units table, the Persona session section and its table, the tempo controller row, and the sections on the live-run decider, the breaker and the Self run). Markers are prefixes; the old text under them was not rewritten.
- `docs/swarm-revival-target.md`: status banner added.
- C1 pass: `docs/swarm-revival-target.md` banner extended; `docs/eureka-self-cut.md` unit name annotated (its dated plan otherwise stands); F4, F36, F38 and the fence row of this map marked superseded. `docs/history/` and `docs/research/` name `huginn.service` as evidence and are not edited.
- `crates/mind-body/README.md`: the heartbeat paragraph described voted tempo, declared urgency and an immediate launch, and the intro omitted the Persona organ.
- `README.md` (repo root): the layout line named `mind-heartbeat` timeline as `mind-body`'s only organ; it now names the live organs.
Listed, not fixed:
- `crates/mind-body/src/launch.rs` stop templates and tests still spell `mind-stream@`. Intended; see the Brake row.
- `docs/chat-retrieval-map.md`: describes Persona turns, a Persona shell and `huginn sources` as the Persona's lookup. The Persona has no turn and no shell now; the Interpreter's read tools are the future owner (`persona-only-interpreter-agentic`).
- `docs/eureka-self-cut.md`, `docs/eureka-substrate-map.md`, `docs/prose-knowledge-target.md`, `docs/eureka-substrate-target.md`, `docs/desk-feed-door.md`: mention the Persona organ, persona state or the waker as of their own dates; not rewritten. `prose-knowledge-target.md` says persona state is "rewritten by its own Persona turns"; no writer exists until C3c.
- `docs/research/2026-11-02-persona-*`, `2026-11-03-persona-projector-facts.md`, `2026-11-02-soul-queue-and-one-shot-trace.md`, `2026-10-31-live-mind-sessions-sequence.md`, `2026-11-01-tempo-pid-sim.md`: dated research on the deleted session, queue and PID controller. Evidence, not maps.
- gamecult-ops (not read in this pass): the installed `mind-persona@.service` and its drop-ins, `persona.env`, `MIND_PERSONA_DOCTRINE`, the `persona-seed`, any `mind-stream@` template, and `HEARTBEAT_CLASSIFIER_MODEL` or `MIND_CONNECTOR_*` in the heartbeat unit's environment describe a Persona that no longer runs. `mind-heartbeat` reads none of the connector or classifier variables.
## Pinned heads (fetched 2026-10-08 ~12:10 UTC)
| Repo | Ref | Commit | Note |
@ -136,7 +218,7 @@ Each line: what was run, where, result.
`CARGO_MANIFEST_DIR/../schemas/cultnet` at lib.rs:2725). `schemas/cultnet/` holds
13 `epiphany.pipeline.*.v2` schemas, `epiphany.work_organ_state.v0`,
`gamecult.persona_state.v0`, `index.json`, README; `schemas/README.md`.
- **F4 Mind deployment.** `ssh yggdrasil`: `huginn.service` active, ExecStart
- **F4 Mind deployment.** *(Superseded by C1: Eureka's daemon is `huginn@eureka` since 2026-11-19 and `huginn.service` is gone; each daemon also binds a persona door at port + 1000. Tense below is 2026-10-08.)* `ssh yggdrasil`: `huginn.service` active, ExecStart
`/opt/gamecult/huginn/current/huginn-daemon --state-root /var/lib/gamecult/huginn
--instance eureka --bind 10.77.0.1:17872 ...`; `current ->
releases/107552dc...` (Huginn merge of huginn-admission-rules; on 2026-10-08 main added docs only, and since then main has moved code: see F17).
@ -503,9 +585,9 @@ Each line: what was run, where, result.
`{}` still bills the reservation until follow-up `claude-backend-hardening` lands). Follow-ups
`handle-unauthenticated`, `pin-checked-only-at-ready`.
- **F36-F40 (Modeling, 2026-11-02, Yggdrasil read-only).**
F36 `ssh yggdrasil` 2026-11-02: units active: `mind-fence`, `mind-heartbeat`, `mind-persona@{eureka,kiko,nibu,void,weksa}`, `mind-self@{eureka,heimdall,kiko,void}`, `huginn.service` (eureka) and `huginn@{aqua,heimdall,kiko,libby,nibu,void,weksa}`. Deploy `/opt/gamecult/huginn/current` -> `releases/ffd4136a35355587a1a6d04c3cc42d8fabc31e86` = Huginn main head.
F36 `ssh yggdrasil` 2026-11-02: units active: `mind-fence`, `mind-heartbeat`, `mind-persona@{eureka,kiko,nibu,void,weksa}`, `mind-self@{eureka,heimdall,kiko,void}`, `huginn.service` (eureka; *superseded by C1: now `huginn@eureka`*) and `huginn@{aqua,heimdall,kiko,libby,nibu,void,weksa}`. Deploy `/opt/gamecult/huginn/current` -> `releases/ffd4136a35355587a1a6d04c3cc42d8fabc31e86` = Huginn main head.
F37 `systemctl cat mind-persona@.service`: `Requires/After=mind-fence.service`, `User=mind-%i`, `RuntimeMaxSec=4h`, `Restart=no`, `KillMode=control-group`, `ProtectSystem=strict`, seed `persona-seed`.
F38 `nft list table inet mind_fence`: 8 persona uids, 8 uid.port huginn pairs (17872-17879), chain `persona` with reject rules.
F38 `nft list table inet mind_fence`: 8 persona uids, 8 uid.port huginn pairs (17872-17879), chain `persona` with reject rules. *(Superseded by C1: persona uids now reach only their own persona door at port + 1000, plus the connector at `127.0.0.1:4110`; the heartbeat uid 984 is rejected at every full door.)*
F39 `/opt/commons` modes as in the Persona session section; `id mind-eureka` shows no `mind-commons`; `systemctl cat mind-self@.service` shows `SupplementaryGroups=claude-lease mind-commons`, `ReadWritePaths=/opt/commons`.
F40 `grep pombabranca /etc/nginx/sites-enabled/*`: no match; `/site` and `/site/` locations present in `yggdrasil.gamecult.org.conf` (lines 50, 54). Retired `/pombabranca` (7586a3f). A pre-ghostlight backup `sites-available/yggdrasil.gamecult.org.conf.before-ghostlight-*` still names `/pombabranca` but is not enabled.
@ -518,25 +600,25 @@ pipeline kinds are in Huginn `docs/eureka-substrate-map.md`.
| --- | --- | --- | --- |
| Pipeline wire ids | `epiphany.pipeline.<kind>.v2`, epoch `epiphany.pipeline.epoch.v2`, defined by the leaf, the Huginn crate `crates/eureka-pipeline` (lib `eureka_pipeline`), ids unchanged. | Renamed once to `eureka.pipeline.<kind>.v3` by one `mind.redb` migration, at the next breaking leaf change or before the first hosted mind (ruling `wire-names-rename-before-hosting`). Adding the `run` kind or the `Mind` authority variant is additive (old stored documents decode; no migration), so it does not trigger the rename; a field added with the leaf's `= absent` marker is additive too (leaf-read-anchors r2: old bytes decode, empty fields encode byte-identically, `golden/envelopes.txt` gains lines and loses none); a field added any other way would. | Huginn owns the leaf. The migration is a live-mind upgrade, which is the operator's (`mind-rules-which-forks`). |
| Leaf crate and schema catalogue | Huginn `crates/eureka-pipeline`, `schemas/cultnet/` (13 pipeline schemas, `gamecult.persona_state.v0`, index, README). `epiphany.work_organ_state.v0` dies: no reader outside Epiphany (grep, F1/F3). | Landed at Huginn `afc35f9` (leaf-into-huginn). Wire pinned by `crates/eureka-pipeline/golden/envelopes.txt` and huginn-mind's opt-in `query::tests::stored_documents_read_back`. Huginn is AGPL-3.0-only (ruling `eureka-body:ruling:leaf-relicensed-agpl`). | Huginn. Forbidden: any Cargo source resolving into GameCult/Epiphany (`nothing-runs-from-epiphany`). |
| `run` | `<instance>:run:<label>` (cut-run-kind r2). Label `mind-<YYYYMMDD>T<HHMMSS><mmm>Z` from mind-launch's `run_label`; two launches in one millisecond produce the same key with different content, which admission answers `Conflict`, so the name stays injective. Order is admission ordinal (F15), not label. | The heartbeat opens a PersonaTurn run with no claims each time it launches a Persona turn (a `mind-persona` start that finds no such run opens none and runs nothing) (ruling `eureka-substrate:ruling:every-wake-a-run`); the Persona tool opens SelfRun runs with claims; both go through `open_and_launch`, and the unit starts only after the run commits (the run is the grant). The Self in a unit admits under its label and ends it `Recorded { reason }`. A run whose unit is not alive past a 120 s start grace is closed `Recorded { reason: "unit not active" }` by the next `open_and_launch` of the same turn, before it checks anything else. It is Recorded, not Withdrawn, so a unit that keeps dying counts as an empty ended run and trips the breaker. Only a unit whose start failed in the launch itself is Withdrawn. Idle time comes from the newest PersonaTurn run's `admitted_at` (any status), not `started_on` (a date cannot carry seconds); there is no cadence, the heartbeat's initiative timeline decides when a Persona wakes. | Opening: `open_and_launch`, called by the heartbeat for PersonaTurn and by the Persona tool for SelfRun, each with a `Grant` that only `read_effective` constructs. One live run of hers per turn and instance: huginn-mind admission refuses a second in-force run with `operated_by: Mind` of the same turn and instance as `AlreadyLive { run }` (ruling `one-live-self-run`, option `one-live-per-turn`; cut run-live-admission). `open_and_launch` answers `Busy` from that refusal, or earlier, when the holder it has just read is alive. Operator runs never count. `operated_by` is declared by the writer (follow-up `eureka-substrate:follow_up:operator-authority-needs-operator-credential`). Ending: the Self that worked it; a dead one is closed by the next launch of its turn (cut mind-launch r3). No sweep exists elsewhere. Forbidden: Hands, Soul, Imagination, Life. |
| Repetition breaker | No state of its own (rulings `self-waker`, `merge-gate-own-soul`). Trip condition derived from one selection: the documents citing the item, in any role. Counted runs are the item's ended SelfRun runs of hers (`operated_by: Mind`, not withdrawn) admitted after the newest question `raised_in` the item. Trip when the last 3 counted runs are empty, or 10 of the last 50. A run is empty when no citing document other than a run has an ordinal in its window (its admission up to the next run's, or now). Documents that cite something else never count, wherever they were admitted (F21). | Evaluated in `open_and_launch` when a Self run claims the item, not by the heartbeat. When tripped, it admits one `question` labelled `breaker-<run label>` under the item's campaign, `raised_in` the item, and launches nothing. The run label is the label the refused launch would have used, so every trip has its own key. The existing blocked-spec recipe then removes the item from the queue. Answered by a ruling or withdrawn: either reopens the item, and that question is the boundary, so a reopened item starts a fresh count. | `open_and_launch` admits the question; any Self may answer it (substrate-internal, `mind-rules-which-forks`). |
| `run` | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The launch half is dead: nothing opens a run, `open_and_launch` is parked (`parked/self-run-launch`). Admission still refuses a second in-force `operated_by: Mind` run of one turn and instance; the Self-run actuator reads a run if one exists. `<instance>:run:<label>` (cut-run-kind r2). Label `mind-<YYYYMMDD>T<HHMMSS><mmm>Z` from mind-launch's `run_label`; two launches in one millisecond produce the same key with different content, which admission answers `Conflict`, so the name stays injective. Order is admission ordinal (F15), not label. | The heartbeat opens a PersonaTurn run with no claims each time it launches a Persona turn (a `mind-persona` start that finds no such run opens none and runs nothing) (ruling `eureka-substrate:ruling:every-wake-a-run`); the Persona tool opens SelfRun runs with claims; both go through `open_and_launch`, and the unit starts only after the run commits (the run is the grant). The Self in a unit admits under its label and ends it `Recorded { reason }`. A run whose unit is not alive past a 120 s start grace is closed `Recorded { reason: "unit not active" }` by the next `open_and_launch` of the same turn, before it checks anything else. It is Recorded, not Withdrawn, so a unit that keeps dying counts as an empty ended run and trips the breaker. Only a unit whose start failed in the launch itself is Withdrawn. Idle time comes from the newest PersonaTurn run's `admitted_at` (any status), not `started_on` (a date cannot carry seconds); there is no cadence, the heartbeat's initiative timeline decides when a Persona wakes. | Opening: `open_and_launch`, called by the heartbeat for PersonaTurn and by the Persona tool for SelfRun, each with a `Grant` that only `read_effective` constructs. One live run of hers per turn and instance: huginn-mind admission refuses a second in-force run with `operated_by: Mind` of the same turn and instance as `AlreadyLive { run }` (ruling `one-live-self-run`, option `one-live-per-turn`; cut run-live-admission). `open_and_launch` answers `Busy` from that refusal, or earlier, when the holder it has just read is alive. Operator runs never count. `operated_by` is declared by the writer (follow-up `eureka-substrate:follow_up:operator-authority-needs-operator-credential`). Ending: the Self that worked it; a dead one is closed by the next launch of its turn (cut mind-launch r3). No sweep exists elsewhere. Forbidden: Hands, Soul, Imagination, Life. |
| Repetition breaker | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The breaker and the work queue are deleted (parked). Nothing trips or reopens items. No state of its own (rulings `self-waker`, `merge-gate-own-soul`). Trip condition derived from one selection: the documents citing the item, in any role. Counted runs are the item's ended SelfRun runs of hers (`operated_by: Mind`, not withdrawn) admitted after the newest question `raised_in` the item. Trip when the last 3 counted runs are empty, or 10 of the last 50. A run is empty when no citing document other than a run has an ordinal in its window (its admission up to the next run's, or now). Documents that cite something else never count, wherever they were admitted (F21). | Evaluated in `open_and_launch` when a Self run claims the item, not by the heartbeat. When tripped, it admits one `question` labelled `breaker-<run label>` under the item's campaign, `raised_in` the item, and launches nothing. The run label is the label the refused launch would have used, so every trip has its own key. The existing blocked-spec recipe then removes the item from the queue. Answered by a ruling or withdrawn: either reopens the item, and that question is the boundary, so a reopened item starts a fresh count. | `open_and_launch` admits the question; any Self may answer it (substrate-internal, `mind-rules-which-forks`). |
| Brake | One document per instance in a root-owned CultCache store `/etc/gamecult/minds/<instance>/control.cc`, type `eureka.control.brake.v1 { released: bool, set_at, set_by }`. | Replaced whole by the operator's CLI; never appended. Absent or undecodable reads as held. `mind-control brake hold` writes it held and then, in the same command, stops her running units: `systemctl stop` (blocking) over `mind-self@<i>:*` and `mind-persona@<i>:*`, through `SystemdLauncher::stop_all` (cut brake-stop; ruling `self-run-actuator`; F18-F20). | Operator only (ruling `brake-dial-root-store-now`); her units read it, and the file is not writable by any user she runs as. The hold is the one stopper of her units. `read_effective` is the one reader. Its `Released` answer carries a `Grant` (cadence and run cap, private fields, not `Clone`), which `open_and_launch` takes by value, so no run opens without a released reading (cut mind-launch r3). |
| Swarm dial (supersedes the per-instance burn-rate dial) | `CONTROL_ROOT/swarm.cc` only; the per-instance `control.cc` holds the brake and nothing else. `eureka.control.burn_rate.v1`, `Grant.cadence` and `base_cooldown_s` are deleted (cut mind-heartbeat). | Operator CLI `mind-control swarm ...`. | Ceilings: heat 2, base rate 100 USD/h, base run 50 USD, k 16. |
| 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. |
| 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 | **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 | `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 | 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 | `/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 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 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. |
| Mind fence | nft table `inet mind_fence` | Reloaded at every Persona start; absent after any nft flush until then | gamecult-ops |
| Persona doctrine set | `MIND_PERSONA_DOCTRINE` | Changed only by an installer run at a new skill pin | gamecult-ops installer + Eureka skill repo |
| Mind web builds (`cut-minds-web.h4`; gamecult-ops `6564bd4`, `0c0ee90`) | `/srv/minds-web/<mind>/<build>/`, served as `https://minds.gamecult.org/<mind>/<build>/`. Live 2026-11-02: root `root:root 0755`, eight folders (aqua, eureka, heimdall, kiko, libby, nibu, void, weksa) each `mind-<m>-self:mind-<m>-self 0755`, all empty; vhost `/etc/nginx/sites-enabled/minds.gamecult.org.conf` present; `/eureka/` answers 404 (no build yet). | A Mind's Self run writes a build folder; nginx serves it static: no proxy, no cookie, no CSP, no autoindex, `disable_symlinks if_not_owner`, dotfiles 404, one location for every Mind (a new Mind needs a folder, not an nginx edit). | The Mind's own Self unit alone (`ReadWritePaths=-/srv/minds-web/<m>` in `mind-self@<m>.service.d/endpoint.conf`, seen for aqua, eureka, heimdall, kiko; no Persona drop-in names minds-web). The installer owns the folders; no Mind writes another's folder; root-owned `/srv/cinny` stays refused (a chat-origin preview slot was refused: a Mind's script would share the chat client's origin). Void's beta is `/srv/minds-web/void/`; the `/srv/site` grant was dropped (`b970917`). | **Shared origin recorded:** all Minds share the one origin `minds.gamecult.org`, same-site with `chat.gamecult.org`, so a script one Mind publishes can read another's storage, and no credential or cookie may ever be put on these pages. Per-Mind origins need a separate registrable domain, waiting on the operator's domain choice (gamecult-ops `docs/research/2026-11-02-artifact-host-safety.md`). A running Self unit takes a new grant at its next start. |
| Identity diffs | The pair of receipts of two consecutive Persona puts whose identity fields (publicName, publicDescription, presentation, values) differ. Derived, not stored. | Composed by the Persona organ at put time and sent as one delivery request through the crossing; a failed post is retried by Bifrost's delivery journal, not by her. | Persona organ composes; Bifrost posts under the permit. No rate limit. |
| Identity diffs | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No organ composes them; C6 returns them. The pair of receipts of two consecutive Persona puts whose identity fields (publicName, publicDescription, presentation, values) differ. Derived, not stored. | Composed by the Persona organ at put time and sent as one delivery request through the crossing; a failed post is retried by Bifrost's delivery journal, not by her. | Persona organ composes; Bifrost posts under the permit. No rate limit. |
| Discord body surfaces | Outbound: crossing ids `epiphany.persona_discord_delivery_request.v0` and `..._permit.v0`, agent `epiphany.Persona`, runtime `epiphany-starfire` (F6), renamed to `eureka.*` and `eureka-yggdrasil` in the mouth rebinding (`mouth-crossing-on-yggdrasil`). Inbound: Bifrost persona-feedback deliveries for target `epiphany` (F6). Persona-session tools reach both (`body-includes-discord`). | Request, permit, post, receipt (Bifrost journal). Inbound deliveries: **unprobed** who records that a delivery was answered; `run-is-the-grant` forbids her organ from holding that fact. Blocks the Persona cuts only, not the cuts admitted today. | Bifrost owns posting and delivery records; her permit issuer grants while the brake is released. |
| Units and instance templates | `mind-heartbeat.service` (one, not per instance), `mind-self@<instance>:<label>.service`, `mind-persona@<instance>.service` (instance only, never `:<label>`; a long-lived leased `claude` session, capped by `RuntimeMaxSec=4h` and `MIND_PERSONA_RUN_CAP_S=14400`), `mind-fence.service` (one); users `mind-<instance>` (organs) and `mind-<instance>-self` (Self runs); state `/var/lib/gamecult/minds/<instance>/`; control `/etc/gamecult/minds/<instance>/`. Instance `eureka`. | Hand-installed by gamecult-ops now; Idunn targets declared before the first hosted member, which deletes the hand install (`mind-units-templated-interim`). | gamecult-ops installs; Idunn later. Starting: `open_and_launch` through `SystemdLauncher::start`, as her users, who are granted start only. The instance in a unit name is always the mind's (`MindPort::instance`), passed to every `Launcher` call; `SystemdLauncher` holds none. The instance and label are validated by the leaf's grammar before any `systemctl` argv is built. Stopping: only the operator's `brake hold`, as root (cut brake-stop). The unit-level brake gate and the start-only grant are follow-up `mind-units-brake-gate`. None of this exists on Yggdrasil yet (F19, F22). Each piece's identity, lifecycle and authority: the section "The mind units" below (cut mind-units-install; unit names pending question `mind-unit-names`). |
| Self-run credential | None in her unit. The connector holds the one subscription token; a Self run borrows it as a lease over a unix socket (`CLAUDE_LEASE_SOCKET`), and the token reaches `claude` only as a descriptor it reads once (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`). The child's environment is cleared and rebuilt from an allow-list (`PATH`, `LANG`, `LC_*`, `TERM`, and its own `HOME` and `CLAUDE_CONFIG_DIR`), so no credential variable in the unit can outrank the lease. | Rotated by the operator at the connector, never in her unit: no `EnvironmentFile` carries a token for `mind-self@` (rulings `self-runs-through-connector`, `self-run-credential-lease`; `self-run-token-reach` is superseded). | The connector's: one lease per unit invocation, bound to the peer; the unit holds no credential variable. Her `claude` runs her tools, so anything in the unit's environment is readable from `/proc/<claude>/environ` by her Bash (ruling `claude-code-runs-her-tools-2`). Since `persona-session-landed` the Persona unit borrows the same lease (`SupplementaryGroups=claude-lease`; lease row PersonaTurn bound to `mind-persona@<m>`). |
| Wake frame | Fixed prompt frame (provenance, jurisdiction, brake obedience) in `/etc/gamecult/minds/<instance>/wake-frame.md`, root-owned. Composed by the Persona organ from host config; the waker passes the unit only the instance and the run label. | Changed only by an install. | Host config (ruling `self-waker` rider 2); never a file her runs merge into. |
| Units and instance templates | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The Persona unit ends at `no organ`; the heartbeat starts it and nothing else; `mind-self@` is started by nobody. `mind-heartbeat.service` (one, not per instance), `mind-self@<instance>:<label>.service`, `mind-persona@<instance>.service` (instance only, never `:<label>`; a long-lived leased `claude` session, capped by `RuntimeMaxSec=4h` and `MIND_PERSONA_RUN_CAP_S=14400`), `mind-fence.service` (one); users `mind-<instance>` (organs) and `mind-<instance>-self` (Self runs); state `/var/lib/gamecult/minds/<instance>/`; control `/etc/gamecult/minds/<instance>/`. Instance `eureka`. | Hand-installed by gamecult-ops now; Idunn targets declared before the first hosted member, which deletes the hand install (`mind-units-templated-interim`). | gamecult-ops installs; Idunn later. Starting: `open_and_launch` through `SystemdLauncher::start`, as her users, who are granted start only. The instance in a unit name is always the mind's (`MindPort::instance`), passed to every `Launcher` call; `SystemdLauncher` holds none. The instance and label are validated by the leaf's grammar before any `systemctl` argv is built. Stopping: only the operator's `brake hold`, as root (cut brake-stop). The unit-level brake gate and the start-only grant are follow-up `mind-units-brake-gate`. None of this exists on Yggdrasil yet (F19, F22). Each piece's identity, lifecycle and authority: the section "The mind units" below (cut mind-units-install; unit names pending question `mind-unit-names`). |
| Self-run credential | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The Persona unit no longer uses the lease; C3b may. None in her unit. The connector holds the one subscription token; a Self run borrows it as a lease over a unix socket (`CLAUDE_LEASE_SOCKET`), and the token reaches `claude` only as a descriptor it reads once (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`). The child's environment is cleared and rebuilt from an allow-list (`PATH`, `LANG`, `LC_*`, `TERM`, and its own `HOME` and `CLAUDE_CONFIG_DIR`), so no credential variable in the unit can outrank the lease. | Rotated by the operator at the connector, never in her unit: no `EnvironmentFile` carries a token for `mind-self@` (rulings `self-runs-through-connector`, `self-run-credential-lease`; `self-run-token-reach` is superseded). | The connector's: one lease per unit invocation, bound to the peer; the unit holds no credential variable. Her `claude` runs her tools, so anything in the unit's environment is readable from `/proc/<claude>/environ` by her Bash (ruling `claude-code-runs-her-tools-2`). Since `persona-session-landed` the Persona unit borrows the same lease (`SupplementaryGroups=claude-lease`; lease row PersonaTurn bound to `mind-persona@<m>`). |
| Wake frame | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The Persona organ composes nothing now. Fixed prompt frame (provenance, jurisdiction, brake obedience) in `/etc/gamecult/minds/<instance>/wake-frame.md`, root-owned. Composed by the Persona organ from host config; the waker passes the unit only the instance and the run label. | Changed only by an install. | Host config (ruling `self-waker` rider 2); never a file her runs merge into. |
| Epiphany residue | F5, F8, F11, as they stood before the teardown. | Teardown landed (gamecult-ops `9c12adb`); what it did not name is follow-up `eureka-body:follow_up:epiphany-body-leftovers`; the repo is archived last. | gamecult-ops for host and repo tooling; Idunn for its legacy target list (follow-up). |
## The mind units: identity, lifecycle and authority
@ -550,17 +632,17 @@ hers per turn (`one-live-self-run`) and only then can `User=` name a per-instanc
| Thing | Identity | Lifecycle | Who may start, stop, enable or change it |
| --- | --- | --- | --- |
| Heartbeat unit | One `mind-heartbeat.service` (not per instance; `mind-wake@` timers and units are retired). Needs `HEARTBEAT_PERSONAS` (each entry ends with that Persona's own Huginn `rudp://<ip>:<port>`: each Mind is its own daemon, ruling `swarm-one-connector-many-callers-mind-per-daemon`), `MIND_PERSONA_OPERATOR`, `BIFROST_CHAT_ENDPOINT` and `_KEY_FILE`, `MIND_CONNECTOR_ENDPOINT`, `_KEY_FILE`, `HEARTBEAT_CLASSIFIER_MODEL`, `STATE_DIRECTORY`. | Idunn-managed, sole writer of `heartbeat.cc`. | Install, replace, restart. |
| Persona template | `/etc/systemd/system/mind-persona@.service`. Instance unit `mind-persona@<i>.service` (instance only, never `:<label>`), `User=mind-%i`, `Type=exec`, no `[Install]`, so it cannot be enabled. `Requires=` and `After=mind-fence.service`, with `ExecStartPre=+systemctl reload mind-fence.service`; `SupplementaryGroups=claude-lease`; `LoadCredential=chat-key`; `MIND_PERSONA_CONFIG_SEED=/etc/gamecult/minds/%i/persona-seed`; `ProtectSystem=strict`; `KillMode=control-group`. | Inactive until the heartbeat starts it. It carries one long-lived leased `claude` session (not a one-shot turn) and ends by its own exit, at the cap (`RuntimeMaxSec=4h`, `MIND_PERSONA_RUN_CAP_S=14400`), or by the brake hold's stop (`TimeoutStopSec=30s`, then SIGKILL to the whole cgroup). `Restart=no`, and nothing else restarts it. Every start first runs the gate (below); while the brake is not Released the unit is skipped and ends inactive. `ExecStart` names the Persona organ's binary in the Huginn release, which ships (live, read 2026-11-02: five units active). | Start: `mind-<i>` only, through `open_and_launch` (the waker), by polkit's verb `start` on this one unit name. Stop, kill, restart: root only, which in practice means `mind-control brake hold` (cut brake-stop). Change: root via the script. Enable: nobody. Session, sandbox and fence: the section "The Persona session" below. |
| Self template | `/etc/systemd/system/mind-self@.service`. Instance unit `mind-self@<i>.service`, `User=mind-%i-self`, `Type=exec`, no `[Install]`. | As the Persona unit, with `RuntimeMaxSec=4h`. `ExecStart` names the Self-run actuator's binary in the Huginn release; that cut adds the state directory, `RuntimeDirectory=` (each child's fresh configuration), `MIND_SELF_RUN_CAP_S` equal to `RuntimeMaxSec` in seconds, `CLAUDE_LEASE_SOCKET` and the argv. It adds no token and no `EnvironmentFile` with a credential. | Start: `mind-<i>` only (the Persona's start-Self-run tool through `open_and_launch`), by polkit, verb `start`. Stop, kill, restart: root only. Change: root via the script. Enable: nobody. |
| Organ user | `mind-<i>`: system user and group, shell `/usr/sbin/nologin`, home `/nonexistent`. | Created by the install script if absent and never modified by it after that. Deleted by root at the mind's retirement. Runs the waker and Persona units. | Root creates and deletes it. It may start `mind-persona@<i>` and `mind-self@<i>`, and nothing else. It cannot write the control store (root 0644, dir 0755) or stop a unit. It can signal its own processes with `kill(2)`, as any Unix user can. That only ends spend, and the ended run is closed Recorded by the next launch, so it adds no second stopper of her units. |
| Heartbeat unit | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The heartbeat reads no connector or classifier setting; see the persona-only section for its inputs. One `mind-heartbeat.service` (not per instance; `mind-wake@` timers and units are retired). Needs `HEARTBEAT_PERSONAS` (each entry ends with that Persona's own Huginn `rudp://<ip>:<port>`: each Mind is its own daemon, ruling `swarm-one-connector-many-callers-mind-per-daemon`), `MIND_PERSONA_OPERATOR`, `BIFROST_CHAT_ENDPOINT` and `_KEY_FILE`, `MIND_CONNECTOR_ENDPOINT`, `_KEY_FILE`, `HEARTBEAT_CLASSIFIER_MODEL`, `STATE_DIRECTORY`. | Idunn-managed, sole writer of `heartbeat.cc`. | Install, replace, restart. |
| Persona template | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The unit exits `dead` or `no organ`; it carries no session. `/etc/systemd/system/mind-persona@.service`. Instance unit `mind-persona@<i>.service` (instance only, never `:<label>`), `User=mind-%i`, `Type=exec`, no `[Install]`, so it cannot be enabled. `Requires=` and `After=mind-fence.service`, with `ExecStartPre=+systemctl reload mind-fence.service`; `SupplementaryGroups=claude-lease`; `LoadCredential=chat-key`; `MIND_PERSONA_CONFIG_SEED=/etc/gamecult/minds/%i/persona-seed`; `ProtectSystem=strict`; `KillMode=control-group`. | Inactive until the heartbeat starts it. It carries one long-lived leased `claude` session (not a one-shot turn) and ends by its own exit, at the cap (`RuntimeMaxSec=4h`, `MIND_PERSONA_RUN_CAP_S=14400`), or by the brake hold's stop (`TimeoutStopSec=30s`, then SIGKILL to the whole cgroup). `Restart=no`, and nothing else restarts it. Every start first runs the gate (below); while the brake is not Released the unit is skipped and ends inactive. `ExecStart` names the Persona organ's binary in the Huginn release, which ships (live, read 2026-11-02: five units active). | Start: `mind-<i>` only, through `open_and_launch` (the waker), by polkit's verb `start` on this one unit name. Stop, kill, restart: root only, which in practice means `mind-control brake hold` (cut brake-stop). Change: root via the script. Enable: nobody. Session, sandbox and fence: the section "The Persona session" below. |
| Self template | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Nothing starts it: the Persona start-Self tool is deleted. `/etc/systemd/system/mind-self@.service`. Instance unit `mind-self@<i>.service`, `User=mind-%i-self`, `Type=exec`, no `[Install]`. | As the Persona unit, with `RuntimeMaxSec=4h`. `ExecStart` names the Self-run actuator's binary in the Huginn release; that cut adds the state directory, `RuntimeDirectory=` (each child's fresh configuration), `MIND_SELF_RUN_CAP_S` equal to `RuntimeMaxSec` in seconds, `CLAUDE_LEASE_SOCKET` and the argv. It adds no token and no `EnvironmentFile` with a credential. | Start: `mind-<i>` only (the Persona's start-Self-run tool through `open_and_launch`), by polkit, verb `start`. Stop, kill, restart: root only. Change: root via the script. Enable: nobody. |
| Organ user | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No unit it starts spends or writes the Mind. `mind-<i>`: system user and group, shell `/usr/sbin/nologin`, home `/nonexistent`. | Created by the install script if absent and never modified by it after that. Deleted by root at the mind's retirement. Runs the waker and Persona units. | Root creates and deletes it. It may start `mind-persona@<i>` and `mind-self@<i>`, and nothing else. It cannot write the control store (root 0644, dir 0755) or stop a unit. It can signal its own processes with `kill(2)`, as any Unix user can. That only ends spend, and the ended run is closed Recorded by the next launch, so it adds no second stopper of her units. |
| Self user | `mind-<i>-self`: system user and group, nologin, home `/nonexistent`. The install script refuses an instance slug ending in `-self`, so this name never collides with another mind's organ user. | As the organ user. | Root creates and deletes it. It starts no unit. Polkit refuses it every verb, and the rule refuses any subject whose name ends in `-self`. |
| `mind-control` | `/opt/gamecult/huginn/releases/<sha>/mind-control`, root:root 0700, reached by the `current` symlink; `/usr/local/sbin/mind-control` links to `/opt/gamecult/huginn/current/mind-control`. | Built and installed with each Huginn release by the Release step of `runbooks/huginn-yggdrasil.md`. Replaced when `current` flips. The previous release is kept until the new one verifies. | Install, replace: root via the Release step. Run: root only (mode 0700), which covers the operator's verbs and the gate, which systemd runs as root through the `+` prefix. No user of hers can execute it. |
| `mind-heartbeat` | `/opt/gamecult/huginn/releases/<sha>/mind-heartbeat`, root:root 0755. | Owner of initiative: reads the swarm envelope, the mind (busy, idle, run ends), the mouth (typed sender, `m.mentions`, room) and the connector (classifier urgency, spend); writes `heartbeat.cc` (Initiative per instance, poll traces) and launches Persona turns through `open_and_launch`. The operator tagging or naming a Persona fills its initiative once per message; a member never does. | `mind-heartbeat timeline` prints the latest poll. |
| `mind-heartbeat` | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** It no longer owns initiative, classifies urgency, meters spend or opens runs: it starts Persona units on the beat and on operator and Mind mentions, and writes `heartbeat.cc`. `/opt/gamecult/huginn/releases/<sha>/mind-heartbeat`, root:root 0755. | Owner of initiative: reads the swarm envelope, the mind (busy, idle, run ends), the mouth (typed sender, `m.mentions`, room) and the connector (classifier urgency, spend); writes `heartbeat.cc` (Initiative per instance, poll traces) and launches Persona turns through `open_and_launch`. The operator tagging or naming a Persona fills its initiative once per message; a member never does. | `mind-heartbeat timeline` prints the latest poll. |
| The gate | `ExecCondition=+/opt/gamecult/huginn/current/mind-control --instance %i check` in both spending templates. The verb is cut mind-unit-gate. | Runs at every start of a Persona or Self unit. It exits 0 only when `read_effective` is `Released`; held, absent, undecodable or out of bounds exit 2 (systemd skips on 1-254). It holds no state and writes nothing. | Owner: `read_effective`, the one derivation. Change: a Huginn release (the verb) or the script (the line). It closes the window in which a launch that read Released before a hold starts its unit after the hold's stop (follow-up `mind-units-brake-gate`). |
| Polkit rule | `/etc/polkit-1/rules.d/60-mind-units.rules`, root 0644, source `polkit/60-mind-units.rules` in gamecult-ops. Needs package `polkitd` (absent today, F22; question `mind-unit-start-grant`). | Installed and replaced by the script. Instance-generic: one file serves every mind. | Root changes it. It grants exactly one thing: action `org.freedesktop.systemd1.manage-units`, verb `start`, unit `mind-persona@<i>.service` or `mind-self@<i>.service`, to subject `mind-<i>`. Every other request falls through to systemd's default, `auth_admin`, which an unattended caller cannot satisfy. |
| Control store | `/etc/gamecult/minds/<i>/control.cc`, root:root 0644 in a 0755 dir (cut mind-control-store). | The install script writes `brake hold` once, if no store exists, so a fresh install reads `held` with a name and time rather than `absent`. Afterwards only the operator's verbs change it. | Operator only (`brake-dial-root-store-now`). |
| A unit on a brake hold | The instance unit above. | `brake hold` writes the brake held, then stops both units of the instance and waits; the unit ends inactive, its run stays in force. A start after the hold is skipped by the gate and ends inactive (dead), not failed. The next `open_and_launch` of that turn after a release closes the run Recorded "unit not active" (mind-launch r3 step 0). Nothing restarts a stopped unit: `Restart=no`, the waker does not launch without a Grant, and Idunn does not know the unit. | Stopper: the hold only. Restarter: none. |
| A unit on a brake hold | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No `open_and_launch` closes a dead run; `mind-stream@` is also stopped. The instance unit above. | `brake hold` writes the brake held, then stops both units of the instance and waits; the unit ends inactive, its run stays in force. A start after the hold is skipped by the gate and ends inactive (dead), not failed. The next `open_and_launch` of that turn after a release closes the run Recorded "unit not active" (mind-launch r3 step 0). Nothing restarts a stopped unit: `Restart=no`, the waker does not launch without a Grant, and Idunn does not know the unit. | Stopper: the hold only. Restarter: none. |
| Idunn's view | No binding, no target. | Idunn observes and restarts only workloads it launched itself, and every Idunn workload is a resident service that continuity restarts. It has no one-shot, timer or template kind (F22). So today it never touches these units. The deletion line of the hand install (ruling `mind-units-templated-interim`: Idunn targets before the first hosted member) needs an Idunn job workload that is never continuity-restarted. That is follow-up `idunn-job-workload`. | Idunn: none until that follow-up lands. Its owner then may install and change the templates and users, and must never start or restart a spending unit. |
## Rationale
@ -626,6 +708,8 @@ over the instance's `mind-self@` and `mind-persona@` units (cut brake-stop).
### Who decides one live run, and who ends a dead one
> **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The launch primitive is parked; the admission rule (`AlreadyLive`) stands, the liveness sweep and `Busy` answer are gone.
Soul's verdict `cut-mind-launch.s1` found the one-live rule decided in two places, neither
of them sound. `open_and_launch` read for a live run and then admitted later, so two
interleaved launches both passed. The MCP admit door checked nothing, so a second live run
@ -665,6 +749,8 @@ turn starts Self runs. Neither the waker nor the Persona tool exists, so nothing
### What the breaker counts
> **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The breaker is deleted.
The ruling's rider says a run is empty when it "admitted nothing but their own run". The
built breaker counted every document admitted anywhere in the mind during a run's window.
Under `every-wake-a-run` a PersonaTurn run always lands in that window, so the breaker could
@ -811,6 +897,8 @@ next cut in `contract.rs`, `client.rs` or `envelope.rs`.
### How a Self run is carried (cut `mind-self-run`)
> **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The actuator stands unchanged, but no Persona turn admits briefs and nothing opens its run.
The run document is the grant (`open_and_launch`); the unit takes only `--instance`
(`mind-units-install` r2). So the actuator learns which run it carries from the mind: the one
in-force `operated_by Mind` Self run of its instance, which admission keeps unique
@ -847,18 +935,20 @@ in-force `operated_by Mind` Self run of its instance, which admission keeps uniq
### The Persona session (ruling `persona-session-landed`, Modeling 2026-11-02)
> **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The session, its tools, sandbox and turn text are deleted; this section and section B record what ran at `ffd4136` and `3177b33`.
## B. The Persona session, as the substrate runs it
Ruling `eureka-body:ruling:persona-session-landed` (landed; deployed 2026-11-01 23:31Z, verified: five `mind-persona@` units active: eureka, kiko, nibu, void, weksa). Companion rulings it cites: `live-mind-sessions`, `persona-session-full-sandbox`, `persona-session-unit-leased`, `persona-reply-typed-by-schema`, `persona-session-ships-a1-closes`.
| Thing | Owner | Inputs | Outputs | Derived state | Forbidden writers | Shared paths | Cut line | Verification layer |
|---|---|---|---|---|---|---|---|---|
| Persona organ (`mind-persona`, Huginn `crates/mind-body/src/persona.rs` `carry`) | Huginn. One start of `mind-persona@<i>` adopts the PersonaTurn run the heartbeat opened (none held = `NoRun`, nothing started); it opens no run itself. | Brakes (instance and swarm, read once per process); mouth deliveries (`chat_rudp`, polled every `PERSONA_POLL_S`=5 s while live); her mind (persona state, campaigns in force, responsibilities, recall); `MIND_PERSONA_DOCTRINE` files; plan windows from the lease | Per result: `say` sent through the mouth, `remember` admitted as memories, `settle` resolutions, her `Pulse` vote, `start_self_run` follow-up + `open_and_launch`; then the ack. Closes its run once (`close_run`). | `Progress {acked, turn, answered, last_intent, failure, self_run, refused}` lives in the start, across the session's processes. The mouth's pending deliveries are the truth for "unanswered". | The organ writes no brake and no persona state. A session's text is never scanned: only a decoded `PersonaReply` acts (`decode_reply`). Nothing acks that was not answered; no ack passes an unanswered delivery below the answered seq or a refused batch (PersonaInbox::result owns the ack decision, 0f19eec, Soul s3). | Mouth, mind, lease socket; none shared with the Self | One conversation per process (public rooms together, or one DM room); the next conversation starts a new process in the same start until nothing is pending or `ROTATE_MARGIN_S` before the cap | `crates/mind-body/src/persona/tests.rs`; Soul verdicts s1-s3 on the cut; live units active |
| The session process | `claude` child via `ClaudeSpawner::in_sandbox`, driven by `self_run::session::drive` (the Self's own driver and `decide`). The actuator owns lifetime and everything entering it. | One framed stdin line per batch; system prompt file (`persona-instructions.md` in the unit's runtime scratch: doctrine + persona state + campaigns, read once per process, so a persona-state change reaches a live session only at its next process) | stream-json results, each constrained by `--json-schema` to `PersonaReply` (`intent` first and required) | Session id = uuid5 of run id + `:p<process>`; no resume, no continue, no fork (`persona_args`). The transcript is a cache; the mind is the truth. | Her tools write nothing in the world except through the decoded reply and the sandbox | `/var/lib/mind-<i>/sandbox` (rw), `<scratch>/claude-config` (rw, fresh from `persona-seed` each process), scratch otherwise ro (aab25a5) | The gate is the bwrap argv (`sandbox_args`, ro-bind `/`, tmpfs `/tmp` `/run` `/etc/gamecult` `/var/lib`, private pid table, `--die-with-parent`, shared network) | Probe `scripts/probe-persona-sandbox-under-systemd.sh`; sandbox tests |
| Mind fence (`mind-fence.service`, ruleset `/etc/gamecult/minds/fence.nft`, table `inet mind_fence`) | gamecult-ops. The one boundary on what her session reaches on the host, keyed on uid, so it binds the organ and the sandbox alike. | Rendered by the installer from every installed Persona drop-in | nft output chain: persona uids may reach their own huginn address:port, the mouth (127.0.0.1:17884), the host's public 80/443 and the internet; every other local/private address, loopback services, WireGuard peers, other Minds' huginn, and all broadcast/multicast are rejected | Live: `persona_uids` set of 8 uids, `huginn` set of 8 uid.port pairs | Nobody stops it to open anything: it has no `ExecStop`. `/etc/nftables.conf` begins with `flush ruleset`; a flush leaves the unit "active" over an empty fence, so every Persona start reloads it (`ExecStartPre=+systemctl reload`). | `/etc/gamecult/minds/fence.nft` | Fence is the host boundary; the sandbox is the process boundary. Residuals named in the runbook: abstract unix sockets, Self runs unfenced. Open reach: her shell can `huginn admit` into her own mind (and, inference from the 2026-10-31 probe, another Mind's by declaring its instance) until A1 (`mind-admission-publisher-unproven`; ruling `persona-session-ships-a1-closes`). | `scripts/test-mind-fence.sh` (throwaway container via ygg-verify); `sudo nft list table inet mind_fence` |
| Persona organ (`mind-persona`, Huginn `crates/mind-body/src/persona.rs` `carry`) | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Replaced by the first row of "The persona-only body": the organ is inert. Huginn. One start of `mind-persona@<i>` adopts the PersonaTurn run the heartbeat opened (none held = `NoRun`, nothing started); it opens no run itself. | Brakes (instance and swarm, read once per process); mouth deliveries (`chat_rudp`, polled every `PERSONA_POLL_S`=5 s while live); her mind (persona state, campaigns in force, responsibilities, recall); `MIND_PERSONA_DOCTRINE` files; plan windows from the lease | Per result: `say` sent through the mouth, `remember` admitted as memories, `settle` resolutions, her `Pulse` vote, `start_self_run` follow-up + `open_and_launch`; then the ack. Closes its run once (`close_run`). | `Progress {acked, turn, answered, last_intent, failure, self_run, refused}` lives in the start, across the session's processes. The mouth's pending deliveries are the truth for "unanswered". | The organ writes no brake and no persona state. A session's text is never scanned: only a decoded `PersonaReply` acts (`decode_reply`). Nothing acks that was not answered; no ack passes an unanswered delivery below the answered seq or a refused batch (PersonaInbox::result owns the ack decision, 0f19eec, Soul s3). | Mouth, mind, lease socket; none shared with the Self | One conversation per process (public rooms together, or one DM room); the next conversation starts a new process in the same start until nothing is pending or `ROTATE_MARGIN_S` before the cap | `crates/mind-body/src/persona/tests.rs`; Soul verdicts s1-s3 on the cut; live units active |
| The session process | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Deleted with the Persona session. `claude` child via `ClaudeSpawner::in_sandbox`, driven by `self_run::session::drive` (the Self's own driver and `decide`). The actuator owns lifetime and everything entering it. | One framed stdin line per batch; system prompt file (`persona-instructions.md` in the unit's runtime scratch: doctrine + persona state + campaigns, read once per process, so a persona-state change reaches a live session only at its next process) | stream-json results, each constrained by `--json-schema` to `PersonaReply` (`intent` first and required) | Session id = uuid5 of run id + `:p<process>`; no resume, no continue, no fork (`persona_args`). The transcript is a cache; the mind is the truth. | Her tools write nothing in the world except through the decoded reply and the sandbox | `/var/lib/mind-<i>/sandbox` (rw), `<scratch>/claude-config` (rw, fresh from `persona-seed` each process), scratch otherwise ro (aab25a5) | The gate is the bwrap argv (`sandbox_args`, ro-bind `/`, tmpfs `/tmp` `/run` `/etc/gamecult` `/var/lib`, private pid table, `--die-with-parent`, shared network) | Probe `scripts/probe-persona-sandbox-under-systemd.sh`; sandbox tests |
| Mind fence (`mind-fence.service`, ruleset `/etc/gamecult/minds/fence.nft`, table `inet mind_fence`) | **Superseded by C1 (see "The persona-only body"): a Persona uid reaches only its own persona door (port + 1000, refuses `Admit`) and the connector at `127.0.0.1:4110`; the heartbeat uid 984 is rejected at every full door; `mind-heartbeat.service` is `Requires=`/`After=` the fence. The mouth and "her shell can `huginn admit`" below describe the pre-C1 fence.** gamecult-ops. The one boundary on what her session reaches on the host, keyed on uid, so it binds the organ and the sandbox alike. | Rendered by the installer from every installed Persona drop-in | nft output chain: persona uids may reach their own huginn address:port, the mouth (127.0.0.1:17884), the host's public 80/443 and the internet; every other local/private address, loopback services, WireGuard peers, other Minds' huginn, and all broadcast/multicast are rejected | Live: `persona_uids` set of 8 uids, `huginn` set of 8 uid.port pairs | Nobody stops it to open anything: it has no `ExecStop`. `/etc/nftables.conf` begins with `flush ruleset`; a flush leaves the unit "active" over an empty fence, so every Persona start reloads it (`ExecStartPre=+systemctl reload`). | `/etc/gamecult/minds/fence.nft` | Fence is the host boundary; the sandbox is the process boundary. Residuals named in the runbook: abstract unix sockets, Self runs unfenced. Open reach: her shell can `huginn admit` into her own mind (and, inference from the 2026-10-31 probe, another Mind's by declaring its instance) until A1 (`mind-admission-publisher-unproven`; ruling `persona-session-ships-a1-closes`). | `scripts/test-mind-fence.sh` (throwaway container via ygg-verify); `sudo nft list table inet mind_fence` |
| `/opt/commons` | root. Toolchains `bin/` and `opt/` are `root:root 0755`, no ACL, contents root-owned and `go-w` (rulings `commons-toolchains-root-owned`, `commons-install-forgiveness`). Data dirs `handoff/` and `cast-art/` are `root:mind-commons 2775` with a default group rwx ACL. | Installer repairs the commons before its PATH check on every run | Self units get `/opt/commons/bin` on PATH; installs go through root (her Self "has the root path"; Minds ask @eureka in #minds) | none | Any Mind user writing `bin/` or `opt/`. Persona users are not in `mind-commons` and see `/opt/commons` read-only (bwrap `--ro-bind /`, and `ProtectSystem=strict`). | `mind-self@` has `SupplementaryGroups=claude-lease mind-commons` and `ReadWritePaths=/opt/commons` | Toolchain/data split is the cut; one writer class per dir | Live read: `/opt/commons`, `bin`, `opt` root:root 0755; `handoff`, `cast-art` drwxrwsr-x+ root:mind-commons; installer test asserts no group/other-writable path under `bin/` and `opt/` (baa39fd) |
| Connector callers | ModelConnector (claude-connector) config at `/etc/gamecult/claude-connector/config.cc`, installed by gamecult-ops `install-claude-connector-yggdrasil.sh` | Each Mind is its own caller (`swarm-one-connector-many-callers-mind-per-daemon`) with a root:root 0600 connection key `connection-<m>.key` that no Mind reads | Two lease rows per Mind: SelfRun bound to `mind-self@<m>` and PersonaTurn bound to `mind-persona@<m>` (the lease is bound to the unit invocation and peer uid, capped by `--lease-max-ms` = cap + slack) | Lease socket `/run/claude-connector/lease.sock`, group `claude-lease` | Installer never deletes a key; `--remove-caller` is the one removal (21c5bf9, f4d90a7). The Persona unit no longer holds a connector key or endpoint, and `KitConnector`/`MAX_TURNS_PER_START` are gone (grep of Huginn origin/main: only history docs name them). The heartbeat's connector key is retired (`connection-heartbeat.key.dollar-era-2026-10-31` is a dead file). | `/etc/gamecult/claude-connector/` | Caller = Mind, lease = unit | bring-up `verify pre` expects one SelfRun and one PersonaTurn lease row per Mind (81f82b4) |
| Heartbeat (`mind-heartbeat`) | Huginn. Sole writer of `heartbeat.cc`; opens PersonaTurn and SelfRun runs through `open_and_launch`; classifies nothing, meters nothing. | Swarm envelope, mind, mouth | Starts `mind-persona@<i>`; "busy" is the slot's reading of life: a Persona run whose unit lives (or is in start grace) is busy, a dead holder is not, and the next launch closes it (cbb90d5) | `heartbeat.cc`, read by Persona units via `MIND_HEARTBEAT_STATE` | It never acks a delivery | | The sequence doc's cut 7 (`session-keeper`: floor of one live session, wakes written into live sessions) is not shown landed in the code read; today's heartbeat still launches a unit per beat, and the live session drains deliveries on its own poll. (Unverified beyond the module docs; Soul/Imagination to confirm before the map says "landed".) | |
| Connector callers | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** The PersonaTurn lease row has no caller until C3b; SelfRun is unused while no Self run launches. ModelConnector (claude-connector) config at `/etc/gamecult/claude-connector/config.cc`, installed by gamecult-ops `install-claude-connector-yggdrasil.sh` | Each Mind is its own caller (`swarm-one-connector-many-callers-mind-per-daemon`) with a root:root 0600 connection key `connection-<m>.key` that no Mind reads | Two lease rows per Mind: SelfRun bound to `mind-self@<m>` and PersonaTurn bound to `mind-persona@<m>` (the lease is bound to the unit invocation and peer uid, capped by `--lease-max-ms` = cap + slack) | Lease socket `/run/claude-connector/lease.sock`, group `claude-lease` | Installer never deletes a key; `--remove-caller` is the one removal (21c5bf9, f4d90a7). The Persona unit no longer holds a connector key or endpoint, and `KitConnector`/`MAX_TURNS_PER_START` are gone (grep of Huginn origin/main: only history docs name them). The heartbeat's connector key is retired (`connection-heartbeat.key.dollar-era-2026-10-31` is a dead file). | `/etc/gamecult/claude-connector/` | Caller = Mind, lease = unit | bring-up `verify pre` expects one SelfRun and one PersonaTurn lease row per Mind (81f82b4) |
| Heartbeat (`mind-heartbeat`) | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Replaced by the second row of "The persona-only body"; it opens no run. Huginn. Sole writer of `heartbeat.cc`; opens PersonaTurn and SelfRun runs through `open_and_launch`; classifies nothing, meters nothing. | Swarm envelope, mind, mouth | Starts `mind-persona@<i>`; "busy" is the slot's reading of life: a Persona run whose unit lives (or is in start grace) is busy, a dead holder is not, and the next launch closes it (cbb90d5) | `heartbeat.cc`, read by Persona units via `MIND_HEARTBEAT_STATE` | It never acks a delivery | | The sequence doc's cut 7 (`session-keeper`: floor of one live session, wakes written into live sessions) is not shown landed in the code read; today's heartbeat still launches a unit per beat, and the live session drains deliveries on its own poll. (Unverified beyond the module docs; Soul/Imagination to confirm before the map says "landed".) | |
#### Turn text and reply (cuts `flush-shown`, `turn-core-instruction`, `tell-delta` (`cut-tell-delta.h7`, Huginn 3177b33))
@ -889,11 +979,13 @@ Owner: gamecult-ops installer. `MIND_PERSONA_DOCTRINE` in each Mind's `persona.e
### Index outage, tempo controller (Huginn 3177b33, Modeling 2026-11-02)
> **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Only the index half still stands; the tempo controller half is deleted.
| Thing | Owner | Inputs | Outputs | Derived state | Forbidden writers | Shared paths | Cut line | Verification layer |
|---|---|---|---|---|---|---|---|---|
| Source re-index: upsert before delete (`eureka-body-embed-outage`; `huginn-daemon/src/sources/mod.rs`, `index/qdrant.rs`) | The sources indexer in the daemon. Every chunk it writes is stamped with the head commit; a chunk id is its content. | A repo's changed paths (or the whole repo), the embedder pool | New chunks upserted first. Only then `delete_by(repo, paths, keeping=head)` removes chunks in scope whose `commit` is not the head (Qdrant filter `must` repo/paths, `must_not` commit = head). A retired repo still deletes all (`keeping: None`). | None stored beyond the collection. A failed embed now leaves what the index held (before: delete first, so an embedder outage emptied the paths it was re-indexing). | Deleting before the new chunks are written; a delete that cannot name the head it keeps | Qdrant collection, shared with every Mind's recall | The delete's filter is the cut: stale means "another commit", never "everything at these paths" | `index/tests.rs`, `sources/tests.rs` (the filter pinned `0af7fd2`; the slow-reserve stub `d9a4c27`). Live behavior unprobed here. |
| Embedder pool bounds (`index/ollama.rs`) | The daemon's one embedder client | Primary (GPU) endpoints and the reserve (CPU) endpoints | `EmbedBounds::DEFAULT` for primaries (short, under about 25 s a text); `EmbedBounds::RESERVE` for the reserve: connect 3 s, floor 60 s, 30 s per text, a batch bounded only by the caller's budget | None | Giving a CPU reserve a GPU's bound: it takes 16-27 s a text idle and 52 s loaded and would be given up on | Pool tiers | The tier decides the bound (`pool_bounded`) | `the_reserve_is_given_what_a_cpu_takes_and_a_gpu_is_not`, `a_slow_reserve_answers_under_its_own_bound_where_a_gpus_would_have_failed` |
| Tempo fallback controller (`mind-body/src/tempo.rs`, `tempo/sim.rs`; rulings `tempo-default-is-usage-fitter`, `tempo-fallback-pid-tuned-by-sim`, `tempo-controller-knows-the-ceiling`) | `tempo.rs`: `fallback_beat(...)` is a PID on the gap between the seven-day usage trajectory to the target permille and what was used, acting on the turn rate; gains `GAINS` {kp 0.02, ki 0.01, kd 0} were chosen by the committed sim (`docs/research/2026-11-01-tempo-pid-sim.md`), never by a run-time search. **Merged, not wired**: nothing outside `tempo.rs` and its tests calls `fallback_beat`; the heartbeat still takes `tempo::tally` of votes (heartbeat.rs:687). | A `Reading` (used permille, observed_at, resets_at), the previous `Fallback`, whether a vote decides, and the caller's one `saturated` report (last beat was the floor, or launched nothing because every eligible Mind was busy) | A beat in `FALLBACK_MIN_S`=60 .. `FALLBACK_MAX_S`=3600 s and the next `Fallback` | `Fallback {integral, last_used_permille, last_observed_at_ms, last_now_ms, carry_per_h, window_resets_at_ms, rate_per_h}`. The heartbeat is to own persisting it; it is never published as truth. One call integrates at most `MAX_STEP_MS` (the longest beat); a reading older than `STALE_AFTER_MS` (2x the longest beat) or from an expired window is no evidence; a new window clears the integral; while a vote decides nothing integrates, and the carry fades over `CARRY_FADE_H`=0.25 h. | The sim is test-only and the controller must stay the same function the sim sweeps; the controller must not search at run time; tuned gains are not hand-edited without a rerun | None yet | Controller is pure; the sim is its plant model (8 Minds, busy-time lognormal fit to 1284 turns over 29 h, Self run every 25th turn at 5x cost) | `tempo/tests.rs`; `cargo test -p mind-body tempo::sim::sweep -- --ignored --nocapture` reruns the sweep. The 7 new lines in `public_surface.txt` are the public API. Cut to wire: the heartbeat calls `fallback_beat` when `tally` returns none, owns `Fallback`, and passes `saturated`; not done. |
| Tempo fallback controller (`mind-body/src/tempo.rs`, `tempo/sim.rs`; rulings `tempo-default-is-usage-fitter`, `tempo-fallback-pid-tuned-by-sim`, `tempo-controller-knows-the-ceiling`) | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Deleted (`tally`, `fallback_beat`, `sim`); only `tempo::pick` and `score` remain. `tempo.rs`: `fallback_beat(...)` is a PID on the gap between the seven-day usage trajectory to the target permille and what was used, acting on the turn rate; gains `GAINS` {kp 0.02, ki 0.01, kd 0} were chosen by the committed sim (`docs/research/2026-11-01-tempo-pid-sim.md`), never by a run-time search. **Merged, not wired**: nothing outside `tempo.rs` and its tests calls `fallback_beat`; the heartbeat still takes `tempo::tally` of votes (heartbeat.rs:687). | A `Reading` (used permille, observed_at, resets_at), the previous `Fallback`, whether a vote decides, and the caller's one `saturated` report (last beat was the floor, or launched nothing because every eligible Mind was busy) | A beat in `FALLBACK_MIN_S`=60 .. `FALLBACK_MAX_S`=3600 s and the next `Fallback` | `Fallback {integral, last_used_permille, last_observed_at_ms, last_now_ms, carry_per_h, window_resets_at_ms, rate_per_h}`. The heartbeat is to own persisting it; it is never published as truth. One call integrates at most `MAX_STEP_MS` (the longest beat); a reading older than `STALE_AFTER_MS` (2x the longest beat) or from an expired window is no evidence; a new window clears the integral; while a vote decides nothing integrates, and the carry fades over `CARRY_FADE_H`=0.25 h. | The sim is test-only and the controller must stay the same function the sim sweeps; the controller must not search at run time; tuned gains are not hand-edited without a rerun | None yet | Controller is pure; the sim is its plant model (8 Minds, busy-time lognormal fit to 1284 turns over 29 h, Self run every 25th turn at 5x cost) | `tempo/tests.rs`; `cargo test -p mind-body tempo::sim::sweep -- --ignored --nocapture` reruns the sweep. The 7 new lines in `public_surface.txt` are the public API. Cut to wire: the heartbeat calls `fallback_beat` when `tally` returns none, owns `Fallback`, and passes `saturated`; not done. |
### Swarm by 2026-10-30 (Imagination `imagination-swarm-tonight`, 2026-10-29; historical, superseded 2026-11-02)

View file

@ -161,7 +161,7 @@ From r3 B3, now read as a deletion list rather than a body to rebuild:
2026-10-01). `inventory.md:581-588, 726-785` describes the Starfire cognition
body and the "intended Epiphany deployment body (not installed)". These are
deleted or rewritten in the same cut.
- What stays: `huginn.service`, the Bifrost units (`bifrost-persona-feedback`,
- What stays: `huginn.service` (since C1, 2026-11-19, this is `huginn@eureka`), the Bifrost units (`bifrost-persona-feedback`,
`bifrost-persona-mouth`, the watchdog timer), `codex-connector.service` as a
dead unit until the connector cuts land, the `gamecult-model` group and its
key files, user `codex-connector`.

View file

@ -1,5 +1,9 @@
# Swarm revival: target shape (draft)
> **Superseded in part by C1 (Huginn `57b931f`, 2026-11-19).** Personas reach their Mind only at a persona door (port + 1000) that refuses `Admit`, behind the `mind-fence` nft rules; Eureka's daemon is `huginn@eureka`, not `huginn.service`. See `docs/eureka-body-map.md`.
>
> **Superseded in part by C2 (Huginn `66b85c8`).** The Persona turn, the per-instance waker, the start-Self-run tool and the Self-run launch path this draft plans around are deleted or parked; the live Persona, heartbeat and Self-run rows are in `docs/eureka-body-map.md`, "The persona-only body (after C2)". The mind, instance, share and lifecycle tables below still describe the intended swarm shape, not the running one.
Status: draft target, Imagination (`imagination-swarm`), session
`self-2026-10-09-eureka`, 2026-10-10, written at Huginn `441b1fc`. Campaign
`eureka-body` in Eureka's mind (instance `eureka`). This is a step-0b pass

View file

@ -1656,6 +1656,11 @@
"required": [
"Unavailable"
]
},
{
"description": "The request reached the persona door, which answers reads and the\nmind's own persona document and nothing that writes the mind\n(`HuginnMindRequest::reaches_persona_door`). Nothing was written.",
"type": "string",
"const": "NotThisDoor"
}
]
},

View file

@ -2302,6 +2302,11 @@
"required": [
"Unavailable"
]
},
{
"description": "The request reached the persona door, which answers reads and the\nmind's own persona document and nothing that writes the mind\n(`HuginnMindRequest::reaches_persona_door`). Nothing was written.",
"type": "string",
"const": "NotThisDoor"
}
]
},