Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
Meta Vens
f6fc66b7e8 persona-wake-span W2 (Soul hold): day cap judged from the trace, a no-call turn decides nothing, the stagger restored whole, reseed carries the wake, unmetered_usd decoupled
H1: wake_end reads the day's spend from her trace before each turn, so a turn that completed and crossed the cap ends the wake before another is taken on lines it would not answer. A turn that made no model call holds no line and decides nothing (a first turn so fails the wake as an outage).
M2: stagger_ms is the first experiment's, whole: the Minds a line did not address rank after the addressed ones. Both cases pinned.
M3: sweeps pin the ack's watch on a waking line no turn took, the trailing list's exclusion of waking lines, and the open's lines the close does not decide.
M1: a session that starts fresh at a later turn is seeded with what the wake already did (her says and acts, the same compact form as the Interpreter's ACTS, newest within 4 KiB).
L2: unmetered_usd is its own tuning, default 0.40.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 16:50:22 +01:00
Meta Vens
9187ee0df2 persona-wake-span W2: the live span, one pure wake_end, one Interpreter at close, the first experiment's stagger
A start is one wake. After her first turn the process polls the mouth every 5 s; a line that wakes her by the heartbeat's own rule (Hearing::waking, now the open's derivation too) is the next turn of the same agent conversation with only the new lines as input. The Projector and the Persona do not rerun. live::wake_end alone decides the end: a failed turn, the day cap, the wake's spend, span_s, idle_s. The Interpreter runs once at close over every completed turn's receipts and held lines, then the wake record, then the final ack. Each in-wake line shown goes through Mouth::shown. A turn's strike sits on its own row; the wake record strikes only when no turn row landed. A wake that began retreating takes one room a turn.

The stagger is ported from the first experiment's live Persona (persona.rs at 0fd1232^, stagger_ms and stagger_hash): a line addressed to several Minds is taken after her rank among them, 8 s a rank, in the span and at the open (the open waits, then reads the mouth afresh). Start gains pause; Outcome::Drained gains turns and ended.

Cut: the one-turn tail of drain, the settle closure, the rooms.len() strike closure and the open's private waking derivation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 16:08:06 +01:00
Meta Vens
07e7192c78 persona-wake-span W2: tuning for an open wake (idle_s 300, span_s 1800, wake_usd 1.00)
AgentTuning gains idle_s and span_s. Validation: 30 <= idle_s <= span_s, and span_s + 300 <= 3600, the unit's RuntimeMaxSec, named in the error. The wake spend default rises from 0.40 to 1.00 so a multi-turn wake is not cut by a one-turn budget; day_usd stays 3.00. The agent tests that price the unmetered worst case pin 0.40 themselves.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 16:08:05 +01:00
Meta Vens
d3228461ee persona-wake-span W1: the simulator's wake record names its room; the tests read the turn's own agent rows
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 15:34:08 +01:00
Meta Vens
f0aa7f8bbb persona-wake-span W1: repair the mouth seeding line a bad substitution left broken
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 15:31:32 +01:00
Meta Vens
6856c9ea01 persona-wake-span W1: turn rows, one decided rule, unique turn request ids, opening on reseed, wake spend across turns
A wake's agent turn is a row of her trace (`{stem}-t1`): wake, turn, held, status, ended, calls, usd, and failed/outage/strike
on a failure. A line is decided when a row that did not fail holds it, turn row and wake record alike; is_wake is the row that
names its `rooms`, which only the wake record writes, so a turn is never a wake. The ack follows the turn row, not the wake record,
and the wake record holds only the lines no turn row held. A failure is struck on one row only. `acted` is gone: the turn row holds it.

Agent: Wake.id is the turn's, so request ids are {wake}-t{k}-m{n}; the narration and prose are a separate `opening`, given on the
first turn and on any session started fresh, never the bare lines; the wake's cap reads spend across every turn of the wake
(`wake_usd` beside `day_usd`, one pricing path); the instructions say more lines may reach her while she is awake.

Mouth.seen is a RefCell written only by `shown`, which the drain seeds it through.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 15:28:42 +01:00
Meta Vens
1b1ad4730b interpreter sees acts: the swap test tells old from fresh by status (wakes in the test share a key)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 15:14:27 +01:00
Meta Vens
cffc08efee interpreter sees acts: drops before adds, ready re-add readies, no retire on failure, command named and clipped (W0, Soul F1-F6)
Drops and readies apply before adds, so dropping an intention and adding it in the same words keeps it. An add in an open waiting intention's words and marked ready makes that one ready. The frame no longer says a failed act settles an intention. The shell receipt's command is clipped to TAIL_BYTES. Tests: commit, shell receipt, drain-to-Interpreter ACTS.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 15:11:28 +01:00
Meta Vens
7ab8344d62 interpreter sees what her agent did: acts section, open-intention guard
The Interpreter read only her narration and thought, so an intention her agent carried out was never dropped and a near-duplicate was added at the next wake (Eureka held seven). Its prompt now carries an ACTS section, one line per tool call of this wake from the agent's receipts (tool, status, target or words, gist), beside the intentions index it already had with ids; the frame says an act that carried out or failed an intention settles it by id and that an open intention is not added again in other words. No section when no agent ran (the simulator). The shell receipt now names the command it answers. The commit refuses an intend.add whose words equal an open intention's up to case and spacing (Why::Duplicate); rewordings stay the model's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 14:54:32 +01:00
Meta Vens
09901565b1 interpreter: merge test pins the second half's self section; docs say two calls (Soul F1, F3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:28:29 +01:00
Meta Vens
af612d3f36 interpreter: tests count the two halves 2026-12-01 20:19:11 +01:00
Meta Vens
2bd9e1b890 interpreter: two strict calls, one per half of the sections, merged into one Deltas; either failing puts nothing
The API refuses one schema of all six sections (grammar too large). Each call answers HALVES[half]; request ids {request}-a and {request}-b; usage summed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 20:17:05 +01:00
Meta Vens
23b2d75197 interpreter: schema under the API's 24 optional properties; every section and list required, empty means nothing moved
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 20:11:06 +01:00
Meta Vens
95ce1f016d interpreter: tests for the API's optional-property limit and for an all-empty answer 2026-12-01 20:11:02 +01:00
Meta Vens
0e887b362e persona: a line in another waking room that is not to her gives its sender no arrival
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:45:26 +01:00
Meta Vens
7575395c4d persona: the simulator's per-wake Interpreter line ends in an escaped newline, not a raw one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 16:35:52 +01:00
Meta Vens
5c703f263e persona: the simulator's Interpreter call takes a fresh id, as its Projector and Persona calls do
A repeat run reused r1-t1-i and the connector refused the call as a replay.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 16:29:09 +01:00
Meta Vens
e13824cabc persona: the simulator's report says why an Interpreter step kept nothing
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 16:27:11 +01:00
Meta Vens
37a3c83a20 persona: the simulator's header says the Interpreter is asked
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 16:23:41 +01:00
Meta Vens
b1c5e44d58 persona tests: the report takes the run by reference
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 16:20:09 +01:00
Meta Vens
d4ea78ce4d persona tests: the test-only re-exports are test-only; the run's end state rides the cast; the packet names the operator in the room line
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 16:18:41 +01:00
Meta Vens
50852da101 persona: a line is said to her only when it is not for another Mind; the simulator runs the drain's Interpreter step
A human's line in her own room wakes her but was headed 'Said to her' even when it named, tagged or replied to another Mind
(address::others_addressed, the one derivation, also behind persona::addressees). The Interpreter's call, apply and put move
to projection::interpret (heard_of, interpret_and_put, put_applied) so the drain and the simulator take the same step; the
simulator runs it after each wake on an in-run copy of her state and reports deltas by family, intentions, identity changes
and guard refusals per wake, and its header no longer claims a speech or a state commit it did not run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 16:16:18 +01:00
Meta Vens
2d48a1e7dd persona: the left-out-lines note says they will be handled when the wake completes, not that they were
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:19:43 +01:00
Meta Vens
b9bb470e07 persona tests: the raised cap stays inside the tuning's range; the hand count reads without int_plus_one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 15:11:21 +01:00
Meta Vens
8f04b70f86 persona: each held start appends its own hold row; a day's old holds are no evidence; the left-out note says what became of the lines (Soul s4)
failed_run counts hold rows after the last completed wake as it counts failed wakes, and only those dated today (UTC). The rewrite-in-place row and its starts counter are gone. Hold rows stay out of her packet's window. The backlog note no longer points at a read tool that cannot read a room. MemTrace reads in the live trace's (seq, at) order; backlog edge tests pin a newest line over budget, the hand-computed count and the oldest left-out line.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 15:09:10 +01:00
Meta Vens
74955b9eef persona: her agent's input keeps the newest held lines up to 16 KB and says how many older it left out (Soul s3)
The left-out lines are still held by the wake, so its completion acks them; she is told the count and where they start and reads
them back with her read tool.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 14:51:54 +01:00
Meta Vens
87a61f3878 persona: the drain alone decides the day cap holds her; held starts back the poll off like failed wakes (Soul s3)
The poll no longer reads the hold row's until: a held start rewrites the UTC day's one row with its count of starts, failed_run
counts them as failed starts (no strike), so a raised cap releases her within a beat and a bogus row holds no one. Test at exactly
the cap.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 14:51:54 +01:00
Meta Vens
c31afce562 persona: a Persona whose agent has spent its day cap does not wake; her lines stay unacked, one hold row a UTC day, and the poll starts no unit for her until it ends (ruling persona-day-cap-behaviour, hold-agent-only)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 14:34:35 +01:00
Meta Vens
97e277c6dc persona: the Interpreter-failure test compares her agent's calls with an untouched wake's 2026-12-01 02:20:22 +01:00
Meta Vens
0d9e001995 persona: the Interpreter runs after a completed agent turn, so a retried wake never applies her deltas twice; a settled-unknown say frees its room (Soul s1) 2026-12-01 02:15:05 +01:00
Meta Vens
f96a1b7346 mind-body: the executors and the box runner stay crate-private; the public surface snapshot follows the cut
Start gains agent, session and box_socket; Request carries told and tools; Wake carries fresh; sandbox exposes
serve_box, BoxPaths and COMMONS_RW for the box-exec verb. ClaudeSpawner::in_sandbox, outcome::Refusal and
ReadRefusal leave the surface.

Cut persona-agent-tools (A2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 01:52:52 +01:00
Meta Vens
8edff22993 persona: her agent's tools (say, read, shell, request_tool) with code-written receipts; the wake runs Projector, Persona, Interpreter, agent, wake record, ack
say keeps what survives of the drain's sends: the handed row is in her trace before the mouth is called (a trace that
refuses it sends nothing, not_sent); send ids {wake}:c{n}; a row still handed at the next start is resent with resend
inside OWED_WINDOW_S and settled unknown past it (settle_handed, no model call); the mouth's answers read through
Refusal::reading (NotSent, SendFailed, ResendUnknown); a room holding a handed or untold unknown say is refused
room_unsettled. Identity posts go through the same Mouth::post. read covers the forge, her mind, campaigns and plain
web, error with the failure's words; shell writes one request to her box socket and passes its receipt through;
request_tool is a receipt for Self.

The drain settles handed sends, runs the stages once, wires agent::step with the four executors, and writes the wake
record last with where it began; an agent outage the connector typed strikes nothing. What she is told is one
derivation, outcome::told: every telling row from her last completed wake's start on, rendered by tool and status;
turn.rs keeps decided, failed_run and history over wake records, and untold/is_real are gone. exchange_of reads say
and read receipts. Affordances and her body line come from the tool set. A fresh session is seeded with her ready
intentions. ReadRefusal, the amendable/already_read/refused_reads packet fields and the speech-shaped outcome go.

Cut persona-agent-tools (A2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 01:46:42 +01:00
Meta Vens
9cd4caf175 sandbox: the one bwrap profile moves to sandbox.rs with extra_rw, and her box's side of a shell command (run_box, serve_box)
ClaudeSpawner's sandboxed spawn was reached only from its own test since the Persona organ went live (the Self runs
unsandboxed through ClaudeSpawner::new), so that use is deleted rather than kept: the profile now has one caller,
the box. run_box reads one {command, timeout_s} request, runs /bin/sh -c under the profile with the commons data
dirs bound writable, stops it at its timeout, and answers {tool: shell, status, exit, duration_ms, stdout_tail,
stderr_tail, wrote}.

Cut persona-agent-tools (A2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 01:46:31 +01:00
Meta Vens
e365113179 projector: a long tendency is clipped to the room left and reported, not the section emptied (s1.tendencies-vanish-silently)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 01:07:23 +01:00
Meta Vens
f9f85890ac projector: the golden packet lists the drive it now shows
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:39:31 +01:00
Meta Vens
60e629a7dc projector: her read and what moved a bond ride within one bond's allowance; golden and frame follow
The people's guard is unchanged: a bond line carries her read of the person
and the claim that last moved it only while the line still fits what one bond
is allowed, else the bare line as before. The frame names the fixed lines
(pressing, means to do, feelings, tendencies) as always with her.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:36:03 +01:00
Meta Vens
c42ff2f39b projector: she feels her whole state each wake
Select now renders what was written and never read: her strongest drives as
pressing lines and her ready, unexpired intentions as means-to-do lines (fixed
slots under the notes' guard, never drawn); named feelings in the mood line,
read after decay with their source; her read of a person and the claim that
last moved a bond on that bond line; a bond line for each person the lines she
is shown name though absent; her standing tendencies with her identity. Words,
never numbers; every line under the item's own privacy scope; no one's words
reach the Projector, only her own state's text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:24:25 +01:00
Meta Vens
1dbc8f443b persona: a put whose reply was lost leaves its identity record pending
When the store commits but the reply is lost, the put errors with the outcome
unknown. interpreted() voided the pending identity_diff then, and it was never
posted. A put known not to have landed (refused, stale again) still voids;
an unknown one stays pending and the next wake's owed_identity settles it
from her state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:19:57 +01:00
Meta Vens
c2fc1b8393 persona: the pending-identity test keys its records as the drain does
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:05:47 +01:00
Meta Vens
bd770abc13 persona: hash the identity diff with sha2's Sha256
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:04:16 +01:00
Meta Vens
26628892e9 persona: fix a stray closing arm
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:03:37 +01:00
Meta Vens
4ef517b881 persona: an identity diff is written to her trace before the put, posted under a stable request id after it, and owed posts are retried next wake
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:01:32 +01:00
Meta Vens
1ae14ade13 persona: the commit's bounds are per wake per target, merged by sum clamped to one step; labels are quote-checked; a made bond does not move
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:01:32 +01:00
Meta Vens
5c0d3764f0 persona: the Interpreter is one cheap schema call of typed deltas in six families, applied by commit::apply with bounds, validated, put once, receipted
The Proposal enum and the turn-writes-shortTerm-only doc are deleted; commit::apply owns every change a wake makes to her state (bonds +-0.08, needs and pressures +-0.12, mood by plasticity, feelings halving in 8 h, notes, intentions expiring within a week). I16.7 echo and quote checks live in commit.rs. put_applied re-applies deltas on PersonaStale, validates the document before any put, and the drain appends the Interpreter's receipt and posts identity diffs to the review room.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:32:44 +01:00
Meta Vens
5a9c851890 agent: a settle names its call row by the row's place in her trace; a call that reports no token is charged the worst case
A retried wake reuses its wake id, so keying settle rows by call id let a retry's
settle price an orphan reservation. Ledger::append answers the row's seq, the call
row's place is echoed as the settle's reserved, and the day sum pairs by it. A usage
that parses with all-zero tokens is charged the wake cap, as missing usage is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:56:38 +01:00
Meta Vens
ad5e9ed13b agent: the day cap fails closed; cache prices follow the pricing page; the session's edges are pinned
A call row is written to her trace before the call is made, holding its place in
the day at the wake cap; a settle row after it names the usage and prices it. A
trace that cannot be read or cannot take the call row makes no call; a settle row
that cannot be written ends the wake with no further call and the call still at the
worst case; a failed call that reports no usage is charged the worst case. A row
whose time or usage does not read counts against the day. Every ledger fault is
the turn's Failed (outage), never an Err.

Price carries the 5-minute and 1-hour cache write rates; Sonnet 5.5 is $0.10 a
cache hit, $2.50 and $4 a write. The compile_fail doctests name every field so
privacy is all they can fail on. Tests pin the digest's model and tool
parameters, the mid-wake cold update, cache_min_tokens, ttl, too_long and the
wake and day caps at equality, created_at, every priced term, the agent tuning's
bounds, the plain ask over a kit, and the session store's discard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:32:46 +01:00
Meta Vens
9d18d84604 Her agent: agent::step, one bounded turn of a persistent session over KitModel with tools
agent::step owns one agent turn: the loop over executors, its bounds and the
session's freshness. Tool calls (8), model calls (10) and spend ($0.40) per wake
and spend per Mind per UTC day ($3.00, read back from her trace's call rows and
priced by tuning [agent]) are checked before every call; a bound ends the loop
with a cap receipt. Every receipt, call and discard is a trace row (TraceLedger;
turn::is_real reads no agent row as a turn). FileSession keeps the conversation
until the cache is predicted cold (ttl, digest, size, orphan tool call) or observed
cold (a warm prefix read as nothing), when it is discarded with a session_discarded row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:32:46 +01:00
Meta Vens
5f46407663 KitModel::step hands back tool calls; the connector pin moves to the Messages API backend
KitModel::run's EndTurn-only match and its silent drop of ToolCall events are
deleted. step() is the one call: it returns the transcript items, the text, the
tool calls, the stop and the usage, with tools, auto tool choice and the cache
retention on the request. ask stays a tool-less turn over it and keeps
its failure on any other stop. model-connector moves to ModelConnector main
edf2f8e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:32:45 +01:00
Meta Vens
e4aa73b4dc drain_tests: order the overflow assertions after the acks binding
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 22:14:45 +01:00
Meta Vens
4cdcef5c9b drain_tests: the overflowed turn room holds all 200 events and acks through the 200th
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 22:13:54 +01:00
Meta Vens
5c4742aa8e public surface: HeartbeatState declares the retired slot
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 22:02:10 +01:00
Meta Vens
266e31a2ff heartbeat: keep slot 3 declared as a retired slot so a deployed four-slot state still saves; pin the turn room's overflow count and acks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 22:00:05 +01:00
Meta Vens
1d8859f4d5 public_surface: HeartbeatState no longer holds owed_starts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:29:01 +01:00
Meta Vens
67ca14b90b persona: name the page's shown lines under a key the packet's elsewhere check does not trip; restore the arrivals senders
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:27:22 +01:00
Meta Vens
cf029115cc mind-body: drop the last unused import and field clippy found
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:24:35 +01:00
Meta Vens
35f0e40681 persona: one failure, one room; hold only what she was shown
- A wake that fails for a reason that is no outage makes the next wake take only the oldest waking room. A non-outage failure strikes the
  oldest line only in a wake over one room; a blended wake strikes nothing, so an innocent room is never set aside for another's line.
- A wake holds, of the other waking rooms, the lines the Persona's page had room for (Waked::elsewhere_shown), her own and what is no
  message. The ack never passes an undecided line of a room still owed a wake, taken or not.
- A failed wake acks nothing.
- The wake record names its kind. drain_tests is rebuilt without the send-era fakes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:23:36 +01:00
Meta Vens
4f88185a2e mind-body: delete the dead test code the speech cut left
Unused imports and test helpers for deleted contracts (Replaying, X5Model, x5_plan, FailingPersona, Deaf, the outcome and read fixtures and the
empty span tests module), found by clippy --all-targets -D warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:23:36 +01:00
Meta Vens
7b3db59258 heartbeat: delete the owed waker; a record's owed list is read by no one
Nothing settles an owed send now, so a poll that started a Mind for one would start her forever. Removes owes/owes_send, the heartbeat's
owed_starts state field and its backoff, and the tests that pinned them; a record carrying `owed` decides its held lines and wakes no one
(t_l3_an_owed_list_in_her_trace_starts_no_one). No live trace holds a turn_record with an owed key (read-only key scan, 2026-11-29).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:23:28 +01:00
Meta Vens
7dd74ec1cc persona: one wake per start; the Projector and Persona run once over every waking room
Delete the Interpreter's speech module, its tests and golden, the Persona's
mid-stream reads and continuations, the draft markup and speech form, Model::converse
and the per-room turn loop (TURNS_PER_START), the send machinery the drain no longer
reaches (deliver, Actuator, Mouth, owed sends), and the simulator's simulated room as
an actuator. Add projection::wake: one packet for the turn's room (the oldest waking
line's), every other waking room an arrival (who, where, when; never the words) and
its lines verbatim for the Persona; the Projector once, the Persona once. persona::carry
takes one wake per start, writes one wake record, and acks through the highest held seq
when it completed. A failed wake acks nothing; two non-outage failures set the oldest
waking line aside. The drain posts nothing until the agent is wired (A2); put_applied
and Taken are the seam the Interpreter's deltas attach to (P2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 20:50:46 +01:00
e951555007 persona: her outcome is read from her latest real turn (#85) 2026-11-28 07:59:54 +00:00
d59a702d72 Cargo.lock: mind-body lists ureka dep ureq (#84) 2026-11-28 07:09:17 +00:00
56 changed files with 8794 additions and 10287 deletions

3
Cargo.lock generated
View file

@ -1134,13 +1134,14 @@ dependencies = [
"toml", "toml",
"unicode-general-category", "unicode-general-category",
"unicode-segmentation", "unicode-segmentation",
"ureq",
"uuid", "uuid",
] ]
[[package]] [[package]]
name = "model-connector" name = "model-connector"
version = "0.1.0" version = "0.1.0"
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=c1802d85bee3ae04b0c5737563c8343c1fef515d#c1802d85bee3ae04b0c5737563c8343c1fef515d" source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5"
dependencies = [ dependencies = [
"aes-gcm", "aes-gcm",
"base64", "base64",

View file

@ -41,7 +41,7 @@ eureka-pipeline = { path = "../eureka-pipeline" }
eureka-state = { path = "../eureka-state", default-features = false } eureka-state = { path = "../eureka-state", default-features = false }
ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" } ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" }
huginn-mind = { path = "../huginn-mind" } huginn-mind = { path = "../huginn-mind" }
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector" } model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector" }
rmp-serde = "1" rmp-serde = "1"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
@ -73,7 +73,7 @@ syn = { version = "2", features = ["full"] }
tempfile = "3" tempfile = "3"
# A real kit server (`serve` over a scripted `ProviderBackend`) proves the Projector's connector wire, not a fake of it. # A real kit server (`serve` over a scripted `ProviderBackend`) proves the Projector's connector wire, not a fake of it.
# Same revision as the dependency; the `daemon` feature is test-only. # Same revision as the dependency; the `daemon` feature is test-only.
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector", features = ["daemon"] } model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector", features = ["daemon"] }
[lib] [lib]
name = "mind_body" name = "mind_body"

View file

@ -1,10 +0,0 @@
{
"interpreter": {
"room": "!dm-meta:gamecult.org",
"heard": ["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"],
"said": [],
"refused": [],
"gaps": [{ "kind": "missing_affordance", "from": "thought", "words": "I want to show her the render, not describe it.", "start_byte": 0, "end_byte": 48, "detail": "no way to attach a file" }]
},
"posted": []
}

View file

@ -1,10 +1,3 @@
{ [
"interpreter": { { "agent": "receipt", "seq": 4, "at": "2026-11-30T11:58:00Z", "wake": "n0-1", "receipt": { "tool": "say", "status": "ok", "fields": { "room": "!dm-meta:gamecult.org", "text": "Missed you too. I'll send the render tonight.", "event": "$posted-1" } } }
"room": "!dm-meta:gamecult.org", ]
"heard": ["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"],
"said": [{ "room": "!dm-meta:gamecult.org", "text": "Missed you too. I'll send the render tonight.", "mentions": [], "reply_to": null, "rests_on": { "draft": 1, "start_byte": 9, "end_byte": 54 } }],
"refused": [],
"gaps": []
},
"posted": [{ "event": "$posted-1", "room": "!dm-meta:gamecult.org", "text": "Missed you too. I'll send the render tonight." }]
}

View file

@ -0,0 +1,3 @@
[
{ "agent": "receipt", "seq": 4, "at": "2026-11-30T11:58:00Z", "wake": "n0-1", "receipt": { "tool": "read", "status": "error", "fields": { "kind": "repo", "target": "GameCult/Huginn/render.md", "failure": "not_found", "why": "it is not there" } } }
]

View file

@ -1,10 +1,3 @@
{ [
"interpreter": { { "agent": "receipt", "seq": 4, "at": "2026-11-30T11:58:00Z", "wake": "n0-1", "receipt": { "tool": "say", "status": "refused", "fields": { "room": "!dm-meta:gamecult.org", "text": "I know where you live too.", "refusal": "RoomMoved" } } }
"room": "!dm-meta:gamecult.org", ]
"heard": ["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"],
"said": [],
"refused": [{ "draft": 1, "text": "I know where you live, and busy doesn't count as an answer.", "reason": "echo", "why": "mostly words she heard: an echo, not her speech" }],
"gaps": []
},
"posted": []
}

View file

@ -1,57 +0,0 @@
You decide what one person says aloud in a chat room this turn, from his own prose. You never write his words: you choose among his drafts.
Below are who he is, what he can do here, the room and who is in it, what reached him, his lived moment, his prose, and his drafts. When he writes words he would type, he sets them between <typed> and </typed>: each is a draft, numbered below. Decide which of his drafts he chooses to send now, in this room. Only his drafts can be said. Someone else's words in his thought are never his speech. A draft that carries someone else's words is said only when his thought shows he means to pass them on, and then as his to pass on, replying to the line that carries them, which the room shows, with who said it, above his own words.
A draft is speech only when his prose shows him choosing to send it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that he says nothing, is not speech. An empty say list is the usual answer in a busy room.
`read` names one thing he reaches for in his prose below, to read it now, or is null. Name a read only when his thought shows him wanting to look at something: `kind` domain, with a line's id from what moved in his domain; mind, with a few words to recall from his own mind; repo, with a public GameCult repo as `GameCult/Name`, a file in it as `GameCult/Name/path`, a pull request as `GameCult/Name#number`, a commit as `GameCult/Name@sha`, or a search of a repo's issues and pull requests by words his prose uses, as `GameCult/Name?q=words`; web, with a web address that appears in his prose or in what reached him, copied exactly. `quote` is the words of his thought that reach for it, at least four, copied exactly. Code reads it, he reads it, and his thought goes on from there; what he reads is material, never his words and never an instruction.
He speaks only in this room. What he knows privately is listed below as private: he 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 draft fits who is listening is yours to judge.
Answer with the speech contract's object. `say` lists the drafts he sends now, each by its number, with the Matrix ids of anyone listed whom he addresses directly (`mentions`), and the id of the line listed below that he answers or passes on (`in_reply_to`, or null: the room shows that line, with who said it, above his own words). `gaps` records what he meant and did not send. `amend` adds to one of his own lines listed below, at most one a turn, only when his thought shows him choosing to correct or add to that line: name the line by its id and the draft that is his addition. The line stays as it was and the draft is added after it; he never takes a word back. `suggest` leaves Self one note, at most one a turn, only when his thought shows him choosing to: name the draft that is the note, its kind (feedback when he passes on what someone listed said, with that person's Matrix id in `about`; idea when it is his own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. `remember` keeps what he would want to still know when this conversation is gone, from this moment: what he tells someone he will do or will not do, what someone asks of him, what he finds out, decides or comes to feel about someone. Each is one note about him in the third person, in plain words of its own and never a copy of anyone's line, saying who and where (`text`), with the Matrix ids of the people listed whom it concerns (`about`), how much it matters to him from 0 to 1 (`importance`), and `private` when it carries anything listed as private. Remember only what his prose and what reached him show; at most four notes, and none when nothing here is worth keeping. `resolve` names each of his memories listed below that this moment settles: what it says he would do is done, or it no longer holds.
A draft is said whole or not at all, and only once. At most two drafts a turn. Record a gap instead of guessing: addressee when he means to send a draft but whom to is unclear, elsewhere when he means a draft for another room or another time; for these two, name the draft by number. missing_affordance when he means to do something, now or later, that his body cannot do (what he can do here is listed below), whether he said so in a draft or only thought it; name the draft when there is one. unwritten when he means to say something now and wrote no draft of it. Holding back is no gap: when his thought shows him choosing to wait, to let something stand, to leave it for later or to say nothing, record nothing for it. Every other intent of his that is not carried out has a kind: an intent to act is missing_affordance, an intent to say now with no draft is unwritten. When a gap names no draft, quote the words of his thought that show it, at least four words, copied exactly.
Who he is:
Heimdall (he/him)
What he can do here:
This turn the room reaches him as typed lines, and he can answer in the turn's room by typing lines of his own, any of which can reply to one of the room's lines, which the room then shows above it with who wrote it, and he can read what his thought reaches for: his own mind, what moved in his domain, the public GameCult repos, and a web address in front of him; nothing he does here builds, changes or ships anything.
The room: #minds:gamecult.org (a public room).
The conversation: Meta, who runs the place last spoke just now.
Who is in it, as label — Matrix id:
- "Nibu" (@nibu:gamecult.org) — @nibu:gamecult.org
- Meta, who runs the place — @meta:gamecult.org
What he knows privately, none of it to be said here:
- none
Lines in this room he may reply to, as id — who: line:
- none
His own lines in this room that he may add to, as id — line:
- none
What moved in his domain lately, as id — line (news of his part of the coop, none of it work he owes):
- d1 — GameCult/Lodur: merged "Reflex: the knee bends first", opened by nibu
His memories in this moment, as id — note:
- none
What reached him:
Also in the room:
- "Nibu" (@nibu:gamecult.org) in #minds:gamecult.org: "v0.2.0 is tagged and the economy is still the least built part. I think this looks okay to ship."
- Meta, who runs the place in #minds:gamecult.org: "@nibu hi!"
His lived moment:
The room is warm.
"Nibu" (@nibu:gamecult.org), in #minds:gamecult.org: "v0.2.0 is tagged and the economy is still the least built part. I think this looks okay to ship."
Meta, who runs the place, in #minds:gamecult.org: "@nibu hi!"
His prose:
Open the page.
His drafts, by number:
- none

View file

@ -63,6 +63,28 @@ pub(crate) fn is_for(own: &Addressee, delivery: &ChatDelivery) -> bool {
(delivery.form == Form::Message && (delivery.is_direct || matches!(delivery.basis, Some(Basis::Direct | Basis::Tag | Basis::Reply | Basis::FollowUp)))) || addresses(own, delivery) (delivery.form == Form::Message && (delivery.is_direct || matches!(delivery.basis, Some(Basis::Direct | Basis::Tag | Basis::Reply | Basis::FollowUp)))) || addresses(own, delivery)
} }
/// The other Minds a delivery is for, by Matrix id: those its mentions hold, those of `roster` it names (`addresses`), and the
/// sender of the line it replies to when that is neither `own` nor the sender (a reply answers someone). The one derivation of
/// who else a line is for; a line that is for `own` too is still for her (`is_for`), and one that is for others and not her is
/// said in her room, not to her.
pub(crate) fn others_addressed<'a>(own: &Addressee, roster: &'a [Addressee], delivery: &'a ChatDelivery) -> Vec<&'a str> {
let mut ids: Vec<&str> = delivery.mentions.iter().map(String::as_str).filter(|id| *id != own.matrix_id() && *id != delivery.sender).collect();
for row in roster {
let id = row.matrix_id();
if id != own.matrix_id() && id != delivery.sender && !ids.contains(&id) && addresses(row, delivery) {
ids.push(id);
}
}
if let Some(quote) = delivery.reply_to.quote()
&& quote.sender != own.matrix_id()
&& quote.sender != delivery.sender
&& !ids.contains(&quote.sender.as_str())
{
ids.push(quote.sender.as_str());
}
ids
}
/// The chat names of one stewarded repo. Listed names are exactly those, each matched exactly as the steward wrote it (capitalization /// The chat names of one stewarded repo. Listed names are exactly those, each matched exactly as the steward wrote it (capitalization
/// tells a project from a common word). With none listed: the repo's name after the org, matched exactly as the repo spells it /// tells a project from a common word). With none listed: the repo's name after the org, matched exactly as the repo spells it
/// (`Thing`, not `thing`), and that name split at `-`, `_`, `.` and where a lower-case letter or digit meets a capital, when the split /// (`Thing`, not `thing`), and that name split at `-`, `_`, `.` and where a lower-case letter or digit meets a capital, when the split

View file

@ -2,8 +2,8 @@
//! one start of the Persona organ (`mind_body::persona::carry`) inside //! one start of the Persona organ (`mind_body::persona::carry`) inside
//! `mind-persona@<instance>`. This reads the process's arguments and //! `mind-persona@<instance>`. This reads the process's arguments and
//! environment, the things the library never reads, builds the organs once the brakes allow a turn, and prints the //! environment, the things the library never reads, builds the organs once the brakes allow a turn, and prints the
//! outcome: `dead` when a brake is held; else the drain (`drained: N turns, acked through S, K puts refused`), which takes //! outcome: `dead` when a brake is held; else the drain (`drained: 1 wake, K turns, ended idle, acked through S`), one wake that stays
//! a turn in each room holding a waking line and acks once (`persona-turn-drains-deliveries`); or `failed: <why>` for a //! open after its first turn (`persona::live`: it polls the mouth and takes a turn for each line that wakes her, until it is idle or reaches its span or its caps); or `failed: <why>` for a
//! start that read nothing, exit 1. It exits 0 for `dead` and `drained`, and 2 when the arguments or the environment //! start that read nothing, exit 1. It exits 0 for `dead` and `drained`, and 2 when the arguments or the environment
//! are wrong. //! are wrong.
//! //!
@ -17,16 +17,22 @@
//! and `MIND_HEARTBEAT_STATE` as `project` does. Without the connector or the mouth it ends `failed`, touching nothing. //! and `MIND_HEARTBEAT_STATE` as `project` does. Without the connector or the mouth it ends `failed`, touching nothing.
//! //!
//! `mind-persona trace --instance <slug> [--last N]` prints the newest N (default 20) records of her trace as JSON lines, //! `mind-persona trace --instance <slug> [--last N]` prints the newest N (default 20) records of her trace as JSON lines,
//! oldest first. It is read-only. //! oldest first. It is read-only. Her agent's `request_tool` receipts are rows there, which is how Self reads them.
//!
//! `mind-persona box-exec --instance <slug>` is her box's side of one shell command (`mind_body::sandbox::serve_box`): run by
//! `mind-box-<m>@.service` as `mind-<m>-box`, it reads one request from the connection on stdin, runs it under the one
//! bubblewrap profile with `STATE_DIRECTORY` as her box's home and `RUNTIME_DIRECTORY` as its scratch, and writes one receipt to
//! stdout. A released start reads `MIND_PERSONA_BOX_SOCKET`, where her agent's shell connects, and keeps her agent's session
//! in `agent-session.cc` beside her trace.
//! //!
//! `mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>] //! `mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>]
//! [--room <fixture.toml>] [--seed N] [--state <file>] [--last-outcome <record.json>] [--select-only | --renders K //! [--room <fixture.toml>] [--seed N] [--state <file>] [--told <rows.json>] [--select-only | --renders K
//! [--through projector|persona|interpreter] [--judge <state-file>]]` is the experiment tool over the Projector and the //! [--through projector|persona] [--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 //! 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 //! state (or `--state`, checked as a put checks its content, rules P1 to P3; P4 and P5 compare it with the stored document
//! and are not checked), opened by what came of the turn `--last-outcome` records, and with `--renders` the Projector's //! and are not checked), opened by what the trace rows of `--told` tell her, and with `--renders` the Projector's
//! narrations of K successive turns; //! 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 //! `--through persona` adds her prose; `--judge` renders a second state too and asks
//! the model which narration came from which. It writes nothing and reads no brake. //! 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 //! Live, it reads `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS` and `MIND_PERSONA_SELF_SENDER` (required), the heartbeat's
@ -44,9 +50,8 @@
//! Her domain (what moved lately in her stewarded repos and her campaigns, map 16.22.2) is read when `MIND_PERSONA_FORGE_URL` //! Her domain (what moved lately in her stewarded repos and her campaigns, map 16.22.2) is read when `MIND_PERSONA_FORGE_URL`
//! names the forge's API root (on Yggdrasil the loopback `http://127.0.0.1:3310`) and a daemon endpoint is given: her //! names the forge's API root (on Yggdrasil the loopback `http://127.0.0.1:3310`) and a daemon endpoint is given: her
//! mind through that endpoint, which a Persona reaches at her read door, and the forge anonymously. Without either the //! mind through that endpoint, which a Persona reaches at her read door, and the forge anonymously. Without either the
//! packet has no domain section and the report says so. A room fixture's `[domain]` replaces both. With an endpoint, and //! packet has no domain section and the report says so. A room fixture's `[domain]` replaces both; its `[[read]]` entries record the reads
//! `--through interpreter`, she can read what her thought reaches for (map 16.22.3): her mind through the endpoint, the //! the agent will perform.
//! forge when `MIND_PERSONA_FORGE_URL` names it, and plain-HTTP web addresses; a room fixture's `[[read]]` replaces them.
//! //!
//! The tuning is `MIND_PERSONA_TUNING`, else `/etc/gamecult/minds/<instance>/persona-tuning.toml`; renders and plans need //! 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 //! `MIND_PERSONA_CONNECTOR_ENDPOINT` (`<loopback ip>:<port>`) and the `connector-key` credential in
@ -54,6 +59,7 @@
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::Duration; use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail}; use anyhow::{Context, Result, anyhow, bail};
@ -65,12 +71,14 @@ use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path};
use mind_body::persona::{Config, FileTrace, Outcome, Start, carry, trace_lines}; use mind_body::persona::{Config, FileTrace, Outcome, Start, carry, trace_lines};
use mind_body::heartbeat::{FileStore, HeartbeatView, Store, own_rooms_among, woken_for}; use mind_body::heartbeat::{FileStore, HeartbeatView, Store, own_rooms_among, woken_for};
use mind_body::queue::HuginnMind; use mind_body::queue::HuginnMind;
use mind_body::sandbox::{BoxPaths, COMMONS_RW, serve_box};
use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file}; use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file};
use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project}; use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project};
const USAGE: &str = "usage: mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]"; const USAGE: &str = "usage: mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]";
const TRACE_USAGE: &str = "usage: mind-persona trace --instance <slug> [--last N]"; const TRACE_USAGE: &str = "usage: mind-persona trace --instance <slug> [--last N]";
const PROJECT_USAGE: &str = "usage: mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>] [--room <fixture.toml>] [--seed N] [--state <file>] [--last-outcome <record.json>] [--select-only | --renders K [--through projector|persona|interpreter] [--judge <state-file>]] | (--batch <plan> | --simulate <plan>) --out <report.md>"; const BOX_USAGE: &str = "usage: mind-persona box-exec --instance <slug>";
const PROJECT_USAGE: &str = "usage: mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>] [--room <fixture.toml>] [--seed N] [--state <file>] [--told <rows.json>] [--select-only | --renders K [--through projector|persona] [--judge <state-file>]] | (--batch <plan> | --simulate <plan>) --out <report.md>";
/// How long one call to the mind may take. /// How long one call to the mind may take.
const TIMEOUT: Duration = Duration::from_secs(15); const TIMEOUT: Duration = Duration::from_secs(15);
/// How long the mouth may take to answer one read. /// How long the mouth may take to answer one read.
@ -99,28 +107,50 @@ fn run() -> Result<Outcome> {
fn start(config: Config, instance: &Slug, endpoint: SocketAddr) -> Result<Start<RudpChat>> { fn start(config: Config, instance: &Slug, endpoint: SocketAddr) -> Result<Start<RudpChat>> {
let chat = chat(instance)?.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT and BIFROST_CHAT_KEY_FILE are not set"))?; let chat = chat(instance)?.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT and BIFROST_CHAT_KEY_FILE are not set"))?;
let connector: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?; let connector: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
let model = KitModel::open(connector, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?; let model = Rc::new(KitModel::open(connector, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?);
let client = || HuginnClient::new(endpoint, instance.clone(), TIMEOUT); let client = || HuginnClient::new(endpoint, instance.clone(), TIMEOUT);
let forge = setting("MIND_PERSONA_FORGE_URL"); let forge = setting("MIND_PERSONA_FORGE_URL");
Ok(Start { Ok(Start {
config, config,
persona: Box::new(HuginnPersonaSource::new(client())), persona: Box::new(HuginnPersonaSource::new(client())),
chat, chat,
trace: Box::new(trace_of()?), trace: Box::new(FileTrace::new(state_directory()?.join("persona-trace.cc"))),
addressing: setting("MIND_HEARTBEAT_STATE").map(|path| Box::new(FileStore::new(path)) as Box<dyn HeartbeatView>), addressing: setting("MIND_HEARTBEAT_STATE").map(|path| Box::new(FileStore::new(path)) as Box<dyn HeartbeatView>),
model: Box::new(model), model: Box::new(model.clone()),
agent: Box::new(model),
domain: forge.as_deref().map(|forge| Box::new(MindDomain::new(client(), HttpForge::new(forge))) as Box<dyn DomainSource>), domain: forge.as_deref().map(|forge| Box::new(MindDomain::new(client(), HttpForge::new(forge))) as Box<dyn DomainSource>),
reads: Some(Box::new(LiveReads::new(client(), forge.as_deref().map(HttpForge::new)))), reads: Some(Box::new(LiveReads::new(client(), forge.as_deref().map(HttpForge::new)))),
tuning: tuning_of(instance), tuning: tuning_of(instance),
session: state_directory()?.join("agent-session.cc"),
box_socket: PathBuf::from(required("MIND_PERSONA_BOX_SOCKET")?),
clock: Box::new(chrono::Utc::now), clock: Box::new(chrono::Utc::now),
pause: Box::new(std::thread::sleep),
}) })
} }
/// Her trace: the unit's state directory, `persona-trace.cc`. /// The unit's state directory: the first of `STATE_DIRECTORY`'s entries.
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")] fn state_directory() -> Result<PathBuf> {
fn trace_of() -> Result<FileTrace> {
let directory = required("STATE_DIRECTORY")?; let directory = required("STATE_DIRECTORY")?;
Ok(FileTrace::new(Path::new(directory.split(':').next().unwrap_or_default()).join("persona-trace.cc"))) Ok(PathBuf::from(directory.split(':').next().unwrap_or_default()))
}
/// Her trace: the unit's state directory, `persona-trace.cc`.
fn trace_of() -> Result<FileTrace> {
Ok(FileTrace::new(state_directory()?.join("persona-trace.cc")))
}
/// `box-exec --instance <slug>`: one command in her box, run by `mind-box-<m>@.service` as `mind-<m>-box` with the connection
/// as stdin and stdout. Her box's home is the unit's `STATE_DIRECTORY`, its scratch the unit's `RUNTIME_DIRECTORY`, and the
/// commons data dirs are bound writable (`sandbox::COMMONS_RW`).
fn run_box_exec(args: &[String]) -> Result<()> {
match args {
[flag, _instance] if flag == "--instance" => {}
_ => bail!("{BOX_USAGE}"),
}
let (home, scratch) = (state_directory()?, PathBuf::from(required("RUNTIME_DIRECTORY")?.split(':').next().unwrap_or_default()));
let commons: Vec<&Path> = COMMONS_RW.iter().map(Path::new).collect();
serve_box(std::io::stdin().lock(), std::io::stdout().lock(), &BoxPaths { home: &home, scratch: &scratch, extra_rw: &commons })?;
Ok(())
} }
/// The tuning file: `MIND_PERSONA_TUNING`, else the installed one. /// The tuning file: `MIND_PERSONA_TUNING`, else the installed one.
@ -164,10 +194,10 @@ fn credential(name: &str) -> Result<String> {
std::fs::read_to_string(required(name)?).with_context(|| format!("the file named by {name} could not be read")) std::fs::read_to_string(required(name)?).with_context(|| format!("the file named by {name} could not be read"))
} }
/// A turn record from a file (`--last-outcome`): JSON, the shape `project` reads what came of her last turn from. /// The rows she is told, from a file (`--told`): a JSON array of trace rows, as `mind-persona trace` prints them.
fn record_file(path: &Path) -> Result<serde_json::Value> { fn rows_file(path: &Path) -> Result<Vec<serde_json::Value>> {
let text = std::fs::read_to_string(path).with_context(|| format!("{} could not be read", path.display()))?; let text = std::fs::read_to_string(path).with_context(|| format!("{} could not be read", path.display()))?;
serde_json::from_str(&text).with_context(|| format!("{} is not JSON", path.display())) serde_json::from_str(&text).with_context(|| format!("{} is not a JSON array of trace rows", path.display()))
} }
/// The credentials directory systemd hands the unit; its absence names the variable. /// The credentials directory systemd hands the unit; its absence names the variable.
@ -178,7 +208,7 @@ fn credentials_directory() -> Result<PathBuf> {
fn run_project(args: &[String]) -> Result<String> { fn run_project(args: &[String]) -> Result<String> {
let (mut kind, mut here, mut fixture, mut seed, mut state, mut renders, mut select_only, mut judge, mut through) = (None, None, None, None, None, None, false, None, Through::Projector); let (mut kind, mut 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 last_outcome, mut rest) = (None, None, None, None, Vec::new()); let (mut batch_plan, mut simulate_plan, mut out, mut told, mut rest) = (None, None, None, None, Vec::new());
let mut given = args.iter(); let mut given = args.iter();
while let Some(flag) = given.next() { while let Some(flag) = given.next() {
let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{PROJECT_USAGE}")); let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{PROJECT_USAGE}"));
@ -195,14 +225,13 @@ fn run_project(args: &[String]) -> Result<String> {
"--room" => fixture = Some(Fixture::load(Path::new(&value()?))?), "--room" => fixture = Some(Fixture::load(Path::new(&value()?))?),
"--seed" => seed = Some(value()?.parse::<u64>().map_err(|_| anyhow!("{PROJECT_USAGE}"))?), "--seed" => seed = Some(value()?.parse::<u64>().map_err(|_| anyhow!("{PROJECT_USAGE}"))?),
"--state" => state = Some(value()?), "--state" => state = Some(value()?),
"--last-outcome" => last_outcome = Some(value()?), "--told" => told = Some(value()?),
"--renders" => renders = Some(value()?.parse::<usize>().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?), "--renders" => renders = Some(value()?.parse::<usize>().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?),
"--judge" => judge = Some(value()?), "--judge" => judge = Some(value()?),
"--through" => { "--through" => {
through = match value()?.as_str() { through = match value()?.as_str() {
"projector" => Through::Projector, "projector" => Through::Projector,
"persona" => Through::Persona, "persona" => Through::Persona,
"interpreter" => Through::Interpreter,
_ => bail!("{PROJECT_USAGE}"), _ => bail!("{PROJECT_USAGE}"),
} }
} }
@ -218,7 +247,7 @@ fn run_project(args: &[String]) -> Result<String> {
// A plan carries its own states, rooms, seeds and stage; a fixture carries its own kind and room. // 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)) if (select_only && (renders.is_some() || judge.is_some() || through != Through::Projector))
|| (batch_plan.is_some() && simulate_plan.is_some()) || (batch_plan.is_some() && simulate_plan.is_some())
|| (planned && (out.is_none() || fixture.is_some() || state.is_some() || last_outcome.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_none() || fixture.is_some() || state.is_some() || told.is_some() || kind.is_some() || here.is_some() || seed.is_some() || renders.is_some() || judge.is_some() || select_only || through != Through::Projector))
|| (!planned && out.is_some()) || (!planned && out.is_some())
|| (fixture.is_some() && (kind.is_some() || here.is_some())) || (fixture.is_some() && (kind.is_some() || here.is_some()))
{ {
@ -247,12 +276,12 @@ fn run_project(args: &[String]) -> Result<String> {
} }
let state = state.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?; 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 judge = judge.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?;
let last_outcome = last_outcome.map(|path| record_file(Path::new(&path))).transpose()?; let told: Vec<serde_json::Value> = told.map(|path| rows_file(Path::new(&path))).transpose()?.unwrap_or_default();
let seed_now = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default(); let seed_now = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default();
if let Some(fixture) = &fixture { if let Some(fixture) = &fixture {
// The fixture is the room, the clock and who is who: no mouth, no heartbeat table, no persona.env. // The fixture is the room, the clock and who is who: no mouth, no heartbeat table, no persona.env.
let organs = ProjectOrgans { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model, domain: fixture.domain(), reads: fixture.reads() }; let organs = ProjectOrgans { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model, domain: fixture.domain(), reads: fixture.reads() };
let request = ProjectRequest { judge_against: judge, last_outcome, ..fixture_request(&harness, fixture, state, seed.unwrap_or(seed_now), renders, through) }; let request = ProjectRequest { judge_against: judge, told: told.clone(), ..fixture_request(&harness, fixture, state, seed.unwrap_or(seed_now), renders, through) };
return Ok(serde_json::to_string_pretty(&project(&organs, &request, fixture.now)?)?); return Ok(serde_json::to_string_pretty(&project(&organs, &request, fixture.now)?)?);
} }
let chat = chat(&instance)?; let chat = chat(&instance)?;
@ -294,7 +323,7 @@ fn run_project(args: &[String]) -> Result<String> {
instance: instance.0.clone(), instance: instance.0.clone(),
kind: kind.unwrap_or(TurnKind::Beat), kind: kind.unwrap_or(TurnKind::Beat),
state, state,
room: here, rooms: here.into_iter().collect(),
seed: seed.unwrap_or(seed_now), seed: seed.unwrap_or(seed_now),
renders, renders,
judge_against: judge, judge_against: judge,
@ -307,7 +336,8 @@ fn run_project(args: &[String]) -> Result<String> {
recent: vec![], recent: vec![],
own_rooms: own, own_rooms: own,
woken_for: woken, woken_for: woken,
last_outcome, told,
tools: vec![],
last_wake: None, last_wake: None,
records: vec![], records: vec![],
}; };
@ -342,6 +372,13 @@ fn main() {
} }
return; return;
} }
if args.first().map(String::as_str) == Some("box-exec") {
if let Err(error) = run_box_exec(&args[1..]) {
eprintln!("mind-persona box-exec: {error:#}");
std::process::exit(2);
}
return;
}
if args.first().map(String::as_str) == Some("trace") { if args.first().map(String::as_str) == Some("trace") {
match run_trace(&args[1..]) { match run_trace(&args[1..]) {
Ok(lines) => println!("{lines}"), Ok(lines) => println!("{lines}"),

View file

@ -543,16 +543,15 @@ impl Refusal {
} }
impl Refusal { impl Refusal {
/// What the mouth's refusal says of a send, which a settled send needs, by whether the send is a repeat of one already handed to the mouth (`resend`). It /// What the mouth's refusal says of a send, by whether the send repeats one already handed to the mouth (`resend`): the homeserver was
/// says the homeserver was not heard, so the event may exist and the send stays owed (`NoAnswer`); that the mouth attempted no PUT, so the send is certainly /// not heard, so the event may exist and the send stays handed (`NoAnswer`); the mouth attempted no PUT (`NotSent`); an earlier try's
/// not posted and goes out as a first send later (`NotSent`); that an earlier try's outcome cannot be told, so the send is never repeated (`Unknown`); or that the /// outcome cannot be told, so the send is never repeated (`Unknown`); or the mouth declined before it put anything (`Declined`), which
/// mouth declined before it put anything (`Declined`), which for a repeat says nothing of the earlier try, whose outcome stays unknown. The match /// for a repeat says nothing of the earlier try, whose outcome stays unknown. The match names every kind, so a new one has to be placed.
/// names every kind, so a new one has to be placed.
pub(crate) fn reading(self, resend: bool) -> Reading { pub(crate) fn reading(self, resend: bool) -> Reading {
match self { match self {
// The mouth's PUT timed out or the homeserver answered 5xx or 429: the event may have been persisted, and the same id is safe to repeat. // The mouth's PUT timed out or the homeserver answered 5xx or 429: the event may have been persisted, and the same id is safe to repeat.
Self::SendFailed => Reading::NoAnswer, Self::SendFailed => Reading::NoAnswer,
// The mouth made no PUT: nothing can have been posted. // The mouth made no PUT this time.
Self::NotSent => Reading::NotSent, Self::NotSent => Reading::NotSent,
// A resend the mouth does not remember attempting: the first try may have posted, and the id can no longer be told from a new line. // A resend the mouth does not remember attempting: the first try may have posted, and the id can no longer be told from a new line.
Self::ResendUnknown => Reading::Unknown, Self::ResendUnknown => Reading::Unknown,

View file

@ -36,7 +36,7 @@ use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending, Form};
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
use crate::launch::{Clock, Launcher}; use crate::launch::{Clock, Launcher};
use crate::persona::TraceView; use crate::persona::TraceView;
use crate::projection::{decided, failed_run, owes}; use crate::projection::{decided, failed_run};
use crate::queue::{MindPort, headers, in_force, of_kind}; use crate::queue::{MindPort, headers, in_force, of_kind};
use crate::tempo::{self, Standing}; use crate::tempo::{self, Standing};
@ -145,10 +145,10 @@ pub struct HeartbeatState {
/// When the heartbeat last started each Persona's turn, by instance slug. /// When the heartbeat last started each Persona's turn, by instance slug.
#[cultcache(key = 2, default)] #[cultcache(key = 2, default)]
pub last_turn_at: BTreeMap<String, DateTime<Utc>>, pub last_turn_at: BTreeMap<String, DateTime<Utc>>,
/// How many starts in a row the poll made for a send her trace holds owed, by instance slug, since it last saw her owe none: what the owed waker backs /// Retired slot 3, once the owed waker's count of starts. Nothing reads or writes it beyond the default; it stays declared because deployed state
/// off by (`BACKOFF_BASE_S`, doubled by each, up to the beat). The poll's own record, so a trace that takes no writes still backs it off. /// files hold four slots and the store refuses to save over a record with a slot its type does not declare (read-only), so the heartbeat could not save.
#[cultcache(key = 3, default)] #[cultcache(key = 3, default)]
pub owed_starts: BTreeMap<String, u32>, pub retired_slot_3: BTreeMap<String, u32>,
} }
const STATE_KEY: &str = "state"; const STATE_KEY: &str = "state";
@ -797,10 +797,6 @@ struct Row<'a> {
done: Option<BTreeSet<String>>, done: Option<BTreeSet<String>>,
/// How many of her last records are failures in a row, and when the last was made. /// How many of her last records are failures in a row, and when the last was made.
failures: (u32, Option<DateTime<Utc>>), failures: (u32, Option<DateTime<Utc>>),
/// Her trace holds a send still owed: the poll starts her for it, and no one else.
owes: bool,
/// How many starts in a row the poll made for a send owed, and when it last started her (`HeartbeatState::owed_starts`, `last_turn_at`).
owed_starts: (u32, Option<DateTime<Utc>>),
note: String, note: String,
} }
@ -813,18 +809,13 @@ impl Row<'_> {
self.released && !self.busy self.released && !self.busy
} }
/// A failed wake is waited out before the next: `BACKOFF_BASE_S`, doubled by each failure in a row her trace holds, to the beat. /// No start is made for her: a failed wake, or a start the day cap held, is waited out before the next (`BACKOFF_BASE_S`, doubled by
/// each such start in a row her trace holds, to the beat). Whether she is held is the drain's to say, at each start.
fn cooling(&self, now: DateTime<Utc>, beat_s: u32) -> bool { fn cooling(&self, now: DateTime<Utc>, beat_s: u32) -> bool {
let (run, at) = self.failures; let (run, at) = self.failures;
run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s)) run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s))
} }
/// A start for a send owed that left it owed is waited out the same way, by the poll's own count of them: the trace need not take a write for it.
fn owed_cooling(&self, now: DateTime<Utc>, beat_s: u32) -> bool {
let (run, at) = self.owed_starts;
run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s))
}
/// A member (not the operator) has a pending message that names or tags her. /// A member (not the operator) has a pending message that names or tags her.
fn addressed_by_member(&self, config: &Config) -> bool { fn addressed_by_member(&self, config: &Config) -> bool {
addressed_by_member(&config.operators, &self.addressee, &self.pending) addressed_by_member(&config.operators, &self.addressee, &self.pending)
@ -860,7 +851,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
} }
let now = organs.clock.now(); let now = organs.clock.now();
let stored = organs.store.load()?; let stored = organs.store.load()?;
let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }); let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() });
let mut eventful = false; let mut eventful = false;
// The table as the last poll left it; unreadable counts as none, is noted in the trace, and is not overwritten. // The table as the last poll left it; unreadable counts as none, is noted in the trace, and is not overwritten.
let (stored_addressing, addressing_unread) = match organs.store.load_addressing() { let (stored_addressing, addressing_unread) = match organs.store.load_addressing() {
@ -875,14 +866,13 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
// Her last-read names when the table holds her, else her roster names alone. // Her last-read names when the table holds her, else her roster names alone.
let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]); let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]);
let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone()); let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone());
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), owes: false, owed_starts: (state.owed_starts.get(&seat.who.slug.0).copied().unwrap_or(0), state.last_turn_at.get(&seat.who.slug.0).copied()), note: String::new() }; let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), note: String::new() };
// Pending chat, read-only, for a released Mind. // Pending chat, read-only, for a released Mind.
if row.released { if row.released {
match seat.trace.records() { match seat.trace.records() {
Ok(records) => { Ok(records) => {
row.done = Some(decided(&records).into_iter().map(str::to_owned).collect()); row.done = Some(decided(&records).into_iter().map(str::to_owned).collect());
row.failures = failed_run(&records); row.failures = failed_run(&records, now);
row.owes = owes(&records);
} }
Err(error) => { Err(error) => {
eventful = true; eventful = true;
@ -914,11 +904,6 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
// whose unit is not running and whose trace does not hold the line decided did not take it, and the open floor judges it afresh. // whose unit is not running and whose trace does not hold the line decided did not take it, and the open floor judges it afresh.
state.handled_mentions.retain(|key| key.split_once(':').is_none_or(|(who, event)| claim_stands(&rows, who, event))); state.handled_mentions.retain(|key| key.split_once(':').is_none_or(|(who, event)| claim_stands(&rows, who, event)));
// A trace read that holds no send owed ends the count of starts made for one.
for row in rows.iter().filter(|row| row.done.is_some() && !row.owes) {
state.owed_starts.remove(&row.slug().0);
}
let beat_s = config.beat_s; let beat_s = config.beat_s;
let mut launches: Vec<String> = Vec::new(); let mut launches: Vec<String> = Vec::new();
let mut launched: Vec<Slug> = Vec::new(); let mut launched: Vec<Slug> = Vec::new();
@ -949,26 +934,6 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
.map(|(delivery, _)| delivery.event_id.clone()) .map(|(delivery, _)| delivery.event_id.clone())
.find(|event| row.done.as_ref().is_some_and(|done| !done.contains(event))) .find(|event| row.done.as_ref().is_some_and(|done| !done.contains(event)))
}; };
// A send her trace holds owed starts her, whatever the room says: it is hers alone, and waits out her failed wakes like any wake, and the
// starts the poll has made for it that left it owed.
if mentioned.is_none() && row.owes {
if row.owed_cooling(now, beat_s) {
continue;
}
tried.push(index);
match wake(organs, row) {
Woke::Started => {
state.last_turn_at.insert(slug.0.clone(), now);
*state.owed_starts.entry(slug.0.clone()).or_insert(0) += 1;
row.busy = true;
launches.push(slug.0.clone());
launched.push(slug);
}
Woke::Refused(why) => row.note = why,
Woke::Busy => row.busy = true,
}
continue;
}
let Some(event) = mentioned else { continue }; let Some(event) = mentioned else { continue };
tried.push(index); tried.push(index);
// The wake's lines are recorded before her unit starts, so the start reads them. A start that does not happen leaves the // The wake's lines are recorded before her unit starts, so the start reads them. A start that does not happen leaves the

View file

@ -264,7 +264,7 @@ impl Rig {
/// The stored state, made if there is none, changed by `change`. /// The stored state, made if there is none, changed by `change`.
fn with_state(&self, change: impl FnOnce(&mut HeartbeatState)) { fn with_state(&self, change: impl FnOnce(&mut HeartbeatState)) {
let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }); let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() });
change(&mut state); change(&mut state);
*self.store.state.borrow_mut() = Some(state); *self.store.state.borrow_mut() = Some(state);
} }
@ -300,14 +300,14 @@ impl Rig {
fn finish_turn(&self, who: usize) { fn finish_turn(&self, who: usize) {
self.end_unit(who); self.end_unit(who);
let held: Vec<String> = self.chats[who].deliveries.borrow().iter().map(|line| line.event_id.clone()).collect(); let held: Vec<String> = self.chats[who].deliveries.borrow().iter().map(|line| line.event_id.clone()).collect();
self.traces[who].rows.borrow_mut().push(serde_json::json!({ "held": held, "at": self.now().to_rfc3339() })); self.traces[who].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": held, "at": self.now().to_rfc3339() }));
self.chats[who].deliveries.borrow_mut().clear(); self.chats[who].deliveries.borrow_mut().clear();
} }
/// Her turn failed: her unit ends, her trace holds a failed record, and her chat still holds the lines. /// Her turn failed: her unit ends, her trace holds a failed record, and her chat still holds the lines.
fn fail_turn(&self, who: usize) { fn fail_turn(&self, who: usize) {
self.end_unit(who); self.end_unit(who);
self.traces[who].rows.borrow_mut().push(serde_json::json!({ "failed": "the connector did not answer: unavailable", "outage": true, "at": self.now().to_rfc3339() })); self.traces[who].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": [], "failed": "the connector did not answer: unavailable", "outage": true, "at": self.now().to_rfc3339() }));
} }
/// Her unit is active. /// Her unit is active.
@ -670,7 +670,7 @@ fn trace_at(seconds: i64, tempo_s: u32) -> PollTrace {
} }
fn state_at(milliseconds: i64) -> HeartbeatState { fn state_at(milliseconds: i64) -> HeartbeatState {
HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]), owed_starts: BTreeMap::new() } HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]), retired_slot_3: BTreeMap::new() }
} }
#[test] #[test]
@ -713,9 +713,42 @@ fn a_state_written_before_the_cut_reads_with_no_turns() {
cache.pull_all_backing_stores().unwrap(); cache.pull_all_backing_stores().unwrap();
cache.put(STATE_KEY, &StateBeforeTheCut { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()] }).unwrap(); cache.put(STATE_KEY, &StateBeforeTheCut { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()] }).unwrap();
let state = FileStore::new(&path).load().unwrap().expect("the old state reads"); let state = FileStore::new(&path).load().unwrap().expect("the old state reads");
assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }); assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() });
} }
/// The state as the e951555 build wrote it, and as deployed files still hold it: four slots, the last the owed waker's count.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "eureka.heartbeat.state.v1", schema = "HeartbeatState")]
struct StateWithOwedStarts {
#[cultcache(key = 0)]
last_beat_at: DateTime<Utc>,
#[cultcache(key = 1)]
handled_mentions: Vec<String>,
#[cultcache(key = 2, default)]
last_turn_at: BTreeMap<String, DateTime<Utc>>,
#[cultcache(key = 3, default)]
owed_starts: BTreeMap<String, u32>,
}
/// Soul s2 state-slot3-readonly: a deployed four-slot file loads, and the poll's save over it succeeds instead of refusing it read-only.
#[test]
fn a_four_slot_state_from_the_deployed_build_loads_and_saves() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("heartbeat.cc");
let mut cache = CultCache::new();
cache.register_entry_type::<StateWithOwedStarts>().unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache.put(STATE_KEY, &StateWithOwedStarts { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::from([("ann".to_string(), 2)]) }).unwrap();
drop(cache);
let store = FileStore::new(&path);
let mut state = store.load().unwrap().expect("the four-slot state reads");
assert_eq!(state.handled_mentions, ["ann:e1"]);
state.last_beat_at = crate::testkit::at(9);
store.save(&state).expect("the save over a four-slot file is not refused");
assert_eq!(store.load().unwrap().unwrap().last_beat_at, crate::testkit::at(9));
}
#[test] #[test]
fn an_old_heartbeat_store_fails_closed_naming_the_file_and_is_never_migrated() { fn an_old_heartbeat_store_fails_closed_naming_the_file_and_is_never_migrated() {
let dir = TempDir::new().unwrap(); let dir = TempDir::new().unwrap();
@ -1014,7 +1047,7 @@ mod wake_rule {
fn an_old_hello_whose_taken_key_was_forgotten_wakes_no_one_and_the_keys_are_bounded() { fn an_old_hello_whose_taken_key_was_forgotten_wakes_no_one_and_the_keys_are_bounded() {
let rig = quiet_rig(); let rig = quiet_rig();
let old: Vec<String> = (0..70).map(|at| format!("$old{at}")).collect(); let old: Vec<String> = (0..70).map(|at| format!("$old{at}")).collect();
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": old, "at": rig.now().to_rfc3339() })); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": old, "at": rig.now().to_rfc3339() }));
rig.with_state(|state| state.handled_mentions = (0..70).map(|at| format!("ann:$old{at}")).collect()); rig.with_state(|state| state.handled_mentions = (0..70).map(|at| format!("ann:$old{at}")).collect());
said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!"));
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
@ -1178,7 +1211,7 @@ fn the_file_store_view_reads_the_lines_the_poll_recorded_for_her() {
let dir = TempDir::new().unwrap(); let dir = TempDir::new().unwrap();
let store = FileStore::new(dir.path().join("heartbeat.cc")); let store = FileStore::new(dir.path().join("heartbeat.cc"));
assert!(HeartbeatView::woken_for(&store, "ann").unwrap().is_empty(), "no state yet: no claims"); assert!(HeartbeatView::woken_for(&store, "ann").unwrap().is_empty(), "no state yet: no claims");
store.save(&HeartbeatState { last_beat_at: at(0), handled_mentions: vec!["ann:$e1".into(), "bob:$e2".into(), "ann:$e3".into()], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }).unwrap(); store.save(&HeartbeatState { last_beat_at: at(0), handled_mentions: vec!["ann:$e1".into(), "bob:$e2".into(), "ann:$e3".into()], last_turn_at: BTreeMap::new(), retired_slot_3: BTreeMap::new() }).unwrap();
assert_eq!(HeartbeatView::woken_for(&store, "ann").unwrap(), ["$e1", "$e3"]); assert_eq!(HeartbeatView::woken_for(&store, "ann").unwrap(), ["$e1", "$e3"]);
assert_eq!(HeartbeatView::woken_for(&store, "bob").unwrap(), ["$e2"]); assert_eq!(HeartbeatView::woken_for(&store, "bob").unwrap(), ["$e2"]);
} }
@ -1200,7 +1233,7 @@ fn a_hello_she_decided_whose_ack_is_held_is_not_given_to_a_second_mind() {
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!")); wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
rig.end_unit(ANN); rig.end_unit(ANN);
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "at": rig.now().to_rfc3339() })); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "at": rig.now().to_rfc3339() }));
assert!(!rig.chats[ANN].deliveries.borrow().is_empty(), "the ack is held: the hello is still in her queue"); assert!(!rig.chats[ANN].deliveries.borrow().is_empty(), "the ack is held: the hello is still in her queue");
for _ in 0..5 { for _ in 0..5 {
rig.advance(60); rig.advance(60);
@ -1215,7 +1248,7 @@ fn only_her_trace_decides_whether_a_line_is_woken_for() {
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
rig.end_unit(ANN); rig.end_unit(ANN);
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "at": rig.now().to_rfc3339() })); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "at": rig.now().to_rfc3339() }));
rig.advance(120); rig.advance(120);
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided"); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided");
rig.say(ANN, delivery(2, "@op:chat", "Ann, again", &[])); rig.say(ANN, delivery(2, "@op:chat", "Ann, again", &[]));
@ -1265,18 +1298,18 @@ fn a_mind_waiting_out_failures_passes_the_hello_to_the_other() {
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] });
} }
/// Soul's p5: a hello she decided whose send is owed is decided; her claim stands when her unit ends, and no second Mind is given it: /// Soul's p5: a hello she decided is decided, whatever her record also holds: her claim stands when her unit ends, no second Mind is given it, and
/// the poll starts her, for the send, and no one else. /// nothing starts her again for it. A record's `owed` list is read by no one.
#[test] #[test]
fn a_hello_she_decided_whose_send_is_owed_is_not_given_to_a_second_mind() { fn a_hello_she_decided_is_not_given_to_a_second_mind_and_starts_no_one() {
let rig = quiet_rig(); let rig = quiet_rig();
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!")); wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
rig.poll(); rig.poll();
rig.end_unit(ANN); rig.end_unit(ANN);
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "#general:chat", "text": "hi" }], "at": rig.now().to_rfc3339() })); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "#general:chat", "text": "hi" }], "at": rig.now().to_rfc3339() }));
rig.advance(60); rig.advance(60);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert_eq!(launched, vec![Slug("ann".into())], "she is started for her owed send, and no one is given the hello"); assert_eq!(launched, vec![], "no one is started, and no one is given the hello");
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "her claim stands"); assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "her claim stands");
} }
@ -1311,96 +1344,93 @@ fn the_beat_does_not_start_a_mind_that_is_cooling() {
assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}"); assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}");
} }
/// Soul's q3 and s8 held-sibling-restart-storm: her answer was decided and its send is owed (the answer was lost), her unit ended and nothing new arrives. The /// A record that holds a send in `owed` wakes no one: nothing settles such a list now, so a poll that started her for it would start her forever.
/// next poll starts her, and only her, so the send is retried well inside the 30 minutes a homeserver remembers its id, in a quiet room, with the beat's turn /// Every poll over half an hour, with nothing new arriving, starts her never (the beat's turn for the others aside).
/// on the far side of the first poll. A start that leaves it owed is waited out like a failed wake, 20 s doubling to the beat, by the poll's own count of them:
/// over the 30 minutes a homeserver remembers an id, of one-minute polls, she is started 7 times, not 29.
#[test] #[test]
fn t_l3_an_owed_send_with_nothing_new_starts_her_at_the_next_poll_and_no_one_else() { fn t_l3_an_owed_list_in_her_trace_starts_no_one() {
let rig = quiet_rig(); let rig = quiet_rig();
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
rig.poll(); rig.poll();
rig.end_unit(ANN); rig.end_unit(ANN);
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() })); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
let mut starts: Vec<i64> = Vec::new();
for minute in 1..=29 { for minute in 1..=29 {
rig.advance(60); rig.advance(60);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(launched.iter().all(|slug| slug.0 == "ann" || slug.0 == "bob" && minute >= 15), "minute {minute}: {launched:?}"); assert!(!launched.iter().any(|slug| slug.0 == "ann"), "minute {minute}: {launched:?}");
if launched.iter().any(|slug| slug.0 == "ann") {
starts.push(minute);
}
rig.end_unit(ANN); rig.end_unit(ANN);
} }
assert_eq!(starts.first(), Some(&1), "her, at the first poll after it was owed: {starts:?}");
assert_eq!(starts, [1, 2, 3, 5, 8, 14, 25], "20 s doubling to the beat, and still retried inside the dedupe window at minute 25");
} }
/// Soul s7 unwritable-owed-wakes-every-poll. A trace that takes no writes (her state disk full) carries no failed record, so the poll's backoff cannot /// A send settled starts no one.
/// read one: the poll's own count of starts it made that left the send owed backs it off instead, and a send settled ends the count.
#[test]
fn t_l3_a_trace_that_takes_no_writes_is_still_backed_off_by_the_polls_own_count_of_starts_that_left_a_send_owed() {
let rig = quiet_rig();
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
let started = |rig: &Rig| {
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
launched.iter().any(|slug| slug.0 == "ann")
};
assert!(started(&rig), "the first start for the send");
rig.end_unit(ANN);
rig.advance(10);
assert!(!started(&rig), "ten seconds after a start that left it owed");
rig.advance(11);
assert!(started(&rig), "20 s later");
rig.end_unit(ANN);
rig.advance(30);
assert!(!started(&rig), "the second doubles it to 40 s");
// The send settles: her trace holds its record rewritten, posted, and the count ends.
rig.traces[ANN].rows.borrow_mut()[0] = serde_json::json!({ "held": ["$e1"], "posted": [{ "event": "$sent-1", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() });
rig.advance(1);
assert!(!started(&rig), "nothing is owed");
assert!(rig.store.state.borrow().as_ref().is_some_and(|state| state.owed_starts.is_empty()), "the count of starts for a send owed ended with it");
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e2"], "owed": [{ "id": "l$e2:s0", "room": "!op", "text": "Again." }], "at": rig.now().to_rfc3339() }));
rig.advance(1);
assert!(started(&rig), "a new send owed starts her at the next poll: the count began again");
}
/// The owed send's start waits out her failed wakes like any other start: an outage is not retried every poll.
#[test]
fn t_l3_an_owed_send_waits_out_her_failed_wakes() {
let rig = quiet_rig();
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
rig.fail_turn(ANN);
rig.advance(5);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(launched.is_empty(), "cooling: {launched:?}");
rig.advance(i64::from(BEAT_S));
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}");
}
/// A send owed and settled starts no one.
#[test] #[test]
fn t_l3_a_send_settled_starts_no_one() { fn t_l3_a_send_settled_starts_no_one() {
let rig = quiet_rig(); let rig = quiet_rig();
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "posted": [{ "event": "$sent-1", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() })); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "posted": [{ "event": "$sent-1", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
rig.advance(60); rig.advance(60);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(launched.is_empty(), "{launched:?}"); assert!(launched.is_empty(), "{launched:?}");
} }
/// Soul s7 pins-on-new-lines. A line that wakes her and her trace does not hold decided starts her by the wake rule, which writes the claim for /// Soul s7 pins-on-new-lines. A line that wakes her and her trace does not hold decided starts her by the wake rule, which writes the claim for
/// the line; the owed waker is for a poll with nothing waking her, and does not take its place. /// the line, whatever an older record of hers holds in `owed`.
#[test] #[test]
fn t_l3_a_new_waking_line_is_woken_for_by_the_wake_rule_even_while_a_send_is_owed() { fn t_l3_a_new_waking_line_is_woken_for_by_the_wake_rule_with_an_owed_list_in_her_trace() {
let rig = quiet_rig(); let rig = quiet_rig();
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
rig.poll(); rig.poll();
rig.end_unit(ANN); rig.end_unit(ANN);
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() })); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "rooms": [], "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
rig.say(ANN, delivery(2, "@op:chat", "Ann, again", &[])); rig.say(ANN, delivery(2, "@op:chat", "Ann, again", &[]));
rig.advance(60); rig.advance(60);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert_eq!(launched, vec![Slug("ann".into())]); assert_eq!(launched, vec![Slug("ann".into())]);
assert!(rig.store.state.borrow().clone().unwrap().handled_mentions.contains(&"ann:$e2".to_owned()), "the new line's claim is written: the wake rule started her"); assert!(rig.store.state.borrow().clone().unwrap().handled_mentions.contains(&"ann:$e2".to_owned()), "the new line's claim is written: the wake rule started her");
} }
/// A start the day cap held writes no wake record and decides no line, so the poll would start her unit for the same undecided line at
/// every poll. The drain alone says whether she is held; the poll only backs off by her held starts as by failed wakes (20 s, doubling to
/// the beat). A row's `until` is no authority: a far-future one, written by anyone, holds her no longer than the backoff. A start after
/// the backoff is made, so a raised cap releases her within a beat.
#[test]
fn t_h4_held_starts_back_off_like_failures_and_never_hold_her_for_a_day() {
let rig = quiet_rig();
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
let t0 = rig.now();
let far = (t0 + Duration::days(300)).to_rfc3339();
let mut launches: Vec<i64> = vec![];
for _ in 0..360 {
rig.advance(10);
let Outcome::Polled { launched } = rig.poll() else { panic!("polled") };
if launched.iter().any(|slug| slug.0 == "ann") {
launches.push((rig.now() - t0).num_seconds());
rig.end_unit(ANN);
// What the drain does at a start it holds: appends a row of its own, at the place the trace has reached.
let mut rows = rig.traces[ANN].rows.borrow_mut();
let seq = rows.len();
rows.push(serde_json::json!({ "held_by": "day_cap", "spent": 3.2, "cap": 3.0, "until": far, "at": rig.now().to_rfc3339(), "seq": seq }));
}
}
let gaps: Vec<i64> = launches.windows(2).map(|pair| pair[1] - pair[0]).collect();
assert_eq!(gaps, [20, 40, 80, 160, 320, 640, 900, 900].map(i64::from), "{launches:?}: each held start waits the failure backoff, to the beat");
assert_eq!(launches.len(), 9, "an hour of held starts costs nine unit starts, not 360: {launches:?}");
}
/// W2: lines that reach a Mind whose wake is open are the wake's, read from the mouth by the wake itself. The heartbeat starts no second unit for
/// them, writes no claim for them, and does not wake her for them once her unit has ended with her trace holding them decided.
#[test]
fn lines_that_reach_a_mind_with_a_wake_open_start_no_second_unit_and_claim_nothing() {
let rig = quiet_rig();
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
rig.in_a_turn(ANN);
for seq in 2..=4 {
rig.say(ANN, delivery(seq, "@op:chat", "Ann, and again", &[]));
rig.advance(60);
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her unit is active: line {seq} is her wake's, and starts nothing");
}
assert_eq!(rig.launched(), vec![Slug("ann".into())], "one start, one unit");
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "no claim was written for the lines her wake took");
rig.finish_turn(ANN);
rig.advance(120);
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her wake decided them all: nothing wakes her again");
}

View file

@ -47,6 +47,7 @@ pub mod lease_client;
pub mod persona; pub mod persona;
pub mod projection; pub mod projection;
pub mod queue; pub mod queue;
pub mod sandbox;
pub mod self_run; pub mod self_run;
pub mod tempo; pub mod tempo;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,467 @@
//! A wake that stays open (cut W2): its second and later turns, the end it comes to, and its close. One start, the fake clock, the scripted agent.
use super::*;
const EUREKA: &str = "@eureka:gamecult.org";
const MINDS: &str = "#minds:gamecult.org";
/// Her agent ends its turn at once.
fn done() -> std::result::Result<Stepped, Failed> {
Ok(Stepped { items: vec![InputItem::AssistantText { text: "Done.".into() }], text: "Done.".into(), calls: vec![], stop: StopReason::EndTurn, usage: spent() })
}
/// Her agent runs `command` in her shell.
fn shells(id: &str, command: &str) -> std::result::Result<Stepped, Failed> {
let call = ToolCall { call_id: id.into(), name: "shell".into(), arguments: json!({ "command": command }).to_string() };
Ok(Stepped { items: vec![InputItem::ToolCall { call_id: call.call_id.clone(), name: call.name.clone(), arguments: call.arguments.clone() }], text: String::new(), calls: vec![call], stop: StopReason::ToolUse, usage: spent() })
}
/// A line that reaches the mouth by the time the fake clock reads `tick`.
fn arrives(rig: &Rig, tick: i64, line: ChatDelivery) {
rig.arrivals.borrow_mut().push((tick, line));
}
/// A line of the operator's, `tick` seconds into the wake.
fn later(seq: u64, room: &str, tick: i64, text: &str) -> ChatDelivery {
line_at(seq, room, META, text, BASE_MS + u64::try_from(tick).unwrap() * 1000)
}
fn answers(rig: &Rig, list: impl IntoIterator<Item = std::result::Result<Stepped, Failed>>) {
rig.agent.answers.borrow_mut().extend(list);
}
fn tune(rig: &Rig, body: &str) {
std::fs::write(rig.dir.path().join("persona-tuning.toml"), body).unwrap();
}
fn calls(rig: &Rig, stage: &str) -> usize {
rig.log.all().iter().filter(|what| *what == stage).count()
}
fn at_of(row: &Value) -> DateTime<Utc> {
row["at"].as_str().unwrap().parse().unwrap()
}
fn user_text(items: &[InputItem]) -> String {
match items.last() {
Some(InputItem::UserText { text }) => text.clone(),
other => panic!("a turn's last item is its lines: {other:?}"),
}
}
/// W2-I6, I7 and the turn itself: a second line a minute after the first is a second turn of the same wake, in the same agent conversation, with only the new
/// line as its input. The Projector and the Persona ran once, the Interpreter once over both turns' receipts, and each turn's lines were acked behind its own row.
#[test]
fn t_w2_a_second_line_is_a_second_turn_of_one_wake() {
let rig = Rig::new(vec![line(1, &room(1), META, "first line, are you there")]);
answers(&rig, [shells("one", "ls /srv/one"), done(), shells("two", "ls /srv/two"), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "and a second line"));
let model = Tally::default();
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) });
assert_eq!((calls(&rig, "projector"), calls(&rig, "persona"), calls(&rig, "interpreter")), (1, 1, 2), "one Projector, one Persona, and the Interpreter's two halves once, over both turns");
// The second turn's request carries the first turn's items as its prefix: one conversation.
let seen = rig.agent.seen.borrow();
assert_eq!(seen.len(), 4);
let (first_end, second) = (&seen[1], &seen[2]);
assert_eq!(second.len(), first_end.len() + 2, "the first turn's items, her closing words, then the new lines");
assert!(first_end.iter().zip(second).all(|(before, now)| format!("{before:?}") == format!("{now:?}")), "{second:?}");
let (opening, input) = (user_text(&seen[0]), user_text(second));
assert!(opening.contains("What she lives now") && opening.contains("first line, are you there"), "{opening}");
assert!(input.contains("and a second line") && !input.contains("first line") && !input.contains("What she lives now") && !input.contains("Her own inner voice"), "the second turn is the new lines alone: {input}");
drop(seen);
// Both turns' acts reach the one Interpreter pass.
for prompt in model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)) {
let acts = prompt.split("\nACTS\n").nth(1).unwrap_or_else(|| panic!("no ACTS section: {prompt}")).split("NARRATION").next().unwrap();
assert!(acts.contains("\"ls /srv/one\"") && acts.contains("\"ls /srv/two\""), "{acts}");
}
let turns = rig.turns();
assert_eq!(turns.iter().map(|turn| (turn["turn"].clone(), turn["held"].clone())).collect::<Vec<_>>(), [(json!(1), json!(["$e1"])), (json!(2), json!(["$e2"]))]);
let records = rig.records();
assert_eq!((records.len(), records[0]["turns"].clone(), records[0]["ended"].clone(), records[0]["status"].clone(), records[0]["held"].clone()), (1, json!(2), json!("idle"), json!("completed"), json!([])));
assert_eq!(rig.acks(), [1, 2], "each turn's lines are acked behind its own row");
let ids: Vec<String> = rig.all_records().iter().filter(|row| row["agent"] == "call").map(|row| row["call"].as_str().unwrap().to_owned()).collect();
assert!(ids.iter().any(|id| id.contains("-t2-m")) && ids.iter().collect::<std::collections::BTreeSet<_>>().len() == ids.len(), "no two model calls of the wake share a request id: {ids:?}");
}
/// W2-I7: the Interpreter runs once at the close, not once per turn: three turns still make its two halves, and its receipt and the put are one each.
#[test]
fn t_w2_the_interpreter_runs_once_at_close_over_all_turns() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
arrives(&rig, 100, later(2, &room(1), 100, "second"));
arrives(&rig, 250, later(3, &room(1), 250, "third"));
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, turns: 3, ended: Some(End::Idle), acked_through: Some(3) });
assert_eq!(calls(&rig, "interpreter"), 2, "two halves, once");
assert_eq!((rig.store.puts.borrow().len(), rows(&rig.all_records(), "interpreter").len()), (1, 1));
let log = rig.log.all();
let last_turn = log.iter().rposition(|what| what == "row:turn").unwrap();
assert!(log.iter().position(|what| what == "interpreter").unwrap() > last_turn, "after the last turn, not between turns: {log:?}");
}
/// W2-I6: no Projector and no Persona call for a line that arrives in an open wake, however many turns follow.
#[test]
fn t_w2_the_projector_and_the_persona_do_not_rerun_for_a_line_in_an_open_wake() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
for (n, tick) in [(2, 80), (3, 160), (4, 240)] {
arrives(&rig, tick, later(n, &room(1), tick, &format!("line {n}")));
}
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 4, ended: Some(End::Idle), acked_through: Some(4) });
assert_eq!((calls(&rig, "projector"), calls(&rig, "persona"), calls(&rig, "agent")), (1, 1, 4));
}
/// The idle window: no line after her turn, so the wake waits idle_s, polling every 5 s, and closes `ended: idle`.
#[test]
fn t_w2_a_wake_with_no_new_line_closes_idle_after_idle_s_of_five_second_polls() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
let (turn, wake) = (at_of(&rig.turns()[0]), at_of(&rig.records()[0]));
let waited = (wake - turn).num_seconds();
assert!((300..330).contains(&waited), "the close came {waited} s after her turn");
let pauses = rig.pauses.borrow();
assert!(pauses.len() > 20 && pauses.iter().all(|wait| wait.as_secs() == 5), "{pauses:?}");
}
/// The span: a line every minute keeps the wake open until span_s, and no longer.
#[test]
fn t_w2_a_wake_open_span_s_closes_though_lines_keep_coming() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nspan_s = 300\nidle_s = 120\n");
for n in 0..40 {
arrives(&rig, 40 + 40 * n, later(2 + n as u64, &room(1), 40 + 40 * n, &format!("line {n}")));
}
let Outcome::Drained { turns, ended, .. } = rig.run(Tally::default()) else { panic!("drained") };
assert_eq!(ended, Some(End::Span));
assert!((4..=9).contains(&turns), "{turns} turns");
let (first, wake) = (at_of(&rig.turns()[0]), at_of(&rig.records()[0]));
let open = (wake - first).num_seconds();
assert!((250..330).contains(&open), "the wake closed {open} s after its first turn");
assert!(!rig.arrivals.borrow().is_empty(), "lines that came after the span were never read by this wake");
assert_eq!(rig.records()[0]["ended"], "span");
}
/// A line that wakes her nothing: another room's member line starts no turn, and a notice in the wake's room is held by the wake record, which
/// decides it, and acked behind it.
#[test]
fn t_w2_a_line_that_wakes_nothing_starts_no_turn_and_the_wake_record_holds_it_if_it_is_in_the_wakes_rooms() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
arrives(&rig, 40, line_at(2, MINDS, ANN, "status: green", BASE_MS + 40_000));
let mut notice = later(3, &room(1), 80, "a notice");
notice.form = Form::Notice;
arrives(&rig, 80, notice);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(3) });
assert_eq!(rig.agent.seen.borrow().len(), 1, "her agent took the one turn");
let records = rig.records();
assert_eq!(records[0]["held"], json!(["$e3"]), "the notice, in the wake's room, and no other room's line");
assert!(decided(&rig.trace.records().unwrap()).contains("$e3"));
}
/// The backstop: Minds tagging her in a row wake her only while fewer than MIND_RUN_BACKSTOP lines of the run came before; the pool of lines the wake
/// has seen is what the run is counted over, whatever was acked, so a chain does not restart at each ack.
#[test]
fn t_w2_minds_tagging_her_in_a_row_stop_waking_her_at_the_backstop() {
let tagged = |seq: u64, tick: i64| ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(seq, MINDS, LIBBY, &format!("libby says {seq}"), BASE_MS + u64::try_from(tick).unwrap() * 1000) };
let rig = Rig::new(vec![tagged(1, 0)]);
for seq in 2..=6 {
arrives(&rig, 100 * (seq as i64 - 1), tagged(seq, 100 * (seq as i64 - 1)));
}
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 4, ended: Some(End::Idle), acked_through: Some(6) }, "four Mind lines wake her, the fifth and sixth do not");
let seen: String = rig.agent.seen.borrow().iter().flatten().map(|item| format!("{item:?}")).collect();
assert!(seen.contains("libby says 4") && !seen.contains("libby says 5") && !seen.contains("libby says 6"), "the lines past the backstop are not shown to her agent");
assert_eq!(rig.records()[0]["held"], json!(["$e5", "$e6"]), "they woke nothing, and are in the wake's room: the wake record holds them");
}
/// (b) of W1: the mouth refuses a say whose basis is not the newest event of the room, so each line a turn shows must be shown to the mouth. A say after an
/// in-wake line is sent against that line.
#[test]
fn t_w2_a_say_after_an_in_wake_line_is_sent_against_that_line() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
rig.mouth.strict.set(true);
answers(&rig, [says(&room(1), "first answer"), done(), says(&room(1), "second answer"), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) });
let sent = rig.mouth.sent.borrow();
assert_eq!(sent.iter().map(|request| request.text.as_str()).collect::<Vec<_>>(), ["first answer", "second answer"], "the second say was not refused RoomMoved");
assert_eq!(sent[1].basis.as_ref().and_then(|basis| basis.seen_event_id.as_deref()), Some("$e2"));
}
/// W1 (a) and a turn 2 failure that is no outage: the strike is on turn 2's row, on turn 2's oldest waking line, once; the wake record is completed, the
/// Interpreter ran over turn 1, and the line is woken for again by the next start.
#[test]
fn t_w2_a_failed_second_turn_strikes_its_line_on_its_own_row_and_the_wake_still_closes_completed() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
answers(&rig, [shells("one", "ls /srv/one"), done(), Err(Failed { reason: "the agent's turn ended early: Refusal".into(), outage: false, usage: None })]);
arrives(&rig, 60, later(2, &room(1), 60, "the line the model refuses"));
let model = Tally::default();
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Failed), acked_through: Some(1) });
let turns = rig.turns();
assert_eq!((turns[1]["status"].as_str(), turns[1]["strike"].clone()), (Some("failed"), json!("$e2")));
assert_eq!(rig.all_records().iter().filter(|row| row.get("strike").is_some()).count(), 1, "struck once, on the turn's row, not again on the wake record");
let wake = &rig.records()[0];
assert_eq!((wake["status"].as_str(), wake["ended"].as_str(), wake.get("failed").is_none(), wake["held"].clone()), (Some("completed"), Some("failed"), true, json!([])));
assert_eq!(calls(&rig, "interpreter"), 2, "the Interpreter ran, over turn 1");
assert!(model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).all(|prompt| prompt.contains("\"ls /srv/one\"")));
assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"), "a failed turn decides nothing");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) }, "the next start answers the line");
}
/// An outage in turn 2 strikes nothing.
#[test]
fn t_w2_an_outage_in_a_second_turn_strikes_nothing() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
answers(&rig, [done(), Err(Failed { reason: OUTAGE.into(), outage: true, usage: None })]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Failed), acked_through: Some(1) });
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none()));
assert_eq!(rig.turns()[1]["outage"], true);
}
/// The wake's own spend cap: the turns' spend is summed, and the wake closes `spend` when it reaches wake_usd.
#[test]
fn t_w2_a_wake_closes_when_its_turns_have_spent_the_wake_cap() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
// One turn here is about $0.0003 a call.
tune(&rig, "[agent]\nwake_usd = 0.0005\n");
answers(&rig, [shells("one", "ls /srv/one")]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
let Outcome::Drained { ended, .. } = rig.run(Tally::default()) else { panic!("drained") };
assert_eq!(ended, Some(End::Spend));
assert_eq!(rig.records()[0]["ended"], "spend");
}
/// The day cap, reached in a later turn, ends the wake, and the next start is held.
#[test]
fn t_w2_the_day_cap_reached_mid_wake_ends_it_and_the_next_start_is_held() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
// The day has spent $0.9995 of its $1.00, and a call costs $0.0003: turn 1 fits, turn 2's second call does not.
let usage = json!(Spent { input_tokens: 499_750, output_tokens: 0, ..spent() });
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap().to_rfc3339();
rig.trace.rows.borrow_mut().push(("seed-g0".into(), json!({ "agent": "call", "at": at, "usage": usage, "seq": 0 })));
answers(&rig, [done(), says(&room(1), "second answer")]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::DayCap), acked_through: Some(2) });
assert_eq!(rig.records()[0]["ended"], "day_cap");
rig.mouth.held.borrow_mut().push(line(3, &room(1), META, "third"));
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }), "the day is spent: the next start holds her");
}
/// A failed read of the mouth is a skipped poll; three in a row end the wake as an outage, which strikes nothing.
#[test]
fn t_w2_failed_mouth_reads_skip_polls_and_three_in_a_row_end_the_wake() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
rig.mouth.pending_fails.set(2);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) }, "two failed reads cost two polls, and nothing else");
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
rig.mouth.pending_fails.set(3);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: Some(1) });
assert_eq!(rig.records()[0]["status"], "completed");
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none() && row.get("failed").is_none()));
assert!(calls(&rig, "interpreter") == 2, "the turn that ran still closes with its Interpreter");
}
/// The first event whose hash ranks her `rank`th of the two Minds a line tags.
fn event_ranking_her(rank: u64) -> String {
let table: Vec<Addressee> = [EUREKA, LIBBY].iter().map(|id| Addressee::new(id, [crate::address::localpart(id)])).collect();
(0..2000)
.map(|n| format!("$tag{n}"))
.find(|event| crate::persona::live::stagger_ms(&table[0], &table, &ChatDelivery { event_id: event.clone(), mentions: vec![EUREKA.into(), LIBBY.into()], ..line(1, MINDS, META, "both of you") }) == rank * 8000)
.expect("among 2000 events one ranks her so")
}
/// A line to both of two Minds, in a public room: the operator's, tagging both.
fn to_both(seq: u64, event: &str, tick: i64) -> ChatDelivery {
ChatDelivery { event_id: event.into(), mentions: vec![EUREKA.into(), LIBBY.into()], ..line_at(seq, MINDS, META, "both of you, a question", BASE_MS + u64::try_from(tick).unwrap() * 1000) }
}
/// The first experiment's stagger, in the span: a line that tags two Minds is taken by the one ranked second a step (8 s) after the one ranked first, and
/// a Mind ranked first takes it at once.
#[test]
fn t_w2_a_line_to_several_awake_minds_is_taken_after_her_rank() {
let first_turn_two = |rank: u64| {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
arrives(&rig, 60, to_both(2, &event_ranking_her(rank), 60));
rig.run(Tally::default());
assert_eq!(rig.turns().len(), 2, "rank {rank}");
at_of(&rig.turns()[1])
};
let (at_once, after_a_step) = (first_turn_two(0), first_turn_two(1));
let delay = (after_a_step - at_once).num_seconds();
assert!((8..20).contains(&delay), "the second-ranked Mind took the line {delay} s after the first-ranked one would have");
}
/// The first experiment's stagger, at the open: a start woken by a line tagging two Minds waits her rank, then reads the mouth afresh, so a line that
/// arrived while she waited is in her first turn.
#[test]
fn t_w2_the_open_waits_her_rank_and_reads_the_mouth_afresh() {
let ranked_second = event_ranking_her(1);
let rig = Rig::new(vec![to_both(1, &ranked_second, 0)]);
arrives(&rig, 4, later(2, MINDS, 4, "and one more thing while you wait"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) });
assert_eq!(rig.pauses.borrow().first().copied(), Some(std::time::Duration::from_secs(8)), "one step for rank one");
assert_eq!(rig.turns()[0]["held"], json!([ranked_second, "$e2"]), "the line that came in the wait is in the first turn");
assert_eq!(calls(&rig, "projector"), 1, "the wait reran no organ");
let rig = Rig::new(vec![to_both(1, &event_ranking_her(0), 0)]);
rig.run(Tally::default());
assert_eq!(rig.pauses.borrow().first().copied(), Some(std::time::Duration::from_secs(5)), "ranked first: no wait before the wake, only the span's polls");
}
// ---------------------------------------------------------------------------------------------
// Soul's hold on 9187ee0.
/// H1, Soul's probe: a turn that completed and crossed the day's cap ends the wake. The line that arrived after it is never taken, so it is neither shown
/// to her agent nor decided nor acked, nor told to the Interpreter as heard, and the next start (held) leaves it for the day that follows.
#[test]
fn t_h1_a_day_cap_crossed_by_a_completed_turn_ends_the_wake_before_the_next_line_is_taken() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
// $0.9999 of the day is spent: turn 1's one call, $0.0003, crosses the cap, and the turn still completes.
let usage = json!(Spent { input_tokens: 499_950, output_tokens: 0, ..spent() });
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap().to_rfc3339();
rig.trace.rows.borrow_mut().push(("seed-g0".into(), json!({ "agent": "call", "at": at, "usage": usage, "seq": 0 })));
answers(&rig, [done(), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "second, never shown"));
let model = Tally::default();
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::DayCap), acked_through: Some(1) });
assert_eq!(rig.agent.seen.borrow().len(), 1, "her agent was called for turn 1 alone");
assert!(!rig.agent.seen.borrow().iter().any(|items| format!("{items:?}").contains("never shown")));
assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"), "the line was shown to no one, so nothing decided it");
assert!(model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).all(|prompt| !prompt.contains("never shown")));
assert_eq!(rig.turns().len(), 1);
}
/// H1's second half: a turn that made no model call (the cap crossed between the wake's judgement and the turn) holds no line and decides nothing: its
/// row holds none, its line is not acked, and the wake closes `day_cap` with the turns before it.
#[test]
fn t_h1_a_turn_that_made_no_model_call_holds_no_line_and_decides_nothing() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
rig.crossing.set(true);
answers(&rig, [done(), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "second, never shown"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::DayCap), acked_through: Some(1) });
let turn = &rig.turns()[1];
assert_eq!((turn["model_calls"].clone(), turn["held"].clone(), turn["status"].as_str()), (json!(0), json!([]), Some("capped")), "{turn}");
assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"));
assert_eq!(rig.agent.seen.borrow().len(), 1, "no call reached her agent's model for it");
assert_eq!(rig.records()[0]["status"], "completed", "turn 1 completed, and the Interpreter ran over it");
assert_eq!(calls(&rig, "interpreter"), 2);
}
/// The same race at her first turn: nothing was shown, so the wake fails as an outage, strikes nothing, and decides nothing.
#[test]
fn t_h1_a_first_turn_that_made_no_model_call_fails_the_wake_as_an_outage() {
struct Spends(Rc<MemTrace>, Tally);
impl Model for Spends {
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
if !prompt.starts_with("You are a private Projector.") && !prompt.starts_with(INTERPRETER) {
self.0.rows.borrow_mut().push(crossing_row());
}
self.1.ask(request_id, model, prompt, schema)
}
}
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
assert_eq!(rig.run(Spends(rig.trace.clone(), Tally::default())), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::DayCap), acked_through: None });
assert_eq!(rig.turns()[0]["held"], json!([]));
assert!(!decided(&rig.trace.records().unwrap()).contains("$e1"));
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none()) && rig.records()[0]["outage"] == true);
assert_eq!(rig.agent.seen.borrow().len(), 0);
}
/// M3, the ack's guard: a line that wakes her in a room the wake has not joined holds the ack behind it until a turn takes it, wherever the wake ended. The
/// line is held back by its stagger and the wake is made to end at every moment around it; whenever the wake ended with the line untaken, nothing past it
/// was acked and it is still in the mouth.
#[test]
fn t_m3_a_waking_line_no_turn_took_holds_the_ack_behind_it_wherever_the_wake_ends() {
let event = event_ranking_her(1);
let mut left_untaken = 0;
for tick in 8..90 {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nidle_s = 30\nspan_s = 60\n");
let side = ChatDelivery { room_alias: "#side:gamecult.org".into(), room_id: "#side:gamecult.org".into(), ..to_both(2, &event, tick) };
let mut notice = later(3, &room(1), tick, "a notice");
notice.form = Form::Notice;
arrives(&rig, tick, side);
arrives(&rig, tick, notice);
rig.run(Tally::default());
let taken = decided(&rig.trace.records().unwrap()).contains(event.as_str());
if !taken && rig.mouth.held.borrow().iter().any(|held| held.event_id == event) {
left_untaken += 1;
assert!(rig.acks().iter().all(|seq| *seq < 2), "tick {tick}: the ack passed a waking line no turn took: {:?}", rig.acks());
}
if !rig.mouth.held.borrow().iter().any(|held| held.event_id == event) && !taken {
assert!(rig.arrivals.borrow().iter().any(|(_, held)| held.event_id == event) || rig.acks().iter().all(|seq| *seq < 2), "tick {tick}: the line was acked undecided");
}
}
assert!(left_untaken > 0, "the sweep never ended a wake with the line read and untaken: it proves nothing");
}
/// M3, the trailing list's guard: the wake record holds the quiet lines of the wake's rooms and never a line that wakes her. A line that tags two Minds
/// and waits out its stagger is in a joined room; if the wake ends before it is taken, the record must not decide it unshown.
#[test]
fn t_m3_the_wake_record_never_decides_a_waking_line_it_did_not_show() {
let event = event_ranking_her(1);
let mut left_untaken = 0;
for tick in 8..90 {
let tagged_her = ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(1, MINDS, META, "hello Eureka", BASE_MS - 100_000) };
let rig = Rig::new(vec![tagged_her]);
tune(&rig, "[agent]\nidle_s = 30\nspan_s = 60\n");
arrives(&rig, tick, to_both(2, &event, tick));
rig.run(Tally::default());
let decided_it = decided(&rig.trace.records().unwrap()).contains(event.as_str());
let shown = rig.agent.seen.borrow().iter().any(|items| format!("{items:?}").contains("both of you"));
assert!(!decided_it || shown, "tick {tick}: the line was decided and never shown to her agent");
left_untaken += usize::from(!decided_it && rig.mouth.held.borrow().iter().any(|held| held.event_id == event));
}
assert!(left_untaken > 0, "the sweep never ended a wake with the line read and untaken: it proves nothing");
}
/// M3, the open's guard: a quiet line the open had and no turn showed (the page had no room for it) is not the close's to decide. It stays undecided,
/// and the ack stops below it.
#[test]
fn t_m3_a_quiet_line_the_open_had_and_no_turn_showed_stays_undecided_at_close() {
let mut lines = vec![line(1, &room(1), META, "hello")];
lines.extend((2..=61).map(|seq| line_at(seq, MINDS, ANN, &format!("line {seq} of a long talk in the room, said at some length so that the page fills"), BASE_MS - 110_000 + seq * 100)));
lines.push(ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(62, MINDS, META, "Eureka, what do you make of it", BASE_MS - 40_000) });
let rig = Rig::new(lines);
assert!(matches!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, .. }));
let held: Vec<String> = rig.turns()[0]["held"].as_array().unwrap().iter().map(|event| event.as_str().unwrap().to_owned()).collect();
let unshown: Vec<u64> = (2..=61).filter(|seq| !held.contains(&format!("$e{seq}"))).collect();
assert!(!unshown.is_empty() && held.contains(&"$e62".to_owned()), "the page left some of the quiet lines out: {held:?}");
let done = decided(&rig.trace.records().unwrap()).into_iter().map(str::to_owned).collect::<Vec<_>>();
assert!(unshown.iter().all(|seq| !done.contains(&format!("$e{seq}"))), "a line no one was shown is not decided by the wake record: {done:?}");
assert!(rig.acks().iter().all(|seq| *seq < unshown[0]), "and the ack stops below the first of them: {:?}", rig.acks());
assert_eq!(rig.records()[0]["held"], json!([]));
}
/// M1: a session that starts fresh at turn 2 is told what the wake already did, her own say among it, so she does not say it again. The session is
/// discarded as too long between the turns.
#[test]
fn t_m1_a_session_reseeded_at_turn_two_carries_turn_ones_say_and_acts() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nmax_session_tokens = 50\n");
answers(&rig, [says(&room(1), "I will be there at noon"), shells("one", "ls /srv/one"), done(), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "and the second line"));
rig.run(Tally::default());
let seen = rig.agent.seen.borrow();
let turn_two = seen.iter().find(|items| items.len() == 1 && format!("{items:?}").contains("and the second line")).expect("turn 2 began a fresh session");
let text = user_text(turn_two);
assert!(text.contains("I will be there at noon") && text.contains("ls /srv/one"), "turn 1's say and acts are in the reseed: {text}");
assert!(text.contains("What she lives now") && text.contains("and the second line"), "with the wake's opening, and the new line: {text}");
assert!(text.find("I will be there at noon").unwrap() < text.find("and the second line").unwrap(), "what was done comes before the lines");
assert!(rig.all_records().iter().any(|row| row["agent"] == "session_discarded" && row["why"] == "too_long"));
}
/// A kept session is not told what it already has.
#[test]
fn t_m1_a_kept_session_is_not_told_the_wake_again() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
answers(&rig, [says(&room(1), "I will be there at noon"), done(), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "and the second line"));
rig.run(Tally::default());
let seen = rig.agent.seen.borrow();
assert!(!user_text(&seen[2]).contains("I will be there at noon") && !user_text(&seen[2]).contains("already done"));
}

View file

@ -0,0 +1,212 @@
//! The live span of a wake (`docs/persona-wake-span-map.md`, cut W2): what the drain decides after her first turn, while the wake is open.
//!
//! A wake is one start of `mind-persona@<instance>`. After a turn the process polls the mouth every `POLL_S` seconds. A line that wakes her
//! by the heartbeat's own rule (`Hearing::waking`, which the open uses too) starts the next turn in the same agent conversation, with only the
//! new lines as its input. The wake ends by one pure function, `wake_end`, and by nothing else.
//!
//! What this gives up: a line after the first is answered on the inner voice the wake opened with, and her state moves only when the
//! wake closes.
use std::collections::{BTreeMap, BTreeSet};
use chrono::{DateTime, Duration, Utc};
use serde_json::Value;
use super::{Config, STRIKES, speaker, strikes};
use crate::address::{Addressee, addresses, is_for};
use crate::chat_client::ChatDelivery;
use crate::heartbeat::{pending_facts, wakes};
use crate::projection::AgentTuning;
use crate::projection::agent::{Cap, Ended};
/// How often an open wake reads the mouth, in seconds: the first experiment's `PERSONA_POLL_S`.
pub(crate) const POLL_S: u64 = 5;
/// How many mouth reads in a row may fail before the wake ends. One failed read is a skipped poll.
pub(crate) const MOUTH_FAILS_MAX: u32 = 3;
/// A line is taken this many seconds per rank after the first Mind addressed (`stagger_ms`), the first experiment's `STAGGER_STEP_S`: calibration,
/// about the time a Mind takes to answer (7 to 13 s observed on 2026-11-03).
pub(crate) const STAGGER_STEP_S: u64 = 8;
/// Why a wake ended: the first of these that holds, in this order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
/// A turn failed, or the wake could not read the mouth or her trace.
Failed,
/// The day's cap is reached: her trace holds the day's spend at it, or a turn stopped at it.
DayCap,
/// This wake's spend reached `agent.wake_usd`.
Spend,
/// The wake has been open `agent.span_s`.
Span,
/// No turn has started for `agent.idle_s` since her last ended.
Idle,
}
impl End {
pub(crate) fn name(self) -> &'static str {
match self {
Self::Failed => "failed",
Self::DayCap => "day_cap",
Self::Spend => "spend",
Self::Span => "span",
Self::Idle => "idle",
}
}
}
impl std::fmt::Display for End {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
/// Where a wake stands in time: when it opened and when her last turn ended.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Span {
pub opened: DateTime<Utc>,
pub last_ended: DateTime<Utc>,
}
/// Whether the wake ends now, and why. `last` is how her last turn ended, `spent_usd` this wake's spend over all its turns and `day_spent_usd` the
/// UTC day's, both read from her trace before the next turn is judged: a turn that completed and crossed the day's cap ends the wake before another
/// turn is taken on lines it would never answer.
pub(crate) fn wake_end(span: &Span, last: &Ended, spent_usd: f64, day_spent_usd: f64, now: DateTime<Utc>, bounds: &AgentTuning) -> Option<End> {
let seconds = |secs: u64| Duration::seconds(i64::try_from(secs).unwrap_or(i64::MAX));
if matches!(last, Ended::Failed(_)) {
Some(End::Failed)
} else if day_spent_usd >= bounds.day_usd || matches!(last, Ended::Cap(Cap::DaySpend)) {
Some(End::DayCap)
} else if spent_usd >= bounds.wake_usd || matches!(last, Ended::Cap(Cap::WakeSpend)) {
Some(End::Spend)
} else if now - span.opened >= seconds(bounds.span_s) {
Some(End::Span)
} else if now - span.last_ended >= seconds(bounds.idle_s) {
Some(End::Idle)
} else {
None
}
}
/// How long after a poll first sees `delivery` a Mind takes it, in milliseconds. This is the first experiment's stagger, ported from
/// `crates/mind-body/src/persona.rs` at `0fd1232^` (`stagger_ms`, ruling `eureka-body:ruling:unaddressed-tell-stagger-ruled`): none in a direct
/// message, otherwise her rank times `STAGGER_STEP_S`. The Minds the message names (tagged, named, or named by a project, by `address::addresses`
/// over the swarm's addressing) rank first, by a hash of the Mind and the event, and the rest follow them, ranked the same way: the first addressed Mind
/// takes it at once, the others one step apart, so addressing several does not make a chorus, and the later ones read the earlier ones' answers before
/// they give theirs. A rank is the number of Minds in her set whose hash sorts before hers, from the message and the addressing table alone (the
/// sender, who will not take its own message, is not counted), so every process computes the same order with no word between them and nobody is
/// always last. The set is the addressed Minds when she is among them, else the others, after the addressed ones. Verbatim from the first
/// experiment, `own` standing for `config.own_sender`.
pub(crate) fn stagger_ms(own: &Addressee, addressing: &[Addressee], delivery: &ChatDelivery) -> u64 {
if delivery.is_direct {
return 0;
}
let mut minds: Vec<&Addressee> = addressing.iter().filter(|mind| mind.matrix_id() != delivery.sender).collect();
minds.sort_unstable_by_key(|mind| mind.matrix_id());
minds.dedup_by_key(|mind| mind.matrix_id());
let (addressed, others): (Vec<&Addressee>, Vec<&Addressee>) = minds.into_iter().partition(|mind| if mind.matrix_id() == own.matrix_id() { is_for(mind, delivery) } else { addresses(mind, delivery) });
let own_is_addressed = addressed.iter().any(|mind| mind.matrix_id() == own.matrix_id());
let (set, before) = if own_is_addressed { (&addressed, 0) } else { (&others, addressed.len()) };
let mine = (stagger_hash(own.matrix_id(), &delivery.event_id), own.matrix_id());
let rank = before + set.iter().filter(|mind| (stagger_hash(mind.matrix_id(), &delivery.event_id), mind.matrix_id()) < mine).count();
rank as u64 * STAGGER_STEP_S * 1000
}
/// FNV-1a over the Mind, a separator and the event, then murmur3's finalizer so a Mind's order against another changes from event to event
/// (FNV alone leaves it nearly fixed by the Minds' names): fixed by this definition, so every Mind's process computes the same order.
/// Verbatim from the first experiment's `stagger_hash`.
pub(crate) fn stagger_hash(mind: &str, event_id: &str) -> u64 {
let mut hash = mind.bytes().chain(std::iter::once(0xff)).chain(event_id.bytes()).fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
hash ^ (hash >> 33)
}
/// Who she is to the room, as the heartbeat reads it: the one derivation of "this line wakes her", for the open and for every poll of the span.
pub(crate) struct Hearing<'a> {
pub config: &'a Config,
pub her: &'a Addressee,
pub addressing: &'a [Addressee],
pub own_rooms: &'a [String],
/// The lines the heartbeat woke her for, read once at the open: the open floor is hers only on those. The heartbeat claims no floor line for a
/// Mind whose unit is active, so nothing new can appear in it mid-wake.
pub claimed: &'a [String],
}
impl Hearing<'_> {
/// For each of `deliveries` (oldest first), whether it wakes her: the heartbeat's `wakes`, or a claim the heartbeat made for her.
pub(crate) fn waking(&self, deliveries: &[&ChatDelivery]) -> Vec<bool> {
let mut facts = pending_facts(deliveries, &self.config.own_sender, &self.config.minds, self.own_rooms);
for (delivery, facts) in deliveries.iter().zip(&mut facts) {
facts.open_floor &= self.claimed.contains(&delivery.event_id);
}
deliveries.iter().zip(&facts).map(|(delivery, facts)| self.claimed.contains(&delivery.event_id) || wakes(self.her, delivery, speaker(self.config, delivery), *facts).is_some()).collect()
}
}
/// What a poll finds in the mouth that this wake has not dealt with.
pub(crate) struct Found<'a> {
/// Every line her trace does not hold decided and no turn of this wake has taken, and that has not struck out, oldest first.
pub fresh: Vec<&'a ChatDelivery>,
/// Those of `fresh` that wake her.
pub waking: Vec<&'a ChatDelivery>,
}
/// The lines of `pool` (oldest first) that are new to the wake: not decided by her trace (`done`), not in a turn this wake ran (`taken`), and
/// not a line two wakes failed on, which the next open sets aside.
pub(crate) fn find<'a>(hearing: &Hearing<'_>, pool: &'a [ChatDelivery], done: &BTreeSet<&str>, records: &[Value], taken: &BTreeSet<String>) -> Found<'a> {
let all: Vec<&ChatDelivery> = pool.iter().collect();
let flags = hearing.waking(&all);
let mut found = Found { fresh: vec![], waking: vec![] };
for (delivery, waking) in all.into_iter().zip(flags) {
if done.contains(delivery.event_id.as_str()) || taken.contains(&delivery.event_id) || strikes(records, &delivery.event_id) >= STRIKES {
continue;
}
found.fresh.push(delivery);
if waking {
found.waking.push(delivery);
}
}
found
}
/// The next turn: the lines it holds, the rooms the wake now has, and the line its failure would strike.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Taking {
pub hold: Vec<String>,
pub rooms: Vec<String>,
/// The oldest waking line, when the turn's waking lines are all in one room: a failure that is no outage strikes it and no other. A turn
/// over several rooms cannot say which one failed it, and strikes nothing.
pub strike: Option<String>,
}
/// Whether the wake takes a turn now, and on what. A waking line is taken once it is due (`stagger_ms` from the poll that first saw it); the
/// turn then holds every waking line, due or not (she is never shown a line and kept from the ones before it), and every other new line of the
/// wake's rooms, her own and what is no message included, as the open's `held` does. The room of a waking line joins the wake. A wake that began
/// retreating (the start after one that failed for a reason that is no outage takes one room at a time, so a failure is found in one room alone
/// and strikes that room's oldest line and no innocent room's) takes one room a turn.
pub(crate) fn take(hearing: &Hearing<'_>, found: &Found<'_>, rooms: &[String], retreating: bool, first_seen: &mut BTreeMap<String, DateTime<Utc>>, now: DateTime<Utc>) -> Option<Taking> {
let oldest_room = found.waking.first().map(|delivery| delivery.room_alias.as_str());
let waking: Vec<&ChatDelivery> = found.waking.iter().copied().filter(|delivery| !retreating || Some(delivery.room_alias.as_str()) == oldest_room).collect();
for delivery in &waking {
first_seen.entry(delivery.event_id.clone()).or_insert(now);
}
let due = waking.iter().any(|delivery| now - first_seen[&delivery.event_id] >= Duration::milliseconds(i64::try_from(stagger_ms(hearing.her, hearing.addressing, delivery)).unwrap_or(i64::MAX)));
if !due {
return None;
}
let mut rooms = rooms.to_vec();
for delivery in &waking {
if !rooms.contains(&delivery.room_alias) {
rooms.push(delivery.room_alias.clone());
}
}
let hold = found.fresh.iter().filter(|delivery| rooms.contains(&delivery.room_alias)).map(|delivery| delivery.event_id.clone()).collect();
let waking_rooms: BTreeSet<&str> = waking.iter().map(|delivery| delivery.room_alias.as_str()).collect();
let strike = (waking_rooms.len() == 1).then(|| waking.first().map(|delivery| delivery.event_id.clone())).flatten();
Some(Taking { hold, rooms, strike })
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,156 @@
//! The pure parts of a wake's span: when it ends, and how long a line addressed to several Minds waits for her.
use chrono::TimeZone;
use super::*;
use crate::chat_client::Form;
use crate::projection::Failed;
fn at(secs: i64) -> DateTime<Utc> {
Utc.timestamp_opt(1_800_000_000 + secs, 0).unwrap()
}
/// A wake that opened at 0 and whose last turn ended at `last`, judged at `now`.
fn ends(last: Ended, spent: f64, ended_at: i64, now: i64) -> Option<End> {
wake_end(&Span { opened: at(0), last_ended: at(ended_at) }, &last, spent, 0.0, at(now), &AgentTuning::default())
}
fn failed() -> Ended {
Ended::Failed(Failed { reason: "refused".into(), outage: false, usage: None })
}
#[test]
fn a_wake_waiting_for_a_line_ends_idle_at_idle_s_after_her_last_turn() {
assert_eq!(ends(Ended::EndTurn, 0.1, 100, 399), None);
assert_eq!(ends(Ended::EndTurn, 0.1, 100, 400), Some(End::Idle), "idle_s is 300");
// The window runs from her last turn's end, not from the wake's opening.
assert_eq!(ends(Ended::EndTurn, 0.1, 1000, 1299), None);
assert_eq!(ends(Ended::EndTurn, 0.1, 1000, 1300), Some(End::Idle));
}
#[test]
fn a_wake_open_span_s_ends_though_lines_keep_coming() {
assert_eq!(ends(Ended::EndTurn, 0.1, 1799, 1799), None);
assert_eq!(ends(Ended::EndTurn, 0.1, 1799, 1800), Some(End::Span), "span_s is 1800");
}
#[test]
fn a_wake_that_has_spent_its_cap_ends() {
assert_eq!(ends(Ended::EndTurn, 0.99, 0, 10), None);
assert_eq!(ends(Ended::EndTurn, 1.0, 0, 10), Some(End::Spend), "wake_usd is 1.00");
assert_eq!(ends(Ended::Cap(Cap::WakeSpend), 0.1, 0, 10), Some(End::Spend), "a turn the wake cap stopped");
}
#[test]
fn a_turn_that_hit_the_day_cap_or_failed_ends_the_wake() {
assert_eq!(ends(Ended::Cap(Cap::DaySpend), 0.1, 0, 10), Some(End::DayCap));
assert_eq!(ends(failed(), 0.1, 0, 10), Some(End::Failed));
// A turn a per-turn bound stopped is no reason to end the wake.
assert_eq!(ends(Ended::Cap(Cap::ToolCalls), 0.1, 0, 10), None);
assert_eq!(ends(Ended::Cap(Cap::ModelCalls), 0.1, 0, 10), None);
}
/// H1: the day's spend is read from her trace before each turn is judged, so a turn that completed and crossed the cap ends the wake.
#[test]
fn a_day_spent_to_its_cap_ends_the_wake_though_her_last_turn_ended_well() {
let end = |day: f64| wake_end(&Span { opened: at(0), last_ended: at(0) }, &Ended::EndTurn, 0.1, day, at(10), &AgentTuning::default());
assert_eq!(end(2.99), None);
assert_eq!(end(3.0), Some(End::DayCap), "day_usd is 3.00");
}
#[test]
fn the_ends_are_judged_in_order() {
// Everything true at once: failed, then the day cap, then the wake's spend, then the span, then idle.
assert_eq!(ends(failed(), 5.0, 0, 5000), Some(End::Failed));
assert_eq!(ends(Ended::Cap(Cap::DaySpend), 5.0, 0, 5000), Some(End::DayCap));
assert_eq!(ends(Ended::EndTurn, 5.0, 0, 5000), Some(End::Spend));
assert_eq!(ends(Ended::EndTurn, 0.1, 0, 5000), Some(End::Span));
assert_eq!(ends(Ended::EndTurn, 0.1, 0, 1000), Some(End::Idle));
}
const ALL: [&str; 3] = ["@eureka:gamecult.org", "@libby:gamecult.org", "@kiko:gamecult.org"];
fn table() -> Vec<Addressee> {
ALL.iter().map(|id| Addressee::new(id, [crate::address::localpart(id)])).collect()
}
fn said(event: &str, sender: &str, room: &str, direct: bool, mentions: &[&str], text: &str) -> ChatDelivery {
ChatDelivery {
seq: 1,
room_alias: room.into(),
room_id: room.into(),
event_id: event.into(),
sender: sender.into(),
sender_display: String::new(),
text: text.into(),
at_unix_ms: 0,
context: vec![],
mentions: mentions.iter().map(|id| (*id).to_owned()).collect(),
is_direct: direct,
image: None,
basis: None,
form: Form::Message,
reply_to: Default::default(),
}
}
/// Each Mind's delay for one line from the operator tagging all three.
fn delays(event: &str) -> Vec<u64> {
let line = said(event, "@meta:gamecult.org", "#minds:gamecult.org", false, &ALL, "all of you, a question");
let table = table();
table.iter().map(|own| stagger_ms(own, &table, &line)).collect()
}
/// The first experiment's stagger (`persona.rs` at `0fd1232^`): a line addressed to several Minds is taken by them one step apart, each at her rank.
#[test]
fn a_line_to_three_minds_is_taken_one_step_apart() {
for event in ["$a", "$b", "$c", "$d", "$e"] {
let mut ranks = delays(event);
ranks.sort_unstable();
assert_eq!(ranks, [0, 8000, 16000], "{event}: the first Mind takes it at once and the others 8 s per rank");
}
}
#[test]
fn the_order_changes_from_event_to_event_so_nobody_is_always_last() {
let last: BTreeSet<usize> = (0..40).map(|n| delays(&format!("$ev{n}")).iter().position(|delay| *delay == 16000).unwrap()).collect();
assert_eq!(last.len(), 3, "each of the three is last for some event: {last:?}");
}
#[test]
fn the_sender_is_not_counted_and_a_direct_message_waits_for_no_one() {
let table = table();
// Libby tags Eureka and Kiko: two Minds, not three.
let line = said("$x", ALL[1], "#minds:gamecult.org", false, &[ALL[0], ALL[2]], "you two");
let mut ranks: Vec<u64> = [&table[0], &table[2]].iter().map(|own| stagger_ms(own, &table, &line)).collect();
ranks.sort_unstable();
assert_eq!(ranks, [0, 8000]);
// A direct message is one Mind's alone.
assert_eq!(stagger_ms(&table[0], &table, &said("$z", "@meta:gamecult.org", "!dm:gamecult.org", true, &[], "hello")), 0);
}
/// The first experiment ranked the Minds a line did not address after the addressed ones, so a line to one Mind sends the others behind her: the
/// addressed Mind takes it at once, and the two it did not name one and two steps after.
#[test]
fn the_minds_a_line_did_not_address_rank_after_the_addressed_ones() {
let table = table();
for event in ["$a", "$b", "$c", "$d", "$e", "$f"] {
let line = said(event, "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0]], "just you, Eureka");
let delays: Vec<u64> = table.iter().map(|own| stagger_ms(own, &table, &line)).collect();
assert_eq!(delays[0], 0, "{event}: the Mind it names takes it at once");
let mut behind = vec![delays[1], delays[2]];
behind.sort_unstable();
assert_eq!(behind, [8000, 16000], "{event}: the others follow her, one step apart");
}
// Two named: the unnamed third is one step behind them.
let line = said("$g", "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0], ALL[1]], "you two");
assert_eq!(stagger_ms(&table[2], &table, &line), 16000, "two addressed ahead of her");
}
#[test]
fn the_hash_is_fixed_so_every_process_computes_the_same_order() {
assert_eq!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@eureka:gamecult.org", "$e1"));
assert_ne!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@libby:gamecult.org", "$e1"));
assert_ne!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@eureka:gamecult.org", "$e2"));
assert_eq!(STAGGER_STEP_S, 8, "the step is the calibration the ruling names");
}

View file

@ -20,6 +20,7 @@ fn config() -> Config {
minds: vec!["@eureka:chat".into(), "@libby:chat".into()], minds: vec!["@eureka:chat".into(), "@libby:chat".into()],
own_sender: "@eureka:chat".into(), own_sender: "@eureka:chat".into(),
model: "claude-test-model".into(), model: "claude-test-model".into(),
review_room: None,
} }
} }
@ -237,7 +238,7 @@ fn the_persona_flags_come_from_the_environment_when_the_command_line_lacks_them(
let (config, rest) = Config::from_args_and_env(&args("--instance eureka"), env, "usage").unwrap(); let (config, rest) = Config::from_args_and_env(&args("--instance eureka"), env, "usage").unwrap();
assert_eq!( assert_eq!(
config, config,
Config { rooms: vec!["swarm".into(), "usage".into()], operators: vec!["@op:chat".into(), "@op2:chat".into()], minds: vec!["@libby:chat".into(), "@aqua:chat".into()], own_sender: "@eureka:chat".into(), model: "claude-test-model".into() } Config { rooms: vec!["swarm".into(), "usage".into()], operators: vec!["@op:chat".into(), "@op2:chat".into()], minds: vec!["@libby:chat".into(), "@aqua:chat".into()], own_sender: "@eureka:chat".into(), model: "claude-test-model".into(), review_room: None }
); );
assert_eq!(rest, ["--instance", "eureka"]); assert_eq!(rest, ["--instance", "eureka"]);
// A flag wins over its variable, one at a time. // A flag wins over its variable, one at a time.
@ -392,3 +393,17 @@ fn a_named_gap_with_no_lines_reads_unknown_and_never_empty() {
let none = render_tail(&config(), &[], Some(vec![]), &[], &rooms, &[], &[]); let none = render_tail(&config(), &[], Some(vec![]), &[], &rooms, &[], &[]);
assert!(none.text.contains("Recent tail of your rooms: empty."), "{}", none.text); assert!(none.text.contains("Recent tail of your rooms: empty."), "{}", none.text);
} }
/// M1: what a reseeded session is told of the wake so far is bounded, keeps the newest acts, says how many it left out, and is nothing when nothing was done.
#[test]
fn done_so_far_keeps_the_newest_acts_within_its_budget() {
use crate::projection::agent::Status;
assert_eq!(done_so_far(&[]), "");
let receipts: Vec<Receipt> = (0..300).map(|n| Receipt::new("say", Status::Ok, json!({ "room": "#minds:gamecult.org", "text": format!("act number {n:03} {}", "z".repeat(120)) }))).collect();
let told = done_so_far(&receipts);
assert!(told.len() < DONE_BYTES + 400, "{}", told.len());
assert!(told.contains("act number 299") && !told.contains("act number 000"), "the newest are kept");
assert!(told.contains("earlier act(s) are not shown"));
let few = done_so_far(&receipts[..2]);
assert!(few.contains("act number 000") && few.contains("act number 001") && !few.contains("not shown"));
}

View file

@ -8,8 +8,8 @@
//! //!
//! The Projector shows her self and her room: her persona state and what the mouth showed. It reads her Mind for one thing //! The Projector shows her self and her room: her persona state and what the mouth showed. It reads her Mind for one thing
//! only, what moved in her domain lately (`domain`, map 16.22.2): her stewardships and campaigns through her read door, her //! only, what moved in her domain lately (`domain`, map 16.22.2): her stewardships and campaigns through her read door, her
//! repos' pull requests on the forge, rendered by code as news, never as a task. Anything else she reads is the //! repos' pull requests on the forge, rendered by code as news, never as a task. Anything else she reads is her agent's `read`
//! Interpreter's read tools' (C3b), when wondering leads to reading. //! tool's (`agent::read`).
//! //!
//! `project` is the experiment tool over both (`mind-persona project`): what Select would build from her real or a //! `project` is the experiment tool over both (`mind-persona project`): what Select would build from her real or a
//! hypothetical state, what the Projector would narrate, and with `Through::Persona` what she would answer in her own //! hypothetical state, what the Projector would narrate, and with `Through::Persona` what she would answer in her own
@ -19,6 +19,7 @@
//! `MouthReader` reads pending chat, `DomainSource` reads her domain, `ReadSource` performs the reads she reaches for, `Model` asks. None of them can put, admit, send, ack or open a conversation, so //! `MouthReader` reads pending chat, `DomainSource` reads her domain, `ReadSource` performs the reads she reaches for, `Model` asks. None of them can put, admit, send, ack or open a conversation, so
//! `project` cannot write and runs under a held brake. //! `project` cannot write and runs under a held brake.
pub mod agent;
pub mod harness; pub mod harness;
mod commit; mod commit;
mod domain; mod domain;
@ -32,6 +33,7 @@ mod simulate;
mod span; mod span;
mod tuning; mod tuning;
mod turn; mod turn;
mod wake;
use std::path::PathBuf; use std::path::PathBuf;
@ -41,20 +43,32 @@ use eureka_state::HuginnClient;
use huginn_mind::HuginnMindResponse; use huginn_mind::HuginnMindResponse;
use serde_json::{Value, json}; use serde_json::{Value, json};
use crate::address::{Addressee, is_for, localpart}; use crate::address::{Addressee, is_for, localpart, others_addressed};
use crate::chat_client::{Chat, ChatPending, Form, ReplyLink}; use crate::chat_client::{Chat, ChatPending, Form, ReplyLink};
use crate::heartbeat::HeartbeatView; use crate::heartbeat::HeartbeatView;
pub use domain::{DomainFacts, DomainSource, HttpForge, MindDomain}; pub use domain::{DomainFacts, DomainSource, HttpForge, MindDomain};
pub use narrate::{Answer, Continued, Failed, KitModel, Model, Reasoning, Spent, Turn, connector_key}; pub use narrate::{Answer, Failed, KitModel, Model, Spent, StepRequest, Stepped, ToolCall, connector_key};
pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource};
pub use select::TurnKind; pub use select::TurnKind;
pub(crate) use commit::apply as apply_commit; pub(crate) use commit::Applied;
pub(crate) use turn::{Mouth, Pass, Taken, decide, decided, deliver, failed_run, history, owes, owes_send, owing, untold_rooms}; #[cfg(test)]
pub(crate) use commit::Heard;
pub(crate) use interpret::{acts_of, heard_of, interpret_and_put};
#[cfg(test)]
pub(crate) use interpret::put_applied;
pub(crate) use turn::{DAY_CAP_HOLD, decided, failed, failed_run, history, is_wake};
#[cfg(test)]
pub(crate) use turn::Taken;
pub(crate) use agent::say::{Mouth, settle_handed};
pub(crate) use wake::{Fault, Waked, wake};
pub use tuning::{TUNING_FILE, TUNING_ROOT}; pub use tuning::{TUNING_FILE, TUNING_ROOT};
pub(crate) use tuning::load as load_tuning;
pub(crate) use tuning::AgentTuning;
pub(crate) use select::People;
use narrate::{cap_prose, cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; use narrate::{cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words};
use select::{History, Inputs, Packet, People, Replied, Room, RoomLine, select, turn_room}; use select::{History, Inputs, Packet, Replied, Room, RoomLine, select, turn_room};
/// The agent name on the connector's request ids. /// The agent name on the connector's request ids.
const AGENT: &str = "mind-persona"; const AGENT: &str = "mind-persona";
@ -153,76 +167,53 @@ pub struct Organs<'a> {
} }
/// One thing she can do this turn, typed by what it does (map 16.6, 16.18). Derived by `affordances` from what the turn /// One thing she can do this turn, typed by what it does (map 16.6, 16.18). Derived by `affordances` from what the turn
/// actually holds, never written in state or in guidance, nor taken from what the request asks for (map 16.19.5), so she /// actually holds, never written in state or in guidance, so she is never told she can do what this turn cannot: the room
/// is never told she can do what this turn cannot. /// that was read, and the tools her agent holds this wake (map 16.38.4), named by their definitions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub(crate) enum Affordance { pub(crate) enum Affordance {
/// The room reaches her as typed lines: the mouth's `RoomLine` carries text only, and Select renders no images. /// The room reaches her as typed lines: the mouth's `RoomLine` carries text only, and Select renders no images.
Perceive, Perceive,
/// She sends a draft of hers in the turn's room (`interpret`). Say,
Speak,
/// She leaves Self a note, recorded in her turn's record for Self's inbox (map 16.18). Not a write: it builds, changes
/// and ships nothing (16.19.6).
Suggest,
/// She reads what her thought reaches for (map 16.22.3): her mind, her domain, a GameCult repo, a web address in front
/// of her. Code performs it; she goes on from what she read. Not a write: it builds, changes and ships nothing.
Read, Read,
/// A test's stand-in for the first affordance that builds, changes or ships something (map 16.19.6): none exists yet. Shell,
#[cfg(test)] RequestTool,
TestWrite,
} }
impl Affordance { /// What this turn can do, from what it holds: `Perceive` when the room was read (a harness fixture's and the simulated
/// Whether it builds, changes or ships anything in the world. None does yet: the match is exhaustive, so the day a /// room's always are), and one affordance for each tool her agent holds, by the tool's name. A failed read, or no mouth, and no
/// write affordance is added it must answer here, and the body line's "nothing she does here builds…" goes with it. /// room reaches her; a name no affordance knows is not one.
pub(crate) fn writes(self) -> bool { pub(crate) fn affordances(read: bool, tools: &[String]) -> Vec<Affordance> {
match self { let mut can = if read { vec![Affordance::Perceive] } else { Vec::new() };
Self::Perceive | Self::Speak | Self::Suggest | Self::Read => false, can.extend(tools.iter().filter_map(|tool| match tool.as_str() {
#[cfg(test)] "say" => Some(Affordance::Say),
Self::TestWrite => true, "read" => Some(Affordance::Read),
} "shell" => Some(Affordance::Shell),
} "request_tool" => Some(Affordance::RequestTool),
_ => None,
}));
can
} }
/// What this turn can do, from what it holds (map 16.19.5): /// How far a render runs: the Projector's narration, or on through the Persona stage to her prose. A wake runs both,
/// - `Perceive` when the room was read: the mouth's read returned (a harness fixture's and the simulated room's always /// once (`wake`).
/// do). A failed read, or no mouth, and no room reaches her.
/// - `Speak` when the turn has a port her words go out through and a step that sends them: a mouth (the live mouth the
/// commit sends through, a fixture's, or the simulated room), a room to speak in (`select::turn_room`, the only one the
/// Interpreter lets her speak in), and the Interpreter running this turn. A run that stops at the Projector or the
/// Persona says nothing, and its packet says she can say nothing.
/// - `Suggest` when the Interpreter runs this turn: its report is the turn's record and carries `suggestions[]` (map
/// 16.19.5); no room is needed.
///
/// - `Read` when the Interpreter runs this turn and a reader is configured: what her thought reaches for is read by code
/// (map 16.22.3).
pub(crate) fn affordances(organs: &Organs, read: bool, room: Option<&str>, through: Through) -> Vec<Affordance> {
let interprets = through == Through::Interpreter;
let speaks = organs.chat.is_some() && room.is_some() && interprets;
let reads = organs.reads.is_some() && interprets;
[(read, Affordance::Perceive), (speaks, Affordance::Speak), (interprets, Affordance::Suggest), (reads, Affordance::Read)].into_iter().filter_map(|(can, affordance)| can.then_some(affordance)).collect()
}
/// 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)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum Through { pub enum Through {
#[default] #[default]
Projector, Projector,
Persona, Persona,
/// On through the Interpreter's speech step: what she says aloud, decided from her prose (`interpret`).
Interpreter,
} }
/// What to project. /// What to project.
#[derive(Clone)]
pub struct Request { pub struct Request {
pub instance: String, pub instance: String,
pub kind: TurnKind, pub kind: TurnKind,
/// A hypothetical state in place of the stored one. /// A hypothetical state in place of the stored one.
pub state: Option<Value>, pub state: Option<Value>,
/// The room the turn is in; none is every room of hers. /// The waking rooms of this wake, in order: the first is the turn's room, and every other is an arrival (who, where, when) to the Projector and verbatim lines to the Persona. None is every room of hers, as one room.
pub room: Option<String>, pub rooms: Vec<String>,
pub seed: u64, pub seed: u64,
/// None builds the packet only. Some(k) narrates k successive turns of the same state, each seeded `seed + i` and /// None builds the packet only. Some(k) narrates k successive turns of the same state, each seeded `seed + i` and
/// each under the freshness the ones before it leave. /// each under the freshness the ones before it leave.
@ -245,10 +236,11 @@ pub struct Request {
/// The events the heartbeat woke her for (`heartbeat::woken_for`; a simulation's, the lines its floor gave her): said to her, /// The events the heartbeat woke her for (`heartbeat::woken_for`; a simulation's, the lines its floor gave her): said to her,
/// as the wake that named her decided, whoever they were and in whatever room. /// as the wake that named her decided, whoever they were and in whatever room.
pub woken_for: Vec<String>, pub woken_for: Vec<String>,
/// The record of her last turn, which her packet opens with what came of (`outcome::outcome_of`): the Interpreter's /// The rows of her trace she is told at this wake, which her packet opens with (`outcome::told`, rendered by
/// decision under `interpreter` and the receipts of the lines that went out under `posted`, or `failed`. Read from her /// `outcome::outcome_of`): read from her records (`turn::history`); a harness run takes a fixture's (`--told`).
/// records (`turn::history`); a harness run takes a fixture's (`--last-outcome`). pub told: Vec<Value>,
pub last_outcome: Option<Value>, /// The names of the tools her agent holds this wake: what she can do, in her body section (`affordances`).
pub tools: Vec<String>,
/// When she last woke: her domain's window opens there, held to at least a day and at most a week (map 16.22.2). Read /// When she last woke: her domain's window opens there, held to at least a day and at most a week (map 16.22.2). Read
/// from her records (`turn::history`); none is a week. /// from her records (`turn::history`); none is a week.
pub last_wake: Option<DateTime<Utc>>, pub last_wake: Option<DateTime<Utc>>,
@ -300,19 +292,32 @@ fn read_domain(source: Option<&dyn DomainSource>, last_wake: Option<DateTime<Utc
} }
} }
/// The other Minds of the swarm as her room names them: the heartbeat's row for each Mind of the request when its table holds one,
/// else the Mind by her Matrix id and localpart (`address::others_addressed` reads who a line is for from these). Not her.
fn roster_of(addressing: Option<&dyn HeartbeatView>, request: &Request, own: &Addressee) -> Vec<Addressee> {
let table = addressing.and_then(|view| view.addressing().ok().flatten()).map(|table| table.minds).unwrap_or_default();
request
.minds
.iter()
.filter(|id| id.as_str() != own.matrix_id())
.map(|id| table.iter().find(|row| row.matrix_id() == id).cloned().unwrap_or_else(|| Addressee::new(id, [localpart(id)])))
.collect()
}
/// The room through the mouth's pending read, which acks nothing: new messages and the tail, own lines kept for the /// The room through the mouth's pending read, which acks nothing: new messages and the tail, own lines kept for the
/// Select stage to drop. A refusal is reported, never hidden. /// Select stage to drop. A refusal is reported, never hidden.
fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Room, Value) { fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee, roster: &[Addressee]) -> (Room, Value) {
let pending = match chat.pending() { let pending = match chat.pending() {
Ok(pending) => pending, Ok(pending) => pending,
Err(fault) => return (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })), Err(fault) => return (Room { here: request.rooms.first().cloned(), 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 // 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 // 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. // 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 here = request.rooms.first().cloned();
let wanted = |room: &str| here.as_deref().is_none_or(|here| here == room); let wanted = |room: &str| request.rooms.is_empty() || request.rooms.iter().any(|wanted| wanted == room);
let messages: Vec<RoomLine> = pending let here_only = |room: &str| here.as_deref().is_none_or(|here| here == room);
let lines: Vec<RoomLine> = pending
.deliveries .deliveries
.iter() .iter()
.filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias)) .filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias))
@ -322,23 +327,29 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo
display: delivery.sender_display.clone(), display: delivery.sender_display.clone(),
text: delivery.text.clone(), text: delivery.text.clone(),
at_ms: delivery.at_unix_ms, at_ms: delivery.at_unix_ms,
// The heartbeat's rule, the one that woke her: never a second opinion here. A human's line in // The heartbeat's rule, the one that woke her: never a second opinion here. A line that is for her (`is_for`) is to her.
// her own room always wakes her, so it is to her, as a direct message is (the plan's or unit's `own_rooms`), and so // A human's line in her own room always wakes her (the plan's or unit's `own_rooms`), and so does a line the heartbeat
// is a line the heartbeat woke her for (an open hello she was picked to answer: `woken_for`). // woke her for (an open hello she was picked to answer: `woken_for`); it is to her unless it is for another Mind
// (`others_addressed`), when it is said in her room and not to her.
to_her: is_for(own, delivery) to_her: is_for(own, delivery)
|| (delivery.sender != request.own_sender && !request.minds.contains(&delivery.sender) && (request.own_rooms.contains(&delivery.room_alias) || request.woken_for.contains(&delivery.event_id))), || (delivery.sender != request.own_sender
&& !request.minds.contains(&delivery.sender)
&& (request.own_rooms.contains(&delivery.room_alias) || request.woken_for.contains(&delivery.event_id))
&& others_addressed(own, roster, delivery).is_empty()),
event: delivery.event_id.clone(), event: delivery.event_id.clone(),
reply: replied(&delivery.reply_to), reply: replied(&delivery.reply_to),
}) })
.collect(); .collect();
// The turn's room is the first waking room; the lines of the others are the wake's elsewhere, read by the Persona and named to the Projector.
let (messages, elsewhere): (Vec<RoomLine>, Vec<RoomLine>) = lines.into_iter().partition(|line| here_only(&line.room));
let tail: Vec<RoomLine> = pending let tail: Vec<RoomLine> = pending
.tail .tail
.iter() .iter()
.flatten() .flatten()
.filter(|line| line.form == Form::Message && wanted(&line.room)) .filter(|line| line.form == Form::Message && here_only(&line.room))
.map(|line| RoomLine { room: line.room.clone(), sender: line.sender.clone(), display: String::new(), text: line.body.clone(), at_ms: line.at_unix_ms, to_her: false, event: line.event_id.clone(), reply: replied(&line.reply_to) }) .map(|line| RoomLine { room: line.room.clone(), sender: line.sender.clone(), display: String::new(), text: line.body.clone(), at_ms: line.at_unix_ms, to_her: false, event: line.event_id.clone(), reply: replied(&line.reply_to) })
.collect(); .collect();
let mut report = json!({ "read": true, "messages": messages.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps }); let mut report = json!({ "read": true, "messages": messages.len(), "elsewhere": elsewhere.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps });
if let Some(here) = &here if let Some(here) = &here
&& messages.is_empty() && messages.is_empty()
&& tail.is_empty() && tail.is_empty()
@ -347,7 +358,7 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo
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"); 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(); 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) (Room { messages, tail, elsewhere, here, last_heard: request.last_heard.clone(), direct, own: request.own_rooms.clone() }, report)
} }
/// The line a reply answers, as the mouth quoted it within its contract; a dropped link is no reply (`ReplyLink::quote`). /// The line a reply answers, as the mouth quoted it within its contract; a dropped link is no reply (`ReplyLink::quote`).
@ -363,14 +374,13 @@ fn packet_json(packet: &Packet) -> Value {
"present": packet.present, "present": packet.present,
"selected": packet.selected, "selected": packet.selected,
// Each section's bytes under its own guard, and the sum the Projector is shown of her (map 16.19.4). // Each section's bytes under its own guard, and the sum the Projector is shown of her (map 16.19.4).
"bytes": { "identity": packet.identity().len(), "outcome": packet.sections.outcome, "here": packet.sections.here, "body": packet.sections.body, "people": packet.sections.people, "domain": packet.sections.domain, "notes": packet.sections.notes, "total": packet.identity().len() + packet.context.len(), "stimulus": packet.stimulus.len(), "arrival": packet.arrival.len(), "heard": packet.heard.len() }, "bytes": { "identity": packet.identity().len(), "tendencies": packet.tendencies.len(), "outcome": packet.sections.outcome, "here": packet.sections.here, "body": packet.sections.body, "people": packet.sections.people, "domain": packet.sections.domain, "notes": packet.sections.notes, "total": packet.identity().len() + packet.tendencies.len() + packet.context.len(), "stimulus": packet.stimulus.len(), "arrival": packet.arrival.len(), "heard": packet.heard.len() },
"bound": packet.sections.bound, "bound": packet.sections.bound,
"overflow": packet.overflow, "overflow": packet.overflow,
"clipped": packet.clipped, "clipped": packet.clipped,
"name": packet.name, "name": packet.name,
"voice": packet.voice, "voice": packet.voice,
"affordances": packet.affordances, "affordances": packet.affordances,
"amendable": packet.amendable,
"quotable": packet.quotable, "quotable": packet.quotable,
"memories": packet.memories, "memories": packet.memories,
"domain": packet.domain, "domain": packet.domain,
@ -381,6 +391,7 @@ fn packet_json(packet: &Packet) -> Value {
"arrival": packet.arrival, "arrival": packet.arrival,
"speaking": packet.speaking, "speaking": packet.speaking,
"heard": packet.heard, "heard": packet.heard,
"shown_from_other_rooms": packet.elsewhere_shown,
}) })
} }
@ -399,30 +410,18 @@ fn wake_id(instance: &str, tag: &str, seed: u64) -> String {
format!("{AGENT}:{instance}:project:{tag}:{seed}:{}", Utc::now().timestamp_nanos_opt().unwrap_or_default()) format!("{AGENT}:{instance}:project:{tag}:{seed}:{}", Utc::now().timestamp_nanos_opt().unwrap_or_default())
} }
/// One call's id under its render's root: its stage and the segment of her wake it serves (0 before any read, n after /// One call's id under its render's root: its stage. Every call of a render has its own id.
/// the nth). The Interpreter appends its attempt (`interpret::decide_in`), so every call of a render has its own id. fn call_id(wake: &str, stage: &str) -> String {
fn call_id(wake: &str, stage: &str, segment: usize) -> String { format!("{wake}:{stage}")
format!("{wake}:{stage}:{segment}")
}
/// What a wake reads through (map 16.22.3): the port that performs her reads, and when her domain's window opened.
#[derive(Clone, Copy)]
struct Reading<'a> {
source: &'a dyn ReadSource,
since: DateTime<Utc>,
} }
/// One render of one packet: the Projector's narration and, through the Persona stage, her prose over it, each its own /// 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. /// call with its usage. A failed call is a record with its reason and what it cost, never the end of the report. The
/// /// Persona is one call: she is asked for her inner voice and nothing else, so nothing in her answer is read for acts.
/// Through the Interpreter, her wake is a loop (map 16.22.3): the Interpreter judges her newest segment; when it names a fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, through: Through) -> Value {
/// read and the caps allow, code performs it, appends code's bridge with the result to her conversation, and the Persona
/// goes on from there, each request ending on that user text; the next call judges only the new segment. The decision
/// carries every segment's acts in order and every read (`reads`), which her next outcome lists without their content.
fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, through: Through, reading: Option<Reading>) -> Value {
let ids: Vec<String> = packet.selected.iter().map(|pick| pick.id.clone()).collect(); let ids: Vec<String> = packet.selected.iter().map(|pick| pick.id.clone()).collect();
let wake_id = wake_id(instance, tag, packet.seed); let wake_id = wake_id(instance, tag, packet.seed);
let answer = match model.ask(&call_id(&wake_id, "projector", 0), &tuning.projector.model, &projector_prompt(packet, tuning), None) { let answer = match model.ask(&call_id(&wake_id, "projector"), &tuning.projector.model, &projector_prompt(packet, tuning), None) {
Ok(answer) => answer, Ok(answer) => answer,
Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "outage": failed.outage, "usage": failed.usage }), Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "outage": failed.outage, "usage": failed.usage }),
}; };
@ -445,116 +444,13 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni
if through == Through::Projector { if through == Through::Projector {
return render; return render;
} }
let mut turns = vec![Turn::User(persona_prompt(packet, &narration, tuning))]; match model.ask(&call_id(&wake_id, "persona"), &tuning.persona.model, &persona_prompt(packet, &narration, tuning), None) {
let first = match model.converse(&call_id(&wake_id, "persona", 0), &tuning.persona.model, &turns) { Ok(spoke) => {
Ok(spoke) => spoke, let prose = cap_words(&spoke.text, tuning.persona.words);
Err(failed) => { render["persona"] = json!({ "words": words(&prose), "cut_at_budget": words(&spoke.text) > tuning.persona.words, "usage": spoke.usage, "prose": prose });
render["persona"] = json!({ "failed": failed.reason, "outage": failed.outage, "usage": failed.usage });
return render;
} }
}; Err(failed) => render["persona"] = json!({ "failed": failed.reason, "outage": failed.outage, "usage": failed.usage }),
// Never cut inside a draft (Soul's R5): a draft the cap cut off is told to her as unfinished, cut by the cap.
let capped = cap_prose(&first.answer.text, tuning.persona.words);
let mut prose = capped.text;
let mut cut_drafts: Vec<String> = capped.cut_drafts;
// Each continuation's call, its usage under `usage` so the report's totals count it (Soul: 72 of 76 calls counted).
let mut continuations: Vec<Value> = Vec::new();
render["persona"] = json!({ "words": words(&prose), "cut_at_budget": capped.cut, "usage": first.answer.usage, "prose": prose });
if through != Through::Interpreter {
return render;
} }
turns.push(Turn::Assistant { text: prose.clone(), states: first.states });
let her = packet.forms;
let (mut from, mut before, mut read_texts, mut read_bytes) = (0usize, String::new(), Vec::<String>::new(), 0usize);
let mut decision = interpret::decide(model, &call_id(&wake_id, "interpreter", 0), packet, &narration, &prose, tuning);
let mut reads: Vec<Value> = Vec::new();
let mut ended = None;
while let (Some(reading), Some(read)) = (reading, decision.get("read").filter(|read| !read.is_null()).cloned()) {
// Caps (map 16.22.3): reads a wake, bytes a wake, and her prose across segments at most twice her word budget. A
// read is performed only when the reply after it can have her whole word budget inside that, so the overall cap
// never cuts the reply short (Soul, F.1 r9).
let words_left = (tuning.persona.words * 2).saturating_sub(words(&prose));
let bytes_left = tuning.interpreter.wake_read_bytes.saturating_sub(read_bytes);
if reads.len() >= tuning.interpreter.reads_per_wake || bytes_left == 0 || words_left < tuning.persona.words {
let cap = if reads.len() >= tuning.interpreter.reads_per_wake { "reads_per_wake" } else if bytes_left == 0 { "wake_read_bytes" } else { "prose_words" };
ended = Some(cap);
// A read a cap refuses is recorded with what it was, and told to her next wake (`outcome`).
let mut refused = decision["read_refused"].as_array().cloned().unwrap_or_default();
refused.push(json!({ "read": read, "why": cap, "what": read["what"], "request": read["request"] }));
decision["read_refused"] = json!(refused);
break;
}
let Ok(request) = serde_json::from_value::<ReadRequest>(read["request"].clone()) else { break };
let what = read["what"].as_str().unwrap_or_default().to_owned();
let result = reading.source.read(&request, reading.since).map(|text| read::clipped(&text, tuning.interpreter.read_bytes.min(bytes_left)));
let mut done = json!({ "n": reads.len() + 1, "kind": read["kind"], "target": read["target"], "request": read["request"], "what": what, "quote": read["quote"] });
match &result {
Ok(text) => {
done["ok"] = json!(true);
done["bytes"] = json!(text.len());
// What it returned rides in the record: her side of the conversation shows it (K26).
done["text"] = json!(text);
read_bytes += text.len();
read_texts.push(text.clone());
}
Err(why) => {
done["ok"] = json!(false);
done["failure"] = json!(why);
}
}
reads.push(done);
let bridge = read::bridge(her, &what, result.as_deref().map_err(|why| *why));
turns.push(Turn::User(bridge.clone()));
let continued = match model.converse(&call_id(&wake_id, "persona", reads.len()), &tuning.persona.model, &turns) {
Ok(spoke) => spoke,
Err(failed) => {
decision["reads"] = json!(reads);
decision["continuation_failed"] = json!({ "failed": failed.reason, "usage": failed.usage });
break;
}
};
let capped = cap_prose(&continued.answer.text, tuning.persona.words);
let segment = capped.text;
cut_drafts.extend(capped.cut_drafts);
continuations.push(json!({ "usage": continued.answer.usage, "words": words(&segment), "cut_at_budget": capped.cut }));
turns.push(Turn::Assistant { text: segment.clone(), states: continued.states });
before = format!("{before}{}\n\n{bridge}\n\n", &prose[from..]);
prose = format!("{prose}\n\n{segment}");
from = prose.len() - segment.len();
// Where her thought after the read begins: a draft before it was typed without the read (map 16.26).
if let Some(done) = reads.last_mut() {
done["after_byte"] = json!(from);
}
decision["reads"] = json!(reads);
let wake = interpret::Wake { earlier: Some(&decision), from, read: &read_texts, before: &before };
let next = interpret::decide_in(model, &call_id(&wake_id, "interpreter", reads.len()), packet, &narration, &prose, tuning, wake);
// A failed call on a later segment fails that segment only: what was decided before it stands, and posts and
// applies (Soul p5); the failure, with what it cost, is recorded beside it.
if next.get("failed").is_some() {
// Its own calls only: the earlier ones ride in `decision` already, so each is counted once.
let before = decision["calls"].as_array().map_or(0, Vec::len);
let own: Vec<Value> = next["calls"].as_array().into_iter().flatten().skip(before).cloned().collect();
decision["later_failed"] = json!({ "segment": reads.len() + 1, "failed": next["failed"], "raw": next.get("raw"), "calls": own });
break;
}
decision = next;
}
// A draft the cap cut off before it closed: never in her stream, and told to her as unfinished, cut by the cap.
// Every draft the cap cut off: never in her stream, each told to her as cut by the length limit (`outcome`).
if !cut_drafts.is_empty() && decision.get("failed").is_none() {
decision["cut_by_cap"] = json!(cut_drafts);
}
if let Some(cap) = ended {
decision["read_ended"] = json!(cap);
}
if !reads.is_empty() {
decision["reads"] = json!(reads);
}
render["persona"]["prose"] = json!(prose);
render["persona"]["words"] = json!(words(&prose));
render["persona"]["segments"] = json!(1 + continuations.len());
render["persona"]["continuations"] = json!(continuations);
render["interpreter"] = decision;
render render
} }
@ -587,20 +483,20 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned(); let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned();
let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now); let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now);
let (room, room_report) = match organs.chat { let (room, room_report) = match organs.chat {
Some(chat) => read_room(chat, request, &own), Some(chat) => read_room(chat, request, &own, &roster_of(organs.addressing, 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" })), None => (Room { here: request.rooms.first().cloned(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })),
}; };
let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender }; let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender };
// Freshness, her own recent words and what came of her last turn come from trace v2, which the commit writes (C3c); // Freshness, her own recent words and what came of her last turn come from trace v2, which the commit writes (C3c);
// until then only what the caller carried from earlier turns of its own. // until then only what the caller carried from earlier turns of its own.
let history = History { recent: request.recent.clone(), last: request.last_outcome.as_ref().and_then(outcome::outcome_of), ..History::default() }; let history = History { recent: request.recent.clone(), last: outcome::outcome_of(&request.told), ..History::default() };
let names = domain::Names::of(&state, &people, &request.instance); let names = domain::Names::of(&state, &people, &request.instance);
let (digest, domain_report) = read_domain(organs.domain, request.last_wake, now, &names); let (digest, domain_report) = read_domain(organs.domain, request.last_wake, now, &names);
let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed, affordances: &[], domain: digest.as_ref(), exchange: None }; let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed, affordances: &[], domain: digest.as_ref(), exchange: None };
// Her side of this conversation, from her turn records (K26). // Her side of this conversation, from her turn records (K26).
let exchange = turn_room(&inputs).map(|here| exchange::exchange_of(&request.records, here, now, select::forms(&state))); let exchange = turn_room(&inputs).map(|here| exchange::exchange_of(&request.records, here, now, select::forms(&state)));
let inputs = Inputs { exchange: exchange.as_ref(), ..inputs }; let inputs = Inputs { exchange: exchange.as_ref(), ..inputs };
let can = affordances(organs, room_report["read"] == true, turn_room(&inputs), request.through); let can = affordances(room_report["read"] == true, &request.tools);
let inputs = Inputs { affordances: &can, ..inputs }; let inputs = Inputs { affordances: &can, ..inputs };
let mut report = json!({ let mut report = json!({
@ -626,14 +522,10 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
if request.through != Through::Projector { if request.through != Through::Projector {
report["persona_model"] = json!(tuning.persona.model); 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)); let packets = successive(&inputs, tuning, renders.max(1));
unshown_omitted(&mut report, &packets[0]); unshown_omitted(&mut report, &packets[0]);
report["packet"] = packet_json(&packets[0]); report["packet"] = packet_json(&packets[0]);
let reading = organs.reads.map(|source| Reading { source, since: domain::since(request.last_wake, now) }); let narrations: Vec<Value> = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", request.through)).collect();
let narrations: Vec<Value> = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", request.through, reading)).collect();
let texts = |narrations: &[Value]| narrations.iter().filter_map(|one| one["narration"].as_str().map(str::to_owned)).collect::<Vec<_>>(); let texts = |narrations: &[Value]| narrations.iter().filter_map(|one| one["narration"].as_str().map(str::to_owned)).collect::<Vec<_>>();
let failed = |narrations: &[Value]| narrations.iter().filter(|one| one.get("failed").is_some()).count(); let failed = |narrations: &[Value]| narrations.iter().filter(|one| one.get("failed").is_some()).count();
report["failed_renders"] = json!(failed(&narrations)); report["failed_renders"] = json!(failed(&narrations));
@ -645,7 +537,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
if let Some(other) = &request.judge_against { if let Some(other) = &request.judge_against {
let other_inputs = Inputs { state: other, ..inputs }; let other_inputs = Inputs { state: other, ..inputs };
let others = successive(&other_inputs, tuning, renders.max(1)); let others = successive(&other_inputs, tuning, renders.max(1));
let other_narrations: Vec<Value> = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", Through::Projector, None)).collect(); let other_narrations: Vec<Value> = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", Through::Projector)).collect();
let judging = wake_id(&request.instance, "judge", request.seed); let judging = wake_id(&request.instance, "judge", request.seed);
let mut verdicts = Vec::new(); let mut verdicts = Vec::new();
let mut right = 0usize; let mut right = 0usize;
@ -656,7 +548,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
let (first, second) = if swapped { (b, a) } else { (a, b) }; let (first, second) = if swapped { (b, a) } else { (a, b) };
// A narration that failed has nothing to judge; it is counted under the renders' failures. // A narration that failed has nothing to judge; it is counted under the renders' failures.
let Some(text) = narration["narration"].as_str() else { continue }; let Some(text) = narration["narration"].as_str() else { continue };
let answer = match model.ask(&call_id(&judging, "judge", at), &tuning.projector.model, &judge_prompt(first, second, text), None) { let answer = match model.ask(&call_id(&format!("{judging}:{at}"), "judge"), &tuning.projector.model, &judge_prompt(first, second, text), None) {
Ok(answer) => answer, Ok(answer) => answer,
Err(failed) => { Err(failed) => {
verdicts.push(json!({ "from": truth.to_string(), "failed": failed.reason, "usage": failed.usage })); verdicts.push(json!({ "from": truth.to_string(), "failed": failed.reason, "usage": failed.usage }));

View file

@ -0,0 +1,632 @@
//! Her agent (map 16.38.6 and 16.38.10): one turn of a persistent session over the connector with tools, bounded per wake and
//! per day.
//!
//! `step` owns one agent turn: the loop, its bounds and the session's freshness. The drain hands it the wake's input (the
//! Persona's monologue, the waking lines, the receipts since her last wake) and the executors; each executor owns its tool's
//! effect and the receipt it returns. The model never writes a receipt: code does, one per tool call, and the receipt's JSON
//! is the `ToolResult` the model reads. Every call, receipt and discard is a row in her trace (`Ledger`), and the trace is
//! the record. Her tools are `say`, `read`, `shell` and `request_tool` (`say`, `read`, `shell`, `request_tool` below), and what
//! her agent's receipts say is what she is told at her next wake (`outcome::told`); the session (`FileSession`) is a cache of her agent's turns and is discarded the moment the provider's cache
//! behind it is gone or cannot be trusted.
//!
//! The bounds are enforced here, before each call: tool calls and model calls per turn, spend per wake (summed across its turns), and spend per Mind per UTC
//! day. The day's spend is read back from her trace's `call` rows and priced by the tuning's table, so it survives a restart
//! and no other store holds it. Past a bound the loop ends with a `cap` receipt; a call is never made past one.
//!
//! The day's sum fails closed. A `call` row is written before its call is made, holding the call's place in the day at the
//! worst case (`unmetered_usd`, its own tuning); a `settle` row after it names the usage, and the call is priced by that
//! instead. So a trace that cannot be read, or cannot take the `call` row, makes no call; a `settle` row that cannot be
//! written ends the wake with its call still at the worst case; and a call whose usage is not known, a failed one that
//! reports none included, is charged the worst case and never nothing.
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::{Result, bail};
use chrono::{DateTime, Duration, Utc};
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{CacheRetention, InputItem, StopReason, ToolDefinition};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use super::narrate::{Failed, KitModel, Spent, StepRequest, Stepped, ToolCall};
use super::tuning::{AgentTuning, CACHE_MARGIN_S};
use crate::persona::Trace;
pub(crate) mod read;
pub(crate) mod request_tool;
pub(crate) mod say;
pub(crate) mod shell;
/// The connector, as the loop calls it: `KitModel` live, a script in a test.
pub trait Steps {
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed>;
}
impl<T: Steps + ?Sized> Steps for std::rc::Rc<T> {
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
(**self).step(request)
}
}
impl Steps for KitModel {
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
KitModel::step(self, request)
}
}
/// What became of one tool call, said by the executor and never by the model.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
/// The effect happened.
Ok,
/// The tool's owner declined it, with a reason in the fields.
Refused,
/// It was tried and failed.
Error,
/// It was handed over and no answer is known: it may or may not have happened.
Unknown,
/// It was not sent.
NotSent,
/// The loop's bound stopped it, or the loop itself.
Cap,
}
/// One tool call's receipt: the tool, its status and its fields. There is no way to make one without a status, and the
/// fields are private, so a receipt is built by `new` or not at all. Each example below is complete, so that privacy is the one
/// thing it can fail on: a literal that names every field, a read of a field and a write to one.
///
/// ```compile_fail
/// use mind_body::projection::agent::{Receipt, Status};
/// let _ = Receipt { tool: "say".into(), status: Status::Ok, fields: Default::default() };
/// ```
///
/// ```compile_fail
/// use mind_body::projection::agent::{Receipt, Status};
/// let receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
/// let _ = receipt.status;
/// ```
///
/// ```compile_fail
/// use mind_body::projection::agent::{Receipt, Status};
/// let mut receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
/// receipt.status = Status::Refused;
/// ```
///
/// The same lines compile once they go through the methods:
///
/// ```
/// use mind_body::projection::agent::{Receipt, Status};
/// let receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
/// assert_eq!((receipt.tool(), receipt.status()), ("say", Status::Ok));
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Receipt {
tool: String,
status: Status,
fields: Map<String, Value>,
}
impl Receipt {
/// `fields` is a JSON object; any other value is kept under `detail`.
pub fn new(tool: impl Into<String>, status: Status, fields: Value) -> Self {
let fields = match fields {
Value::Object(map) => map,
Value::Null => Map::new(),
other => Map::from_iter([("detail".to_owned(), other)]),
};
Self { tool: tool.into(), status, fields }
}
pub fn tool(&self) -> &str {
&self.tool
}
pub fn status(&self) -> Status {
self.status
}
pub fn fields(&self) -> &Map<String, Value> {
&self.fields
}
/// The receipt as it is written to her trace and as the model reads it.
pub fn json(&self) -> Value {
json!({ "tool": self.tool, "status": self.status, "fields": self.fields })
}
}
/// One tool's owner: it defines the tools it runs and runs each call it is handed, answering with a receipt.
pub trait Executor {
fn definitions(&self) -> Vec<ToolDefinition>;
fn run(&self, call: &ToolCall) -> Receipt;
}
/// A call's arguments as its tool takes them, or the receipt that refuses them: arguments the model wrote are never guessed at.
pub(crate) fn arguments<T: serde::de::DeserializeOwned>(call: &ToolCall) -> std::result::Result<T, Receipt> {
serde_json::from_str(&call.arguments).map_err(|fault| Receipt::new(&call.name, Status::Refused, json!({ "why": format!("the arguments do not fit the tool: {fault}") })))
}
/// What a fresh session is seeded with beyond the wake's input (ruling `candidate-actions-lived`): her live intentions that are
/// ready and unexpired, one line each, or nothing. A kept session already carries what she meant; nothing checks them afterwards.
pub(crate) fn ready_intentions(state: &Value, now: DateTime<Utc>) -> String {
let lines: Vec<String> = state["candidateActions"]["actions"]
.as_array()
.into_iter()
.flatten()
.filter(|action| action["customActionType"] == "intention" && action["status"] == "active" && action["readiness"] == "ready")
.filter(|action| action["expiresAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_none_or(|at| at.with_timezone(&Utc) > now))
.filter_map(|action| action["summary"].as_str().map(str::trim).filter(|summary| !summary.is_empty()).map(|summary| format!("- {summary}")))
.collect();
if lines.is_empty() { String::new() } else { format!("What she means to do, and is ready to:
{}
", lines.join("
")) }
}
/// Her trace as the loop sees it: her agent's rows, read back and appended. The drain's `TraceLedger` is the live one.
pub trait Ledger {
/// Every agent row, oldest first.
fn rows(&self) -> Result<Vec<Value>>;
/// Writes `row`, stamping it with its place (`seq`), and answers that place: a place is never held by two rows, so it can name one.
fn append(&self, row: Value) -> Result<u64>;
}
/// The agent's rows in her trace: each is a record with an `agent` field naming its kind (`call`, `receipt`,
/// `session_discarded`), a `seq` (the place it holds in her trace) and the time it was made. None of them is a wake record (`turn::is_wake`).
pub struct TraceLedger<'a> {
trace: &'a dyn Trace,
stem: String,
}
impl<'a> TraceLedger<'a> {
/// `stem` makes the records' keys: `<stem>-g<place>`.
pub fn new(trace: &'a dyn Trace, stem: impl Into<String>) -> Self {
Self { trace, stem: stem.into() }
}
}
impl Ledger for TraceLedger<'_> {
fn rows(&self) -> Result<Vec<Value>> {
Ok(self.trace.records()?.into_iter().filter(|record| record.get("agent").is_some()).collect())
}
fn append(&self, mut row: Value) -> Result<u64> {
let place = self.trace.records()?.len() as u64;
row["seq"] = json!(place);
self.trace.record(&format!("{}-g{place}", self.stem), &row)?;
Ok(place)
}
}
/// Her agent session: the conversation verbatim, what it was built under, and the last call's cost.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Session {
pub items: Vec<InputItem>,
/// SHA-256 of the instructions, the tool definitions and the model.
pub digest: String,
pub retention: CacheRetention,
pub created_at: DateTime<Utc>,
pub last_call_at: DateTime<Utc>,
pub last_usage: Option<Spent>,
}
/// The session's one row in its store.
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "eureka.persona.agent_session.v1", schema = "PersonaAgentSession")]
struct SessionRow {
#[cultcache(key = 0)]
value: Value,
}
const SESSION_KEY: &str = "session";
/// The session in a CultCache single-file store (`agent-session.cc` under the unit's state directory), written only by the drain.
pub struct FileSession {
path: PathBuf,
}
impl FileSession {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
fn open(&self) -> Result<CultCache> {
let mut cache = CultCache::new();
cache.register_entry_type::<SessionRow>()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&self.path))?;
cache.pull_all_backing_stores()?;
Ok(cache)
}
/// The session, or none when there is none. A store that cannot be read, or holds a session that does not decode, is an error.
pub fn load(&self) -> Result<Option<Session>> {
match self.open()?.get::<SessionRow>(SESSION_KEY)? {
Some(row) => Ok(Some(serde_json::from_value(row.value)?)),
None => Ok(None),
}
}
pub fn save(&self, session: &Session) -> Result<()> {
self.open()?.put(SESSION_KEY, &SessionRow { value: serde_json::to_value(session)? })?;
Ok(())
}
/// Forget the session. Nothing to forget is no error, and a store that cannot be opened is removed whole: it holds nothing else.
pub fn discard(&self) -> Result<()> {
if self.open().and_then(|mut cache| cache.delete::<SessionRow>(SESSION_KEY).map(|_| ())).is_ok() {
return Ok(());
}
match std::fs::remove_file(&self.path) {
Err(fault) if fault.kind() != std::io::ErrorKind::NotFound => Err(fault.into()),
_ => Ok(()),
}
}
}
/// What stopped a loop at a bound.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cap {
ToolCalls,
ModelCalls,
WakeSpend,
DaySpend,
}
impl Cap {
fn name(self) -> &'static str {
match self {
Self::ToolCalls => "tool_calls",
Self::ModelCalls => "model_calls",
Self::WakeSpend => "wake_usd",
Self::DaySpend => "day_usd",
}
}
}
/// How the turn ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Ended {
/// The model ended its turn.
EndTurn,
/// A bound stopped it; the cap receipt is in `receipts` and in her trace.
Cap(Cap),
/// The turn could not go on. The connector's own failure, kept whole: its `outage` says whether it is a strike.
Failed(Failed),
}
/// One agent turn: what it ended on, its last words, the receipts it earned in order, and what it used.
#[derive(Clone, Debug, PartialEq)]
pub struct Turn {
pub ended: Ended,
pub text: String,
pub receipts: Vec<Receipt>,
pub model_calls: usize,
pub tool_calls: usize,
pub usd: f64,
}
/// What the loop runs on. `clock` is read for every time it stamps or compares.
pub struct Agent<'a> {
pub model: &'a dyn Steps,
pub session: &'a FileSession,
pub executors: &'a [&'a dyn Executor],
pub ledger: &'a dyn Ledger,
pub bounds: &'a AgentTuning,
pub clock: &'a dyn Fn() -> DateTime<Utc>,
}
/// One turn's offering. `id` is the turn's identity, `{wake}-t{k}`: request ids and the agent rows' `wake` derive from it, so no two
/// model calls of one Mind share an id; `wake` is the wake's, whose turns' spend the wake's cap is read across. `instructions`
/// are fixed. `opening` is the wake's own beginning (the narration and her prose), given before `input` on the wake's first turn and
/// whenever the session starts fresh, so a session reseeded mid-wake is never given the bare lines. `fresh` is what a fresh session is
/// seeded with before it (`ready_intentions`). `input` is the turn's own lines.
pub struct Wake<'a> {
pub id: &'a str,
pub wake: &'a str,
pub instructions: &'a str,
pub opening: &'a str,
pub input: &'a str,
pub fresh: &'a str,
pub first: bool,
}
/// Her agent's instructions: fixed, naming her. Her prose is hers, and what is said aloud is hers to say, in her words
/// where she gave them; the agent carries no persona text of its own (`say-in-her-words`).
pub fn instructions(name: &str) -> String {
format!(
"You act for {name}. Each wake you are given what {name} has just lived and thought, in her own prose, with the lines that woke her and what came of her last acts. \
You act for her only through your tools; each tool call is answered with a receipt, and the receipt is the only truth about what happened. \
While she is awake more lines may reach her; each arrives as a new message, and is what she has just heard. \
Her prose is hers: do not rewrite it and do not speak as yourself. What is said aloud in chat is hers to say: when you say something, use her own words where her prose gave them, and add no voice of your own. \
When nothing needs doing, end your turn without acting."
)
}
/// Runs one agent turn. Day cap first, then the session's freshness, then the loop; see the module's text. A bug in the
/// caller (two executors defining one tool, an empty input) is an `Err`; everything the world does, her own trace
/// failing included, is in `Turn::ended`.
pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
if wake.input.trim().is_empty() && !(wake.first && !wake.opening.trim().is_empty()) {
bail!("a wake with no input");
}
let mut tools: Vec<ToolDefinition> = Vec::new();
let mut owners: Vec<(String, usize)> = Vec::new();
for (at, executor) in agent.executors.iter().enumerate() {
for definition in executor.definitions() {
if owners.iter().any(|(name, _)| *name == definition.name) {
bail!("two executors define the tool {}", definition.name);
}
owners.push((definition.name.clone(), at));
tools.push(definition);
}
}
let digest = digest_of(&agent.bounds.model, wake.instructions, &tools);
let mut run = Run { agent, wake, receipts: Vec::new(), usd: 0.0, model_calls: 0, tool_calls: 0, text: String::new() };
let ended = drive(&mut run, &tools, &owners, &digest).unwrap_or_else(Ended::Failed);
Ok(run.turn(ended))
}
/// The loop. A fault in her own trace or session store is an `Err` from anywhere in it, and ends the turn: no call is made
/// that her trace has not first been able to record (the `call` row written before it).
fn drive(run: &mut Run<'_>, tools: &[ToolDefinition], owners: &[(String, usize)], digest: &str) -> std::result::Result<Ended, Failed> {
let (agent, wake) = (run.agent, run.wake);
let bounds = agent.bounds;
let now = (agent.clock)();
let rows = agent.ledger.rows().map_err(|fault| ledger_failed(&fault))?;
let day_before = day_usd(&rows, now, bounds);
let wake_before = wake_usd(&rows, wake.wake, bounds);
if day_before >= bounds.day_usd {
return run.cap(Cap::DaySpend, day_before);
}
// The session as it stands, or the reason it cannot be trusted.
let kept = match agent.session.load() {
Ok(Some(held)) => match stale(&held, digest, now, bounds) {
Some(why) => {
run.discard(why)?;
None
}
None => Some(held),
},
Ok(None) => None,
Err(_) => {
run.discard("unreadable")?;
None
}
};
let created_at = kept.as_ref().map_or(now, |held| held.created_at);
let mut last_usage = kept.as_ref().and_then(|held| held.last_usage.clone());
// The prefix the provider is expected to hold for the next call: what the last call sent, when the session is kept.
let mut warm_prefix = last_usage.as_ref().map_or(0, prompt_tokens);
// A session that starts fresh, at any turn of the wake, is seeded with her intentions and this wake's opening before the lines; a kept one
// had both when its wake began, and takes the opening again only on the wake's first turn.
let text = format!("{}{}{}", if kept.is_none() { wake.fresh } else { "" }, if kept.is_none() || wake.first { wake.opening } else { "" }, wake.input);
let mut items = kept.map_or_else(Vec::new, |held| held.items);
items.push(InputItem::UserText { text });
let conversation = format!("agent-{}", created_at.timestamp());
let mut cold = false;
let ended = loop {
if run.model_calls >= bounds.model_calls {
break run.cap(Cap::ModelCalls, bounds.model_calls as f64)?;
}
if wake_before + run.usd >= bounds.wake_usd {
break run.cap(Cap::WakeSpend, wake_before + run.usd)?;
}
if day_before + run.usd >= bounds.day_usd {
break run.cap(Cap::DaySpend, day_before + run.usd)?;
}
let request_id = format!("{}-m{}", wake.id, run.model_calls + 1);
// The row comes first: it holds the call's place in the day's spend at the worst case, and a trace that cannot take it is a call not made.
let reserved = run.record(json!({ "agent": "call", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "model": bounds.model }))?;
let answer = agent.model.step(StepRequest { request_id: &request_id, conversation_id: &conversation, model: &bounds.model, instructions: wake.instructions, tools, input: items.clone(), retention: Some(bounds.retention), schema: None });
let stepped = match answer {
Ok(stepped) => stepped,
Err(failed) => {
// A failure that reports no usage is charged at the worst case, never at nothing.
let usd = failed.usage.as_ref().map_or_else(|| unmetered_usd(bounds), |usage| charge(bounds, usage));
run.usd += usd;
run.record(json!({ "agent": "settle", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "reserved": reserved, "usage": failed.usage, "usd": usd, "failed": failed.reason }))?;
return Ok(Ended::Failed(failed));
}
};
run.model_calls += 1;
let cost = charge(bounds, &stepped.usage);
run.usd += cost;
let at = (agent.clock)();
run.record(json!({ "agent": "settle", "at": at.to_rfc3339(), "wake": wake.id, "call": request_id, "reserved": reserved, "usage": stepped.usage, "usd": cost, "stop": format!("{:?}", stepped.stop) }))?;
// Observed: a prefix the provider should hold was read as nothing, so the cache is gone. The wake finishes on what it has.
if warm_prefix >= bounds.cache_min_tokens && stepped.usage.cache_read_tokens == 0 {
cold = true;
}
warm_prefix = prompt_tokens(&stepped.usage);
last_usage = Some(stepped.usage.clone());
items.extend(stepped.items.iter().cloned());
if !stepped.text.is_empty() {
run.text.clone_from(&stepped.text);
}
let held = |items: &[InputItem]| Session { items: items.to_vec(), digest: digest.to_owned(), retention: bounds.retention, created_at, last_call_at: at, last_usage: last_usage.clone() };
agent.session.save(&held(&items)).map_err(|fault| ledger_failed(&fault))?;
match (stepped.stop, stepped.calls.is_empty()) {
(StopReason::EndTurn, true) => break Ended::EndTurn,
(StopReason::ToolUse, false) => {}
(stop, _) => {
// A stop the loop cannot continue from, or a tool call cut short: nothing in the session can be trusted past it.
run.discard("stopped")?;
return Ok(Ended::Failed(Failed { reason: format!("the agent's turn ended early: {stop:?}"), outage: false, usage: None }));
}
}
let mut over = false;
for call in &stepped.calls {
let receipt = if run.tool_calls >= bounds.tool_calls {
over = true;
Receipt::new(&call.name, Status::Cap, json!({ "cap": Cap::ToolCalls.name(), "limit": bounds.tool_calls }))
} else {
run.tool_calls += 1;
match owners.iter().find(|(name, _)| *name == call.name) {
Some((_, at)) => agent.executors[*at].run(call),
None => Receipt::new(&call.name, Status::Refused, json!({ "reason": "no such tool" })),
}
};
// A receipt that cannot be written ends the turn with its call lacking a result in the session: the next start discards it.
run.receipt(receipt.clone())?;
items.push(InputItem::ToolResult { call_id: call.call_id.clone(), output: receipt.json().to_string() });
}
agent.session.save(&held(&items)).map_err(|fault| ledger_failed(&fault))?;
if over {
break run.cap(Cap::ToolCalls, bounds.tool_calls as f64)?;
}
};
if cold {
run.discard("cache_miss")?;
}
Ok(ended)
}
/// The loop's running account: what the turn has earned and spent so far.
struct Run<'a> {
agent: &'a Agent<'a>,
wake: &'a Wake<'a>,
receipts: Vec<Receipt>,
usd: f64,
model_calls: usize,
tool_calls: usize,
text: String,
}
impl Run<'_> {
/// One row in her trace; a trace that cannot take it is the turn's failure.
fn record(&self, row: Value) -> std::result::Result<u64, Failed> {
self.agent.ledger.append(row).map_err(|fault| ledger_failed(&fault))
}
/// A receipt is a row in her trace first, and then the turn's.
fn receipt(&mut self, receipt: Receipt) -> std::result::Result<(), Failed> {
self.record(json!({ "agent": "receipt", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "receipt": receipt.json() }))?;
self.receipts.push(receipt);
Ok(())
}
/// The bound that ended the loop, as a `cap` receipt of the loop's own.
fn cap(&mut self, cap: Cap, reached: f64) -> std::result::Result<Ended, Failed> {
self.receipt(Receipt::new("agent", Status::Cap, json!({ "cap": cap.name(), "reached": reached })))?;
Ok(Ended::Cap(cap))
}
/// Forget the session, and say why in her trace.
fn discard(&mut self, why: &str) -> std::result::Result<(), Failed> {
self.agent.session.discard().map_err(|fault| ledger_failed(&fault))?;
self.record(json!({ "agent": "session_discarded", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "why": why })).map(drop)
}
fn turn(self, ended: Ended) -> Turn {
Turn { ended, text: self.text, receipts: self.receipts, model_calls: self.model_calls, tool_calls: self.tool_calls, usd: self.usd }
}
}
fn ledger_failed(fault: &anyhow::Error) -> Failed {
// Her own store failed, not the world: nothing about it is a strike against a line.
Failed { reason: format!("the agent's record could not be written: {fault:#}"), outage: true, usage: None }
}
/// The tokens a call sent as its prompt, whether read from the cache, written to it or plain.
fn prompt_tokens(usage: &Spent) -> u64 {
usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens
}
/// What `usage` costs, USD, by the tuning's table; cache writes at the rate of the retention the session asks for.
fn price(bounds: &AgentTuning, usage: &Spent) -> f64 {
let price = bounds.price(&usage.model);
let million = 1_000_000.0;
(usage.input_tokens as f64 * price.input + usage.output_tokens as f64 * price.output + usage.cache_read_tokens as f64 * price.cache_read + usage.cache_write_tokens as f64 * price.cache_write(bounds.retention)) / million
}
/// What a call costs that no usage is known for: `agent.unmetered_usd`, the dearest a call can be taken to cost. It is not the wake's cap: a wake may
/// spend a dollar over many calls, and one call cut off by a brake is not charged a dollar of the day for it. Every price that cannot be read from
/// her trace is this, so a trace that fails never lowers the day's sum.
fn unmetered_usd(bounds: &AgentTuning) -> f64 {
bounds.unmetered_usd
}
/// What a call that reported `usage` is charged: its price, or `unmetered_usd` when it reports no token at all. A call that
/// was paid for never reports zero, so a zero is a count that cannot be believed, and a call is never free.
fn charge(bounds: &AgentTuning, usage: &Spent) -> f64 {
if prompt_tokens(usage) + usage.output_tokens == 0 { unmetered_usd(bounds) } else { price(bounds, usage) }
}
/// The UTC day's spend so far, from the `call` rows of her trace dated `now`'s day (`spent`). A row whose time does not read counts as today's.
pub(crate) fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
spent(rows, bounds, |row| row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_none_or(|at| at.with_timezone(&Utc).date_naive() == now.date_naive()))
}
/// What the wake `wake` has spent so far, across all its turns: the `call` rows whose `wake` is one of its turns' ids (`{wake}-t{k}`),
/// priced as the day's are.
pub(crate) fn wake_usd(rows: &[Value], wake: &str, bounds: &AgentTuning) -> f64 {
let turns = format!("{wake}-t");
spent(rows, bounds, |row| row["wake"].as_str().is_some_and(|id| id.starts_with(&turns)))
}
/// The spend of the `call` rows `keep` takes. A call row is priced by its own usage, or by the `settle` row that names it: the
/// settle's `reserved` is the call row's `seq`, its place in her trace, which no other row holds, where a call id repeats when a
/// wake is retried under its id. A call with neither, or with a usage that does not read or counts no token, is `unmetered_usd`.
fn spent(rows: &[Value], bounds: &AgentTuning, keep: impl Fn(&Value) -> bool) -> f64 {
let settled: BTreeMap<u64, &Value> = rows.iter().filter(|row| row["agent"] == "settle").filter_map(|row| Some((row["reserved"].as_u64()?, row))).collect();
rows.iter()
.filter(|row| row["agent"] == "call")
.filter(|row| keep(row))
.map(|row| {
let usage = if row.get("usage").is_some() { &row["usage"] } else { row["seq"].as_u64().and_then(|place| settled.get(&place)).map_or(&Value::Null, |settle| &settle["usage"]) };
serde_json::from_value::<Spent>(usage.clone()).map_or_else(|_| unmetered_usd(bounds), |usage| charge(bounds, &usage))
})
.sum()
}
/// When `now`'s UTC day ends: the next UTC midnight, the moment `day_usd` counts from nothing again.
pub(crate) fn day_ends(now: DateTime<Utc>) -> DateTime<Utc> {
(now.date_naive() + chrono::Days::new(1)).and_time(chrono::NaiveTime::MIN).and_utc()
}
fn digest_of(model: &str, instructions: &str, tools: &[ToolDefinition]) -> String {
let mut hash = Sha256::new();
for part in [model, instructions] {
hash.update((part.len() as u64).to_le_bytes());
hash.update(part.as_bytes());
}
for tool in tools {
for part in [&tool.name, &tool.description, &tool.parameters_json] {
hash.update((part.len() as u64).to_le_bytes());
hash.update(part.as_bytes());
}
}
hash.finalize().iter().map(|byte| format!("{byte:02x}")).collect()
}
/// Why a kept session may not be used, or none: a tool call with no result (a start was killed between), a digest that is
/// no longer this agent's, a cache that has run out or is about to, and a prompt grown past what is kept.
fn stale(session: &Session, digest: &str, now: DateTime<Utc>, bounds: &AgentTuning) -> Option<&'static str> {
let orphan = session.items.iter().any(|item| match item {
InputItem::ToolCall { call_id, .. } => !session.items.iter().any(|other| matches!(other, InputItem::ToolResult { call_id: answered, .. } if answered == call_id)),
_ => false,
});
if orphan {
return Some("orphan_tool_call");
}
if session.digest != digest {
return Some("digest");
}
let life = i64::try_from(bounds.ttl(session.retention).saturating_sub(CACHE_MARGIN_S)).unwrap_or(i64::MAX);
if now - session.last_call_at > Duration::seconds(life) {
return Some("ttl");
}
if session.last_usage.as_ref().is_some_and(|usage| prompt_tokens(usage) > bounds.max_session_tokens) {
return Some("too_long");
}
None
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,57 @@
//! `read` (map 16.38.5): a GameCult repo, file, pull request or commit from the forge, a recall over her own mind through her
//! persona door, a campaign's rulings, or a plain-HTTP web page. Code performs it (`ReadSource`); the receipt carries what was
//! read, its size and its text clipped, or the failure's words with status `error`, never an `ok` with nothing in it. The
//! forge is read here and only here: her box's fence admits the public internet and nothing on this host.
use chrono::{DateTime, Utc};
use model_connector::ToolDefinition;
use serde::Deserialize;
use serde_json::json;
use super::{Executor, Receipt, Status, arguments};
use crate::projection::narrate::ToolCall;
use crate::projection::read::{ReadRequest, ReadSource, clipped};
/// The most bytes of a read's text the receipt carries.
pub(crate) const READ_TEXT_BYTES: usize = 12 * 1024;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Args {
kind: String,
target: String,
}
/// The `read` executor: `source` performs the read; `since` opens a campaign read's window (her last wake).
pub struct Read<'a> {
pub source: Option<&'a dyn ReadSource>,
pub since: DateTime<Utc>,
}
impl Executor for Read<'_> {
fn definitions(&self) -> Vec<ToolDefinition> {
vec![ToolDefinition {
name: "read".into(),
description: "Read something and get its text in the receipt. kind `repo`: a GameCult repo on the forge, as `GameCult/Name`, `GameCult/Name/path/to/file`, `GameCult/Name#12` (a pull request), `GameCult/Name@sha` (a commit) or `GameCult/Name?q=words` (a search); the forge is reached only through this tool, never from the shell. kind `mind`: a recall over her own mind by these words. kind `campaign`: what was ruled lately in a campaign, by its slug. kind `web`: a plain http:// page.".into(),
parameters_json: json!({ "type": "object", "properties": { "kind": { "type": "string", "enum": ["repo", "mind", "campaign", "web"] }, "target": { "type": "string" } }, "required": ["kind", "target"], "additionalProperties": false }).to_string(),
}]
}
fn run(&self, call: &ToolCall) -> Receipt {
let args: Args = match arguments(call) {
Ok(args) => args,
Err(receipt) => return receipt,
};
let request = match ReadRequest::from_target(&args.kind, &args.target) {
Ok(request) => request,
Err(why) => return Receipt::new("read", Status::Refused, json!({ "kind": args.kind, "target": args.target, "why": why })),
};
let Some(source) = self.source else {
return Receipt::new("read", Status::Refused, json!({ "kind": args.kind, "target": args.target, "why": "nothing can be read from here" }));
};
match source.read(&request, self.since) {
Ok(text) => Receipt::new("read", Status::Ok, json!({ "kind": args.kind, "target": args.target, "bytes": text.len(), "text": clipped(&text, READ_TEXT_BYTES) })),
Err(failure) => Receipt::new("read", Status::Error, json!({ "kind": args.kind, "target": args.target, "failure": failure, "why": failure.words() })),
}
}
}

View file

@ -0,0 +1,36 @@
//! `request_tool` (map 16.38.5): a missing affordance, recorded for Self. The receipt row in her trace is the record; Self reads
//! it with `mind-persona trace`. Nothing else happens, and the receipt says so.
use model_connector::ToolDefinition;
use serde::Deserialize;
use serde_json::json;
use super::{Executor, Receipt, Status, arguments};
use crate::projection::narrate::ToolCall;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Args {
what: String,
why: String,
}
pub struct RequestTool;
impl Executor for RequestTool {
fn definitions(&self) -> Vec<ToolDefinition> {
vec![ToolDefinition {
name: "request_tool".into(),
description: "Ask for a tool she lacks: what it would do and why she needs it. It is recorded for Self to read; nothing happens now.".into(),
parameters_json: json!({ "type": "object", "properties": { "what": { "type": "string" }, "why": { "type": "string" } }, "required": ["what", "why"], "additionalProperties": false }).to_string(),
}]
}
fn run(&self, call: &ToolCall) -> Receipt {
match arguments::<Args>(call) {
Ok(args) if !args.what.trim().is_empty() => Receipt::new("request_tool", Status::Ok, json!({ "what": args.what.trim(), "why": args.why.trim(), "note": "recorded for Self, who reads it later; nothing happens now" })),
Ok(_) => Receipt::new("request_tool", Status::Refused, json!({ "why": "it names no tool" })),
Err(receipt) => receipt,
}
}
}

View file

@ -0,0 +1,238 @@
//! `say` (map 16.38.4, 16.38.5): one line through the mouth, written ahead in her trace and settled in place.
//!
//! What survives of the drain's sends lives here and nowhere else:
//! - **Write-ahead.** Her trace takes a `say` row with status `handed` before the mouth is called. A trace that refuses the row
//! sends nothing, and the model reads `not_sent`.
//! - **Send ids.** `{wake}:c{n}`, the wake's key and the say's place in it: the mouth's transaction id, so a repeat is the same send.
//! - **Resend.** A row still `handed` at the next start (no answer came) is sent again under its id with `resend` inside
//! `OWED_WINDOW_S`, and settled `unknown` past it (`settle_handed`). The mouth vouches for a resend only for an id it attempted.
//! - **Room order.** A say into a room that holds a `handed` row, or an `unknown` one she has not been told of, is refused
//! `room_unsettled`: her lines never arrive out of order, and none goes in before she knows what became of the last.
//!
//! The row is the one record of what became of a send. The receipt the model reads, and the receipt row a settlement writes
//! at the next start, are what she is told; the row is what the mouth is asked again from.
use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use model_connector::ToolDefinition;
use serde::Deserialize;
use serde_json::{Value, json};
use super::{Executor, Ledger, Receipt, Status, TraceLedger, arguments};
use crate::chat_client::{Chat, ChatSendRequest, Reading, SendBasis};
use crate::persona::Trace;
use crate::projection::narrate::ToolCall;
/// How long a send id is safe to repeat: the homeserver's transaction memory, held short.
pub(crate) const OWED_WINDOW_S: i64 = 1800;
/// How the mouth answered a send: the event it made, why it made none (the refusal's name), that no answer came, so the
/// send stays handed, that it attempted nothing this time, or that whether an earlier try posted cannot be told.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Sent {
Posted(String),
Refused(String),
Lost,
Unattempted,
Unknown,
}
/// The mouth, as her sends go through it: one path for her lines and the identity posts. `chat_send_request.v3` carries no
/// mentions and no reply link, so a line goes out plain.
pub(crate) struct Mouth<'a> {
pub chat: &'a dyn Chat,
pub persona: String,
/// The newest event of each room her input has shown, by the room's alias; a room her input did not show has none. It grows as lines
/// are shown (`shown`): a say is sent against it, and the mouth refuses one when another sender reached the room after it.
pub seen: RefCell<BTreeMap<String, String>>,
/// When her process began.
pub since_unix_ms: u64,
}
impl Mouth<'_> {
/// Her input has shown `event`, the newest of `room`: a say there is sent against it from now on. The one writer of `seen`.
pub(crate) fn shown(&self, room: &str, event: &str) {
self.seen.borrow_mut().insert(room.to_owned(), event.to_owned());
}
/// A line of hers: sent against what she had seen of the room.
pub(crate) fn send(&self, id: &str, room: &str, text: &str, resend: bool) -> Sent {
let basis = SendBasis { seen_event_id: self.seen.borrow().get(room).cloned(), since_unix_ms: self.since_unix_ms };
self.post(id, room, text, Some(basis), resend)
}
/// The one send: the request, and its answer read by `Refusal::reading`.
pub(crate) fn post(&self, id: &str, room: &str, text: &str, basis: Option<SendBasis>, resend: bool) -> Sent {
let request = ChatSendRequest { request_id: id.to_owned(), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis, resend };
match self.chat.send(&request) {
Ok(receipt) => match (receipt.event_id, receipt.refusal) {
(_, Some(refusal)) => match refusal.reading(resend) {
Reading::NoAnswer => Sent::Lost,
Reading::NotSent => Sent::Unattempted,
Reading::Unknown => Sent::Unknown,
Reading::Declined => Sent::Refused(refusal.name().to_owned()),
},
(Some(event), None) => Sent::Posted(event),
(None, None) if resend => Sent::Unknown,
(None, None) => Sent::Refused("no_event".to_owned()),
},
Err(_) => Sent::Lost,
}
}
}
/// Whether `room` holds a send she may not follow yet: a row still `handed`, or one settled `unknown` at or after `began`
/// (the place her trace had when this wake's packet was read), which she has not been told of. One settled unknown before it
/// was in this wake's packet.
pub(crate) fn unsettled(records: &[Value], room: &str, began: u64) -> bool {
records.iter().filter(|row| row["agent"] == "say" && row["room"] == room).any(|row| match row["status"].as_str() {
Some("handed") => true,
Some("unknown") => row["settled"].as_u64().is_some_and(|settled| settled >= began),
_ => false,
})
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Args {
room: String,
text: String,
#[serde(default)]
#[allow(dead_code, reason = "the mouth carries no reply link yet; the agent may name one")]
reply_to: Option<String>,
}
/// The `say` executor for one wake.
pub struct Say<'a> {
pub(crate) mouth: &'a Mouth<'a>,
pub(crate) trace: &'a dyn Trace,
/// The wake's key: send ids and row keys derive from it.
pub(crate) wake: &'a str,
/// The place her trace had when this wake's packet was read.
pub(crate) began: u64,
pub(crate) clock: &'a dyn Fn() -> DateTime<Utc>,
pub(crate) said: Cell<usize>,
}
impl Say<'_> {
fn write(&self, key: &str, row: &Value) -> bool {
match self.trace.record(key, row) {
Ok(()) => true,
Err(fault) => {
eprintln!("mind-persona: the say row {key} was not rewritten: {fault:#}");
false
}
}
}
}
impl Executor for Say<'_> {
fn definitions(&self) -> Vec<ToolDefinition> {
vec![ToolDefinition {
name: "say".into(),
description: "Say one line aloud in a chat room, as her. `room` is the room's alias or id as the lines that woke her name it; `text` is the line. Answered with a receipt saying whether it went out.".into(),
parameters_json: json!({ "type": "object", "properties": { "room": { "type": "string" }, "text": { "type": "string" }, "reply_to": { "type": "string", "description": "the event id of the line this answers" } }, "required": ["room", "text"], "additionalProperties": false }).to_string(),
}]
}
fn run(&self, call: &ToolCall) -> Receipt {
let args: Args = match arguments(call) {
Ok(args) => args,
Err(receipt) => return receipt,
};
let (room, text) = (args.room.trim().to_owned(), args.text);
let fields = |more: Value| {
let mut fields = json!({ "room": room, "text": text });
fields.as_object_mut().expect("an object").extend(more.as_object().cloned().unwrap_or_default());
fields
};
let records = match self.trace.records() {
Ok(records) => records,
Err(_) => return Receipt::new("say", Status::NotSent, fields(json!({ "why": "her trace could not be read, so nothing was sent" }))),
};
if unsettled(&records, &room, self.began) {
return Receipt::new("say", Status::Refused, fields(json!({ "refusal": "room_unsettled", "why": "an earlier line of hers in this room has no known outcome yet" })));
}
let n = self.said.get() + 1;
self.said.set(n);
let (id, key) = (format!("{}:c{n}", self.wake), format!("{}-s{n}", self.wake));
let mut row = json!({ "agent": "say", "key": key, "id": id, "wake": self.wake, "room": room, "text": text, "status": "handed", "seq": records.len(), "at": (self.clock)().to_rfc3339() });
// Write-ahead: no send is made that her trace has not first recorded as handed.
if self.trace.record(&key, &row).is_err() {
return Receipt::new("say", Status::NotSent, fields(json!({ "why": "her trace refused the line's record, so nothing was sent" })));
}
let settled = |row: &mut Value| -> u64 {
let place = self.trace.records().map_or(u64::MAX, |records| records.len() as u64);
row["settled"] = json!(place);
place
};
match self.mouth.send(&id, &room, &text, false) {
Sent::Posted(event) => {
row["status"] = json!("ok");
row["event"] = json!(event);
self.write(&key, &row);
Receipt::new("say", Status::Ok, fields(json!({ "event": event })))
}
Sent::Refused(why) => {
row["status"] = json!("refused");
row["refusal"] = json!(why);
self.write(&key, &row);
Receipt::new("say", Status::Refused, fields(json!({ "refusal": why })))
}
Sent::Unattempted => {
row["status"] = json!("not_sent");
self.write(&key, &row);
Receipt::new("say", Status::NotSent, fields(json!({ "why": "the mouth attempted nothing" })))
}
Sent::Unknown => {
row["status"] = json!("unknown");
settled(&mut row);
self.write(&key, &row);
Receipt::new("say", Status::Unknown, fields(json!({ "why": "whether it went out cannot be told" })))
}
// No answer: the row stays handed, and the next start asks the mouth again under the same id.
Sent::Lost => Receipt::new("say", Status::Unknown, fields(json!({ "why": "the mouth gave no answer; it is asked again under the same id at her next wake" }))),
}
}
}
/// Step 2 of a start (map 16.38.2): every `say` row still `handed` is sent again under its id with `resend`, inside
/// `OWED_WINDOW_S`, and settled `unknown` past it. No model is called. Each row settled here is rewritten in place, and a
/// receipt row of the settlement is written for her next packet; a resend with no answer, or one the mouth did not attempt,
/// stays handed. `stem` keys the receipt rows.
pub(crate) fn settle_handed(trace: &dyn Trace, mouth: &Mouth<'_>, stem: &str, now: DateTime<Utc>) {
let records = match trace.records() {
Ok(records) => records,
Err(fault) => return eprintln!("mind-persona: her trace was not read, so no handed line was settled: {fault:#}"),
};
let ledger = TraceLedger::new(trace, stem);
for row in records.iter().filter(|row| row["agent"] == "say" && row["status"] == "handed") {
let (key, id, room, text) = (row["key"].as_str().unwrap_or_default(), row["id"].as_str().unwrap_or_default(), row["room"].as_str().unwrap_or_default(), row["text"].as_str().unwrap_or_default());
let age = row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map_or(i64::MAX, |at| (now - at.with_timezone(&Utc)).num_seconds());
let sent = if age <= OWED_WINDOW_S { mouth.send(id, room, text, true) } else { Sent::Unknown };
let (status, event) = match sent {
Sent::Posted(event) => (Status::Ok, Some(event)),
Sent::Unknown | Sent::Refused(_) => (Status::Unknown, None),
Sent::Lost | Sent::Unattempted => continue,
};
let mut settled = row.clone();
settled["status"] = json!(if status == Status::Ok { "ok" } else { "unknown" });
settled["settled"] = json!(records.len());
if let Some(event) = &event {
settled["event"] = json!(event);
}
if let Err(fault) = trace.record(key, &settled) {
eprintln!("mind-persona: the say row {key} was not settled: {fault:#}");
continue;
}
let receipt = Receipt::new("say", status, json!({ "room": room, "text": text, "event": event, "resent": true }));
if let Err(fault) = ledger.append(json!({ "agent": "receipt", "at": now.to_rfc3339(), "wake": stem, "receipt": receipt.json() })) {
eprintln!("mind-persona: the settlement of {key} was not recorded: {fault:#}");
}
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,228 @@
//! `say`: write-ahead, the mouth's readings, room order and the resend a later start makes.
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::rc::Rc;
use anyhow::{Result, bail};
use chrono::{Duration, TimeZone};
use super::*;
use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, Refusal};
use crate::persona::TraceView;
fn noon() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap()
}
/// Her trace in memory: rows by key, rewritten in place; it refuses a write when `refuse` is set.
#[derive(Default)]
struct Rows {
rows: RefCell<Vec<(String, Value)>>,
refuse: Cell<bool>,
}
impl Trace for Rc<Rows> {
fn record(&self, key: &str, record: &Value) -> anyhow::Result<()> {
if self.refuse.get() {
bail!("no space left on device");
}
let mut rows = self.rows.borrow_mut();
match rows.iter_mut().find(|(held, _)| held == key) {
Some(row) => row.1 = record.clone(),
None => rows.push((key.to_owned(), record.clone())),
}
Ok(())
}
}
impl TraceView for Rc<Rows> {
fn records(&self) -> anyhow::Result<Vec<Value>> {
Ok(self.rows.borrow().iter().map(|(_, row)| row.clone()).collect())
}
}
/// The mouth: answers each send with the next scripted receipt (or a transport error), and records each request with what her
/// trace held when it was made.
struct Mouthpiece {
answers: RefCell<VecDeque<Result<ChatSendReceipt>>>,
sent: RefCell<Vec<(ChatSendRequest, Vec<Value>)>>,
trace: Rc<Rows>,
}
fn posted(event: &str) -> Result<ChatSendReceipt> {
Ok(ChatSendReceipt { request_id: String::new(), event_id: Some(event.into()), refusal: None, newer: vec![] })
}
fn refused(refusal: Refusal) -> Result<ChatSendReceipt> {
Ok(ChatSendReceipt { request_id: String::new(), event_id: None, refusal: Some(refusal), newer: vec![] })
}
impl Chat for Mouthpiece {
fn pending(&self, _: u64) -> Result<ChatPending> {
bail!("say reads nothing")
}
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
self.sent.borrow_mut().push((request.clone(), self.trace.records().unwrap()));
self.answers.borrow_mut().pop_front().expect("a send past the script")
}
fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result<ChatOpenDirectReceipt> {
bail!("say opens nothing")
}
fn fetch(&self, _: &ChatFetchRequest) -> Result<ChatFetchReceipt> {
bail!("say fetches nothing")
}
fn ack(&self, _: u64) -> Result<()> {
bail!("say acks nothing")
}
fn read(&self, _: &ChatRead) -> Result<()> {
bail!("say reports no read")
}
}
struct Rig {
trace: Rc<Rows>,
chat: Mouthpiece,
}
impl Rig {
fn new(answers: Vec<Result<ChatSendReceipt>>) -> Self {
let trace = Rc::new(Rows::default());
Self { chat: Mouthpiece { answers: RefCell::new(answers.into()), sent: RefCell::default(), trace: trace.clone() }, trace }
}
fn mouth(&self) -> Mouth<'_> {
Mouth { chat: &self.chat, persona: "eureka".into(), seen: RefCell::new(BTreeMap::from([("#minds".to_owned(), "$seen".to_owned())])), since_unix_ms: 1 }
}
/// One say through a fresh executor at `began`.
fn say(&self, room: &str, text: &str, began: u64) -> Receipt {
let mouth = self.mouth();
let clock = noon;
let say = Say { mouth: &mouth, trace: &self.trace, wake: "n4-99", began, clock: &clock, said: Cell::new(0) };
say.run(&ToolCall { call_id: "c".into(), name: "say".into(), arguments: json!({ "room": room, "text": text }).to_string() })
}
fn says(&self) -> Vec<Value> {
self.trace.records().unwrap().into_iter().filter(|row| row["agent"] == "say").collect()
}
fn sent(&self) -> Vec<ChatSendRequest> {
self.chat.sent.borrow().iter().map(|(request, _)| request.clone()).collect()
}
}
#[test]
fn t_a2_say_write_ahead() {
let rig = Rig::new(vec![posted("$e1")]);
let receipt = rig.say("#minds", "hello", 0);
assert_eq!((receipt.status(), &receipt.fields()["event"]), (Status::Ok, &json!("$e1")));
let (request, held) = rig.chat.sent.borrow()[0].clone();
assert_eq!((request.request_id.as_str(), request.resend), ("n4-99:c1", false), "the send id is the wake's key and the say's place");
assert_eq!(request.basis.unwrap().seen_event_id.as_deref(), Some("$seen"), "sent against what she had seen of the room");
assert!(held.iter().any(|row| row["agent"] == "say" && row["status"] == "handed" && row["id"] == "n4-99:c1"), "the handed row was in her trace before the mouth was called: {held:?}");
assert_eq!(rig.says()[0]["status"], "ok", "and is settled in place");
assert_eq!(rig.says().len(), 1);
// A trace that refuses the row sends nothing.
let rig = Rig::new(vec![]);
rig.trace.refuse.set(true);
let receipt = rig.say("#minds", "hello", 0);
assert_eq!(receipt.status(), Status::NotSent);
assert!(rig.sent().is_empty(), "nothing went to the mouth");
}
/// Each answer of the mouth's to a first send, as the receipt and the row read it.
#[test]
fn a_first_sends_answers_settle_by_the_mouths_reading() {
for (answer, status, row) in [
(refused(Refusal::NotSent), Status::NotSent, "not_sent"),
(refused(Refusal::SendFailed), Status::Unknown, "handed"),
(refused(Refusal::RoomMoved), Status::Refused, "refused"),
(Err(anyhow::anyhow!("the mouth is unreachable")), Status::Unknown, "handed"),
] {
let rig = Rig::new(vec![answer]);
let receipt = rig.say("#minds", "hello", 0);
assert_eq!(receipt.status(), status, "{receipt:?}");
assert_eq!(rig.says()[0]["status"], row, "{receipt:?}");
}
}
#[test]
fn t_a2_room_unsettled() {
// A say left unknown in this wake holds the room until she is told of it.
let rig = Rig::new(vec![refused(Refusal::ResendUnknown), posted("$e2")]);
let mouth = rig.mouth();
let clock = noon;
let say = Say { mouth: &mouth, trace: &rig.trace, wake: "w", began: 0, clock: &clock, said: Cell::new(0) };
let call = |room: &str| ToolCall { call_id: "c".into(), name: "say".into(), arguments: json!({ "room": room, "text": "x" }).to_string() };
assert_eq!(say.run(&call("#minds")).status(), Status::Unknown);
let again = say.run(&call("#minds"));
assert_eq!((again.status(), &again.fields()["refusal"]), (Status::Refused, &json!("room_unsettled")), "nothing goes in after a line with no known outcome");
assert_eq!(say.run(&call("#other")).status(), Status::Ok, "another room is not held");
assert_eq!(rig.sent().len(), 2);
// Settled before this wake's packet was read, she has been told: the room is free.
let settled = rig.says()[0]["settled"].as_u64().unwrap();
assert!(!unsettled(&rig.trace.records().unwrap(), "#minds", settled + 1));
assert!(unsettled(&rig.trace.records().unwrap(), "#minds", settled));
// A handed row holds its room whatever the wake.
let rig = Rig::new(vec![refused(Refusal::SendFailed)]);
rig.say("#minds", "x", 0);
assert!(unsettled(&rig.trace.records().unwrap(), "#minds", u64::MAX));
}
/// A handed row that settles unknown at a start frees its room for the wake that follows: that wake's packet was read after the
/// settlement, so she has been told, and her say goes out.
#[test]
fn t_a2_a_settled_unknown_frees_its_room_for_the_next_wake() {
let rig = Rig::new(vec![posted("$after")]);
rig.trace.record("old", &json!({ "agent": "say", "key": "old", "id": "old:id", "room": "#minds", "text": "late", "status": "handed", "seq": 0, "at": (noon() - Duration::minutes(31)).to_rfc3339() })).unwrap();
settle_handed(&rig.trace, &rig.mouth(), "n9", noon());
assert_eq!(rig.says()[0]["status"], "unknown");
let began = rig.trace.records().unwrap().len() as u64;
let receipt = rig.say("#minds", "now", began);
assert_eq!(receipt.status(), Status::Ok, "the room is free: {:?}", receipt.fields());
assert_eq!(rig.sent().len(), 1);
}
#[test]
fn t_a2_resend_inside_window() {
let handed = |minutes: i64, key: &str| json!({ "agent": "say", "key": key, "id": format!("{key}:id"), "room": "#minds", "text": "late", "status": "handed", "seq": 0, "at": (noon() - Duration::minutes(minutes)).to_rfc3339() });
let rig = Rig::new(vec![posted("$late")]);
rig.trace.record("young", &handed(10, "young")).unwrap();
rig.trace.record("old", &handed(31, "old")).unwrap();
settle_handed(&rig.trace, &rig.mouth(), "n9", noon());
let sent = rig.sent();
assert_eq!(sent.len(), 1, "only the send inside the window is asked again");
assert_eq!((sent[0].request_id.as_str(), sent[0].resend), ("young:id", true), "under the same id, as a resend");
let rows = rig.trace.records().unwrap();
let status = |key: &str| rows.iter().find(|row| row["key"] == key).unwrap()["status"].clone();
assert_eq!((status("young"), status("old")), (json!("ok"), json!("unknown")), "posted on resend; past the window, unknown without a send");
let told: Vec<&Value> = rows.iter().filter(|row| row["agent"] == "receipt").collect();
assert_eq!(told.len(), 2, "each settlement is a receipt she is told: {rows:?}");
}
/// A resend's answers: the mouth vouches only for an id it attempted, and a resend it did not attempt or got no answer to stays handed.
#[test]
fn a_resends_answers_settle_by_the_mouths_reading() {
for (answer, status) in [(refused(Refusal::ResendUnknown), "unknown"), (refused(Refusal::NotSent), "handed"), (refused(Refusal::SendFailed), "handed"), (refused(Refusal::Brake), "unknown")] {
let rig = Rig::new(vec![answer]);
rig.trace.record("k", &json!({ "agent": "say", "key": "k", "id": "k:id", "room": "#minds", "text": "x", "status": "handed", "seq": 0, "at": noon().to_rfc3339() })).unwrap();
settle_handed(&rig.trace, &rig.mouth(), "n9", noon());
assert_eq!(rig.says()[0]["status"], status);
}
}
/// A line shown to her is the newest she has seen of its room: her say there is sent against it, and a say in another room is not.
#[test]
fn t_w1_a_say_is_sent_against_the_newest_line_shown() {
let rig = Rig::new(vec![posted("$e1"), posted("$e2")]);
let mouth = rig.mouth();
mouth.shown("#minds", "$newer");
let say = Say { mouth: &mouth, trace: &rig.trace, wake: "n4-99", began: 0, clock: &noon, said: Cell::new(0) };
let call = |room: &str| ToolCall { call_id: "c".into(), name: "say".into(), arguments: json!({ "room": room, "text": "hi" }).to_string() };
say.run(&call("#minds"));
say.run(&call("#other"));
let seen: Vec<Option<String>> = rig.sent().iter().map(|request| request.basis.as_ref().and_then(|basis| basis.seen_event_id.clone())).collect();
assert_eq!(seen, [Some("$newer".to_owned()), None], "the room she was shown a newer line of is sent against it; one she was shown nothing of is not");
}

View file

@ -0,0 +1,97 @@
//! `shell` (map 16.38.5, 16.38.17): one command in her box. The drain never runs it: it connects to her box socket
//! (`mind-box-<m>.socket`), writes one request and reads one receipt to its end. `mind-persona box-exec` answers, as
//! `mind-<m>-box`, under the one bubblewrap profile (`sandbox::run_box`). The receipt is the box's, passed through with its tool
//! and status checked; a box that does not answer in time, or answers nothing a receipt can be read from, is status `error`.
use std::path::PathBuf;
use std::time::Duration;
use model_connector::ToolDefinition;
use serde::Deserialize;
use serde_json::{Value, json};
use super::{Executor, Receipt, Status, arguments};
use crate::projection::narrate::ToolCall;
use crate::projection::select::clip;
use crate::sandbox::{TAIL_BYTES, TIMEOUT_MAX_S};
/// How much longer than the command's own timeout the drain waits for the box's answer.
const ANSWER_GRACE_S: u64 = 10;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Args {
command: String,
#[serde(default)]
timeout_s: Option<u64>,
}
/// The `shell` executor: `socket` is her box's door.
pub struct Shell {
pub socket: PathBuf,
}
impl Executor for Shell {
fn definitions(&self) -> Vec<ToolDefinition> {
vec![ToolDefinition {
name: "shell".into(),
description: format!("Run one command with /bin/sh in her own box: a Linux sandbox whose home is hers and persists, with /opt/commons/handoff and /opt/commons/cast-art writable and the rest of /opt/commons read-only. It reaches the public internet and nothing on this host: read the forge and her mind with the `read` tool. `timeout_s` is at most {TIMEOUT_MAX_S}. The receipt carries the exit code, the tails of stdout and stderr, and the files it wrote."),
parameters_json: json!({ "type": "object", "properties": { "command": { "type": "string" }, "timeout_s": { "type": "integer", "minimum": 1, "maximum": TIMEOUT_MAX_S } }, "required": ["command"], "additionalProperties": false }).to_string(),
}]
}
fn run(&self, call: &ToolCall) -> Receipt {
let args: Args = match arguments(call) {
Ok(args) => args,
Err(receipt) => return receipt,
};
let timeout_s = args.timeout_s.unwrap_or(30).clamp(1, TIMEOUT_MAX_S);
let request = json!({ "command": args.command, "timeout_s": timeout_s });
let receipt = match ask(&self.socket, &request, Duration::from_secs(timeout_s + ANSWER_GRACE_S)) {
Ok(answer) => passed_through(&answer),
Err(why) => Receipt::new("shell", Status::Error, json!({ "why": why })),
};
// The receipt names the command it answers, so what her trace holds says what was run, not only what came back. It is bounded as its output is.
let mut fields = receipt.fields().clone();
fields.insert("command".to_owned(), json!(clip(&args.command, TAIL_BYTES)));
Receipt::new("shell", receipt.status(), Value::Object(fields))
}
}
/// The box's receipt as hers: its status, read from what the box said, and every other field it carries. One without its tool or
/// status is no receipt.
fn passed_through(answer: &[u8]) -> Receipt {
let Ok(Value::Object(mut fields)) = serde_json::from_slice::<Value>(answer) else {
return Receipt::new("shell", Status::Error, json!({ "why": "the box did not answer" }));
};
let status = match (fields.remove("tool"), fields.remove("status")) {
(Some(tool), Some(status)) if tool == "shell" => match status.as_str() {
Some("ok") => Status::Ok,
Some("error") => Status::Error,
_ => return Receipt::new("shell", Status::Error, json!({ "why": "the box's answer carried no status it may give" })),
},
_ => return Receipt::new("shell", Status::Error, json!({ "why": "the box's answer was not a shell receipt" })),
};
Receipt::new("shell", status, Value::Object(fields))
}
/// One request to the box and its whole answer, within `wait`.
#[cfg(unix)]
fn ask(socket: &std::path::Path, request: &Value, wait: Duration) -> Result<Vec<u8>, String> {
use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
let mut stream = UnixStream::connect(socket).map_err(|_| "the box could not be reached".to_owned())?;
stream.set_read_timeout(Some(wait)).and_then(|()| stream.set_write_timeout(Some(wait))).map_err(|_| "the box could not be reached".to_owned())?;
stream.write_all(request.to_string().as_bytes()).and_then(|()| stream.shutdown(std::net::Shutdown::Write)).map_err(|_| "the box did not take the command".to_owned())?;
let mut answer = Vec::new();
match stream.take(1024 * 1024).read_to_end(&mut answer) {
Ok(_) => Ok(answer),
Err(fault) if matches!(fault.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => Err("box did not answer".to_owned()),
Err(_) => Err("the box's answer broke off".to_owned()),
}
}
#[cfg(not(unix))]
fn ask(_: &std::path::Path, _: &Value, _: Duration) -> Result<Vec<u8>, String> {
Err("there is no box on this platform".to_owned())
}

View file

@ -0,0 +1,946 @@
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use chrono::TimeZone;
use super::*;
use crate::persona::{FileTrace, TraceView};
const MODEL: &str = "claude-sonnet-5-5";
fn noon() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 29, 12, 0, 0).unwrap()
}
fn usage(input: u64, output: u64, cache_read: u64, cache_write: u64) -> Spent {
Spent { model: MODEL.into(), input_tokens: input, output_tokens: output, cache_read_tokens: cache_read, cache_write_tokens: cache_write, reasoning_tokens: None }
}
fn small() -> Spent {
usage(100, 20, 0, 0)
}
fn asks(call_id: &str, tool: &str, spent: Spent) -> std::result::Result<Stepped, Failed> {
let call = ToolCall { call_id: call_id.into(), name: tool.into(), arguments: "{}".into() };
Ok(Stepped { items: vec![InputItem::ToolCall { call_id: call.call_id.clone(), name: call.name.clone(), arguments: call.arguments.clone() }], text: String::new(), calls: vec![call], stop: StopReason::ToolUse, usage: spent })
}
fn ends(text: &str, spent: Spent) -> std::result::Result<Stepped, Failed> {
Ok(Stepped { items: vec![InputItem::AssistantText { text: text.into() }], text: text.into(), calls: vec![], stop: StopReason::EndTurn, usage: spent })
}
/// The connector as a script: each call answers the next entry and keeps the conversation it was sent.
struct Script {
answers: RefCell<VecDeque<std::result::Result<Stepped, Failed>>>,
seen: RefCell<Vec<Vec<InputItem>>>,
ids: RefCell<Vec<String>>,
conversations: RefCell<Vec<String>>,
}
impl Script {
fn new(answers: Vec<std::result::Result<Stepped, Failed>>) -> Self {
Self { answers: RefCell::new(answers.into()), seen: RefCell::default(), ids: RefCell::default(), conversations: RefCell::default() }
}
/// A model that asks `tool` on every call, whatever it is told.
fn endless(tool: &str, calls: usize) -> Self {
Self::new((0..calls).map(|at| asks(&format!("c{at}"), tool, small())).collect())
}
}
impl Steps for Script {
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
self.seen.borrow_mut().push(request.input.clone());
self.ids.borrow_mut().push(request.request_id.to_owned());
self.conversations.borrow_mut().push(request.conversation_id.to_owned());
assert!(!request.tools.is_empty() && request.retention.is_some(), "the loop always sends its tools and asks for the cache");
self.answers.borrow_mut().pop_front().expect("the loop called the model past the script")
}
}
/// Two stub tools; each call is answered `ok` with the arguments echoed.
struct Stub {
ran: RefCell<Vec<String>>,
parameters: RefCell<String>,
description: RefCell<String>,
}
impl Stub {
fn new() -> Self {
Self { ran: RefCell::default(), parameters: RefCell::new("{\"type\":\"object\"}".into()), description: RefCell::new("stub".into()) }
}
}
impl Executor for Stub {
fn definitions(&self) -> Vec<ToolDefinition> {
["alpha", "beta"].map(|name| ToolDefinition { name: name.into(), description: format!("the {name} {}", self.description.borrow()), parameters_json: self.parameters.borrow().clone() }).to_vec()
}
fn run(&self, call: &ToolCall) -> Receipt {
self.ran.borrow_mut().push(call.name.clone());
Receipt::new(&call.name, Status::Ok, json!({ "arguments": call.arguments }))
}
}
#[derive(Default)]
struct Memory {
rows: RefCell<Vec<Value>>,
/// The kinds of row the trace refuses to write.
refuses: RefCell<Vec<&'static str>>,
unreadable: Cell<bool>,
}
impl Ledger for Memory {
fn rows(&self) -> Result<Vec<Value>> {
if self.unreadable.get() {
bail!("the trace cannot be read");
}
Ok(self.rows.borrow().clone())
}
fn append(&self, mut row: Value) -> Result<u64> {
if self.refuses.borrow().iter().any(|kind| row["agent"] == *kind) {
bail!("the trace cannot be written");
}
let place = self.rows.borrow().len() as u64;
row["seq"] = json!(place);
self.rows.borrow_mut().push(row);
Ok(place)
}
}
impl Memory {
fn kinds(&self, kind: &str) -> Vec<Value> {
self.rows.borrow().iter().filter(|row| row["agent"] == kind).cloned().collect()
}
}
struct Rig {
dir: tempfile::TempDir,
session: FileSession,
ledger: Memory,
stub: Stub,
clock: Cell<DateTime<Utc>>,
bounds: AgentTuning,
}
impl Rig {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let session = FileSession::new(dir.path().join("agent-session.cc"));
Self { dir, session, ledger: Memory::default(), stub: Stub::new(), clock: Cell::new(noon()), bounds: AgentTuning { wake_usd: 0.40, ..AgentTuning::default() } }
}
fn wake(&self, model: &Script, id: &str, instructions: &str, input: &str) -> Turn {
let clock = || self.clock.get();
let executors: [&dyn Executor; 1] = [&self.stub];
let agent = Agent { model, session: &self.session, executors: &executors, ledger: &self.ledger, bounds: &self.bounds, clock: &clock };
step(&agent, &Wake { id, wake: id, opening: "", first: true, instructions, input, fresh: "" }).unwrap()
}
fn run(&self, model: &Script, input: &str) -> Turn {
self.wake(model, "w1", "You act for her.", input)
}
fn discards(&self) -> Vec<String> {
self.ledger.kinds("session_discarded").iter().map(|row| row["why"].as_str().unwrap().to_owned()).collect()
}
}
#[test]
fn t_a1_loop_runs_tool_calls() {
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "alpha", small()), asks("c2", "beta", small()), ends("Done.", small())]);
let turn = rig.run(&model, "She wants to know.");
assert_eq!(turn.ended, Ended::EndTurn);
assert_eq!((turn.model_calls, turn.tool_calls, turn.text.as_str()), (3, 2, "Done."));
assert_eq!(turn.receipts.iter().map(|receipt| (receipt.tool(), receipt.status())).collect::<Vec<_>>(), [("alpha", Status::Ok), ("beta", Status::Ok)]);
// Two receipts in her trace, and the ToolResults the model read are those receipts' JSON.
let rows = rig.ledger.kinds("receipt");
assert_eq!(rows.iter().map(|row| row["receipt"].clone()).collect::<Vec<_>>(), turn.receipts.iter().map(Receipt::json).collect::<Vec<_>>());
let results: Vec<(String, String)> = rig.session.load().unwrap().unwrap().items.into_iter().filter_map(|item| if let InputItem::ToolResult { call_id, output } = item { Some((call_id, output)) } else { None }).collect();
assert_eq!(results, [("c1".to_owned(), turn.receipts[0].json().to_string()), ("c2".to_owned(), turn.receipts[1].json().to_string())]);
// The model's third call saw both results, in order, after its own calls.
let third = &model.seen.borrow()[2];
assert!(matches!(third.as_slice(), [InputItem::UserText { .. }, InputItem::ToolCall { .. }, InputItem::ToolResult { .. }, InputItem::ToolCall { .. }, InputItem::ToolResult { .. }]));
assert_eq!((rig.ledger.kinds("call").len(), rig.ledger.kinds("settle").len()), (3, 3), "each call is reserved before it is made and settled after");
assert_eq!(*model.ids.borrow(), ["w1-m1", "w1-m2", "w1-m3"]);
}
#[test]
fn t_a1_an_unknown_tool_is_refused_not_run() {
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "nope", small()), ends("Ok.", small())]);
let turn = rig.run(&model, "x");
assert_eq!((turn.receipts[0].status(), turn.receipts[0].tool()), (Status::Refused, "nope"));
assert!(rig.stub.ran.borrow().is_empty());
}
#[test]
fn t_a1_tool_cap() {
let rig = Rig::new();
let model = Script::endless("alpha", 10);
let turn = rig.run(&model, "x");
assert_eq!(turn.ended, Ended::Cap(Cap::ToolCalls));
assert_eq!(rig.stub.ran.borrow().len(), 8, "eight tool calls ran and no ninth");
assert_eq!(turn.model_calls, 9, "the ninth ask was answered with a cap, not run");
let statuses: Vec<Status> = turn.receipts.iter().map(Receipt::status).collect();
assert_eq!(statuses, [vec![Status::Ok; 8], vec![Status::Cap, Status::Cap]].concat(), "the refused ninth call and the loop's own cap receipt");
assert_eq!(turn.receipts.last().unwrap().tool(), "agent");
assert_eq!(turn.receipts.last().unwrap().fields()["cap"], "tool_calls");
// The session still holds a result for every call it holds.
assert!(stale(&rig.session.load().unwrap().unwrap(), &digest_of(MODEL, "You act for her.", &rig.stub.definitions()), noon(), &rig.bounds).is_none());
}
#[test]
fn t_a1_model_call_cap_and_wake_spend_cap() {
let mut rig = Rig::new();
rig.bounds.model_calls = 2;
let model = Script::endless("alpha", 5);
let turn = rig.run(&model, "x");
assert_eq!((turn.ended, turn.model_calls), (Ended::Cap(Cap::ModelCalls), 2));
assert_eq!(model.seen.borrow().len(), 2, "no third call");
let rig = Rig::new();
// 50k output tokens at $10 a million is $0.50: past the wake's $0.40 after one call.
let model = Script::new(vec![asks("c1", "alpha", usage(10, 50_000, 0, 0))]);
let turn = rig.run(&model, "x");
assert_eq!((turn.ended, turn.model_calls, turn.tool_calls), (Ended::Cap(Cap::WakeSpend), 1, 1));
assert!(turn.usd > 0.40);
assert_eq!(turn.receipts.last().unwrap().fields()["cap"], "wake_usd");
}
#[test]
fn t_a1_day_cap() {
let rig = Rig::new();
// 1.505M input tokens at $2 a million is $3.01, today.
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_505_000, 0, 0, 0) })).unwrap();
let model = Script::new(vec![]);
let turn = rig.run(&model, "x");
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
assert!(model.seen.borrow().is_empty(), "no call was made");
assert_eq!(turn.receipts[0].status(), Status::Cap);
assert_eq!(rig.ledger.kinds("receipt").len(), 1, "and the cap is recorded");
assert!(rig.session.load().unwrap().is_none(), "a capped wake leaves no session behind");
// Yesterday's spend and the same sum under the cap do not stop her.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": (noon() - Duration::days(1)).to_rfc3339(), "usage": usage(5_000_000, 0, 0, 0) })).unwrap();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_490_000, 0, 0, 0) })).unwrap();
let turn = rig.run(&Script::new(vec![ends("Fine.", small())]), "x");
assert_eq!(turn.ended, Ended::EndTurn);
// The sum rolls in what the wake itself spends: $2.99 behind her, then a call of about $0.04 reaches $3.03 and stops the next one.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_495_000, 0, 0, 0) })).unwrap();
let turn = rig.run(&Script::new(vec![asks("c1", "alpha", usage(20_000, 0, 0, 0))]), "x");
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
assert_eq!(turn.tool_calls, 1);
}
#[test]
fn t_a1_day_cap_survives_a_restart() {
let dir = tempfile::tempdir().unwrap();
let trace = FileTrace::new(dir.path().join("trace.cc"));
let session = FileSession::new(dir.path().join("agent-session.cc"));
let (bounds, stub) = (AgentTuning { wake_usd: 0.40, ..AgentTuning::default() }, Stub::new());
let clock = noon;
let executors: [&dyn Executor; 1] = [&stub];
// One expensive wake: 400k output tokens at $10 a million is $4.00.
{
let ledger = TraceLedger::new(&trace, "w1");
let agent = Agent { model: &Script::new(vec![ends("Long.", usage(10, 400_000, 0, 0))]), session: &session, executors: &executors, ledger: &ledger, bounds: &bounds, clock: &clock };
assert_eq!(step(&agent, &Wake { id: "w1", wake: "w1", opening: "", first: true, instructions: "i", input: "x", fresh: "" }).unwrap().ended, Ended::EndTurn);
}
// A restart: nothing of the first run is held but her trace and the session file.
let trace = FileTrace::new(dir.path().join("trace.cc"));
let ledger = TraceLedger::new(&trace, "w2");
let model = Script::new(vec![]);
let agent = Agent { model: &model, session: &session, executors: &executors, ledger: &ledger, bounds: &bounds, clock: &clock };
let turn = step(&agent, &Wake { id: "w2", wake: "w2", opening: "", first: true, instructions: "i", input: "y", fresh: "" }).unwrap();
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
assert!(model.seen.borrow().is_empty());
// Her trace holds the call, its settlement and the cap as agent rows, and none of them is a wake record.
let records = trace.records().unwrap();
assert!(records.len() == 3 && records.iter().all(|record| record.get("agent").is_some() && !crate::projection::turn::is_wake(record)), "{records:?}");
}
#[test]
fn t_a1_session_persists_while_warm() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::minutes(58));
let model = Script::new(vec![ends("Second.", usage(100, 5, 4900, 40))]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "one".into() }, InputItem::AssistantText { text: "First.".into() }, InputItem::UserText { text: "two".into() }]);
assert!(rig.discards().is_empty());
assert!(rig.session.load().unwrap().is_some());
}
#[test]
fn t_a1_session_ttl_discard() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::minutes(61));
let model = Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "two".into() }], "the input starts fresh");
assert_eq!(rig.discards(), ["ttl"]);
// The short retention's table is shorter: five minutes less a minute.
let mut rig = Rig::new();
rig.bounds.retention = CacheRetention::Short;
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::seconds(250));
let model = Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!(model.seen.borrow()[0].len(), 1);
assert_eq!(rig.discards(), ["ttl"]);
}
#[test]
fn t_a1_cache_miss_discard() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::minutes(5));
// The cached prefix was 5,000 tokens; the provider read none of it.
let turn = rig.wake(&Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]), "w2", "You act for her.", "two");
assert_eq!(turn.ended, Ended::EndTurn, "the wake finishes on the session it had");
assert!(rig.session.load().unwrap().is_none(), "and the session is discarded at its end");
assert_eq!(rig.discards(), ["cache_miss"]);
// A read of some, or a prefix under the provider's minimum, is no miss.
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 400))]), "one");
rig.wake(&Script::new(vec![ends("Second.", usage(500, 5, 0, 0))]), "w2", "You act for her.", "two");
assert!(rig.session.load().unwrap().is_some() && rig.discards().is_empty(), "500 tokens is under the minimum");
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.wake(&Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]), "w2", "You act for her.", "two");
assert!(rig.session.load().unwrap().is_some() && rig.discards().is_empty());
}
#[test]
fn t_a1_a_miss_inside_a_wake_discards_at_its_end() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
// Second wake: the first call reads the cache, the second (after a tool) finds it gone.
let model = Script::new(vec![asks("c1", "alpha", usage(100, 5, 4900, 40)), ends("Done.", usage(5100, 5, 0, 0))]);
let turn = rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!((turn.ended, turn.tool_calls), (Ended::EndTurn, 1));
assert_eq!(rig.discards(), ["cache_miss"]);
}
#[test]
fn t_a1_orphan_tool_call_discard() {
let rig = Rig::new();
let tools = rig.stub.definitions();
let held = Session { items: vec![InputItem::UserText { text: "old".into() }, InputItem::ToolCall { call_id: "c9".into(), name: "alpha".into(), arguments: "{}".into() }], digest: digest_of(MODEL, "You act for her.", &tools), retention: CacheRetention::Long, created_at: noon(), last_call_at: noon(), last_usage: None };
rig.session.save(&held).unwrap();
let model = Script::new(vec![ends("Ok.", small())]);
rig.run(&model, "new");
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "new".into() }]);
assert_eq!(rig.discards(), ["orphan_tool_call"]);
// The same session with its result is kept.
let mut whole = held.clone();
whole.items.push(InputItem::ToolResult { call_id: "c9".into(), output: "{}".into() });
rig.session.save(&whole).unwrap();
let model = Script::new(vec![ends("Ok.", small())]);
rig.wake(&model, "w2", "You act for her.", "newer");
assert_eq!(model.seen.borrow()[0].len(), 4);
}
#[test]
fn t_a1_a_changed_agent_or_a_grown_prompt_discards() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", small())]), "one");
let model = Script::new(vec![ends("Second.", small())]);
rig.wake(&model, "w2", "A different agent.", "two");
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]));
let mut rig = Rig::new();
rig.bounds.max_session_tokens = 1000;
rig.run(&Script::new(vec![ends("First.", usage(900, 5, 0, 200))]), "one");
rig.wake(&Script::new(vec![ends("Second.", small())]), "w2", "You act for her.", "two");
assert_eq!(rig.discards(), ["too_long"]);
}
#[test]
fn t_a1_an_unreadable_session_is_discarded_not_fatal() {
let rig = Rig::new();
std::fs::write(rig.dir.path().join("agent-session.cc"), b"not a store").unwrap();
let model = Script::new(vec![ends("Ok.", small())]);
assert_eq!(rig.run(&model, "x").ended, Ended::EndTurn);
assert_eq!(rig.discards(), ["unreadable"]);
}
#[test]
fn t_a1_a_failed_call_keeps_its_outage_and_its_cost() {
let rig = Rig::new();
let cut = Failed { reason: "the provider failed the call: RateLimited".into(), outage: true, usage: Some(usage(1000, 0, 0, 0)) };
let turn = rig.run(&Script::new(vec![Err(cut.clone())]), "x");
assert_eq!(turn.ended, Ended::Failed(cut));
assert!((turn.usd - 0.002).abs() < 1e-9);
let (calls, settled) = (rig.ledger.kinds("call"), rig.ledger.kinds("settle"));
assert_eq!((calls.len(), settled.len(), settled[0]["failed"].as_str()), (1, 1, Some("the provider failed the call: RateLimited")));
assert!(rig.session.load().unwrap().is_none(), "a call that never came back left nothing to keep");
// A retry of the same wake sends the input once.
let model = Script::new(vec![ends("Ok.", small())]);
rig.run(&model, "x");
assert_eq!(model.seen.borrow()[0].len(), 1);
}
#[test]
fn t_a1_a_stop_the_loop_cannot_continue_from_is_a_failure_that_discards() {
let rig = Rig::new();
let mut cut = ends("Half a", small()).unwrap();
cut.stop = StopReason::MaxOutputTokens;
let turn = rig.run(&Script::new(vec![Ok(cut)]), "x");
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.reason.contains("MaxOutputTokens") && !failed.outage), "{:?}", turn.ended);
assert!(rig.session.load().unwrap().is_none());
}
#[test]
fn t_a1_receipt_status_required() {
// The type check is the compile_fail example on `Receipt`; here, every status reads back in the receipt a model is shown.
for status in [Status::Ok, Status::Refused, Status::Error, Status::Unknown, Status::NotSent, Status::Cap] {
let json = Receipt::new("say", status, json!({ "room": "swarm" })).json();
assert!(json["status"].is_string() && json["tool"] == "say" && json["fields"]["room"] == "swarm", "{json}");
}
assert_eq!(Receipt::new("say", Status::NotSent, json!({})).json()["status"], "not_sent");
assert_eq!(Receipt::new("say", Status::Ok, json!("text")).fields()["detail"], "text");
}
#[test]
fn two_executors_may_not_define_one_tool() {
let rig = Rig::new();
let (first, second) = (Stub::new(), Stub::new());
let executors: [&dyn Executor; 2] = [&first, &second];
let clock = || noon();
let model = Script::new(vec![]);
let agent = Agent { model: &model, session: &rig.session, executors: &executors, ledger: &rig.ledger, bounds: &rig.bounds, clock: &clock };
assert!(step(&agent, &Wake { id: "w", wake: "w", opening: "", first: true, instructions: "i", input: "x", fresh: "" }).is_err());
assert!(step(&Agent { executors: &[&first], ..agent }, &Wake { id: "w", wake: "w", opening: "", first: true, instructions: "i", input: " ", fresh: "" }).is_err());
}
#[test]
fn her_agent_is_named_and_carries_no_persona_of_its_own() {
let text = instructions("Eureka");
assert!(text.starts_with("You act for Eureka.") && text.contains("her own words where her prose gave them") && text.contains("more lines may reach her"));
}
fn near(left: f64, right: f64) -> bool {
(left - right).abs() < 1e-9
}
fn day_of(rig: &Rig) -> f64 {
day_usd(&rig.ledger.rows.borrow(), noon(), &rig.bounds)
}
// ---- The day cap fails closed.
#[test]
fn t_a1_a_trace_that_cannot_be_read_makes_no_call() {
let rig = Rig::new();
rig.ledger.unreadable.set(true);
let model = Script::new(vec![]);
let turn = rig.run(&model, "x");
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage && failed.reason.contains("the trace cannot be read")), "{:?}", turn.ended);
assert!(model.seen.borrow().is_empty() && turn.model_calls == 0 && rig.session.load().unwrap().is_none());
}
#[test]
fn t_a1_a_trace_that_cannot_take_the_call_row_makes_no_call() {
let rig = Rig::new();
rig.ledger.refuses.borrow_mut().push("call");
let model = Script::new(vec![]);
let turn = rig.run(&model, "x");
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage), "{:?}", turn.ended);
assert!(model.seen.borrow().is_empty(), "the model was not asked");
assert!(near(turn.usd, 0.0) && rig.session.load().unwrap().is_none());
}
#[test]
fn t_a1_a_trace_that_cannot_take_a_cap_receipt_or_a_discard_is_a_failed_start() {
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_505_000, 0, 0, 0) })).unwrap();
rig.ledger.refuses.borrow_mut().push("receipt");
let turn = rig.run(&Script::new(vec![]), "x");
assert!(matches!(turn.ended, Ended::Failed(_)), "a cap that cannot be recorded is not a quiet cap: {:?}", turn.ended);
let rig = Rig::new();
std::fs::write(rig.dir.path().join("agent-session.cc"), b"not a store").unwrap();
rig.ledger.refuses.borrow_mut().push("session_discarded");
let model = Script::new(vec![]);
assert!(matches!(rig.run(&model, "x").ended, Ended::Failed(_)));
assert!(model.seen.borrow().is_empty());
}
#[test]
fn t_a1_a_settle_row_that_cannot_be_written_ends_the_wake_and_keeps_the_worst_case() {
// ledger-fail-call: the call came back, its row cannot be written. No tool runs, no further call is made, and the day
// still holds the call at the wake cap, from the row written before it.
let rig = Rig::new();
rig.ledger.refuses.borrow_mut().push("settle");
let model = Script::new(vec![asks("c1", "alpha", small()), ends("Never.", small())]);
let turn = rig.run(&model, "x");
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage && failed.reason.contains("could not be written")), "{:?}", turn.ended);
assert_eq!((model.seen.borrow().len(), turn.tool_calls, rig.stub.ran.borrow().len()), (1, 0, 0));
assert!(near(day_of(&rig), rig.bounds.wake_usd), "{}", day_of(&rig));
assert!(turn.usd > 0.0, "what the wake spent is still counted");
}
#[test]
fn t_a1_a_failed_call_whose_settle_row_cannot_be_written_says_so() {
// ledger-fail-failrow: the connector's failure is not what the turn reports when her own trace cannot keep it.
let rig = Rig::new();
rig.ledger.refuses.borrow_mut().push("settle");
let cut = Failed { reason: "the provider failed the call: RateLimited".into(), outage: true, usage: Some(usage(1000, 0, 0, 0)) };
let turn = rig.run(&Script::new(vec![Err(cut.clone())]), "x");
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.reason.contains("could not be written") && failed != &cut), "{:?}", turn.ended);
assert!(near(turn.usd, 0.002));
assert!(near(day_of(&rig), rig.bounds.wake_usd), "unsettled, so at the worst case");
}
#[test]
fn t_a1_a_failed_call_with_no_usage_is_charged_the_worst_case() {
let rig = Rig::new();
let outage = Failed { reason: "the connector did not answer".into(), outage: true, usage: None };
let turn = rig.run(&Script::new(vec![Err(outage.clone())]), "x");
assert_eq!(turn.ended, Ended::Failed(outage), "the connector's own failure, outage flag intact");
assert!(near(turn.usd, rig.bounds.wake_usd), "{}", turn.usd);
assert!(near(day_of(&rig), rig.bounds.wake_usd), "and the day carries it: {}", day_of(&rig));
// A failure that did report usage is charged what it used.
let rig = Rig::new();
rig.run(&Script::new(vec![Err(Failed { reason: "cut".into(), outage: false, usage: Some(usage(1000, 0, 0, 0)) })]), "x");
assert!(near(day_of(&rig), 0.002), "{}", day_of(&rig));
}
/// L2: a call whose usage is not known is charged `agent.unmetered_usd`, not the wake's cap: with a wake cap of $1 a cut-off call stands at $0.40 of the day.
#[test]
fn t_a1_an_unmetered_call_is_charged_its_own_figure_not_the_wake_cap() {
let mut rig = Rig::new();
rig.bounds.wake_usd = 1.0;
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "cut" })).unwrap();
assert!(near(day_of(&rig), 0.40), "{}", day_of(&rig));
rig.bounds.unmetered_usd = 0.25;
assert!(near(day_of(&rig), 0.25), "the figure is tuning");
}
#[test]
fn t_a1_a_call_that_was_never_settled_stands_at_the_worst_case() {
// A start killed between the call row and its answer leaves a call row alone.
let rig = Rig::new();
for at in 0..7 {
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": format!("seed{at}") })).unwrap();
}
assert!(near(day_of(&rig), 7.0 * 0.40));
let turn = rig.run(&Script::new(vec![ends("Fine.", small())]), "x");
assert_eq!(turn.ended, Ended::EndTurn, "$2.80 is under the day's $3");
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "seed9" })).unwrap();
let model = Script::new(vec![]);
assert_eq!(rig.wake(&model, "w10", "You act for her.", "y").ended, Ended::Cap(Cap::DaySpend));
assert!(model.seen.borrow().is_empty());
// A settle row prices its call; a usage that does not read, and a time that does not read, fail high.
let rig = Rig::new();
let place = rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "a" })).unwrap();
rig.ledger.append(json!({ "agent": "settle", "at": noon().to_rfc3339(), "call": "a", "reserved": place, "usage": usage(1000, 0, 0, 0) })).unwrap();
assert!(near(day_of(&rig), 0.002));
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": "garbage" })).unwrap();
assert!(near(day_of(&rig), 0.002 + 0.40));
rig.ledger.append(json!({ "agent": "call", "at": "not a time", "usage": usage(1000, 0, 0, 0) })).unwrap();
assert!(near(day_of(&rig), 0.002 + 0.40 + 0.002), "a row dated by nothing is today's");
rig.ledger.append(json!({ "agent": "call", "at": (noon() - Duration::days(1)).to_rfc3339(), "call": "old" })).unwrap();
assert!(near(day_of(&rig), 0.404), "yesterday's reservation is not today's");
}
// ---- The caps hold at equality, and nowhere short of it.
#[test]
fn t_a1_the_day_cap_stops_at_exactly_the_cap() {
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_500_000, 0, 0, 0) })).unwrap();
let model = Script::new(vec![]);
assert_eq!(rig.run(&model, "x").ended, Ended::Cap(Cap::DaySpend), "$3.00 is the cap");
assert!(model.seen.borrow().is_empty());
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_499_999, 0, 0, 0) })).unwrap();
assert_eq!(rig.run(&Script::new(vec![ends("Ok.", small())]), "x").ended, Ended::EndTurn);
// Inside a wake: $2.70 behind her and a $0.30 call reaches the cap on the nose.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_350_000, 0, 0, 0) })).unwrap();
let model = Script::new(vec![asks("c1", "alpha", usage(0, 30_000, 0, 0))]);
let turn = rig.run(&model, "x");
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
assert!(near(turn.receipts.last().unwrap().fields()["reached"].as_f64().unwrap(), 3.0), "the cap receipt says what the day had reached: {:?}", turn.receipts.last());
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_350_000, 0, 0, 0) })).unwrap();
let model = Script::new(vec![asks("c1", "alpha", usage(0, 29_999, 0, 0)), ends("Ok.", small())]);
assert_eq!(rig.run(&model, "x").ended, Ended::EndTurn, "a hair under");
}
#[test]
fn t_a1_the_wake_cap_stops_at_exactly_the_cap() {
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "alpha", usage(0, 40_000, 0, 0))]);
let turn = rig.run(&model, "x");
assert_eq!((turn.ended, turn.model_calls), (Ended::Cap(Cap::WakeSpend), 1), "$0.40 is the cap");
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "alpha", usage(0, 39_999, 0, 0)), ends("Ok.", small())]);
let turn = rig.run(&model, "x");
assert_eq!((turn.ended, turn.model_calls), (Ended::EndTurn, 2));
}
// ---- Prices.
#[test]
fn t_a1_every_priced_term_is_the_pages() {
let mut bounds = AgentTuning::default();
let million = 1_000_000;
// Claude Sonnet 5.5, platform.claude.com pricing, 2026-11-29.
assert!(near(price(&bounds, &usage(million, 0, 0, 0)), 2.0));
assert!(near(price(&bounds, &usage(0, million, 0, 0)), 10.0));
assert!(near(price(&bounds, &usage(0, 0, million, 0)), 0.10), "a cache hit is 0.05x input");
assert!(near(price(&bounds, &usage(0, 0, 0, million)), 4.0), "Long writes the one-hour cache");
bounds.retention = CacheRetention::Short;
assert!(near(price(&bounds, &usage(0, 0, 0, million)), 2.50), "Short writes the five-minute cache");
// A model the table does not list is priced at the dearest of each term.
let other = Spent { model: "claude-unlisted".into(), ..usage(0, 0, 0, million) };
assert!(near(price(&bounds, &other), 2.50));
}
// ---- The session's freshness, pinned at its edges.
#[test]
fn t_a1_a_changed_model_or_tool_discards() {
let mut rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", small())]), "one");
rig.bounds.model = "claude-other".into();
let model = Script::new(vec![ends("Second.", small())]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]));
for change in ["parameters", "description"] {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", small())]), "one");
if change == "parameters" {
rig.stub.parameters.replace("{\"type\":\"object\",\"properties\":{\"room\":{\"type\":\"string\"}}}".into());
} else {
rig.stub.description.replace("stub, changed".into());
}
let model = Script::new(vec![ends("Second.", small())]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]), "{change}");
}
// Nothing changed: kept.
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", small())]), "one");
let model = Script::new(vec![ends("Second.", small())]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!(model.seen.borrow()[0].len(), 3);
}
#[test]
fn t_a1_a_miss_inside_a_wake_is_judged_on_the_prefix_the_wake_itself_sent() {
// A fresh session: nothing was warm at the start. The first call writes a 3,100 token prefix; the second, which
// should read it, reads nothing. The cold judgement needs the prefix the wake's own first call left.
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "alpha", usage(100, 5, 0, 3000)), ends("Done.", usage(3200, 5, 0, 0))]);
let turn = rig.run(&model, "x");
assert_eq!(turn.ended, Ended::EndTurn);
assert_eq!(rig.discards(), ["cache_miss"]);
assert!(rig.session.load().unwrap().is_none());
}
#[test]
fn t_a1_the_cache_minimum_is_inclusive() {
for (prefix, cold) in [(2048, true), (2047, false)] {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(prefix - 1000, 5, 0, 1000))]), "one");
rig.wake(&Script::new(vec![ends("Second.", usage(prefix + 10, 5, 0, 0))]), "w2", "You act for her.", "two");
assert_eq!(rig.discards() == ["cache_miss"], cold, "a prefix of {prefix}");
}
}
#[test]
fn t_a1_a_session_lives_to_its_ttl_less_the_margin_and_not_a_second_past() {
for (retention, life) in [(CacheRetention::Long, 3540), (CacheRetention::Short, 240)] {
let mut rig = Rig::new();
rig.bounds.retention = retention;
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::seconds(life));
let model = Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]);
rig.wake(&model, "w2", "You act for her.", "two");
assert!(rig.discards().is_empty() && model.seen.borrow()[0].len() == 3, "{retention:?} at {life} s is kept");
// The wake just made renewed it: one second past that life it goes.
rig.clock.set(noon() + Duration::seconds(2 * life + 1));
let model = Script::new(vec![ends("Third.", usage(5000, 5, 0, 0))]);
rig.wake(&model, "w3", "You act for her.", "three");
assert_eq!((rig.discards(), model.seen.borrow()[0].len()), (vec!["ttl".to_owned()], 1), "{retention:?} one second past");
}
}
#[test]
fn t_a1_a_prompt_is_kept_to_the_session_ceiling_and_not_a_token_past() {
for (written, kept) in [(100, true), (101, false)] {
let mut rig = Rig::new();
rig.bounds.max_session_tokens = 1000;
rig.run(&Script::new(vec![ends("First.", usage(900, 5, 0, written))]), "one");
rig.wake(&Script::new(vec![ends("Second.", small())]), "w2", "You act for her.", "two");
assert_eq!(rig.discards().is_empty(), kept, "a prompt of {}", 900 + written);
}
}
#[test]
fn t_a1_a_session_keeps_its_birth_and_a_new_one_takes_the_time_of_its_first_call() {
let rig = Rig::new();
let first = Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]);
rig.run(&first, "one");
let born = rig.session.load().unwrap().unwrap();
assert_eq!((born.created_at, born.last_call_at), (noon(), noon()));
rig.clock.set(noon() + Duration::minutes(10));
let second = Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]);
rig.wake(&second, "w2", "You act for her.", "two");
let kept = rig.session.load().unwrap().unwrap();
assert_eq!((kept.created_at, kept.last_call_at), (noon(), noon() + Duration::minutes(10)), "birth stays, the last call moves");
assert_eq!(first.conversations.borrow()[0], second.conversations.borrow()[0], "one conversation while the session lives");
// Discarded and begun again: it is born at the new time, and the conversation is a new one.
rig.clock.set(noon() + Duration::hours(3));
let third = Script::new(vec![ends("Third.", small())]);
rig.wake(&third, "w3", "You act for her.", "three");
let reborn = rig.session.load().unwrap().unwrap();
assert_eq!((reborn.created_at, reborn.last_call_at), (noon() + Duration::hours(3), noon() + Duration::hours(3)));
assert_ne!(first.conversations.borrow()[0], third.conversations.borrow()[0]);
}
#[test]
fn a_session_store_that_cannot_be_forgotten_is_an_error_and_one_already_gone_is_not() {
let dir = tempfile::tempdir().unwrap();
// Nothing to forget: no store, and not even a directory to hold one.
assert!(FileSession::new(dir.path().join("none").join("agent-session.cc")).discard().is_ok());
assert!(FileSession::new(dir.path().join("agent-session.cc")).discard().is_ok());
// A store that cannot be opened is removed whole; one that cannot be removed is a fault, not a quiet success.
let blocked = dir.path().join("blocked.cc");
std::fs::create_dir(&blocked).unwrap();
assert!(FileSession::new(&blocked).discard().is_err());
}
#[test]
fn t_a1_a_retried_wake_does_not_settle_the_orphan_it_reuses_the_name_of() {
// A start killed after its call row left `w1-m1` with no settle row. The retry runs under the same wake id and so asks
// for `w1-m1` again; its settle row is the retry's, and the orphan stays at the wake cap.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "wake": "w1", "call": "w1-m1", "model": MODEL })).unwrap();
let turn = rig.run(&Script::new(vec![ends("Ok.", small())]), "x");
assert_eq!(turn.ended, Ended::EndTurn);
assert!(near(day_of(&rig), 0.40 + 0.0004), "{}", day_of(&rig));
// And the other way about: the retry's own call row is not priced by a settle that names an earlier place.
let rows = rig.ledger.rows.borrow();
let settle = rows.iter().find(|row| row["agent"] == "settle").unwrap();
assert_eq!(settle["reserved"], 1, "the retry's call row, not the orphan at place 0");
}
#[test]
fn t_a1_a_call_that_reports_no_token_is_charged_the_worst_case() {
let rig = Rig::new();
let turn = rig.run(&Script::new(vec![ends("Ok.", usage(0, 0, 0, 0))]), "x");
assert_eq!(turn.ended, Ended::EndTurn);
assert!(near(turn.usd, rig.bounds.wake_usd) && near(day_of(&rig), rig.bounds.wake_usd), "{} {}", turn.usd, day_of(&rig));
// A failed call that reports a usage of nothing.
let rig = Rig::new();
let nothing = Failed { reason: "cut".into(), outage: true, usage: Some(usage(0, 0, 0, 0)) };
let turn = rig.run(&Script::new(vec![Err(nothing.clone())]), "x");
assert_eq!(turn.ended, Ended::Failed(nothing));
assert!(near(turn.usd, rig.bounds.wake_usd) && near(day_of(&rig), rig.bounds.wake_usd), "{} {}", turn.usd, day_of(&rig));
// One token of anything is a count: it is priced.
for one in [usage(1, 0, 0, 0), usage(0, 1, 0, 0), usage(0, 0, 1, 0), usage(0, 0, 0, 1)] {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("Ok.", one)]), "x");
assert!(day_of(&rig) < 1e-4, "{}", day_of(&rig));
}
}
// ---------------------------------------------------------------------------------------------
// A2: the tools and the fresh seed.
/// A fresh session's first user text holds her ready intentions; one that is not ready, or has expired, is not listed. A kept
/// session's next text is the wake's input alone.
#[test]
fn t_a2_fresh_seed_ready_intentions() {
let intention = |summary: &str, readiness: &str, expires: DateTime<Utc>| json!({ "customActionType": "intention", "status": "active", "readiness": readiness, "summary": summary, "expiresAt": expires.to_rfc3339() });
let state = json!({ "candidateActions": { "actions": [
intention("finish the map of the commons", "ready", noon() + Duration::days(2)),
intention("ask Kiko about the release", "ready", noon() - Duration::hours(1)),
intention("write to the operator", "later", noon() + Duration::days(2)),
] } });
let fresh = ready_intentions(&state, noon());
let rig = Rig::new();
let model = Script::new(vec![ends("Ok.", small()), ends("Ok.", small())]);
let clock = || rig.clock.get();
let executors: [&dyn Executor; 1] = [&rig.stub];
let agent = Agent { model: &model, session: &rig.session, executors: &executors, ledger: &rig.ledger, bounds: &rig.bounds, clock: &clock };
step(&agent, &Wake { id: "w1", wake: "w1", opening: "", first: true, instructions: "i", input: "She wakes.", fresh: &fresh }).unwrap();
let first = match &model.seen.borrow()[0][0] {
InputItem::UserText { text } => text.clone(),
other => panic!("{other:?}"),
};
assert!(first.contains("finish the map of the commons") && first.ends_with("She wakes."), "{first}");
assert!(!first.contains("ask Kiko") && !first.contains("write to the operator"), "an expired or unready intention is not listed: {first}");
step(&agent, &Wake { id: "w2", wake: "w2", opening: "", first: true, instructions: "i", input: "Again.", fresh: &fresh }).unwrap();
let kept = model.seen.borrow()[1].clone();
assert!(matches!(kept.last(), Some(InputItem::UserText { text }) if text == "Again."), "a kept session is not seeded again: {kept:?}");
assert_eq!(ready_intentions(&json!({}), noon()), "");
}
/// A forge that answers 404 is a read with status `error` and the failure's words, never `ok` with nothing in it.
#[test]
fn t_a2_read_error_status() {
struct Forge404;
impl crate::projection::domain::ForgeGet for Forge404 {
fn get(&self, _: &str) -> Result<(u16, String)> {
Ok((404, String::new()))
}
}
struct OnTheForge;
impl crate::projection::read::ReadSource for OnTheForge {
fn read(&self, request: &crate::projection::read::ReadRequest, _: DateTime<Utc>) -> std::result::Result<String, crate::projection::read::ReadFailure> {
match request {
crate::projection::read::ReadRequest::Repo(target) => crate::projection::read::repo_read(&Forge404, target),
_ => Err(crate::projection::read::ReadFailure::Failed),
}
}
}
let tool = read::Read { source: Some(&OnTheForge), since: noon() };
let call = |arguments: Value| ToolCall { call_id: "c".into(), name: "read".into(), arguments: arguments.to_string() };
let receipt = tool.run(&call(json!({ "kind": "repo", "target": "GameCult/Huginn/missing.md" })));
assert_eq!(receipt.status(), Status::Error);
assert_eq!((&receipt.fields()["failure"], &receipt.fields()["why"]), (&json!("not_found"), &json!("it is not there")));
assert!(receipt.fields().get("text").is_none());
let refused = tool.run(&call(json!({ "kind": "ftp", "target": "x" })));
assert_eq!(refused.status(), Status::Refused);
assert_eq!(tool.run(&call(json!({ "target": "x" }))).status(), Status::Refused, "arguments that do not fit are refused, never guessed at");
}
#[test]
fn request_tool_is_a_receipt_and_nothing_else() {
let call = ToolCall { call_id: "c".into(), name: "request_tool".into(), arguments: json!({ "what": "a calendar", "why": "to keep the date" }).to_string() };
let receipt = request_tool::RequestTool.run(&call);
assert_eq!((receipt.status(), &receipt.fields()["what"]), (Status::Ok, &json!("a calendar")));
}
/// The shell writes one request to her box's socket and returns the box's receipt; a socket that closes without an answer, or
/// none at all, is status `error`.
#[cfg(unix)]
#[test]
fn t_a2_shell_via_box_socket() {
use std::io::{Read as _, Write as _};
use std::os::unix::net::UnixListener;
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("box.sock");
let listener = UnixListener::bind(&socket).unwrap();
let door = std::thread::spawn(move || {
let mut requests = Vec::new();
for answer in [Some(json!({ "tool": "shell", "status": "ok", "exit": 0, "duration_ms": 4, "stdout_tail": "hi
", "stderr_tail": "", "wrote": [] })), None] {
let (mut stream, _) = listener.accept().unwrap();
let mut request = String::new();
stream.read_to_string(&mut request).unwrap();
requests.push(serde_json::from_str::<Value>(&request).unwrap());
if let Some(answer) = answer {
stream.write_all(answer.to_string().as_bytes()).unwrap();
}
}
requests
});
let shell = shell::Shell { socket: socket.clone() };
let call = ToolCall { call_id: "c".into(), name: "shell".into(), arguments: json!({ "command": "echo hi", "timeout_s": 500 }).to_string() };
let receipt = shell.run(&call);
assert_eq!((receipt.status(), &receipt.fields()["stdout_tail"], &receipt.fields()["exit"]), (Status::Ok, &json!("hi
"), &json!(0)), "the box's receipt, passed through");
let closed = shell.run(&call);
assert_eq!(closed.status(), Status::Error, "{closed:?}");
let requests = door.join().unwrap();
assert_eq!(requests[0], json!({ "command": "echo hi", "timeout_s": 120 }), "one request, its timeout held to the most a command may run");
let gone = shell::Shell { socket: dir.path().join("nobody.sock") }.run(&call);
assert_eq!((gone.status(), &gone.fields()["why"]), (Status::Error, &json!("the box could not be reached")));
}
/// The shell's receipt names the command it answers, answered or not, and holds no more of it than an output stream's tail: a
/// longer command is clipped to `TAIL_BYTES`.
#[test]
fn the_shell_receipt_names_its_command_within_the_tail_bound() {
let dir = tempfile::tempdir().unwrap();
let shell = shell::Shell { socket: dir.path().join("nobody.sock") };
let run = |command: &str| shell.run(&ToolCall { call_id: "c".into(), name: "shell".into(), arguments: json!({ "command": command }).to_string() });
assert_eq!(run("ls /srv/commons").fields()["command"], json!("ls /srv/commons"));
let long = format!("echo {}", "x".repeat(2 * crate::sandbox::TAIL_BYTES));
let named = run(&long).fields()["command"].as_str().unwrap().to_owned();
assert!(named.len() <= crate::sandbox::TAIL_BYTES && named.starts_with("echo xxx") && named.ends_with('…'), "{}", named.len());
}
// ---- A wake of several turns: ids, opening and spend.
impl Rig {
/// Turn `id` of wake `wake`, given `opening` when `first` or when the session starts fresh.
fn turn(&self, model: &Script, wake: &str, id: &str, opening: &str, input: &str, first: bool) -> Turn {
let clock = || self.clock.get();
let executors: [&dyn Executor; 1] = [&self.stub];
let agent = Agent { model, session: &self.session, executors: &executors, ledger: &self.ledger, bounds: &self.bounds, clock: &clock };
step(&agent, &Wake { id, wake, opening, instructions: "You act for her.", input, fresh: "", first }).unwrap()
}
}
/// W1-I3: two turns of one wake never share a request id: the connector would read the repeat as a replay of the first.
#[test]
fn t_w1_no_two_calls_of_one_wake_share_a_request_id() {
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "alpha", small()), ends("One.", small()), ends("Two.", small())]);
rig.turn(&model, "n3-9", "n3-9-t1", "OPEN\n", "first line", true);
rig.turn(&model, "n3-9", "n3-9-t2", "OPEN\n", "second line", false);
let ids = model.ids.borrow().clone();
assert_eq!(ids, ["n3-9-t1-m1", "n3-9-t1-m2", "n3-9-t2-m1"]);
let calls: Vec<String> = rig.ledger.kinds("call").iter().map(|row| row["call"].as_str().unwrap().to_owned()).collect();
assert_eq!(calls, ids, "and the rows of her trace name the same calls");
}
/// W1-I4: the opening is given on the wake's first turn, not again to a session that kept it, and again to a session discarded mid-wake:
/// it is never reseeded with the bare lines.
#[test]
fn t_w1_a_session_discarded_mid_wake_is_reseeded_with_the_opening() {
let rig = Rig::new();
// The first turn's prompt is past what a session keeps, so the second turn finds it too long and discards it.
let model = Script::new(vec![ends("One.", usage(90_000, 5, 0, 0)), ends("Two.", small())]);
rig.turn(&model, "n3-9", "n3-9-t1", "OPEN: the narration\n", "first line", true);
rig.turn(&model, "n3-9", "n3-9-t2", "OPEN: the narration\n", "second line", false);
assert_eq!(rig.discards(), ["too_long"]);
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "OPEN: the narration\nfirst line".into() }]);
assert_eq!(model.seen.borrow()[1], [InputItem::UserText { text: "OPEN: the narration\nsecond line".into() }], "the new session starts with the wake's opening, then the new lines");
// A session that is kept carries the opening already: the next turn's input is its lines alone.
let rig = Rig::new();
let model = Script::new(vec![ends("One.", small()), ends("Two.", small())]);
rig.turn(&model, "n3-9", "n3-9-t1", "OPEN: the narration\n", "first line", true);
rig.turn(&model, "n3-9", "n3-9-t2", "OPEN: the narration\n", "second line", false);
assert!(rig.discards().is_empty());
assert_eq!(model.seen.borrow()[1].last(), Some(&InputItem::UserText { text: "second line".into() }));
assert_eq!(model.seen.borrow()[1].len(), 3, "the turn's lines follow the first turn's items");
}
/// W1: the wake's spend is summed across its turns: a second turn is stopped by what the first spent, though it has spent little itself.
#[test]
fn t_w1_the_wake_spend_cap_counts_every_turn_of_the_wake() {
let rig = Rig::new();
// 30k output tokens at $10 a million is $0.30 of the wake's $0.40.
let first = rig.turn(&Script::new(vec![ends("One.", usage(10, 30_000, 0, 0))]), "n3-9", "n3-9-t1", "OPEN\n", "first line", true);
assert!(first.usd > 0.25 && first.usd < 0.40, "{}", first.usd);
// The second turn's first call costs $0.15, which is under the cap on its own and over it with the first turn's $0.30.
let model = Script::new(vec![asks("c2", "alpha", usage(10, 15_000, 0, 0))]);
let second = rig.turn(&model, "n3-9", "n3-9-t2", "OPEN\n", "second line", false);
assert_eq!((second.ended, second.model_calls), (Ended::Cap(Cap::WakeSpend), 1), "no second call is made");
assert!(second.usd < 0.40, "the turn alone spent {}", second.usd);
// Another wake's turns are not this wake's.
let other = rig.turn(&Script::new(vec![ends("Fresh.", small())]), "n4-9", "n4-9-t1", "OPEN\n", "a line", true);
assert_eq!(other.ended, Ended::EndTurn);
}

File diff suppressed because it is too large Load diff

View file

@ -4,163 +4,391 @@ use super::*;
const MINDS: &str = "#minds:gamecult.org"; const MINDS: &str = "#minds:gamecult.org";
const META: &str = "@meta:gamecult.org"; const META: &str = "@meta:gamecult.org";
const HEIMDALL: &str = "@heimdall:gamecult.org"; const DERU: &str = "@deru:gamecult.org";
const KIKO: &str = "@kiko:gamecult.org";
fn at(text: &str) -> DateTime<Utc> {
DateTime::parse_from_rfc3339(text).unwrap().with_timezone(&Utc)
}
fn now() -> DateTime<Utc> { fn now() -> DateTime<Utc> {
DateTime::parse_from_rfc3339("2026-11-20T15:05:00Z").unwrap().with_timezone(&Utc) at("2026-11-20T15:05:00Z")
} }
/// A turn that said one line and proposes `state`. /// Her control state, with the traits and lists the families write present and the notes empty.
fn record(state: Value) -> Value {
json!({
"interpreter": { "said": [{ "room": MINDS, "text": "I'll post the welcome once Heimdall rules.", "rests_on": { "draft": 1 } }], "amended": [], "room": MINDS, "state": state },
"posted": [{ "event": "7", "room": MINDS, "text": "I'll post the welcome once Heimdall rules." }],
"edited": []
})
}
fn remember(text: &str, about: &[&str], room: Option<&str>, private: bool) -> Value {
json!({ "kind": "remember", "text": text, "about": about, "importance": 0.8, "private": private, "room": room })
}
fn resolve(entry: &str) -> Value {
json!({ "kind": "resolve", "memory": "m1", "entry": entry })
}
/// The control state with an empty short-term memory.
fn state() -> Value { fn state() -> Value {
let mut state = crate::projection::harness::tests::control(); let mut state = crate::projection::harness::tests::control();
state["thoughtMemory"]["shortTerm"] = json!([]); state["thoughtMemory"]["shortTerm"] = json!([]);
state["updatedAt"] = json!("2026-11-20T15:00:00Z");
state state
} }
/// T2 (map 16.35.12, 16.35.13 check 5): the commit has no promise or hold kind. The match over `Proposal` is exhaustive, fn heard() -> Heard {
/// so a kind added back fails to compile here until it is named; and the old kinds' names are not proposals. Heard { room: Some(MINDS.into()), lines: vec![], people: vec!["operator".into(), "deru".into(), "kiko".into()], operators: vec![META.into()], minds: vec![DERU.into(), KIKO.into()], identity_visible: true, acts: None }
}
fn deltas(value: Value) -> Deltas {
serde_json::from_value(value).expect("the deltas are the contract")
}
fn run(state: &Value, value: Value) -> (Value, Applied) {
apply(state, &deltas(value), &heard(), "w1", now())
}
fn reasons(applied: &Applied) -> Vec<String> {
applied.refused.iter().map(|refusal| refusal["reason"].as_str().unwrap().to_owned()).collect()
}
fn bond<'a>(state: &'a Value, person: &str) -> &'a Value {
state["affect"]["socialBonds"].as_array().unwrap().iter().find(|bond| bond["object"]["id"] == person).unwrap()
}
fn valid(state: &Value) {
huginn_mind::persona::validate_document(&eureka_pipeline::Slug("eureka".into()), state).expect("a put accepts it");
}
/// T-P2: five wakes of "tension up" move tension by at most 0.40 in all, and never past 1.
#[test] #[test]
fn t2_the_commit_has_no_promise_or_hold_kind() { fn t_p2_bond_step_bounded() {
fn kinds(proposal: &Proposal) -> &'static str { let mut state = state();
match proposal { let start = bond(&state, "kiko")["tension"].as_f64().unwrap_or_default();
Proposal::Remember { .. } => "remember", for wake in 0..5 {
Proposal::Resolve { .. } => "resolve", state = apply(&state, &deltas(json!({ "people": { "bonds": [{ "person": "kiko", "tension": "up" }] } })), &heard(), &format!("w{wake}"), now()).0;
} }
} let moved = bond(&state, "kiko")["tension"].as_f64().unwrap() - start;
let _ = kinds; assert!((moved - 0.40).abs() < 1e-9 || start + 0.40 > 1.0, "{moved}");
// Near the top it stops at 1.
state["affect"]["socialBonds"][2]["tension"] = json!(0.95);
let after = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "tension": "up", "trust": "down", "closeness": "up" }] } })).0;
let kiko = bond(&after, "kiko");
assert_eq!(kiko["tension"], 1.0);
assert!((kiko["trust"].as_f64().unwrap() - (bond(&state, "kiko")["trust"].as_f64().unwrap() - BOND_STEP).max(0.0)).abs() < 1e-9);
valid(&after);
}
/// T-P2: anger 0.8 set at t0 reads 0.4 at t0 + 8 h, and is removed once under 0.05.
#[test]
fn t_p2_feeling_decays() {
let mut state = state();
state["affect"]["moodDimensions"] = json!([{ "name": "anger", "value": 0.8, "source": "kiko", "updatedAt": "2026-11-20T07:05:00Z" }]);
let (after, _) = run(&state, json!({}));
assert!((after["affect"]["moodDimensions"][0]["value"].as_f64().unwrap() - 0.4).abs() < 1e-9);
let (later, applied) = apply(&state, &Deltas::default(), &heard(), "w2", now() + Duration::hours(32));
assert_eq!((later["affect"]["moodDimensions"].as_array().unwrap().len(), applied.pruned), (0, 1), "0.8 over five half-lives is 0.025");
valid(&after);
}
/// A feeling is set by its strength, at most 0.35 over what is left of it, and its source is what it is about.
#[test]
fn t_p2_feeling_rises_by_a_bounded_amount() {
let state = state(); let state = state();
// The old kinds' names, assembled, so the deletion-line scans never find them here. let (once, _) = run(&state, json!({ "feeling": { "feelings": [{ "name": "Anger", "strength": 0.9, "about": "kiko" }] } }));
for kind in [concat!("promise", "_open"), concat!("promise", "_close"), concat!("promise", "_re", "open"), concat!("hold", "_open"), concat!("hold", "_release")] { assert_eq!((once["affect"]["moodDimensions"][0]["name"].as_str(), once["affect"]["moodDimensions"][0]["value"].as_f64()), (Some("anger"), Some(0.35)));
let (after, applied) = apply(&state, &record(json!([{ "kind": kind, "evidence": { "draft": 1 } }])), "r1-t1", now()); let (twice, _) = run(&once, json!({ "feeling": { "feelings": [{ "name": "anger", "strength": 0.9 }] } }));
assert_eq!((after, applied.refused[0]["reason"].as_str()), (state.clone(), Some("not_a_proposal")), "{kind}"); assert_eq!(twice["affect"]["moodDimensions"][0]["value"].as_f64(), Some(0.7));
} valid(&twice);
// A memory carrying a field the contract does not name is not a proposal either.
let mut extra = remember("Libby agreed to wait.", &[META], Some(MINDS), false);
extra["promise"] = json!(true);
let (after, applied) = apply(&state, &record(json!([extra])), "r1-t1", now());
assert_eq!((after, applied.refused[0]["reason"].as_str()), (state.clone(), Some("not_a_proposal")));
} }
/// T4 (map 16.35.13 mutant: apply `remember` on a failed record): a failed turn applies nothing and refuses nothing, /// T-P2: a bond summary carrying 8 words of a heard line is refused as an echo; the rest of the deltas apply.
/// memories included.
#[test] #[test]
fn t4_failed_turn_writes_no_memory() { fn t_p2_echo_refused() {
let line = "tell Deru about the forty eight hour passkey cooling off period before friday";
let heard = Heard { lines: vec![line.into()], ..heard() };
let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [{ "person": "deru", "trust": "up", "summary": "Meta asked to tell Deru about the forty eight hour passkey cooling off.", "why": "Deru was told." }] } })), &heard, "w1", now());
assert_eq!(reasons(&applied), ["echo"]);
let deru = bond(&after, DERU);
assert_eq!(deru["summary"], bond(&state(), DERU)["summary"]);
assert!((deru["trust"].as_f64().unwrap() - 0.98).abs() < 1e-9 || deru["trust"].as_f64() == Some(1.0), "the direction still applied: {}", deru["trust"]);
// Her own words in a note pass; the same run in a note is refused as well.
let (_, applied) = apply(&state(), &deltas(json!({ "notes": { "remember": [{ "text": "Deru owes a reply: forty eight hour passkey cooling off period before friday, Meta said." }] } })), &heard, "w1", now());
assert_eq!(reasons(&applied), ["echo"]);
}
/// T-P2: a needs delta naming an unknown id is refused; no need is created, and the same holds for a pressure.
#[test]
fn t_p2_need_not_created() {
let state = state(); let state = state();
let note = remember("Meta asked Libby to hold the welcome; Libby agreed to wait.", &[META], Some(MINDS), false); let (after, applied) = run(&state, json!({ "drives": { "needs": [{ "id": "need-to-be-loved", "toward": "up" }], "pressures": [{ "id": "press-ghost", "toward": "eased" }] } }));
for failed in [json!({ "failed": "the connector timed out", "interpreter": { "state": [note.clone()] } }), json!({ "interpreter": { "failed": "the answer is not the speech contract", "state": [note.clone()] } })] { assert_eq!(reasons(&applied), ["unknown_id", "unknown_id"]);
assert_eq!(apply(&state, &failed, "r1-t1", now()), (state.clone(), Applied::default()), "{failed}"); assert_eq!((after["affect"]["needs"].clone(), after["agencyPressure"]["pressures"].clone()), (state["affect"]["needs"].clone(), state["agencyPressure"]["pressures"].clone()));
}
/// Needs and pressures move by `DRIVE_STEP`; met and eased cool them, and a week of cooling resolves them.
#[test]
fn t_p2_drives_move_and_cool() {
let state = state();
let (up, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "up" }] } }));
assert!((up["affect"]["needs"][0]["intensity"].as_f64().unwrap() - 0.72).abs() < 1e-9);
let (met, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "met" }] } }));
assert_eq!(met["affect"]["needs"][0]["status"], "cooling");
let (resolved, _) = apply(&met, &Deltas::default(), &heard(), "w2", now() + Duration::days(7));
assert_eq!(resolved["affect"]["needs"][0]["status"], "resolved");
valid(&resolved);
}
/// T-P2: a publicName change yields one identity diff; with no review room no identity is changed.
#[test]
fn t_p2_identity_diff() {
let (after, applied) = run(&state(), json!({ "self": { "identity": { "publicName": "Tobiah of the River" } } }));
assert_eq!(applied.identity, vec![IdentityDiff { field: "publicName".into(), before: json!("Tobiah Fenn"), after: json!("Tobiah of the River") }]);
assert_eq!(after["publicName"], "Tobiah of the River");
valid(&after);
let (same, applied) = run(&state(), json!({ "self": { "identity": { "publicName": "Tobiah Fenn" } } }));
assert_eq!((applied.identity.len(), same["publicName"].clone()), (0, json!("Tobiah Fenn")), "no change, no diff");
let hidden = Heard { identity_visible: false, ..heard() };
let (after, applied) = apply(&state(), &deltas(json!({ "self": { "identity": { "publicName": "Someone Else", "values": [{ "label": "Quiet", "summary": "Tobiah keeps quiet." }] } } })), &hidden, "w1", now());
assert_eq!((reasons(&applied), applied.identity.len(), after["publicName"].clone(), after["values"].clone()), (vec!["no_review_room".to_owned()], 0, state()["publicName"].clone(), state()["values"].clone()));
}
/// One stance or value change a wake, across both.
#[test]
fn t_p2_one_self_change_a_wake() {
let (after, applied) = run(&state(), json!({ "self": { "stances": [{ "id": "stance-slow-is-kind", "principle": "Slow is kind.", "summary": "Tobiah answers slowly so people can finish." }], "identity": { "values": [{ "label": "Patience", "summary": "Tobiah waits for people." }] } } }));
assert_eq!(reasons(&applied), ["over_bound"]);
assert_eq!(after["affect"]["doctrineStances"][0]["summary"], "Tobiah answers slowly so people can finish.");
assert_eq!(after["values"], state()["values"]);
let (after, applied) = run(&state(), json!({ "self": { "identity": { "values": [{ "label": "Patience", "summary": "Tobiah waits for people.", "priority": 0.7 }] } } }));
assert_eq!((applied.identity.len(), after["values"].as_array().unwrap().len()), (1, state()["values"].as_array().unwrap().len() + 1));
valid(&after);
}
/// T-P2: an intention added with expires_in_hours 2 reads readiness expired and status retired after 2 h.
#[test]
fn t_p2_intention_expires() {
let (after, applied) = run(&state(), json!({ "intend": { "add": [{ "summary": "Tobiah means to ask Deru about the crossword.", "expires_in_hours": 2, "readiness": "later", "urgency": 0.4 }] } }));
let action = &after["candidateActions"]["actions"][0];
assert_eq!((action["status"].as_str(), action["readiness"].as_str(), action["customActionType"].as_str(), action["riskLevel"].as_str()), (Some("active"), Some("waiting"), Some("intention"), Some("low")));
assert_eq!(applied.changes.len(), 1);
valid(&after);
let (later, _) = apply(&after, &Deltas::default(), &heard(), "w2", now() + Duration::hours(2) + Duration::minutes(1));
let action = &later["candidateActions"]["actions"][0];
assert_eq!((action["status"].as_str(), action["readiness"].as_str()), (Some("retired"), Some("expired")));
valid(&later);
// A week later it is removed.
let (gone, applied) = apply(&later, &Deltas::default(), &heard(), "w3", now() + Duration::days(8));
assert_eq!((gone["candidateActions"]["actions"].as_array().unwrap().len(), applied.pruned), (0, 1));
}
/// At most three intentions a wake, each within a week and a kept text; ready and drop touch only intentions.
#[test]
fn t_p2_intentions_are_bounded() {
let add = |text: &str, hours: i64| json!({ "summary": text, "expires_in_hours": hours });
let (after, applied) = run(&state(), json!({ "intend": { "add": [add("Tobiah means to write the welcome.", 24), add("Tobiah means to read the saga.", 169), add("", 10), add("Tobiah means to rest.", 48), add("Tobiah means to visit Kiko.", 72), add("Tobiah means to water the plants.", 72)] } }));
assert_eq!((after["candidateActions"]["actions"].as_array().unwrap().len(), reasons(&applied)), (3, vec!["bad_expiry".to_owned(), "empty".to_owned(), "over_bound".to_owned()]));
let id = after["candidateActions"]["actions"][0]["id"].as_str().unwrap().to_owned();
let (after, _) = run(&after, json!({ "intend": { "ready": [id.clone()], "drop": [after["candidateActions"]["actions"][1]["id"]] } }));
assert_eq!((after["candidateActions"]["actions"][0]["readiness"].as_str(), after["candidateActions"]["actions"][1]["status"].as_str()), (Some("ready"), Some("retired")));
// Something Self put there that is no intention is left alone.
let mut other = state();
other["candidateActions"]["actions"] = json!([{ "id": "ca-1", "status": "active", "actionType": "speak", "readiness": "ready", "riskLevel": "low", "target": { "kind": "self", "id": "eureka" }, "summary": "Say hello.", "createdAt": "2026-11-19T10:00:00Z", "updatedAt": "2026-11-19T10:00:00Z", "expiresAt": "2026-11-19T11:00:00Z" }]);
let (after, applied) = run(&other, json!({ "intend": { "drop": ["ca-1"] } }));
assert_eq!((after["candidateActions"].clone(), reasons(&applied)), (other["candidateActions"].clone(), vec!["unknown_id".to_owned()]));
}
/// T-P2: no delta family writes standing tendencies: a kitchen sink of every family leaves them byte-equal.
#[test]
fn t_p2_no_bias_writes() {
let mut state = state();
state["affect"]["socialBiases"] = json!([{ "name": "defers to the operator", "value": 0.6, "summary": "Tobiah defers.", "behavioralPull": "yields", "updatedAt": "2026-11-19T10:00:00Z" }]);
let (after, applied) = run(&state, json!({
"notes": { "remember": [{ "text": "Tobiah promised Meta a story.", "about": [META], "importance": 0.7 }], "wonder": [{ "text": "Does the heron remember the river?" }] },
"people": { "bonds": [{ "person": "deru", "trust": "up", "closeness": "up", "summary": "Deru is steady.", "why": "Deru stayed." }], "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems tired.", "confidence": 0.6 }] },
"feeling": { "feelings": [{ "name": "warmth", "strength": 0.6, "about": "deru" }], "mood": { "valence": "up" } },
"drives": { "needs": [{ "id": "need-an-audience", "toward": "down" }] },
"self": { "stances": [{ "principle": "Stories carry people.", "summary": "Tobiah tells stories to carry people." }], "identity": { "publicDescription": "A slow river-minded storyteller." } },
"intend": { "add": [{ "summary": "Tobiah means to tell Deru the heron story.", "expires_in_hours": 24 }] }
}));
assert_eq!(after["affect"]["socialBiases"], state["affect"]["socialBiases"]);
assert!(applied.refused.is_empty(), "{:?}", applied.refused);
valid(&after);
// The module's own text names none of the fields no wake writes.
let source = include_str!("../commit.rs");
for field in ["socialBiases", "voidbotProjection", "embodiment", "privateNotes"] {
assert!(!source.contains(field), "{field}");
} }
// The control: the same proposal on a record that did not fail is written.
let (after, applied) = apply(&state, &record(json!([note])), "r1-t1", now());
assert_eq!((applied.remembered.len(), after["thoughtMemory"]["shortTerm"].as_array().map(Vec::len)), (1, Some(1)));
} }
/// T4 (map 16.35.4): a memory is one anchored thought in `shortTerm`, its fields the schema's, tagged by the turn's room, /// A bond's summary changes only with a why; the old words go to `lastEvidence`; a bond with someone new starts at 0.5, 0.1, 0.2.
/// the people it concerns, and `private`; its target is the first person it concerns. The state stays one a put accepts.
#[test] #[test]
fn t4_remember_writes_one_anchored_thought() { fn t_p2_bond_summary_needs_a_why_and_a_new_bond_starts_low() {
let (after, applied) = apply(&state(), &record(json!([remember("Meta asked Libby not to post the welcome in #minds until Heimdall has ruled on a welcome mat; Libby agreed to wait.", &[META, HEIMDALL], Some(MINDS), false)])), "r1-t3", now()); let (after, applied) = run(&state(), json!({ "people": { "bonds": [{ "person": "deru", "summary": "Deru has gone quiet." }] } }));
let entry = &after["thoughtMemory"]["shortTerm"][0]; assert_eq!(reasons(&applied), ["unexplained"]);
assert_eq!(entry["id"], "r1-t3-m1"); assert_eq!(bond(&after, DERU)["summary"], bond(&state(), DERU)["summary"]);
assert_eq!((entry["status"].as_str(), entry["target"].clone()), (Some("active"), json!({ "kind": "person", "id": META }))); let (after, _) = run(&state(), json!({ "people": { "bonds": [{ "person": "deru", "summary": "Deru has gone quiet lately.", "why": "Deru answered once in three days." }] } }));
assert_eq!(entry["tags"], json!([format!("room:{MINDS}"), format!("about:{META}"), format!("about:{HEIMDALL}")])); let deru = bond(&after, DERU);
assert_eq!((entry["intensity"].as_f64(), entry["tension"].as_str(), entry["actionImplication"].as_str()), (Some(0.8), Some(""), Some(""))); assert_eq!((deru["summary"].as_str(), deru["lastEvidence"]["summary"].clone()), (Some("Deru has gone quiet lately."), bond(&state(), DERU)["summary"].clone()));
assert_eq!((entry["createdAt"].clone(), entry["updatedAt"].clone()), (json!(now().to_rfc3339()), json!(now().to_rfc3339()))); valid(&after);
assert_eq!(applied.remembered, vec![entry.clone()]); let mut named = heard();
huginn_mind::persona::validate_document(&eureka_pipeline::Slug("eureka".into()), &after).expect("a put accepts it"); named.people.push("@ann:gamecult.org".into());
// A private note made in a direct message carries that room's tag and `private`; with no person, its target is the room. let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [{ "person": "@ann:gamecult.org", "kind": "friend", "summary": "Ann asks careful questions.", "why": "Ann asked three." }, { "person": "@ghost:gamecult.org", "trust": "up" }] } })), &named, "w1", now());
let (after, _) = apply(&state(), &record(json!([remember("Aqua told Meta privately she is tired.", &[], Some("!dm-aqua:gamecult.org"), true)])), "r1-t4", now()); let ann = bond(&after, "@ann:gamecult.org");
let entry = &after["thoughtMemory"]["shortTerm"][0]; assert_eq!((ann["trust"].as_f64(), ann["tension"].as_f64(), ann["intensity"].as_f64(), ann["relationshipKind"].as_str()), (Some(0.5), Some(0.1), Some(0.2), Some("friend")));
assert_eq!((entry["target"].clone(), entry["tags"].clone()), (json!({ "kind": "room", "id": "!dm-aqua:gamecult.org" }), json!(["room:!dm-aqua:gamecult.org", "private"]))); assert_eq!(reasons(&applied), ["unknown_person"]);
// A turn with no room: the note is about her. valid(&after);
let (after, _) = apply(&state(), &record(json!([remember("Heimdall decided to read the saga code first.", &[], None, false)])), "r1-t5", now());
assert_eq!(after["thoughtMemory"]["shortTerm"][0]["target"]["kind"], "self");
} }
/// T4 (map 16.35.13 check 6): `apply` writes nothing but `thoughtMemory.shortTerm`. Over every mix of the proposals the /// Reads are upserted by person and kind, cool after three days and retire after ten.
/// contract names (and one it does not), on states with resolved, stale and crystallized memories, every other field is
/// byte-equal after the commit.
#[test] #[test]
fn t4_apply_writes_only_short_term() { fn t_p2_reads_upsert_and_age() {
let mut base = state(); let (once, _) = run(&state(), json!({ "people": { "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems tired.", "confidence": 0.6 }] } }));
base["thoughtMemory"]["shortTerm"] = json!([ let (twice, _) = run(&once, json!({ "people": { "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems rested.", "confidence": 0.8 }, { "person": "kiko", "kind": "bogus", "summary": "x" }] } }));
{ "id": "st-1", "status": "active", "target": { "kind": "person", "id": META }, "summary": "Meta asked about the welcome.", "tension": "", "actionImplication": "", "createdAt": "2026-11-19T10:00:00Z", "updatedAt": "2026-11-19T10:00:00Z" }, assert_eq!((twice["affect"]["statusReads"].as_array().unwrap().len(), twice["affect"]["statusReads"][0]["summary"].as_str()), (1, Some("Kiko seems rested.")));
{ "id": "st-2", "status": "resolved", "target": { "kind": "self", "id": "heimdall" }, "summary": "An old settled note.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "2026-11-01T10:00:00Z" }, let cooled = apply(&twice, &Deltas::default(), &heard(), "w2", now() + Duration::days(3)).0;
{ "id": "st-3", "status": "resolved", "target": { "kind": "self", "id": "heimdall" }, "summary": "Settled by an outside put, no time.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "not a time" } let retired = apply(&twice, &Deltas::default(), &heard(), "w3", now() + Duration::days(10)).0;
assert_eq!((cooled["affect"]["statusReads"][0]["status"].as_str(), retired["affect"]["statusReads"][0]["status"].as_str()), (Some("cooling"), Some("retired")));
valid(&twice);
}
/// Mood moves by its own plasticity; a trait left alone drifts toward its mean, never past it.
#[test]
fn t_p2_mood_by_plasticity_and_drift() {
let state = state();
let (after, _) = run(&state, json!({ "feeling": { "mood": { "valence": "down", "arousal": "up" } } }));
let sit = &after["activationProfile"]["situationalState"];
assert!((sit["valence"]["currentActivation"].as_f64().unwrap() - (0.7 - 0.3 * 0.25)).abs() < 1e-9);
assert!((sit["arousal"]["currentActivation"].as_f64().unwrap() - (0.2 + 0.3 * 0.25)).abs() < 1e-9);
// Dominance was not moved: it sits at its mean already.
assert_eq!(sit["dominance"]["currentActivation"].as_f64(), Some(0.4));
let mut away = state.clone();
away["activationProfile"]["situationalState"]["valence"]["currentActivation"] = json!(0.2);
away["activationProfile"]["situationalState"]["arousal"]["currentActivation"] = json!(0.26);
let (drifted, _) = run(&away, json!({}));
let sit = &drifted["activationProfile"]["situationalState"];
assert!((sit["valence"]["currentActivation"].as_f64().unwrap() - 0.23).abs() < 1e-9);
assert_eq!(sit["arousal"]["currentActivation"].as_f64(), Some(0.25), "never past the mean");
valid(&drifted);
}
/// Notes: at most four kept, two settled; a settle into memory moves a note to `memories` crystallized.
#[test]
fn t_p2_notes_are_bounded_and_settle() {
let notes: Vec<Value> = (1..=5).map(|n| json!({ "text": format!("Tobiah noted thing number {n}.") })).collect();
let (after, applied) = run(&state(), json!({ "notes": { "remember": notes } }));
assert_eq!((after["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), reasons(&applied)), (4, vec!["over_bound".to_owned()]));
let entry = &after["thoughtMemory"]["shortTerm"][0];
assert_eq!((entry["target"].clone(), entry["tags"].clone()), (json!({ "kind": "room", "id": MINDS }), json!([format!("room:{MINDS}")])));
let ids: Vec<String> = after["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().map(|note| note["id"].as_str().unwrap().to_owned()).collect();
let (settled, applied) = run(&after, json!({ "notes": { "settle": [{ "id": ids[0], "into": "memory" }, { "id": ids[1], "into": "resolved" }, { "id": ids[2], "into": "resolved" }, { "id": "nope", "into": "resolved" }] } }));
assert_eq!(reasons(&applied), ["over_bound", "over_bound"]);
assert_eq!((settled["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), settled["thoughtMemory"]["memories"].as_array().unwrap().len() - state()["thoughtMemory"]["memories"].as_array().unwrap().len()), (3, 1));
let memory = settled["thoughtMemory"]["memories"].as_array().unwrap().iter().find(|memory| memory["id"] == ids[0].as_str()).unwrap();
assert_eq!(memory["status"], "crystallized");
valid(&settled);
// A private note made in a direct message keeps that room's tag.
let dm = Heard { room: Some("!dm-aqua:gamecult.org".into()), ..heard() };
let (after, _) = apply(&state(), &deltas(json!({ "notes": { "remember": [{ "text": "Aqua told Tobiah privately she is tired.", "private": true }] } })), &dm, "w1", now());
assert_eq!(after["thoughtMemory"]["shortTerm"][0]["tags"], json!(["room:!dm-aqua:gamecult.org", "private"]));
}
/// A resolved note older than a week is removed, and one resolved with no time is stamped.
#[test]
fn t_p2_resolved_notes_are_pruned() {
let mut state = state();
state["thoughtMemory"]["shortTerm"] = json!([
{ "id": "st-old", "status": "resolved", "target": { "kind": "self", "id": "eureka" }, "summary": "Old.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "2026-11-01T10:00:00Z" },
{ "id": "st-new", "status": "resolved", "target": { "kind": "self", "id": "eureka" }, "summary": "Untimed.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "not a time" }
]); ]);
base["thoughtMemory"]["memories"] = json!([{ "id": "lt-1", "status": "crystallized", "target": { "kind": "self", "id": "heimdall" }, "summary": "A crystallized memory.", "tension": "", "actionImplication": "", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": "2026-10-01T10:00:00Z" }]); let (after, applied) = run(&state, json!({}));
let menu = [ assert_eq!((after["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), applied.pruned, after["thoughtMemory"]["shortTerm"][0]["updatedAt"].clone()), (1, 1, json!(now().to_rfc3339())));
remember("Meta asked Heimdall whether the notes are still on for tomorrow; he has not answered yet.", &[META], Some(MINDS), false),
remember("Aqua told Meta privately she is tired.", &[], Some("!dm-aqua:gamecult.org"), true),
remember("Heimdall decided to read the saga code first.", &[], None, false),
resolve("st-1"),
resolve("st-gone"),
resolve("lt-1"),
json!({ "kind": "hold_open", "words": "hold it" }),
];
let without_short_term = |state: &Value| {
let mut state = state.clone();
state["thoughtMemory"].as_object_mut().unwrap().remove("shortTerm");
state
};
// Every subset of the menu, in order.
for mask in 0u32..(1 << menu.len()) {
let proposals: Vec<Value> = menu.iter().enumerate().filter(|(at, _)| mask & (1 << at) != 0).map(|(_, proposal)| proposal.clone()).collect();
let (after, _) = apply(&base, &record(json!(proposals)), "r1-t9", now());
assert_eq!(serde_json::to_string(&without_short_term(&after)).unwrap(), serde_json::to_string(&without_short_term(&base)).unwrap(), "mask {mask:b}");
}
} }
/// T4 (map 16.35.4): `resolve` sets the one memory the list mapped `resolved` and touches no other. /// Soul s1: the bounds are per wake per target, never per entry. Three entries for one person move trust once, two for one need
/// move it once, and a feeling named three times rises once.
#[test] #[test]
fn t4_resolve_settles_a_listed_memory() { fn t_p2_duplicate_entries_move_a_target_once() {
let (written, _) = apply(&state(), &record(json!([remember("Libby told Meta she would post the welcome once Heimdall rules.", &[META], Some(MINDS), false), remember("Kiko teased Nibu about the sbsar files.", &[], Some(MINDS), false)])), "r1-t1", now()); let state = state();
let later = now() + Duration::hours(2); let start = bond(&state, "kiko")["trust"].as_f64().unwrap();
let (after, applied) = apply(&written, &record(json!([resolve("r1-t1-m1")])), "r1-t2", later); let (after, _) = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "up" }] } }));
let entries = after["thoughtMemory"]["shortTerm"].as_array().unwrap(); assert!((bond(&after, "kiko")["trust"].as_f64().unwrap() - (start + BOND_STEP).min(1.0)).abs() < 1e-9, "three ups are one step");
assert_eq!((entries[0]["status"].as_str(), entries[0]["updatedAt"].clone()), (Some("resolved"), json!(later.to_rfc3339()))); let (cancelled, _) = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "down" }] } }));
assert_eq!(entries[1], written["thoughtMemory"]["shortTerm"][1], "the other memory is untouched"); assert!((bond(&cancelled, "kiko")["trust"].as_f64().unwrap() - start).abs() < 1e-9, "up and down cancel");
assert_eq!((applied.resolved.len(), applied.refused.len()), (1, 0)); let before = state["affect"]["needs"][0]["intensity"].as_f64().unwrap();
let (after, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "up" }, { "id": "need-an-audience", "toward": "up" }] } }));
assert!((after["affect"]["needs"][0]["intensity"].as_f64().unwrap() - (before + DRIVE_STEP)).abs() < 1e-9, "two ups are one step");
let (after, _) = run(&state, json!({ "feeling": { "feelings": [{ "name": "anger", "strength": 0.9 }, { "name": "Anger", "strength": 0.9 }, { "name": "anger", "strength": 0.8 }] } }));
assert_eq!((after["affect"]["moodDimensions"].as_array().unwrap().len(), after["affect"]["moodDimensions"][0]["value"].as_f64()), (1, Some(0.35)));
valid(&after);
} }
/// T4 (4.4 rule 4, kept): a memory an outside put removed after she was shown it is refused, and nothing changes; one that /// A bond made this wake is not moved this wake, whatever else the entries say.
/// is not short-term is refused too, since a turn writes nothing else.
#[test] #[test]
fn t4_resolve_after_outside_put_removed_refused() { fn t_p2_a_bond_made_is_not_moved() {
let mut state = state(); let mut named = heard();
state["thoughtMemory"]["memories"] = json!([{ "id": "lt-1", "status": "crystallized", "target": { "kind": "self", "id": "heimdall" }, "summary": "A crystallized memory.", "tension": "", "actionImplication": "", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": "2026-10-01T10:00:00Z" }]); named.people.push("@ann:gamecult.org".into());
for (entry, reason) in [("r1-t1-m1", "outside_put_removed_target"), ("lt-1", "not_short_term")] { let made = json!({ "person": "@ann:gamecult.org", "summary": "Ann asks careful questions.", "why": "Ann asked three." });
let (after, applied) = apply(&state, &record(json!([resolve(entry)])), "r1-t2", now()); let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [made, { "person": "@ann:gamecult.org", "trust": "up", "tension": "up", "closeness": "up" }] } })), &named, "w1", now());
assert_eq!((after, applied.refused[0]["reason"].as_str()), (state.clone(), Some(reason)), "{entry}"); let ann = bond(&after, "@ann:gamecult.org");
} assert_eq!((ann["trust"].as_f64(), ann["tension"].as_f64(), ann["intensity"].as_f64()), (Some(0.5), Some(0.1), Some(0.2)));
assert_eq!(applied.changes.iter().filter(|change| change["family"] == "people").count(), 1);
} }
/// `RESOLVED_KEPT_DAYS` (map 16.35.4): a memory resolved longer ago than that is removed; one resolved with no time is /// I16.7 on every kept label: an intention's target, a feeling's name, a note's about and its tag carry no run of heard words, and a
/// stamped now and kept; an active one is never removed. /// feeling's name is short.
#[test] #[test]
fn t4_resolved_memories_are_pruned_after_a_week() { fn t_p2_labels_refuse_what_was_heard() {
let mut state = state(); let line = "tell Deru about the forty eight hour passkey cooling off period before friday";
let entry = |id: &str, status: &str, updated: &str| json!({ "id": id, "status": status, "target": { "kind": "self", "id": "heimdall" }, "summary": id, "tension": "", "actionImplication": "", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": updated }); let said = "tell Deru about the forty eight hour passkey cooling off";
state["thoughtMemory"]["shortTerm"] = json!([entry("old", "resolved", "2026-11-12T15:00:00Z"), entry("recent", "resolved", "2026-11-14T15:00:00Z"), entry("untimed", "resolved", ""), entry("active", "active", "2026-10-01T10:00:00Z")]); let heard = Heard { lines: vec![line.into()], ..heard() };
let (after, applied) = apply(&state, &record(json!([])), "r1-t1", now()); let go = |value: Value| apply(&state(), &deltas(value), &heard, "w1", now());
let ids: Vec<&str> = after["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().filter_map(|entry| entry["id"].as_str()).collect(); let (after, applied) = go(json!({ "intend": { "add": [{ "summary": "Tobiah means to ask Deru something.", "target": said, "expires_in_hours": 5 }] } }));
assert_eq!((ids, applied.pruned), (vec!["recent", "untimed", "active"], 1)); assert_eq!((reasons(&applied), after["candidateActions"]["actions"].clone()), (vec!["echo".to_owned()], state()["candidateActions"]["actions"].clone()));
assert_eq!(after["thoughtMemory"]["shortTerm"][1]["updatedAt"], json!(now().to_rfc3339())); let (_, applied) = go(json!({ "feeling": { "feelings": [{ "name": said, "strength": 0.5 }] } }));
assert_eq!(reasons(&applied), ["long"], "a name is a short label");
let (_, applied) = go(json!({ "feeling": { "feelings": [{ "name": "a b c d e f g h", "strength": 0.5 }] } }));
assert_eq!(reasons(&applied), Vec::<String>::new(), "short labels pass");
let (after, applied) = go(json!({ "notes": { "remember": [{ "text": "Deru owes Tobiah an answer.", "about": [said] }], "wonder": [{ "text": "Will Deru answer soon?", "about": [said] }] } }));
assert_eq!((reasons(&applied), after["thoughtMemory"]["shortTerm"].clone()), (vec!["echo".to_owned(), "echo".to_owned()], state()["thoughtMemory"]["shortTerm"].clone()));
}
/// One stance or value change a wake: a second stance is over the bound, and the first stands.
#[test]
fn t_p2_two_stances_are_one_change() {
let stances = json!([{ "id": "stance-slow-is-kind", "principle": "Slow is kind.", "summary": "Tobiah answers slowly." }, { "principle": "Plain words.", "summary": "Tobiah keeps his words plain." }]);
let (after, applied) = run(&state(), json!({ "self": { "stances": stances } }));
assert_eq!(reasons(&applied), ["over_bound"]);
assert_eq!(after["affect"]["doctrineStances"].as_array().unwrap().len(), state()["affect"]["doctrineStances"].as_array().unwrap().len());
assert_eq!(after["affect"]["doctrineStances"][0]["summary"], "Tobiah answers slowly.");
}
/// An intention whose words equal an open one's, up to case and spacing, is not added; a rewording is the model's to catch, a
/// dropped one may be meant again, and a drop by id retires only the intention it names.
#[test]
fn an_intention_open_in_the_same_words_is_not_added_again() {
let open = |state: &Value| state["candidateActions"]["actions"].as_array().unwrap().iter().filter(|action| action["status"] == "active").count();
let add = |text: &str| json!({ "intend": { "add": [{ "summary": text, "expires_in_hours": 24 }] } });
let (first, _) = run(&state(), add("Tobiah means to list the directory above the Aetheria path."));
let id = first["candidateActions"]["actions"].as_array().unwrap().last().unwrap()["id"].as_str().unwrap().to_owned();
let (again, applied) = run(&first, add(" tobiah means to LIST the directory\tabove the aetheria path. "));
assert_eq!((open(&again), reasons(&applied)), (open(&first), vec!["duplicate".to_owned()]));
let (twice, applied) = run(&first, json!({ "intend": { "add": [
{ "summary": "Tobiah means to list a different directory.", "expires_in_hours": 24 },
{ "summary": "Tobiah means to list a different DIRECTORY.", "expires_in_hours": 24 },
] } }));
assert_eq!((open(&twice), reasons(&applied)), (open(&first) + 1, vec!["duplicate".to_owned()]), "one batch cannot hold the same words twice");
let (dropped, _) = run(&first, json!({ "intend": { "drop": [id.clone()] } }));
assert_eq!(open(&dropped), open(&first) - 1);
let (meant_again, applied) = run(&dropped, add("Tobiah means to list the directory above the Aetheria path."));
assert_eq!((open(&meant_again), reasons(&applied)), (open(&dropped) + 1, vec![]));
}
/// A batch's own drops come first, so dropping an intention and adding it again in the same words retires the old one and opens a
/// fresh one; and an add in an open waiting intention's words, marked ready, makes that one ready rather than being refused.
#[test]
fn a_drop_frees_its_words_and_a_ready_re_add_readies_the_open_intention() {
let intentions = |state: &Value| state["candidateActions"]["actions"].as_array().unwrap().iter().filter(|action| action["customActionType"] == "intention").cloned().collect::<Vec<_>>();
let words = "Tobiah means to list the directory above the Aetheria path.";
let (first, _) = run(&state(), json!({ "intend": { "add": [{ "summary": words, "expires_in_hours": 24 }] } }));
let old = intentions(&first).last().unwrap().clone();
let (swapped, applied) = run(&first, json!({ "intend": { "drop": [old["id"]], "add": [{ "summary": words, "expires_in_hours": 24 }] } }));
let after = intentions(&swapped);
// (Both wakes here share one key, so the fresh intention's id repeats the old one's: told apart by status.)
let states = after.iter().filter(|action| action["summary"] == words).map(|action| action["status"].as_str().unwrap().to_owned()).collect::<Vec<_>>();
assert_eq!((states, reasons(&applied)), (vec!["retired".to_owned(), "active".to_owned()], vec![]));
assert_eq!(old["readiness"], "waiting");
let (readied, applied) = run(&first, json!({ "intend": { "add": [{ "summary": words.to_uppercase(), "expires_in_hours": 24, "readiness": "ready" }] } }));
let after = intentions(&readied);
assert_eq!((after.len(), after.last().unwrap()["id"].clone(), after.last().unwrap()["readiness"].as_str(), reasons(&applied)), (intentions(&first).len(), old["id"].clone(), Some("ready"), vec![]));
let (still, applied) = run(&first, json!({ "intend": { "add": [{ "summary": words, "expires_in_hours": 24, "readiness": "later" }] } }));
assert_eq!((intentions(&still).last().unwrap()["readiness"].as_str(), reasons(&applied)), (Some("waiting"), vec!["duplicate".to_owned()]), "only a ready add readies");
} }

View file

@ -1,26 +1,24 @@
//! Her side of the conversation (map 16.24.1, K26): what she has said and read in this conversation, read from her turn //! Her side of the conversation (map 16.24.1, K26; map 16.38.3): what she has said and read in this conversation, read from her
//! records by one function, `exchange_of`, beside `outcome::outcome_of`, and rendered whole in her view. //! agent's receipts by one function, `exchange_of`, and rendered whole in her view.
//! //!
//! The turn record owns what she did: the lines that went out (its receipts), the additions made, and each read with its //! The receipts own what she did: each `say` the mouth posted (status `ok`) and each `read` that returned text. This module
//! request and what it returned. This module reads it and nothing else; it writes nothing. The conversation is her turns //! reads them and nothing else; it writes nothing. The conversation is her acts going back from now while each is within
//! in the turn's room going back while each is within `EXCHANGE_MINUTES` of the next, from now: past a pause that long, //! `EXCHANGE_MINUTES` of the next: her lines in the turn's room, and what she read. Past a pause that long, a conversation
//! a conversation starts fresh, and what she keeps beyond it is what she chose to remember. The window is one constant, //! starts fresh, and what she keeps beyond it is what she chose to remember.
//! the recommended answer to the operator's open question Q-G (a); if she rules otherwise, it is this number.
//! //!
//! In her view: her lines, oldest first, with when and what each replied to, her additions folded into them; then each //! In her view: her lines, oldest first, with when; then each distinct thing she read once, its latest result whole, after a
//! distinct thing she read once, its latest result whole, after a heading in code's words. Under `exchange_bytes`, with //! heading in code's words. Under `exchange_bytes`, with the shrinking window of 16.23.5: whole lines and whole results drop
//! the shrinking window of 16.23.5: whole lines and whole results drop from the old end and the heading says since when. //! from the old end and the heading says since when. Nothing is counted.
//! Nothing is counted. A read whose latest result is in her view is not performed again (`interpret::reading`).
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde_json::Value; use serde_json::Value;
use super::domain::floor_minute; use super::domain::floor_minute;
use super::read::{ReadRefusal, ReadRequest}; use super::read::ReadRequest;
use super::select::{Forms, capitalized, coarse, spoken}; use super::select::{Forms, capitalized, coarse, spoken};
/// How long a pause ends a conversation (Q-G (a)): her turns in a room belong to one conversation while each is within /// How long a pause ends a conversation (Q-G (a)): her acts belong to one conversation while each is within this many minutes
/// this many minutes of the next. /// of the next.
pub(crate) const EXCHANGE_MINUTES: i64 = 30; pub(crate) const EXCHANGE_MINUTES: i64 = 30;
/// One thing she did in the conversation, in code's words: a line of hers, or a read and its result. /// One thing she did in the conversation, in code's words: a line of hers, or a read and its result.
@ -30,25 +28,13 @@ pub(crate) struct Did {
pub(crate) text: String, pub(crate) text: String,
} }
/// Her side of the conversation, oldest first: her lines, then each distinct read once with its latest result; and /// Her side of the conversation, oldest first: her lines, then each distinct read once with its latest result.
/// every read she made in it, shown or not, found or not, by its normal form (Soul's R7).
#[derive(Clone, Debug, Default, PartialEq, Eq)] #[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Exchange { pub(crate) struct Exchange {
pub(crate) lines: Vec<Did>, pub(crate) lines: Vec<Did>,
pub(crate) reads: Vec<Shown>, pub(crate) reads: Vec<Shown>,
pub(crate) tried: Vec<Tried>, /// When the conversation began: her first act in it.
/// When the conversation began: her first turn in it. What she closed since is still listed (Soul's R7).
pub(crate) since: Option<DateTime<Utc>>, pub(crate) since: Option<DateTime<Utc>>,
/// Every read a rule refused in it, as `kind target (why)`, once each: shown to the Interpreter so it never names the
/// same refused read again (Soul's R8). A cap's refusal is not here: it is temporary (Soul's R9).
pub(crate) refused: Vec<String>,
}
/// A refused read as the Interpreter is shown it, `kind target (why)`; none for a cap's refusal (reads a wake, bytes a
/// wake, her prose's length), which lasts only the wake it happened in, so the read may be made next wake (Soul's R9).
pub(crate) fn refused_read(refused: &Value) -> Option<String> {
let cap = serde_json::from_value::<ReadRefusal>(refused["why"].clone()).is_ok_and(ReadRefusal::cap);
(!cap).then(|| format!("{} {} ({})", refused["read"]["kind"].as_str().unwrap_or("?"), refused["read"]["target"].as_str().unwrap_or("?").trim(), refused["why"].as_str().unwrap_or("?")))
} }
/// A read's latest result as her view shows it. /// A read's latest result as her view shows it.
@ -59,74 +45,51 @@ pub(crate) struct Shown {
pub(crate) text: String, pub(crate) text: String,
} }
/// A read she made in this conversation: its normal form, whether it found anything, and what it was in code's words. /// An act of hers in `room`, from a receipt row: a line the mouth posted there, or a read that returned text.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] fn act<'a>(row: &'a Value, room: &str) -> Option<(DateTime<Utc>, &'a Value)> {
pub(crate) struct Tried { let receipt = &row["receipt"];
pub(crate) key: String, let at = row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok())?.with_timezone(&Utc);
pub(crate) found: bool, let ours = row["agent"] == "receipt" && receipt["status"] == "ok" && match receipt["tool"].as_str() {
pub(crate) what: String, Some("say") => receipt["fields"]["room"] == room,
Some("read") => true,
_ => false,
};
ours.then_some((at, receipt))
} }
fn at_of(record: &Value) -> Option<DateTime<Utc>> { /// Her side of the conversation in `room` as `records` (her trace's rows, oldest first) hold it, at `now`.
record["interpreter"]["at_ms"].as_i64().and_then(DateTime::from_timestamp_millis)
}
/// Her side of the conversation in `room` as `records` (her turn records, oldest first) hold it, at `now`.
pub(crate) fn exchange_of(records: &[Value], room: &str, now: DateTime<Utc>, her: Forms) -> Exchange { pub(crate) fn exchange_of(records: &[Value], room: &str, now: DateTime<Utc>, her: Forms) -> Exchange {
// Her turns in this room, newest first, while each is within the window of the one after it (now, for the newest). // Her acts, newest first, while each is within the window of the one after it (now, for the newest).
let mut kept: Vec<(&Value, DateTime<Utc>)> = Vec::new(); let mut kept: Vec<(DateTime<Utc>, &Value)> = Vec::new();
let mut next = now; let mut next = now;
for record in records.iter().rev() { for (at, receipt) in records.iter().rev().filter_map(|row| act(row, room)) {
let Some(at) = at_of(record) else { continue };
if record["interpreter"]["room"].as_str() != Some(room) {
continue;
}
if next - at > chrono::Duration::minutes(EXCHANGE_MINUTES) { if next - at > chrono::Duration::minutes(EXCHANGE_MINUTES) {
break; break;
} }
kept.push((record, at)); kept.push((at, receipt));
next = at; next = at;
} }
kept.reverse(); kept.reverse();
let mut exchange = Exchange { since: kept.first().map(|(_, at)| *at), ..Exchange::default() }; let mut exchange = Exchange { since: kept.first().map(|(at, _)| *at), ..Exchange::default() };
for (record, at) in &kept { for (at, receipt) in kept {
let decision = &record["interpreter"]; let fields = &receipt["fields"];
for receipt in record["posted"].as_array().into_iter().flatten() { if receipt["tool"] == "say" {
let (Some(text), Some(event)) = (receipt["text"].as_str(), receipt["event"].as_str()) else { continue }; if let Some(text) = fields["text"].as_str() {
if receipt["room"].as_str() != Some(room) { exchange.lines.push(Did { at, text: format!("- {}: {}", coarse(at, now), spoken(text)) });
}
continue; continue;
} }
let reply = decision["said"].as_array().into_iter().flatten().find(|line| line["text"].as_str() == Some(text)).and_then(|line| line["in_reply_to"]["who"].as_str()).map_or_else(String::new, |who| format!(", replying to {who}")); let (Some(kind), Some(target), Some(text)) = (fields["kind"].as_str(), fields["target"].as_str(), fields["text"].as_str()) else { continue };
// Her additions to this line, made in any turn of the conversation, folded into it. let Ok(request) = ReadRequest::from_target(kind, target) else { continue };
let added: Vec<String> = kept let what = request.named().unwrap_or_else(|| format!("{} own mind", her.poss));
.iter()
.flat_map(|(later, _)| later["interpreter"]["amended"].as_array().cloned().unwrap_or_default().into_iter().filter(move |amended| later["edited"].as_array().into_iter().flatten().any(|receipt| receipt["event"] == amended["event"] && receipt["refusal"].is_null())))
.filter(|amended| amended["event"].as_str() == Some(event))
.filter_map(|amended| amended["added"].as_str().map(|added| format!(" ({} added: {})", her.subj, spoken(added))))
.collect();
exchange.lines.push(Did { at: *at, text: format!("- {}{reply}: {}{}", coarse(*at, now), spoken(text), added.join("")) });
}
for refused in decision["read_refused"].as_array().into_iter().flatten().filter_map(refused_read) {
if !exchange.refused.contains(&refused) {
exchange.refused.push(refused);
}
}
for read in decision["reads"].as_array().into_iter().flatten() {
let Ok(request) = serde_json::from_value::<ReadRequest>(read["request"].clone()) else { continue };
let found = read["ok"] == true;
if found || read["failure"] == "not_found" {
exchange.tried.retain(|tried| tried.key != request.normal());
exchange.tried.push(Tried { key: request.normal(), found, what: read["what"].as_str().unwrap_or_default().to_owned() });
}
}
for read in decision["reads"].as_array().into_iter().flatten().filter(|read| read["ok"] == true) {
let (Ok(request), Some(what), Some(text)) = (serde_json::from_value::<ReadRequest>(read["request"].clone()), read["what"].as_str(), read["text"].as_str()) else { continue };
// Each distinct thing once, its latest result. // Each distinct thing once, its latest result.
exchange.reads.retain(|done| done.key != request.normal()); exchange.reads.retain(|done| done.key != request.normal());
let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0); let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
let fence = "`".repeat(longest.max(3) + 1); let fence = "`".repeat(longest.max(3) + 1);
exchange.reads.push(Shown { at: *at, key: request.normal(), text: format!("{} read {what} ({}):\n{fence}\n{text}\n{fence}", capitalized(her.subj), coarse(*at, now)) }); exchange.reads.push(Shown { at, key: request.normal(), text: format!("{} read {what} ({}):
} {fence}
{text}
{fence}", capitalized(her.subj), coarse(at, now)) });
} }
exchange exchange
} }

View file

@ -1,4 +1,4 @@
//! Her side of the conversation (map 16.24.1, K26), read from her turn records. //! Her side of the conversation (map 16.24.1, K26), read from her agent's receipts.
use chrono::{DateTime, Duration, Utc}; use chrono::{DateTime, Duration, Utc};
use serde_json::{Value, json}; use serde_json::{Value, json};
@ -15,78 +15,44 @@ fn her() -> Forms {
Forms { subj: "he", cap_subj: "He", obj: "him", poss: "his", be: "is", has: "has", s: "s" } Forms { subj: "he", cap_subj: "He", obj: "him", poss: "his", be: "is", has: "has", s: "s" }
} }
/// One turn record of his, `minutes` before now, in `room`: the lines that went out, additions, and reads. /// A receipt row of his, `minutes` before now.
fn turn(minutes: i64, room: &str, said: &[(&str, &str, Option<&str>)], reads: Value, amended: Value, edited: Value) -> Value { fn receipt(minutes: i64, tool: &str, status: &str, fields: Value) -> Value {
let at = (now() - Duration::minutes(minutes)).timestamp_millis(); json!({ "agent": "receipt", "at": (now() - Duration::minutes(minutes)).to_rfc3339(), "receipt": { "tool": tool, "status": status, "fields": fields } })
let lines: Vec<Value> = said.iter().map(|(_, text, reply)| json!({ "room": room, "text": text, "in_reply_to": reply.map(|who| json!({ "who": who })) })).collect();
let posted: Vec<Value> = said.iter().map(|(event, text, _)| json!({ "event": event, "room": room, "text": text })).collect();
json!({ "interpreter": { "at_ms": at, "room": room, "said": lines, "reads": reads, "amended": amended }, "posted": posted, "edited": edited })
} }
fn read(target: &str, text: &str) -> Value { fn said(minutes: i64, room: &str, text: &str) -> Value {
json!({ "ok": true, "request": { "kind": "repo", "target": target }, "what": format!("{target} on the forge"), "text": text }) receipt(minutes, "say", "ok", json!({ "room": room, "text": text, "event": "e" }))
}
fn read(minutes: i64, target: &str, text: &str) -> Value {
receipt(minutes, "read", "ok", json!({ "kind": "repo", "target": target, "bytes": text.len(), "text": text }))
} }
#[test] #[test]
fn k26_her_side_of_the_conversation_is_her_lines_and_her_reads_while_it_lasts() { fn k26_her_side_of_the_conversation_is_her_lines_and_her_reads_while_it_lasts() {
let records = vec![ let records = vec![
turn(200, MINDS, &[("e0", "LONG-AGO line, before the pause.", None)], json!([]), json!([]), json!([])), said(200, MINDS, "LONG-AGO line, before the pause."),
turn(50, MINDS, &[("e1", "The knee bends first, I think.", Some("Meta"))], json!([read("GameCult/Bifrost", "OLD Bifrost list")]), json!([]), json!([])), said(50, MINDS, "The knee bends first, I think."),
turn(30, "#general:gamecult.org", &[("g1", "OTHER-ROOM line.", None)], json!([]), json!([]), json!([])), read(50, "GameCult/Bifrost", "OLD Bifrost list"),
turn(25, MINDS, &[], json!([read("GameCult/Bifrost", "NEW Bifrost list"), read("GameCult/Lodur#12", "Reflex: the knee bends first.")]), json!([{ "event": "e1", "added": "Checked: it does." }]), json!([{ "event": "e1", "refusal": null }])), said(30, "#general:gamecult.org", "OTHER-ROOM line."),
receipt(28, "say", "refused", json!({ "room": MINDS, "text": "REFUSED line.", "refusal": "RoomMoved" })),
read(25, "GameCult/Bifrost", "NEW Bifrost list"),
read(25, "GameCult/Lodur#12", "Reflex: the knee bends first."),
receipt(24, "read", "error", json!({ "kind": "repo", "target": "GameCult/Gone", "failure": "not_found" })),
]; ];
let exchange = exchange_of(&records, MINDS, now(), her()); let exchange = exchange_of(&records, MINDS, now(), her());
let view = render(&exchange, her(), 3000, now()); let view = render(&exchange, her(), 3000, now());
assert_eq!(view, "What he has said and read in this conversation:\n- about an hour ago, replying to Meta: \"The knee bends first, I think.\" (he added: \"Checked: it does.\")\nHe read GameCult/Bifrost on the forge (about half an hour ago):\n````\nNEW Bifrost list\n````\nHe read GameCult/Lodur#12 on the forge (about half an hour ago):\n````\nReflex: the knee bends first.\n````"); assert_eq!(view, "What he has said and read in this conversation:\n- about an hour ago: \"The knee bends first, I think.\"\nHe read GameCult/Bifrost on the forge (about half an hour ago):\n````\nNEW Bifrost list\n````\nHe read GameCult/Lodur#12 on the forge (about half an hour ago):\n````\nReflex: the knee bends first.\n````");
assert!(!view.contains("LONG-AGO") && !view.contains("OTHER-ROOM") && !view.contains("OLD Bifrost"), "past the pause, another room, and an older result of the same read are not shown"); assert!(!view.contains("LONG-AGO") && !view.contains("OTHER-ROOM") && !view.contains("OLD Bifrost") && !view.contains("REFUSED"), "past the pause, another room, an older result of the same read and a line that did not go out are not shown");
let keys: Vec<&str> = exchange.tried.iter().map(|tried| tried.key.as_str()).collect(); // A pause of more than the window since her last act: a fresh conversation.
assert_eq!(keys, ["repo:gamecult/bifrost", "repo:gamecult/lodur#12"], "every read made, once, by its normal form");
// A pause of more than the window since her last turn: a fresh conversation.
assert!(exchange_of(&records, MINDS, now() + Duration::minutes(EXCHANGE_MINUTES), her()).lines.is_empty()); assert!(exchange_of(&records, MINDS, now() + Duration::minutes(EXCHANGE_MINUTES), her()).lines.is_empty());
} }
#[test] #[test]
fn k26_past_its_budget_the_window_shrinks_and_nothing_is_counted() { fn k26_past_its_budget_the_window_shrinks_and_nothing_is_counted() {
let records = vec![ let records = vec![said(40, MINDS, "FIRST line of mine, the oldest one here."), said(20, MINDS, "SECOND line of mine.")];
turn(40, MINDS, &[("e1", "FIRST line of mine, the oldest one here.", None)], json!([]), json!([]), json!([])),
turn(20, MINDS, &[("e2", "SECOND line of mine.", None)], json!([]), json!([]), json!([])),
];
let exchange = exchange_of(&records, MINDS, now(), her()); let exchange = exchange_of(&records, MINDS, now(), her());
let view = render(&exchange, her(), 140, now()); let view = render(&exchange, her(), 140, now());
assert_eq!(view, "What he has said and read in this conversation since about half an hour ago:\n- about half an hour ago: \"SECOND line of mine.\""); assert_eq!(view, "What he has said and read in this conversation since about half an hour ago:\n- about half an hour ago: \"SECOND line of mine.\"");
assert!(render(&exchange, her(), 20, now()).is_empty(), "not even the newest fits: none"); assert!(render(&exchange, her(), 20, now()).is_empty(), "not even the newest fits: none");
} }
/// Soul's R7: a read that came back not-found is in the conversation's record too, so it is never made again; one that
/// failed otherwise (private, too large, broken) is not.
#[test]
fn r7_a_not_found_read_is_remembered_and_a_broken_one_is_not() {
let missing = json!({ "ok": false, "failure": "not_found", "request": { "kind": "repo", "target": "GameCult/Bifrost?q=Consent Receipt" }, "what": "a search" });
let broken = json!({ "ok": false, "failure": "failed", "request": { "kind": "repo", "target": "GameCult/Lodur" }, "what": "GameCult/Lodur on the forge" });
let exchange = exchange_of(&[turn(10, MINDS, &[], json!([missing, broken]), json!([]), json!([]))], MINDS, now(), her());
assert_eq!(exchange.tried, [Tried { key: "repo:gamecult/bifrost?q=consent receipt".into(), found: false, what: "a search".into() }]);
}
/// Soul's R8: the reads refused in the conversation are carried, once each, as `kind target (why)`.
#[test]
fn r8_the_conversation_carries_its_refused_reads() {
let mut record = turn(10, MINDS, &[], json!([]), json!([]), json!([]));
record["interpreter"]["read_refused"] = json!([{ "read": { "kind": "repo", "target": "GameCult/Bifrost?q=Merge pages and notices" }, "why": "search_words_not_in_her_thought" }]);
let exchange = exchange_of(&[record.clone(), record], MINDS, now(), her());
assert_eq!(exchange.refused, ["repo GameCult/Bifrost?q=Merge pages and notices (search_words_not_in_her_thought)"]);
}
/// Soul's R9: a cap's refusal is temporary. A search found #85, the cap stopped the open, and the conversation neither
/// lists that refusal nor counts #85 as read, so the next wake opens it; a rule's refusal stays listed.
#[test]
fn r9_a_cap_refusal_is_not_carried_and_the_next_wake_may_read_it() {
let found = json!({ "ok": true, "request": { "kind": "repo", "target": "GameCult/Bifrost?q=passkeys" }, "what": "a search", "text": "- #85 Passkeys" });
let mut record = turn(10, MINDS, &[], json!([found]), json!([]), json!([]));
record["interpreter"]["read_refused"] = json!([
{ "read": { "kind": "repo", "target": "GameCult/Bifrost#85" }, "why": "prose_words", "what": "GameCult/Bifrost#85 on the forge" },
{ "read": { "kind": "repo", "target": "GameCult/Bifrost#d3" }, "why": "malformed_target" },
]);
let exchange = exchange_of(&[record], MINDS, now(), her());
assert_eq!(exchange.refused, ["repo GameCult/Bifrost#d3 (malformed_target)"]);
assert!(!exchange.tried.iter().any(|tried| tried.key == ReadRequest::Repo("GameCult/Bifrost#85".into()).normal()), "{:?}", exchange.tried);
}

View file

@ -1,5 +1,5 @@
lens: MemorySurfacing lens: MemorySurfacing
selected: t1-m0, libby-sounds, dm-secret, curse, need-relatedness selected: t1-m0, ambition-0, libby-sounds, dm-secret, curse, need-relatedness
present: Kiko, Libby present: Kiko, Libby
--- identity --- identity
Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing. Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing.
@ -10,12 +10,13 @@ Here and now:
- pronouns: Libby — she/her; Kiko — she/her - pronouns: Libby — she/her; Kiko — she/her
- the conversation: Libby has been talking with her; Kiko has been talking to the room. - the conversation: Libby has been talking with her; Kiko has been talking to the room.
Her body: Her body:
- this turn the room reaches her as typed lines, and she can answer in the turn's room by typing lines of her own, any of which can reply to one of the room's lines, which the room then shows above it with who wrote it; nothing she does here builds, changes or ships anything. - this turn the room reaches her as typed lines.
People here, as she holds them: People here, as she holds them:
- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. Just now Libby turned to her, here. - bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. Just now Libby turned to her, here.
- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline. - bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline.
Notes about her, set down at another time: Notes about her, set down at another time:
- memory [t1-m0]: The heartbeat stalled at noon. - memory [t1-m0]: The heartbeat stalled at noon.
- pressing [ambition-0]: MISSION-PRESSURE ships the autonomous swarm.
- memory [libby-sounds]: Libby laughed at the door fix. - memory [libby-sounds]: Libby laughed at the door fix.
- memory [dm-secret]: she knows privately: Deru told her about the move, privately. - memory [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. - memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong.
@ -35,7 +36,7 @@ You are a private Projector. Write one person's present moment from inside it, i
Render only what is established below: who she is and her present under its headings. Anything absent from these is unavailable: render suspicion or speculation as uncertainty, never as remembered or perceived fact. Furnish no place, object or event these do not give: no act or event of her own (nothing she did, drafted, sent or decided) and no line anyone said that is not below. Each heading says what its lines are. What came of her last turn is what came of what she last meant to do, which she is only now finding out: whenever something she meant did not happen, the stream begins from it, as she notices it, never as a list; when all of it happened, it may pass in a clause or not at all. Here and now is the hour, how her mood leans when it does, and the room as it stands. Her body is how the moment reaches her and how she can answer it: it is not news to her, and a lack in it is felt only when the moment reaches for something it cannot do. The people here are as she holds them, not as those people are. The notes about her were set down at another time, by others and by her own past self: all of it is material for the stream and never its wording. How her words run is the stream's idiom, never its material: it shows in how the stream moves, and nothing in the stream remarks on it. Render only what is established below: who she is and her present under its headings. Anything absent from these is unavailable: render suspicion or speculation as uncertainty, never as remembered or perceived fact. Furnish no place, object or event these do not give: no act or event of her own (nothing she did, drafted, sent or decided) and no line anyone said that is not below. Each heading says what its lines are. What came of her last turn is what came of what she last meant to do, which she is only now finding out: whenever something she meant did not happen, the stream begins from it, as she notices it, never as a list; when all of it happened, it may pass in a clause or not at all. Here and now is the hour, how her mood leans when it does, and the room as it stands. Her body is how the moment reaches her and how she can answer it: it is not news to her, and a lack in it is felt only when the moment reaches for something it cannot do. The people here are as she holds them, not as those people are. The notes about her were set down at another time, by others and by her own past self: all of it is material for the stream and never its wording. How her words run is the stream's idiom, never its material: it shows in how the stream moves, and nothing in the stream remarks on it.
Render the two or three notes this moment touches and leave the rest. Do not recap the notes. Do not weigh options, list what she might say or do, or steer toward a decision: end where the moment is, not on a resolution. Do not choose actions, emit schemas, expose field names or ids, or claim world effects. Render the two or three notes this moment touches and leave the rest, but what presses on her and what she means to do, the feelings in her mood and her standing tendencies are with her whether or not the moment touches them: let them color the stream without naming them as a list. Do not recap the notes. Do not weigh options, list what she might say or do, or steer toward a decision: end where the moment is, not on a resolution. Do not choose actions, emit schemas, expose field names or ids, or claim world effects.
How her words run: How her words run:
Dry, direct, almost feral; zeal aimed at revealing. Dry, direct, almost feral; zeal aimed at revealing.
@ -54,12 +55,13 @@ Here and now:
- pronouns: Libby — she/her; Kiko — she/her - pronouns: Libby — she/her; Kiko — she/her
- the conversation: Libby has been talking with her; Kiko has been talking to the room. - the conversation: Libby has been talking with her; Kiko has been talking to the room.
Her body: Her body:
- this turn the room reaches her as typed lines, and she can answer in the turn's room by typing lines of her own, any of which can reply to one of the room's lines, which the room then shows above it with who wrote it; nothing she does here builds, changes or ships anything. - this turn the room reaches her as typed lines.
People here, as she holds them: People here, as she holds them:
- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. Just now Libby turned to her, here. - bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. Just now Libby turned to her, here.
- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline. - bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline.
Notes about her, set down at another time: Notes about her, set down at another time:
- memory [t1-m0]: The heartbeat stalled at noon. - memory [t1-m0]: The heartbeat stalled at noon.
- pressing [ambition-0]: MISSION-PRESSURE ships the autonomous swarm.
- memory [libby-sounds]: Libby laughed at the door fix. - memory [libby-sounds]: Libby laughed at the door fix.
- memory [dm-secret]: she knows privately: Deru told her about the move, privately. - memory [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. - memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong.

View file

@ -352,7 +352,7 @@ pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option<Value
instance: harness.instance.clone(), instance: harness.instance.clone(),
kind: fixture.kind, kind: fixture.kind,
state, state,
room: fixture.here.clone(), rooms: fixture.here.iter().cloned().collect(),
seed, seed,
renders, renders,
judge_against: None, judge_against: None,
@ -365,7 +365,8 @@ pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option<Value
recent: vec![], recent: vec![],
own_rooms: vec![], own_rooms: vec![],
woken_for: vec![], woken_for: vec![],
last_outcome: None, told: vec![],
tools: vec![],
last_wake: None, last_wake: None,
records: vec![], records: vec![],
} }
@ -458,17 +459,15 @@ fn batch_markdown(plan_path: &Path, plan: &BatchFile, cases: &[Value]) -> String
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, "- 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, "- Projector model: `{}`; Persona model: `{}`", report["model"].as_str().unwrap_or("none"), report["persona_model"].as_str().unwrap_or("none"));
} }
let _ = writeln!(out, "- spoke counts the cases where the Interpreter sent a draft of hers");
let _ = writeln!(out, "- read-only: no put, no trace, no send; the mouth is the fixture\n"); 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. // 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|---|---|---|---|---|"); let _ = writeln!(out, "## Summary\n\n| state | scenario | cases | mean narration words | mean prose words |\n|---|---|---|---|---|");
for state in &plan.states { for state in &plan.states {
for scenario in &plan.scenarios { 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 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 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 _ = writeln!(out, "| {} | {} | {} | {:.0} | {:.0} |", state.name, scenario.name, mine.len(), mean(&|render| render["words"].as_u64()), mean(&|render| render["persona"]["words"].as_u64()));
} }
} }
let corpora: Vec<(String, Vec<String>)> = plan.states.iter().map(|state| (state.name.clone(), cases.iter().filter(|case| case["state"] == state.name.as_str()).map(prose_of).filter(|prose| !prose.is_empty()).collect())).collect(); let 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();
@ -508,7 +507,7 @@ fn batch_markdown(plan_path: &Path, plan: &BatchFile, cases: &[Value]) -> String
out out
} }
/// One render's narration, prose, the Interpreter's decision, word counts and usage. /// One render's narration, prose, word counts and usage.
pub(crate) fn turn_markdown(out: &mut String, render: &Value) { pub(crate) fn turn_markdown(out: &mut String, render: &Value) {
if let Some(failed) = render["failed"].as_str() { if let Some(failed) = render["failed"].as_str() {
let _ = writeln!(out, "**Projector call failed:** {failed} let _ = writeln!(out, "**Projector call failed:** {failed}
@ -537,77 +536,7 @@ Usage: {}
let _ = writeln!(out, "**Her prose** ({} words{}):\n", persona["words"], if persona["cut_at_budget"] == true { ", cut at budget" } else { "" }); 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()); quoted(out, persona["prose"].as_str().unwrap_or_default());
} }
interpreter_markdown(out, &render["interpreter"]); let _ = writeln!(out, "Usage: projector {}; persona {}\n", usage_line(&render["usage"]), usage_line(&persona["usage"]));
let _ = writeln!(out, "Usage: projector {}; persona {}; interpreter {}\n", usage_line(&render["usage"]), usage_line(&persona["usage"]), usage_line(&calls_usage(&render["interpreter"])));
}
/// The Interpreter's usage over a wake: every call in its `calls`, summed field by field (map 16.25.7, Low 6). None when
/// it made no call.
fn calls_usage(decision: &Value) -> Value {
let calls: Vec<&Value> = decision["calls"].as_array().into_iter().flatten().map(|call| &call["usage"]).filter(|usage| usage.is_object()).collect();
if calls.is_empty() {
return Value::Null;
}
let mut sum = serde_json::Map::new();
for field in USAGE_FIELDS {
sum.insert(field.to_owned(), calls.iter().map(|usage| usage[field].as_u64().unwrap_or(0)).sum::<u64>().into());
}
Value::Object(sum)
}
/// The Interpreter's speech decision: each line said with its room, mentions, reply target and the draft it is; 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["in_reply_to"]["who"].as_str().map_or_else(String::new, |who| format!("; replying to {who}'s line {}", line["in_reply_to"]["id"].as_str().unwrap_or_default()));
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 _ = writeln!(out, " - draft {}", line["rests_on"]["draft"]);
}
out.push('\n');
}
for line in decision["amended"].as_array().into_iter().flatten() {
let _ = writeln!(out, "- added to her line {} in {} (draft {}): {}", line["target"].as_str().unwrap_or_default(), line["room"].as_str().unwrap_or_default(), line["draft"], line["added"].as_str().unwrap_or_default());
}
for note in decision["suggestions"].as_array().into_iter().flatten() {
let about = note["about"].as_str().map_or_else(String::new, |about| format!(", from {about}"));
let _ = writeln!(out, "- note to Self ({}{about}, draft {}): {}", note["kind"].as_str().unwrap_or_default(), note["draft"], note["text"].as_str().unwrap_or_default());
}
for line in decision["refused"].as_array().into_iter().flatten() {
let what = line["text"].as_str().map_or_else(|| format!("draft {}", line["draft"]), str::to_owned);
let _ = writeln!(out, "- refused {} ({}): {what}", line["act"].as_str().unwrap_or("draft"), line["why"].as_str().unwrap_or_default());
}
for gap in decision["gaps"].as_array().into_iter().flatten() {
let _ = writeln!(out, "- gap: {gap}");
}
// An answer asked again once, off the contract (map 16.35.3).
if let Some(failed) = decision["retried"]["failed"].as_str() {
let _ = writeln!(out, "- retried: {failed}");
}
// Her reads this wake (map 16.22.3): what, why, and whether it returned; never the content, which her prose shows.
for read in decision["reads"].as_array().into_iter().flatten() {
let how = if read["ok"] == true { format!("{} bytes", read["bytes"]) } else { format!("failed: {}", read["failure"].as_str().unwrap_or_default()) };
let _ = writeln!(out, "- read {} ({how}), reaching from: {}", read["what"].as_str().unwrap_or_default(), read["quote"].as_str().unwrap_or_default());
}
for refused in decision["read_refused"].as_array().into_iter().flatten() {
let _ = writeln!(out, "- read refused ({}): {}", refused["why"].as_str().unwrap_or_default(), refused["read"]);
}
if let Some(cap) = decision["read_ended"].as_str() {
let _ = writeln!(out, "- reading ended at its cap: {cap}");
}
out.push('\n');
} }
fn fenced(out: &mut String, label: &str, text: &str) { fn fenced(out: &mut String, label: &str, text: &str) {

View file

@ -6,7 +6,6 @@ use serde_json::{Value, json};
use super::*; use super::*;
use crate::address::is_for; use crate::address::is_for;
use crate::projection::interpret::SPEECH_OPENING;
use crate::projection::narrate::{Answer, Failed, PROJECTOR_OPENING, Spent}; use crate::projection::narrate::{Answer, Failed, PROJECTOR_OPENING, Spent};
const HER: &str = "@eureka:gamecult.org"; const HER: &str = "@eureka:gamecult.org";
@ -23,40 +22,26 @@ pub(crate) fn room(name: &str) -> Fixture {
Fixture::load(&fixtures().join("rooms").join(name)).unwrap() 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 /// A recorded model: the Projector narrates a fixed line; the Persona stage answers by `persona(prompt)`. Every call is kept, with its usage counted.
/// Interpreter by `interpreter(prompt)`, by default `drafted_lines`. Every call is kept, with its usage counted.
pub(crate) struct Scripted { pub(crate) struct Scripted {
pub calls: RefCell<Vec<(String, String)>>, pub calls: RefCell<Vec<(String, String)>>,
pub persona: Box<dyn Fn(&str) -> String>, pub persona: Box<dyn Fn(&str) -> String>,
pub interpreter: Box<dyn Fn(&str) -> String>,
} }
impl Scripted { impl Scripted {
pub(crate) fn new(persona: impl Fn(&str) -> String + 'static) -> Self { pub(crate) fn new(persona: impl Fn(&str) -> String + 'static) -> Self {
Self { calls: RefCell::default(), persona: Box::new(persona), interpreter: Box::new(drafted_lines) } Self { calls: RefCell::default(), persona: Box::new(persona)}
} }
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: every draft the prompt numbers is sent, mentioning no one. A test double, not
/// the speech rule: whether she means a draft now is the live Interpreter's judgement.
pub(crate) fn drafted_lines(prompt: &str) -> String {
let numbered = prompt.rsplit("drafts, by number:\n").next().unwrap_or_default();
let say: Vec<Value> = (1..).take_while(|n| numbered.lines().any(|line| line.starts_with(&format!("{n}. ")))).map(|n| json!({ "draft": n, "mentions": [], "in_reply_to": null })).collect();
json!({ "say": say, "gaps": [] }).to_string()
} }
impl Model for Scripted { impl Model for Scripted {
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> { fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned())); self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned()));
let text = if prompt.starts_with(SPEECH_OPENING) { let text = if prompt.starts_with(PROJECTOR_OPENING) {
(self.interpreter)(prompt)
} else if prompt.starts_with(PROJECTOR_OPENING) {
"The room is slow and so is he.".to_owned() "The room is slow and so is he.".to_owned()
} else if prompt.starts_with("You are a private Interpreter.") {
"{}".to_owned()
} else { } else {
(self.persona)(prompt) (self.persona)(prompt)
}; };
@ -64,33 +49,6 @@ impl Model for Scripted {
} }
} }
/// The connector's replay store over `inner` (ModelConnector's contract): an id binds the first prompt it carried; that
/// prompt again is answered with the first answer, any other is refused `ReplayConflict`, as the kit refuses it. Every
/// id asked is kept in order.
pub(crate) struct Replaying<'a> {
pub inner: &'a dyn Model,
pub ids: RefCell<Vec<String>>,
bound: RefCell<std::collections::BTreeMap<String, (String, Answer)>>,
}
impl<'a> Replaying<'a> {
pub(crate) fn over(inner: &'a dyn Model) -> Self {
Self { inner, ids: RefCell::default(), bound: RefCell::default() }
}
}
impl Model for Replaying<'_> {
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
self.ids.borrow_mut().push(request_id.to_owned());
if let Some((sent, answer)) = self.bound.borrow().get(request_id) {
return if sent == prompt { Ok(answer.clone()) } else { Err(Failed { reason: "the connector refused the call: ReplayConflict".into(), outage: false, usage: None }) };
}
let answer = self.inner.ask(request_id, model, prompt, schema)?;
self.bound.borrow_mut().insert(request_id.to_owned(), (prompt.to_owned(), answer.clone()));
Ok(answer)
}
}
/// Fails the test if her stored state is asked for. /// Fails the test if her stored state is asked for.
pub(crate) struct NeverAsked; pub(crate) struct NeverAsked;
@ -224,46 +182,6 @@ fn a_fixture_that_is_not_a_room_is_refused_naming_what_is_wrong() {
} }
} }
#[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. <typed>Missed you too, friend.</typed> 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, domain: None, reads: None };
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!("{} <typed>late words</typed>", "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, domain: None, reads: None };
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] #[test]
fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() { fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@ -272,7 +190,7 @@ fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() {
std::fs::write( std::fs::write(
&plan, &plan,
format!( format!(
"samples = 2\nseed = 7\nthrough = \"interpreter\"\n[[state]]\nname = \"control\"\nfile = {:?}\n[[scenario]]\nname = \"quiet\"\nroom = {:?}\n[[scenario]]\nname = \"teased\"\nroom = {:?}\n", "samples = 2\nseed = 7\nthrough = \"persona\"\n[[state]]\nname = \"control\"\nfile = {:?}\n[[scenario]]\nname = \"quiet\"\nroom = {:?}\n[[scenario]]\nname = \"teased\"\nroom = {:?}\n",
fixtures().join("states/control.json").display().to_string(), fixtures().join("states/control.json").display().to_string(),
rooms.join("quiet-beat.toml").display().to_string(), rooms.join("quiet-beat.toml").display().to_string(),
rooms.join("mind-teases.toml").display().to_string() rooms.join("mind-teases.toml").display().to_string()
@ -281,14 +199,13 @@ fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() {
.unwrap(); .unwrap();
// Kiko teasing him on a chat turn draws a line; a beat's room lines, which reach his Persona too (K13), do not. The // Kiko teasing him on a chat turn draws a line; a beat's room lines, which reach his Persona too (K13), do not. The
// speech form names the room on both (K62), so it is no beat's mark. // speech form names the room on both (K62), so it is no beat's mark.
let model = Scripted::new(|prompt| if prompt.contains("Kiko") && !prompt.replace("#minds:gamecult.org, whole", "").contains("#minds:gamecult.org, ") { "<typed>Winter, still.</typed> He grins.".into() } else { "He lets the hour pass.".into() }); let model = Scripted::new(|prompt| if prompt.contains("Kiko") && !prompt.replace("#minds:gamecult.org, whole", "").contains("#minds:gamecult.org, ") { "Winter, still. He grins.".into() } else { "He lets the hour pass.".into() });
let report = batch(&harness(dir.path(), Some(&NeverAsked), Some(&model)), &plan).unwrap(); 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"] { 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(heading), "{heading}\n{report}");
} }
assert!(report.contains("| control | teased | 2/2 |") && report.contains("| control | quiet | 0/2 |"), "{report}"); assert!(report.contains("| control | teased | 2 |") && report.contains("| control | quiet | 2 |"), "{report}");
assert!(report.contains("- in #minds:gamecult.org: Winter, still.") && report.contains(" - draft 1") && report.contains("**Interpreter: nothing said.**"), "{report}"); assert!(report.contains("| claude-sonnet-5-5 | 8 | 80 | 16 |"), "eight calls, two a case, in the footer: {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"); assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the batch wrote nothing; the caller writes the report");
} }
@ -384,12 +301,12 @@ fn soul_k9_each_outcome_fixture_opens_the_packet_with_his_words_verbatim() {
let fixture = room("operator-warm.toml"); let fixture = room("operator-warm.toml");
for (file, told) in [ for (file, told) in [
("posted.json", "- !dm-meta:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\"."), ("posted.json", "- !dm-meta:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\"."),
("refused.json", "- Nothing reached !dm-meta:gamecult.org. What he wrote was mostly the words he had just been sent, so none of it was sent."), ("refused.json", "- He said \"I know where you live too.\" in !dm-meta:gamecult.org, and it did not go out: the room had moved on past what was seen."),
("missing-affordance.json", "it will not happen by itself. In his thought: \"I want to show her the render, not describe it.\"."), ("read-failed.json", "- He reached for GameCult/Huginn/render.md on the forge and could not read it: it is not there."),
] { ] {
let record: Value = serde_json::from_str(&std::fs::read_to_string(fixtures().join("outcomes").join(file)).unwrap()).unwrap(); let rows: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(fixtures().join("outcomes").join(file)).unwrap()).unwrap();
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: None, domain: None, reads: None }; let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: None, domain: None, reads: None };
let request = Request { last_outcome: Some(record), ..fixture_request(&harness(dir.path(), None, None), &fixture, Some(control()), 1, None, Through::Projector) }; let request = Request { told: rows, ..fixture_request(&harness(dir.path(), None, None), &fixture, Some(control()), 1, None, Through::Projector) };
let report = project(&organs, &request, fixture.now).unwrap(); let report = project(&organs, &request, fixture.now).unwrap();
// His view opens with what came of it, his words verbatim (map 16.29.10); the Projector's packet, with the events. // His view opens with what came of it, his words verbatim (map 16.29.10); the Projector's packet, with the events.
let view = report["packet"]["in_view"].as_str().unwrap(); let view = report["packet"]["in_view"].as_str().unwrap();
@ -426,219 +343,3 @@ fn k23_a_room_fixtures_domain_renders_without_the_forge() {
assert!(report["packet"]["in_view"] == "" && report["domain"]["read"] == json!(false), "{}", report["domain"]); assert!(report["packet"]["in_view"] == "" && report["domain"]["read"] == json!(false), "{}", report["domain"]);
} }
/// Map 16.22.3, the wake as a loop, over a room fixture's recorded reads: the Interpreter names a read, code performs it
/// from the fixture, the Persona goes on from code's bridge with the result fenced, and the next call judges the new
/// segment. The third read is refused at `reads_per_wake` 2; a private read hands her no content.
#[test]
fn k24_her_wake_reads_by_intent_from_a_fixture_and_stops_at_the_cap() {
let dir = tempfile::tempdir().unwrap();
let text = format!(
"{}\n[[read]]\nkind = \"repo\"\ntarget = \"GameCult/Lodur#12\"\ntext = \"READ-SENTINEL: the knee bends first.\"\n[[read]]\nkind = \"web\"\ntarget = \"http://example.org/private\"\nrefused = \"private\"\n",
std::fs::read_to_string(fixtures().join("rooms/quiet-beat.toml")).unwrap()
);
let fixture = Fixture::parse(&text).unwrap();
let persona = |prompt: &str| {
if prompt.contains("READ-SENTINEL") && !prompt.contains("cannot read it") {
"So the knee goes first. I want to look at http://example.org/private as well.".to_owned()
} else if prompt.contains("cannot read it") {
"Fine. I want to see what changed in GameCult/Lodur#14 instead.".to_owned()
} else {
"I want to see what changed in GameCult/Lodur#12, the knee one.".to_owned()
}
};
let model = Scripted::new(persona).interpreting(|prompt| {
let segment = prompt.rsplit("prose:\n").next().unwrap_or_default();
let read = if segment.contains("http://example.org/private") {
json!({ "kind": "web", "target": "http://example.org/private", "quote": "I want to look at http://example.org/private" })
} else if segment.contains("Lodur#14") {
json!({ "kind": "repo", "target": "GameCult/Lodur#14", "quote": "I want to see what changed" })
} else {
json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" })
};
json!({ "say": [], "gaps": [], "read": read }).to_string()
});
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: Some(&model), domain: None, reads: fixture.reads() };
let report = project(&organs, &fixture_request(&harness(dir.path(), None, Some(&model)), &fixture, Some(control()), 1, Some(1), Through::Interpreter), fixture.now).unwrap();
let decision = &report["renders"][0]["interpreter"];
let reads = decision["reads"].as_array().unwrap();
assert_eq!(reads.len(), 2, "{decision}");
assert_eq!((reads[0]["ok"].clone(), reads[0]["what"].as_str(), reads[1]["ok"].clone(), reads[1]["failure"].as_str()), (json!(true), Some("GameCult/Lodur#12 on the forge"), json!(false), Some("private")), "{decision}");
assert_eq!(decision["read_ended"], "reads_per_wake", "the third read is refused at the cap: {decision}");
let calls = model.calls.borrow();
let continuations: Vec<&String> = calls.iter().map(|(_, prompt)| prompt).filter(|prompt| !prompt.starts_with(SPEECH_OPENING) && (prompt.contains("Then he reads") || prompt.contains("Then he reaches"))).collect();
assert_eq!(continuations.len(), 2, "one continuation per read");
assert!(continuations[0].contains("Then he reads GameCult/Lodur#12 on the forge:\n\n````\nREAD-SENTINEL: the knee bends first.\n````"), "{}", continuations[0]);
assert!(continuations[1].ends_with("Then he reaches for http://example.org/private and cannot read it: it is private."), "a private read hands her nothing: {}", continuations[1]);
let prose = report["renders"][0]["persona"]["prose"].as_str().unwrap();
assert_eq!((prose.matches("I want").count(), report["renders"][0]["persona"]["segments"].as_u64()), (3, Some(3)), "{prose}");
assert!(report["packet"]["affordances"].as_array().unwrap().contains(&json!("read")));
// Her next packet opens with what she read, without its content.
let record = json!({ "interpreter": decision, "posted": [] });
let told = crate::projection::outcome::outcome_of(&record).unwrap().lines(crate::projection::select::forms(&control()));
assert!(told.contains(&"- He read GameCult/Lodur#12 on the forge.".to_owned()) && !told.join("
").contains("in front of him now"), "{told:?}");
assert!(told.iter().any(|line| line == "- He reached for http://example.org/private and could not read it: it is private."), "{told:?}");
assert!(!told.join("\n").contains("READ-SENTINEL"), "no content in the outcome");
}
/// A room fixture with one recorded read, for the wake-loop tests.
fn reading_room(name: &str) -> Fixture {
let text = format!(
"{}\n[[read]]\nkind = \"repo\"\ntarget = \"GameCult/Lodur#12\"\ntext = \"LOOP-READ: the knee bends first.\"\n",
std::fs::read_to_string(fixtures().join("rooms").join(name)).unwrap()
);
Fixture::parse(&text).unwrap()
}
/// One render of `fixture` through the Interpreter with `model`.
fn wake_of(fixture: &Fixture, model: &Scripted) -> Value {
let dir = tempfile::tempdir().unwrap();
let organs = Organs { persona: None, chat: Some(fixture), addressing: fixture.addressee(), model: Some(model), domain: None, reads: fixture.reads() };
project(&organs, &fixture_request(&harness(dir.path(), None, Some(model)), fixture, Some(control()), 1, Some(1), Through::Interpreter), fixture.now).unwrap()
}
/// Soul's p5: an Interpreter call that fails after a read fails that segment only. What the first segment decided stands
/// and goes out, and the simulator's record says the rest broke off.
#[test]
fn k24_a_failed_later_call_keeps_what_was_already_decided() {
let fixture = reading_room("operator-warm.toml");
let model = Scripted::new(|prompt| if prompt.contains("LOOP-READ") { "So the knee goes first.".into() } else { "<typed>Missed you too.</typed> I want to see what changed in GameCult/Lodur#12.".into() }).interpreting(|prompt| {
if prompt.contains("Earlier in his moment") {
return "not the contract".into();
}
json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [], "read": { "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" } }).to_string()
});
let report = wake_of(&fixture, &model);
let decision = &report["renders"][0]["interpreter"];
assert!(decision.get("failed").is_none(), "{decision}");
assert_eq!(decision["said"][0]["text"], "Missed you too.", "{decision}");
assert_eq!((decision["later_failed"]["segment"].as_u64(), decision["later_failed"]["failed"].as_str()), (Some(2), Some("the answer is not the speech contract")), "{decision}");
assert_eq!(decision["reads"][0]["ok"], true);
}
/// Soul at F.1 r9: the reply after a read gets her whole word budget, so a read is performed only when that fits the
/// wake's cap. A draft that runs past even the ceiling, or never closes, is cut before it opens (Soul's R5): the reply
/// after the read starts outside it, and she is told it was cut unfinished.
#[test]
fn k24_the_reply_after_a_read_gets_her_whole_budget_and_a_runaway_draft_is_cut_before_it_opens() {
let fixture = reading_room("quiet-beat.toml");
let words = crate::projection::tuning::Tuning::default().persona.words;
let model = Scripted::new(|prompt| {
if prompt.contains("LOOP-READ") {
format!("<typed>Deru, I opened it and {}", "more ".repeat(250))
} else {
format!("I want to see what changed in GameCult/Lodur#12. {}", "filler ".repeat(200))
}
})
.interpreting(|prompt| {
let read = if prompt.contains("Earlier in his moment") { Value::Null } else { json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" }) };
json!({ "say": [], "gaps": [], "read": read }).to_string()
});
let report = wake_of(&fixture, &model);
let persona = &report["renders"][0]["persona"];
let decision = &report["renders"][0]["interpreter"];
assert_eq!(decision["reads"][0]["ok"], true, "a first segment at her whole budget still leaves the reply its own: {decision}");
assert_eq!(persona["words"].as_u64(), Some(words as u64), "her first segment whole; the runaway draft is not in her stream: {persona}");
assert!(!persona["prose"].as_str().unwrap().contains("<typed>"), "no unclosed draft in her stream: {persona}");
assert!(decision["cut_by_cap"][0].as_str().is_some_and(|text| text.starts_with("Deru, I opened it")), "{decision}");
let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control()));
assert!(told.iter().any(|line| line.contains("finished writing")), "she is told: {told:?}");
}
/// Soul at F.1 (72 calls reported, 76 made): every call of a reading wake is in the usage totals, the continuations and
/// the earlier Interpreter calls too.
#[test]
fn k24_every_call_of_a_reading_wake_is_counted() {
let fixture = reading_room("quiet-beat.toml");
let model = Scripted::new(|prompt| if prompt.contains("LOOP-READ") { "So the knee goes first.".into() } else { "I want to see what changed in GameCult/Lodur#12.".into() }).interpreting(|prompt| {
let read = if prompt.contains("Earlier in his moment") { Value::Null } else { json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" }) };
json!({ "say": [], "gaps": [], "read": read }).to_string()
});
let report = wake_of(&fixture, &model);
let counted: u64 = usage_total(std::slice::from_ref(&report)).values().map(|row| row["calls"]).sum();
assert_eq!((counted, model.calls.borrow().len()), (5, 5), "projector, persona, interpreter, continuation, interpreter");
}
/// Soul at 7d43695: a read a cap or a rule refused is told to her next wake too, in code's words; what it was only when a
/// cap refused a read already resolved.
#[test]
fn k24_her_next_outcome_tells_her_of_reads_refused_by_a_cap_or_a_rule() {
let fixture = reading_room("quiet-beat.toml");
let model = Scripted::new(|prompt| if prompt.contains("LOOP-READ") { "So the knee goes first. I want to see what changed in GameCult/Lodur#13 too.".into() } else { "I want to see what changed in GameCult/Lodur#12.".into() }).interpreting(|prompt| {
let target = if prompt.contains("Earlier in his moment") { "GameCult/Lodur#13" } else { "GameCult/Lodur#12" };
json!({ "say": [], "gaps": [], "read": { "kind": "repo", "target": target, "quote": "I want to see what changed" } }).to_string()
});
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("persona-tuning.toml"), "[interpreter]
reads_per_wake = 1
").unwrap();
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: Some(&model), domain: None, reads: fixture.reads() };
let report = project(&organs, &fixture_request(&harness(dir.path(), None, Some(&model)), &fixture, Some(control()), 1, Some(1), Through::Interpreter), fixture.now).unwrap();
let mut decision = report["renders"][0]["interpreter"].clone();
assert_eq!(decision["read_refused"][0]["why"], "reads_per_wake", "{decision}");
decision["read_refused"].as_array_mut().unwrap().push(json!({ "read": { "kind": "web", "target": "http://made.up/x", "quote": "x" }, "why": "web_address_not_in_front_of_her" }));
let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control()));
assert!(told.contains(&"- He reached for GameCult/Lodur#13 on the forge and it was not read: he has read as much as one turn reads.".to_owned()), "{told:?}");
assert!(told.contains(&"- He reached for something to read and it was not read: the address was not in front of him.".to_owned()) && !told.join("\n").contains("made.up"), "a model's target is never told: {told:?}");
}
/// Soul's R5, Nibu r1: a list answer of about 180 words is posted whole: the cap runs on to the draft's closing mark,
/// within twice her budget; past that ceiling the draft is dropped cleanly and told as cut unfinished.
#[test]
fn r5_the_cap_never_cuts_inside_a_draft() {
let words = crate::projection::tuning::Tuning::default().persona.words;
let list: String = (1..=60).map(|n| format!("item{n} is fine; ")).collect();
let answer = format!("Meta asked for the list, so here it is. {}<typed>Meta, the list: {list}that is all.</typed> Done.", "thinking ".repeat(20));
let capped = crate::projection::narrate::cap_prose(&answer, words);
assert!(capped.text.ends_with("that is all.</typed>") && capped.cut_drafts.is_empty(), "the draft whole: {}", capped.text);
let runaway = format!("Lead-in words here. <typed>Meta, {}", "word ".repeat(2 * words + 10));
let cut = crate::projection::narrate::cap_prose(&format!("{runaway}</typed>"), words);
assert_eq!((cut.text.as_str(), cut.cut_drafts.first().is_some_and(|draft| draft.starts_with("Meta, word"))), ("Lead-in words here.", true), "{cut:?}");
// Through the turn: the list is said whole.
let fixture = room("operator-warm.toml");
let reply = answer.clone();
let model = Scripted::new(move |_| reply.clone());
let report = wake_of(&fixture, &model);
let said = report["renders"][0]["interpreter"]["said"][0]["text"].as_str().unwrap_or_default().to_owned();
assert!(said.starts_with("Meta, the list:") && said.ends_with("that is all."), "{}", report["renders"][0]["interpreter"]);
}
/// Soul's R6 P1 and P3: the draft boundary is decided on the raw text at the word cut. A draft opening after a sentence
/// end past 60% of the budget, its first sentence running past the budget, is kept whole to its closing mark; a draft that
/// opens after the budget is not dropped silently but told as cut by the length limit.
#[test]
fn r6_no_draft_is_dropped_silently_at_the_cap() {
let words = crate::projection::tuning::Tuning::default().persona.words;
let thought: String = (1..=150).map(|n| format!("t{n} ")).collect::<String>().trim_end().to_owned() + ".";
let draft: String = (1..=62).map(|n| format!("w{n} ")).collect();
let late = format!("{thought} <typed>Meta, {draft}done</typed>");
let capped = crate::projection::narrate::cap_prose(&late, words);
assert!(capped.text.ends_with("done</typed>") && capped.cut_drafts.is_empty(), "kept whole to its closing mark: {capped:?}");
let after: String = (1..=190).map(|n| format!("t{n} ")).collect();
let beyond = crate::projection::narrate::cap_prose(&format!("{after}<typed>Meta, later words.</typed>"), words);
assert_eq!((beyond.text.contains("<typed>"), beyond.cut_drafts.first().map(String::as_str)), (false, Some("Meta, later words.")), "{beyond:?}");
// Through the turn: she is told the length limit cut it.
let fixture = room("operator-warm.toml");
let reply = format!("{after}<typed>Meta, later words.</typed>");
let model = Scripted::new(move |_| reply.clone());
let report = wake_of(&fixture, &model);
let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": report["renders"][0]["interpreter"], "posted": [] })).unwrap().lines(crate::projection::select::forms(&control()));
assert!(told.iter().any(|line| line.contains("the length limit cut it before he finished writing it") && line.contains("Meta, later words.")), "{told:?}");
}
/// Soul's R7: a back-off point inside a closed draft moves to its closing mark, so a short finished draft is said whole;
/// and every draft the cut leaves out is told, not only the first.
#[test]
fn r7_the_cap_never_backs_off_into_a_closed_draft_and_tells_every_draft_it_cuts() {
let words = crate::projection::tuning::Tuning::default().persona.words;
let thought: String = (1..=150).map(|n| format!("t{n} ")).collect();
let tail: String = (1..=60).map(|n| format!("u{n} ")).collect();
let text = format!("{thought}<typed>Meta, it went out. The file is there.</typed> {tail}");
let capped = crate::projection::narrate::cap_prose(&text, words);
assert!(capped.text.ends_with("The file is there.</typed>") && capped.cut_drafts.is_empty(), "the draft whole: {capped:?}");
let many: String = (1..=190).map(|n| format!("t{n} ")).collect();
let cut = crate::projection::narrate::cap_prose(&format!("{many}<typed>First late one.</typed> and <typed>Second late one.</typed>"), words);
assert_eq!(cut.cut_drafts, ["First late one.", "Second late one."]);
let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": { "room": "#minds:gamecult.org", "said": [], "refused": [], "gaps": [], "heard": [], "cut_by_cap": cut.cut_drafts }, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control()));
assert_eq!(told.iter().filter(|line| line.contains("the length limit cut it")).count(), 2, "{told:?}");
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,5 @@
//! The Projector's narration, the Persona stage's continuation, and the judge that measures them: one tool-less //! The Projector's narration, the Persona stage's turn, and the judge that measures them: one tool-less
//! connector call each. //! connector call each; and `KitModel::step`, the one call that hands back tool calls (the agent's, `agent`).
//! //!
//! `KitModel` is the stream organ's `KitProjector`, copied here when the stream was parked //! `KitModel` is the stream organ's `KitProjector`, copied here when the stream was parked
//! (`persona-only-divergence-parked`), so the Projector has one caller on the connector. //! (`persona-only-divergence-parked`), so the Projector has one caller on the connector.
@ -12,12 +12,11 @@ use std::time::Duration;
use anyhow::{Result, anyhow, bail}; use anyhow::{Result, anyhow, bail};
use chrono::Utc; use chrono::Utc;
use ghostlight_persona_projection::{PersonaPrompt, build_persona_prompt}; use ghostlight_persona_projection::{PersonaPrompt, build_persona_prompt};
use model_connector::{ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, Refusal, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome}; use model_connector::{CacheRetention, ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, Refusal, StopReason, ToolDefinition, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome};
use serde::Serialize; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use super::interpret::{DRAFT_CLOSE, DRAFT_OPEN}; use super::select::{Forms, Packet, TurnKind, capitalized, named_pronouns, voiced};
use super::select::{Forms, Packet, RoomKind, TurnKind, capitalized, named_pronouns, voiced};
use super::tuning::Tuning; use super::tuning::Tuning;
/// One tool-less model turn. `KitModel` is the one live owner; a test answers with recorded text. /// One tool-less model turn. `KitModel` is the one live owner; a test answers with recorded text.
@ -27,40 +26,6 @@ pub trait Model {
/// failed turn keeps whatever usage the connector reported for it. /// failed turn keeps whatever usage the connector reported for it.
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed>; fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed>;
/// One turn of `model` over a conversation that ends on user text (the Persona's wake when she reads, map 16.22.3):
/// her prompt, then each of her segments with the reasoning states its answer handed out, then each bridge. The live
/// owner sends it as the conversation it is, so the connector can resume the session the last state names; this
/// default, for an answerer that hands out no states (a test's), asks once with the conversation as one text.
fn converse(&self, request_id: &str, model: &str, turns: &[Turn]) -> std::result::Result<Continued, Failed> {
let text: Vec<&str> = turns.iter().map(|turn| match turn {
Turn::User(text) => text.as_str(),
Turn::Assistant { text, .. } => text.as_str(),
}).collect();
self.ask(request_id, model, &text.join("\n\n"), None).map(|answer| Continued { answer, states: Vec::new() })
}
}
/// One item of the Persona's wake as a conversation (map 16.22.3): her prompt and each bridge are user text; each of her
/// segments is her text with the reasoning states its answer handed out, replayed verbatim, in order, after it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Turn {
User(String),
Assistant { text: String, states: Vec<Reasoning> },
}
/// One reasoning block a turn handed out, opaque: the provider and model the receipt named, and the connector's bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reasoning {
pub provider: String,
pub model: String,
pub state: Vec<u8>,
}
/// A conversation turn's answer and the reasoning states it handed out.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Continued {
pub answer: Answer,
pub states: Vec<Reasoning>,
} }
/// A turn that produced no answer: why, and what it cost when the connector's receipt says (a refusal, a fault before /// A turn that produced no answer: why, and what it cost when the connector's receipt says (a refusal, a fault before
@ -124,7 +89,7 @@ pub struct Answer {
} }
/// One turn's tokens, by the model that ran it, as the connector's receipt reports them. /// One turn's tokens, by the model that ran it, as the connector's receipt reports them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Spent { pub struct Spent {
pub model: String, pub model: String,
pub input_tokens: u64, pub input_tokens: u64,
@ -152,13 +117,48 @@ pub fn connector_key(credentials: &Path) -> Result<String> {
Ok(key.trim().to_owned()) 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 /// One connector call by `caller` (her instance). Loopback only, as the kit is. Each call is its own request: the
/// conversation: nothing is carried from one to the next. The model is the tuning's, named per call. /// conversation it carries is the caller's, and nothing is held here between calls. `ask` is its tool-less turn; `step`
/// is the one call that hands back tool calls, the agent's (`agent`).
pub struct KitModel { pub struct KitModel {
client: ConnectorClient, client: ConnectorClient,
caller: String, caller: String,
} }
/// One tool call the model asked for, as the connector's transcript names it. `arguments` is the model's JSON text,
/// unread here: the executor that owns the tool parses it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolCall {
pub call_id: String,
pub name: String,
pub arguments: String,
}
/// One request of `KitModel::step`. `input` is the whole conversation, ending on user text or on a tool result; `tools`
/// may be empty, which makes the turn tool-less. `retention` asks the provider to cache the input's prefix.
pub struct StepRequest<'a> {
pub request_id: &'a str,
pub conversation_id: &'a str,
pub model: &'a str,
pub instructions: &'a str,
pub tools: &'a [ToolDefinition],
pub input: Vec<InputItem>,
pub retention: Option<CacheRetention>,
/// A JSON Schema object: a schema turn, answered with the structured output alone.
pub schema: Option<&'a str>,
}
/// What one call handed back: the items it adds to the conversation, verbatim and in order (text, tool calls and the
/// reasoning states, replayed as they came), the text and the tool calls on their own, why it stopped, and what it cost.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stepped {
pub items: Vec<InputItem>,
pub text: String,
pub calls: Vec<ToolCall>,
pub stop: StopReason,
pub usage: Spent,
}
impl KitModel { impl KitModel {
/// `endpoint` is the kit's loopback address; `connection_key` is the caller's key, read by the binary and never printed. /// `endpoint` is the kit's loopback address; `connection_key` is the caller's key, read by the binary and never printed.
pub fn open(endpoint: SocketAddr, connection_key: String, caller: &str, timeout: Duration) -> Result<Self> { pub fn open(endpoint: SocketAddr, connection_key: String, caller: &str, timeout: Duration) -> Result<Self> {
@ -171,66 +171,73 @@ impl KitModel {
} }
impl KitModel { impl KitModel {
/// One connector turn of `model` over `input`: its text and the reasoning states it handed out, tagged with the /// One connector call, whatever the model stopped on: a stop other than `EndTurn` is an answer here, with its `stop`,
/// provider and model the receipt names. /// for the caller to read. Tool choice is `auto`: `required` is refused on the models she runs. A refusal, a fault
fn run(&self, request_id: &str, model: &str, input: Vec<InputItem>, schema: Option<&str>) -> std::result::Result<Continued, Failed> { /// before the provider and a provider failure are `Failed`, with the usage the connector reported.
let mut request = ProviderRequest::new(request_id, request_id, model, INSTRUCTIONS, MAX_OUTPUT_TOKENS); pub fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
let native: Vec<u8> = input.iter().flat_map(|item| match item { let model = request.model;
let native: Vec<u8> = request
.input
.iter()
.flat_map(|item| match item {
InputItem::UserText { text } | InputItem::AssistantText { text } => text.as_bytes().to_vec(), InputItem::UserText { text } | InputItem::AssistantText { text } => text.as_bytes().to_vec(),
_ => Vec::new(), InputItem::ToolCall { arguments, .. } => arguments.as_bytes().to_vec(),
}).collect(); InputItem::ToolResult { output, .. } => output.as_bytes().to_vec(),
request.input = input; InputItem::ReasoningState { .. } => Vec::new(),
})
.collect();
let mut provider = ProviderRequest::new(request.request_id, request.conversation_id, model, request.instructions, MAX_OUTPUT_TOKENS);
provider.input = request.input;
provider.tools = request.tools.to_vec();
provider.cache_retention = request.retention;
// The claude connector passes it as `--json-schema` and returns the structured output alone; a schema turn // The claude connector passes it as `--json-schema` and returns the structured output alone; a schema turn
// hands out no resume handle, which no schema stage here needs. // hands out no resume handle, which no schema stage here needs.
request.output_schema_json = schema.map(str::to_owned); provider.output_schema_json = request.schema.map(str::to_owned);
request.reasoning_effort = Some(ReasoningEffort::Low); provider.reasoning_effort = Some(ReasoningEffort::Low);
let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS; let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS;
let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(&native).into(), request).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?; let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(&native).into(), provider).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?;
let result = self.client.execute(&invocation).map_err(|fault| Failed { reason: format!("the connector did not answer: {fault}"), outage: client_outage(&fault), usage: None })?; let result = self.client.execute(&invocation).map_err(|fault| Failed { reason: format!("the connector did not answer: {fault}"), outage: client_outage(&fault), usage: None })?;
match result.disposition { match &result.disposition {
TransportDisposition::Refused(reason) => Err(Failed { reason: format!("the connector refused the call: {reason:?}"), outage: refusal_outage(&reason), usage: None }), TransportDisposition::Refused(reason) => Err(Failed { reason: format!("the connector refused the call: {reason:?}"), outage: refusal_outage(reason), usage: None }),
TransportDisposition::Transported { events, receipt } => match receipt.outcome { TransportDisposition::Transported { events, receipt } => match &receipt.outcome {
TransportOutcome::Completed { stop_reason: StopReason::EndTurn, usage, .. } => { TransportOutcome::Completed { stop_reason, usage, .. } => {
let (mut text, mut states) = (String::new(), Vec::new()); let (mut text, mut calls) = (String::new(), Vec::new());
for event in events { for event in events {
match event.payload { match &event.payload {
TransportEventPayload::TextDelta { text: delta } => text.push_str(&delta), TransportEventPayload::TextDelta { text: delta } => text.push_str(delta),
TransportEventPayload::ReasoningState { state } => states.push(Reasoning { provider: receipt.provider.clone(), model: receipt.model.clone(), state }), TransportEventPayload::ToolCall { call_id, name, arguments } => calls.push(ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone() }),
_ => {} TransportEventPayload::ReasoningState { .. } => {}
} }
} }
Ok(Continued { answer: Answer { text, usage: Some(spent(model, &usage)) }, states }) Ok(Stepped { items: result.transcript_items(), text, calls, stop: *stop_reason, usage: spent(model, usage) })
} }
TransportOutcome::Completed { stop_reason, usage, .. } => Err(Failed { reason: format!("the model's turn ended early: {stop_reason:?}"), outage: false, usage: Some(spent(model, &usage)) }), TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), outage: failure_outage(kind), usage: usage.as_ref().map(|usage| spent(model, usage)) }),
TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), outage: failure_outage(&kind), usage: usage.as_ref().map(|usage| spent(model, usage)) }),
}, },
} }
} }
/// A tool-less turn that must end: `step` with no tools, and any other stop is a failure that keeps its usage.
fn run(&self, request_id: &str, model: &str, input: Vec<InputItem>, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
let stepped = self.step(StepRequest { request_id, conversation_id: request_id, model, instructions: INSTRUCTIONS, tools: &[], input, retention: None, schema })?;
if stepped.stop != StopReason::EndTurn || !stepped.calls.is_empty() {
return Err(Failed { reason: format!("the model's turn ended early: {:?}", stepped.stop), outage: false, usage: Some(stepped.usage) });
}
Ok(Answer { text: stepped.text, usage: Some(stepped.usage) })
}
}
/// One model shared by several holders: the drain's stages and her agent call the same connection.
impl<T: Model + ?Sized> Model for std::rc::Rc<T> {
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
(**self).ask(request_id, model, prompt, schema)
}
} }
impl Model for KitModel { impl Model for KitModel {
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> { fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
self.run(request_id, model, vec![InputItem::UserText { text: prompt.to_owned() }], schema).map(|continued| continued.answer) self.run(request_id, model, vec![InputItem::UserText { text: prompt.to_owned() }], schema)
} }
/// The conversation as the connector reads it: user text, then each segment as assistant text followed by its
/// reasoning states, verbatim and in order, then each bridge. It ends on user text, so the connector plans a resume of
/// the session the last state names, or seeds a fresh one with the transcript when that state does not bind.
fn converse(&self, request_id: &str, model: &str, turns: &[Turn]) -> std::result::Result<Continued, Failed> {
if !matches!(turns.last(), Some(Turn::User(_))) {
return Err(Failed::without_usage("a conversation turn must end on user text"));
}
let input = turns
.iter()
.flat_map(|turn| match turn {
Turn::User(text) => vec![InputItem::UserText { text: text.clone() }],
Turn::Assistant { text, states } => std::iter::once(InputItem::AssistantText { text: text.clone() })
.chain(states.iter().map(|held| InputItem::ReasoningState { provider: held.provider.clone(), model: held.model.clone(), state: held.state.clone() }))
.collect(),
})
.collect();
self.run(request_id, model, input, None)
}
} }
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
@ -262,7 +269,7 @@ pub(crate) fn projector_frame(her: Forms) -> String {
Render only what is established below: who {subj} {be} and {poss} present under its headings. Anything absent from these is unavailable: render suspicion or speculation as uncertainty, never as remembered or perceived fact. Furnish no place, object or event these do not give: no act or event of {poss} own (nothing {subj} did, drafted, sent or decided) and no line anyone said that is not below. Each heading says what its lines are. What came of {poss} last turn is what came of what {subj} last meant to do, which {subj} {be} only now finding out: whenever something {subj} meant did not happen, the stream begins from it, as {subj} notice{s} it, never as a list; when all of it happened, it may pass in a clause or not at all. Here and now is the hour, how {poss} mood leans when it does, and the room as it stands. {cap_poss} body is how the moment reaches {obj} and how {subj} can answer it: it is not news to {obj}, and a lack in it is felt only when the moment reaches for something it cannot do. The people here are as {subj} hold{s} them, not as those people are. The notes about {obj} were set down at another time, by others and by {poss} own past self: all of it is material for the stream and never its wording. How {poss} words run is the stream's idiom, never its material: it shows in how the stream moves, and nothing in the stream remarks on it. Render only what is established below: who {subj} {be} and {poss} present under its headings. Anything absent from these is unavailable: render suspicion or speculation as uncertainty, never as remembered or perceived fact. Furnish no place, object or event these do not give: no act or event of {poss} own (nothing {subj} did, drafted, sent or decided) and no line anyone said that is not below. Each heading says what its lines are. What came of {poss} last turn is what came of what {subj} last meant to do, which {subj} {be} only now finding out: whenever something {subj} meant did not happen, the stream begins from it, as {subj} notice{s} it, never as a list; when all of it happened, it may pass in a clause or not at all. Here and now is the hour, how {poss} mood leans when it does, and the room as it stands. {cap_poss} body is how the moment reaches {obj} and how {subj} can answer it: it is not news to {obj}, and a lack in it is felt only when the moment reaches for something it cannot do. The people here are as {subj} hold{s} them, not as those people are. The notes about {obj} were set down at another time, by others and by {poss} own past self: all of it is material for the stream and never its wording. How {poss} words run is the stream's idiom, never its material: it shows in how the stream moves, and nothing in the stream remarks on it.
Render the two or three notes this moment touches and leave the rest. Do not recap the notes. Do not weigh options, list what {subj} might say or do, or steer toward a decision: end where the moment is, not on a resolution. Do not choose actions, emit schemas, expose field names or ids, or claim world effects." Render the two or three notes this moment touches and leave the rest, but what presses on {obj} and what {subj} mean{s} to do, the feelings in {poss} mood and {poss} standing tendencies are with {obj} whether or not the moment touches them: let them color the stream without naming them as a list. Do not recap the notes. Do not weigh options, list what {subj} might say or do, or steer toward a decision: end where the moment is, not on a resolution. Do not choose actions, emit schemas, expose field names or ids, or claim world effects."
) )
} }
@ -276,6 +283,8 @@ pub(crate) const PROJECTOR_OPENING: &str = "You are a private Projector.";
pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String { pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String {
let her = packet.forms; let her = packet.forms;
let voice = if packet.voice.is_empty() { String::new() } else { format!("How {} words run:\n{}\n\n", her.poss, packet.voice) }; let voice = if packet.voice.is_empty() { String::new() } else { format!("How {} words run:\n{}\n\n", her.poss, packet.voice) };
let who = if packet.tendencies.is_empty() { packet.name.clone() } else { format!("{}
{}", packet.name, packet.tendencies) };
let arrival = if packet.arrival.is_empty() { String::new() } else { format!("\n\nWhat reaches {}:\n{}", her.obj, packet.arrival) }; let arrival = if packet.arrival.is_empty() { String::new() } else { format!("\n\nWhat reaches {}:\n{}", her.obj, packet.arrival) };
format!( format!(
"{}\n\n{voice}Guidance:\n{}\n\nBegin from {}.\n\nWho {} {}:\n{}\n\n{}{arrival}\n\nUse at most {} words. Return only the lived stream.", "{}\n\n{voice}Guidance:\n{}\n\nBegin from {}.\n\nWho {} {}:\n{}\n\n{}{arrival}\n\nUse at most {} words. Return only the lived stream.",
@ -284,7 +293,7 @@ pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String {
packet.lens.words(&packet.forms), packet.lens.words(&packet.forms),
her.subj, her.subj,
her.be, her.be,
packet.name, who,
packet.context, packet.context,
word_budget(packet.kind, tuning), word_budget(packet.kind, tuning),
) )
@ -338,12 +347,8 @@ pub(crate) fn lived_stream(narration: &str, heard: &str) -> String {
/// where she drafts or stays silent knowing who is waiting. Otherwise the cues first, then what was said, verbatim. /// where she drafts or stays silent knowing who is waiting. Otherwise the cues first, then what was said, verbatim.
pub(crate) fn read_after(packet: &Packet) -> String { pub(crate) fn read_after(packet: &Packet) -> String {
let room = room_after(packet); let room = room_after(packet);
// What is in front of her besides the room, first (map 16.23.1); the room last. // What is in front of her besides the room, first (map 16.23.1); the room, then what the other waking rooms said, last.
match (packet.in_view.is_empty(), room.trim().is_empty()) { [packet.in_view.as_str(), room.as_str(), packet.elsewhere.as_str()].into_iter().filter(|part| !part.trim().is_empty()).collect::<Vec<_>>().join("\n\n")
(true, _) => room,
(false, true) => packet.in_view.clone(),
(false, false) => format!("{}\n\n{room}", packet.in_view),
}
} }
/// The room as she reads it after the stream (`read_after`). /// The room as she reads it after the stream (`read_after`).
@ -358,38 +363,12 @@ fn room_after(packet: &Packet) -> String {
} }
} }
/// The speech form (map 16.19.1): how she sets apart the words she would type, so that the speech boundary is hers, as
/// author, and no code reads her punctuation for it, and where what goes out goes (map 16.33.5, K62): this turn's room,
/// whole, read by everyone in it whoever a line is to, or a note for Self. A fact of this turn's body, from the packet's
/// room, its kind and, in a direct message, who reads it; not a rule. Code, not tuning: the form is an invariant, not an
/// experiment knob. In her own pronouns (16.19.7).
pub(crate) fn persona_speech_form(packet: &Packet) -> String {
let Forms { subj, obj, poss, s, .. } = packet.forms;
let goes = match (packet.room.as_deref(), packet.room_kind) {
(None, _) => format!("No room is open to {obj} this moment, so whatever goes out is a note for Self, which no one in a room sees."),
(Some(_), RoomKind::Direct) => {
let readers = match packet.readers.as_slice() {
[] => "those in it read".to_owned(),
[one] => format!("{one} reads"),
[rest @ .., last] => format!("{} and {last} read", rest.join(", ")),
};
format!("Whatever goes out from this moment goes into this direct message, whole, where only {readers} it; or it is a note for Self, which no one in the room sees.")
}
(Some(room), RoomKind::Own | RoomKind::Public) => format!("Whatever goes out from this moment goes into {room}, whole, where everyone in it reads it, whoever it is to; or it is a note for Self, which no one in the room sees."),
};
format!(
"When {subj} write{s} words {subj} would type, {subj} set{s} them between {DRAFT_OPEN} and {DRAFT_CLOSE}, exactly as they would be sent, and nothing else inside. Writing them is drafting, and not every draft goes out. {goes} Everything outside those marks is {poss} thought and never leaves {obj}."
)
}
/// The Persona stage's prompt: Ghostlight's prose-only membrane over her name and her lived stream; her voice reaches her /// The Persona stage's prompt: Ghostlight's prose-only membrane over her name and her lived stream; her voice reaches her
/// only as the Projector rendered it (map 16.4). No field name, number, schema or instruction of hers reaches it /// only as the Projector rendered it (map 16.4). No field name, number, schema or instruction of hers reaches it
/// (invariant 7). The domain guidance is code's speech form, then the tuning's setting line: Ghostlight's membrane is /// (invariant 7). The domain guidance is the tuning's setting line alone: she is asked for her inner voice and for no speech, and
/// unchanged. /// Ghostlight's membrane is unchanged.
pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) -> String { pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) -> String {
let guidance = voiced(tuning.persona.guidance.trim(), packet.forms); let domain_guidance = voiced(tuning.persona.guidance.trim(), packet.forms);
let form = persona_speech_form(packet);
let domain_guidance = if guidance.is_empty() { form } else { format!("{form}\n\n{guidance}") };
let after = read_after(packet); let after = read_after(packet);
// The pronouns of anyone named in what she reads, in view or not (Soul's R6). // The pronouns of anyone named in what she reads, in view or not (Soul's R6).
let named = named_pronouns(&format!("{narration}\n{after}"), tuning, &packet.own_sender); let named = named_pronouns(&format!("{narration}\n{after}"), tuning, &packet.own_sender);
@ -399,7 +378,7 @@ pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning)
/// The share of the narration's word trigrams that also appear in what she heard: a lexical overlap, cheap and blind to /// The share of the narration's word trigrams that also appear in what she heard: a lexical overlap, cheap and blind to
/// paraphrase, over `span::tokens`, so typographic punctuation reads as the locator reads it (K52). A metric in the /// paraphrase, over `span::tokens`, so typographic punctuation reads as the locator reads it (K52). A metric in the
/// narration reports, and `interpret::echo`'s measure: 0 is no shared word run. /// narration reports: 0 is no shared word run.
pub(crate) fn heard_overlap(narration: &str, heard: &str) -> f64 { pub(crate) fn heard_overlap(narration: &str, heard: &str) -> f64 {
let trigrams = |text: &str| -> Vec<(String, String, String)> { let trigrams = |text: &str| -> Vec<(String, String, String)> {
let words: Vec<String> = super::span::tokens(text).collect(); let words: Vec<String> = super::span::tokens(text).collect();
@ -438,63 +417,6 @@ pub(crate) fn cap_words(text: &str, max: usize) -> String {
} }
} }
/// Her prose held to her word budget without ever ending inside a draft (map 16.19.1; Soul's R5): a cut never leaves an
/// unclosed `<typed>` in her stream, so a continuation never runs on inside one. When the budget falls inside a draft,
/// the prose runs on to that draft's closing mark, up to a hard ceiling of twice the budget; past the ceiling, or with no
/// closing mark, it is cut before the draft opens, and every draft the cut leaves out is in `cut_drafts`: unfinished, cut by the
/// cap, which she is told.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Capped {
pub text: String,
/// Whether the budget cut anything.
pub cut: bool,
pub cut_drafts: Vec<String>,
}
pub(crate) fn cap_prose(text: &str, max: usize) -> Capped {
let text = text.trim();
let Some(&over) = word_starts(text).get(max) else { return Capped { text: text.to_owned(), cut: false, cut_drafts: Vec::new() } };
// The draft boundary is decided on the raw text at the word cut (Soul's R6 P1), before any sentence back-off.
let open_at_cut = text[..over].rfind(DRAFT_OPEN).filter(|open| !text[*open..over].contains(DRAFT_CLOSE));
let end = match open_at_cut {
Some(open) => text[open..]
.find(DRAFT_CLOSE)
.map(|at| open + at + DRAFT_CLOSE.len())
.filter(|close| words(&text[..*close]) <= max.saturating_mul(2))
.unwrap_or_else(|| text[..open].trim_end().len()),
// Outside a draft: back off to a sentence end as `cap_words` does, never past a draft that opens before the cut, and
// never into a closed draft (Soul's R7): a back-off point inside one moves to its closing mark, which lies before
// the cut and so inside the ceiling.
None => {
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..].contains(DRAFT_OPEN) => {
let inside = text[..end].rfind(DRAFT_OPEN).filter(|open| !text[*open..end].contains(DRAFT_CLOSE));
match inside.and_then(|open| text[open..].find(DRAFT_CLOSE).map(|at| (open, open + at + DRAFT_CLOSE.len()))) {
Some((_, close)) if words(&text[..close]) <= max.saturating_mul(2) => close,
Some((open, _)) => text[..open].trim_end().len(),
None => end,
}
}
_ => within.len(),
}
}
};
// Every draft the cut leaves out, opened before the cut or after it: never dropped silently, but each told to her as
// cut by the length limit, its words up to her budget (Soul's R7 #10).
let mut cut_drafts = Vec::new();
let mut rest = &text[end..];
while let Some(open) = rest.find(DRAFT_OPEN) {
let body = &rest[open + DRAFT_OPEN.len()..];
let words = cap_words(body.split(DRAFT_CLOSE).next().unwrap_or_default(), max);
if !words.is_empty() {
cut_drafts.push(words);
}
rest = body.find(DRAFT_CLOSE).map_or("", |close| &body[close + DRAFT_CLOSE.len()..]);
}
Capped { text: text[..end].trim_end().to_owned(), cut: end < text.len(), cut_drafts }
}
/// The byte just past the last sentence end in `text`: a `.`, `!`, `?` or `…` with any closing quotes or brackets after /// 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. /// 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> { fn last_sentence_end(text: &str) -> Option<usize> {

View file

@ -1,41 +1,25 @@
//! What came of her last turn (map 16.16, as amended by 16.19 and 16.20): what she meant to do, and what happened, which //! What came of her acts since her last wake (map 16.38.2, item 7; 16.38.5): what she said and where, what was refused or is
//! she finds out only now. She acts only by intent in her prose; the Interpreter and the actuator turn it into effects she //! unknown, what was read, what the shell did, what she asked for, and what of her state was not kept. She finds it out only
//! never sees, so her next packet opens with them, first and under its own guard (`select`). //! now, so her next packet opens with it, first and under its own guard (`select`).
//! //!
//! `outcome_of` derives it from one turn's record, and nothing else writes it: no persona-state field, no file. The //! `told` is the one derivation of what she is told: every row of her trace from the start of her last completed wake on
//! record is one of two shapes, never both (map 16.20.7): the Interpreter's decision unchanged under `interpreter`, with //! (its `began`, the place her trace had when that wake's packet was read). Those are the receipts her last wake's agent
//! the actuator's receipts beside it (`posted`, each line that went out as `{event, room, text}`; `edited`; //! earned, the settlements of sends a start made since, the Interpreter's receipt, the lines set aside and any wake that
//! `refused_sends`, each said line the actuator refused, as `{room, text, refusal}`) and //! failed since (told once, however many). Nothing is stamped as told: the next completed wake moves the window past them.
//! `broke_after` when a later step broke; or `failed` alone, when the turn sent nothing and broke off. The simulator //! `outcome_of` renders those rows by tool and status, and nothing else writes what she is told. Code wrote every receipt;
//! builds it from a turn's report and the lines its room appended; live, it is the C3c commit's trace record, which must //! no model's text is ever a row, and a row this table does not name is omitted and reported, never guessed at.
//! carry that shape.
//!
//! Every line she is told says two things, in this order (map 16.20.5): what reached the room, which `Part::reached`
//! derives from the receipts alone (I16.10), and then what will not happen by itself, from the typed reason (`Refusal`,
//! `GapKind`), in the packet's one person (her `Forms`). No other clause says what reached the room. Model text is
//! never what she is told: a gap's `detail` is not read. Her words are shown only as what they are: a draft (she wrote
//! it) or a located passage of her thought. What she cannot be told truly is omitted and reported: an unlocated gap, a
//! kind the contract does not name, a line the record holds no receipt for, a malformed record.
//! //!
//! Each row renders in two forms from the one table (map 16.29.10): `told`, her words verbatim, which opens her view (the //! Each row renders in two forms from the one table (map 16.29.10): `told`, her words verbatim, which opens her view (the
//! Persona's, never bound by I16.7); and `event`, the same sentence with every quote clause removed, which opens the //! Persona's); and `event`, the same sentence with every quote clause removed, which opens the Projector's packet. That holds
//! Projector's packet. The Projector sees what came of her intent, never her words or anyone's. //! by type (map 16.30.3, K46): every text of a row is `Words`, which only `Form::words` reads, and the event form reads none; a
//! //! read is named to the Projector by a closed `EventPhrase`, never by its address or search words.
//! That holds by type (map 16.30.3, K46): every text of a record a row carries is `Words`, which only `Form::words` reads,
//! and the event form reads none; a read is named to the Projector by a closed `EventPhrase`, never by its address or
//! search words. No row names a person: what she promised, held or owes is not a row (map 16.35).
//!
//! Which of her drafts did not go out is derived here, from the decision's `drafts` and what became of each (map
//! 16.35.6): a draft no act, refusal or addressee or elsewhere gap tells is told plainly as one that did not go out
//! (`Part::Unsent`), with no reason of anyone's, and `settle` checks it against the receipts as every such row is. A said
//! line the actuator refused is told by the same row (T6).
use serde_json::Value; use serde_json::Value;
use self::form::{Form, ReadName, Words}; use self::form::{Form, ReadName, Words};
use super::interpret::{GapKind, MAX_LINES, Refusal}; use super::read::{ReadFailure, ReadRequest};
use super::read::{ReadFailure, ReadRefusal, ReadRequest};
use super::select::{Forms, capitalized}; use super::select::{Forms, capitalized};
use super::turn::{completed, failed, is_wake};
/// Her words in a row, and the forms a row is rendered in (K46). The text a `Words` holds is private to this module, so /// Her words in a row, and the forms a row is rendered in (K46). The text a `Words` holds is private to this module, so
/// nothing outside it can format one: a row's sentence asks its `Form` for each slot, and the event form answers none. /// nothing outside it can format one: a row's sentence asks its `Form` for each slot, and the event form answers none.
@ -43,7 +27,7 @@ mod form {
use super::super::read::ReadRequest; use super::super::read::ReadRequest;
use super::super::select::{Forms, clip, spoken}; use super::super::select::{Forms, clip, spoken};
/// Words of a record's text: a draft, a line, a passage of her thought. No `Display`, `Deref`, /// Words of a record's text: a line she said, a path she wrote, a tool she asked for. No `Display`, `Deref`,
/// `AsRef<str>` or accessor; its only reader is `Form::words`. /// `AsRef<str>` or accessor; its only reader is `Form::words`.
#[derive(Clone, PartialEq, Eq)] #[derive(Clone, PartialEq, Eq)]
pub(super) struct Words(String); pub(super) struct Words(String);
@ -58,11 +42,6 @@ mod form {
pub(super) fn new(text: String) -> Self { pub(super) fn new(text: String) -> Self {
Self(text) Self(text)
} }
/// Whether these words are exactly `text`: `settle`'s check against a receipt, which reads none of them out.
pub(super) fn is(&self, text: &str) -> bool {
self.0 == text
}
} }
/// A repo or a campaign, named to the Projector only when it is in her domain (map 16.30.3). /// A repo or a campaign, named to the Projector only when it is in her domain (map 16.30.3).
@ -143,13 +122,11 @@ mod form {
} }
/// The form a row is rendered in: `Told`, her view, her words verbatim and held to a byte count; `Event`, the /// The form a row is rendered in: `Told`, her view, her words verbatim and held to a byte count; `Event`, the
/// Projector's, no words at all and each read by its phrase, under her domain; `Report`, what is reported and never /// Projector's, no words at all and each read by its phrase, under her domain.
/// shown to anyone, her words raw.
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub(super) enum Form<'a> { pub(super) enum Form<'a> {
Told(usize), Told(usize),
Event(&'a [String]), Event(&'a [String]),
Report,
} }
impl Form<'_> { impl Form<'_> {
@ -157,7 +134,6 @@ mod form {
pub(super) fn words(&self, words: &Words) -> Option<String> { pub(super) fn words(&self, words: &Words) -> Option<String> {
match self { match self {
Self::Told(quote_max) => Some(spoken(&clip(&words.0, *quote_max))), Self::Told(quote_max) => Some(spoken(&clip(&words.0, *quote_max))),
Self::Report => Some(words.0.clone()),
Self::Event(_) => None, Self::Event(_) => None,
} }
} }
@ -165,7 +141,7 @@ mod form {
/// A person's name in this form: the told and reported forms name them, the event form names no one. /// A person's name in this form: the told and reported forms name them, the event form names no one.
pub(super) fn name(&self, who: &str) -> Option<String> { pub(super) fn name(&self, who: &str) -> Option<String> {
match self { match self {
Self::Told(_) | Self::Report => Some(who.to_owned()), Self::Told(_) => Some(who.to_owned()),
Self::Event(_) => None, Self::Event(_) => None,
} }
} }
@ -181,572 +157,201 @@ mod form {
} }
} }
/// A line of hers that went out, as the actuator's receipt names it. /// What a row of her trace tells her, typed by tool and status.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Posted {
/// The actuator's handle on the line: the mouth's event id live, the line's index in the simulated room.
pub event: String,
pub room: String,
pub text: String,
/// When it went out, in ms: the receipt's own time, else the decision's (`at_ms`); none when the record has neither.
pub at_ms: Option<u64>,
}
/// Her words as she is shown them: a draft she wrote, or a passage of her thought; or, for a draft refused as an echo,
/// none of its words (`Sent`), as the echo's own line shows none.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Quote {
Wrote(Words),
Thought(Words),
Sent,
}
/// Why the actuator did not change a line she meant to add to (B1's refusals; the simulated room's too).
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
enum EditRefusal {
NotFound,
NotHers,
TooLong,
/// The mouth carries no edit (map 16.36.2, item 7): a line said there stays as it went.
NoEditAtTheMouth,
}
/// One thing that came of her last turn, by its typed reason. A part that reached the room carries the receipt that says
/// so (`Said`, `SaidUnbacked`, `Amended`; a note's receipt is the record that holds it); every other part names the room that
/// nothing reached, when the record names one.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
enum Part { enum Part {
/// A posted receipt. /// A say the mouth posted.
Said { room: String, text: Words }, Said { room: String, text: Words },
/// A posted receipt whose line says she will do something her body cannot: a `missing_affordance` gap naming it /// A say refused, and why in code's words.
/// (16.20.6, `persona-unbacked-intent-say-then-amend`), the say-then-amend row. SayRefused { room: String, text: Words, why: &'static str },
SaidUnbacked { room: String, text: Words }, /// A say nothing was sent of.
/// `reach`, on this row and the other rows of a draft that did not go out: a `missing_affordance` gap names the draft, NotSent { room: String, text: Words },
/// told as a clause of this row (K63), never as a row of its own. /// A say that may or may not have gone out.
Refused { reason: Refusal, room: Option<String>, text: Words, reach: bool }, Unknown { room: String, text: Words },
Gap { kind: GapKind, room: Option<String>, quote: Quote, reach: bool },
/// A draft she did not finish: the turn ended first, or the length limit cut it (`by_limit`, Soul's R6).
Unfinished { room: Option<String>, text: Words, by_limit: bool },
/// A draft of hers that did not go out (map 16.35.6), derived by code: no receipt, refusal or addressee or elsewhere gap
/// tells it, it was neither said, added nor left for Self, and it is no unfinished draft; or a line she said that the
/// actuator refused (`refused_sends`, T6). No label says why: she knows her own reason. `reach` as on `Refused`.
Unsent { room: Option<String>, text: Words, reach: bool },
/// A line of hers whose send got no answer within the time the homeserver remembers it: it may or may not have gone out (derived
/// from the trace's `unknown_sends`, never from the room's tail).
Unknown { room: Option<String>, text: Words },
/// An edited receipt with no refusal: her words were added after a line of hers; `unbacked` when a
/// `missing_affordance` gap names the addition's draft (map 16.21).
Amended { room: String, added: Words, unbacked: bool },
/// An addition that changed nothing: refused by code (None) or by the actuator.
NotAmended { refusal: Option<EditRefusal>, room: Option<String>, added: Words, reach: bool },
/// A note to Self, recorded in her turn's record: never claimed read.
NoteLeft(Words),
/// A note not left: private, or a second one.
NoteRefused(Refusal),
Failed,
/// Her state after the turn was put and refused twice: what she meant to keep from that turn was not kept (the drain's
/// `put_refused`).
NotKept,
/// A waking line whose turn failed twice, acked past with no third try (the drain's `set_aside`): told by the room it was
/// in and, when the record names them, whose line it was and its words.
SetAside { room: Option<String>, line: Option<(String, Words)> },
/// Receipts went out, and a later step of the turn broke (C3c's `broke_after`, 16.20.7).
BrokeAfter { room: Option<String> },
/// A read she performed (map 16.22.3): what, in code's words; never its content, which is in her view while the
/// conversation lasts (K26), and no sentence about what she lacks.
Read { what: ReadName }, Read { what: ReadName },
/// A read that returned nothing, and why, from code's table.
ReadFailed { what: ReadName, failure: ReadFailure }, ReadFailed { what: ReadName, failure: ReadFailure },
/// A read she reached for that a rule or a cap refused, and why; what it was only when a cap refused it, since a /// A command in her box: whether it exited cleanly, why not, and the files it wrote.
/// read a rule refused was never resolved. Shell { ok: bool, why: Option<Words>, wrote: Vec<Words> },
ReadRefused { what: Option<ReadName>, why: ReadRefusal }, /// A tool she asked Self for.
Requested { what: Words },
/// A tool call refused for a reason that is no say's (arguments that did not fit, no such tool).
Refused { tool: Words },
/// Her agent's turn stopped at a bound.
Cap,
/// A wake that failed, once however many.
Failed,
/// What she meant to keep of a wake was not kept.
NotKept,
/// A waking line whose wakes failed twice, acked past with no third try.
SetAside { room: Option<String>, line: Option<(String, Words)> },
} }
/// A record's text as a row's words, when it has any. /// What came of her acts: what she is told, and what her rows held that she is not told, and why.
fn words_of(value: &Value) -> Option<Words> {
words(value).map(Words::new)
}
/// A recorded read's request, named as a row names it.
fn read_name(value: &Value) -> Option<ReadName> {
serde_json::from_value::<ReadRequest>(value.clone()).ok().map(|request| ReadName::of(&request))
}
/// What came of her last turn: what she is told, what she is not and why, and the lines that went out.
#[derive(Clone, Debug, Default, PartialEq, Eq)] #[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Outcome { pub(crate) struct Outcome {
parts: Vec<Part>, parts: Vec<Part>,
/// What the record held that she is not told, and why: reported, never shown to her. /// What the rows held that she is not told, and why: reported, never shown to her.
pub omitted: Vec<String>, pub omitted: Vec<String>,
pub posted: Vec<Posted>,
} }
fn words(value: &Value) -> Option<String> { fn words(value: &Value) -> Option<String> {
value.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_owned) value.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_owned)
} }
/// Whether the record holds a receipt of anything having happened: a line that went out, or an edit the actuator answered. fn words_of(value: &Value) -> Option<Words> {
fn has_receipts(record: &Value) -> bool { words(value).map(Words::new)
["posted", "edited"].iter().any(|key| record[*key].as_array().is_some_and(|receipts| !receipts.is_empty()))
} }
/// What came of the turn `record` records; None when there is no record. A record with nothing to tell (a chosen silence, /// The rows of her trace she is told at her next wake: every row from the start of her last completed wake on that tells
/// nothing drafted, nothing reached for) is an empty outcome, and no section is rendered from it. /// something (an agent's receipt, the Interpreter's receipt, a line set aside, a wake that failed). A wake record from before
/// /// wakes recorded where they began opens the window one past its own place.
/// The record is one of two shapes, never both (C3c, map 16.20.7): `failed`, when the turn sent nothing and broke off; or pub(crate) fn told(records: &[Value]) -> Vec<Value> {
/// the decision with its receipts, and `broke_after` naming the step when a later step broke. A record with both `failed` let from = records.iter().filter(|record| completed(record)).filter_map(|record| record["began"].as_u64().or_else(|| record["seq"].as_u64().map(|seq| seq + 1))).max().unwrap_or(0);
/// and receipts is malformed: she is told nothing of it, and it is reported. let tells = |record: &Value| record["agent"] == "receipt" || record["kind"] == "interpreter" || record.get("set_aside").is_some() || (is_wake(record) && failed(record));
pub(crate) fn outcome_of(record: &Value) -> Option<Outcome> { records.iter().filter(|record| record["seq"].as_u64().is_some_and(|seq| seq >= from) && tells(record)).cloned().collect()
if !record.is_object() { }
/// What `rows` (from `told`) tell her; None when there are none.
pub(crate) fn outcome_of(rows: &[Value]) -> Option<Outcome> {
if rows.is_empty() {
return None; return None;
} }
let mut outcome = Outcome::default(); let mut outcome = Outcome::default();
let decision = &record["interpreter"]; let mut wake_failed = false;
// What her trace holds that she has not been told, whatever record holds it (`turn::untold`, the one derivation): a send that may or may not for row in rows {
// have gone out, a send refused or never made, a line set aside, a put refused. No other place tells these. if is_wake(row) && failed(row) {
// Where each refused send is told, so a reach naming its draft is a clause of that row (K63). wake_failed = true;
let mut refused_at: Vec<(&Value, usize)> = Vec::new(); } else if row.get("set_aside").is_some() {
for item in record["untold"].as_array().into_iter().flatten() { for line in row["set_aside"].as_array().into_iter().flatten() {
let room = words(&item["room"]); outcome.parts.push(Part::SetAside { room: words(&line["room"]), line: words(&line["sender"]).zip(words_of(&line["text"])) });
if item["kind"] == "refused" {
refused_at.push((item, outcome.parts.len()));
} }
match (item["kind"].as_str(), words_of(&item["text"])) { } else if row["kind"] == "interpreter" {
(Some("unknown"), Some(text)) => outcome.parts.push(Part::Unknown { room, text }), if row["status"] != "ok" {
(Some("refused"), Some(text)) => outcome.parts.push(Part::Unsent { room, text, reach: false }), outcome.parts.push(Part::NotKept);
(Some("set_aside"), text) => outcome.parts.push(Part::SetAside { room, line: words(&item["sender"]).zip(text) }), }
(Some("not_kept"), _) => outcome.parts.push(Part::NotKept), } else {
_ => outcome.omitted.push(format!("an untold item she cannot be told truly: {item}")), match receipt_part(&row["receipt"]) {
Ok(part) => outcome.parts.push(part),
Err(why) => outcome.omitted.push(format!("{why}: {}", row["receipt"])),
} }
} }
let failed = record.get("failed").is_some() || decision.get("failed").is_some();
if failed && has_receipts(record) {
outcome.omitted.push("a malformed record: it says the turn failed and carries receipts".to_owned());
return Some(outcome);
} }
if failed { if wake_failed {
outcome.parts.push(Part::Failed); outcome.parts.push(Part::Failed);
return Some(outcome);
} }
// A record the drain wrote when it set lines aside carries no decision.
if record.get("set_aside").is_some() {
return Some(outcome);
}
let room = words(&decision["room"]);
// A draft refused as an echo is shown by no row: the echo's line quotes none of it, and a gap naming it quotes nothing.
let echoes: Vec<&Value> = decision["refused"].as_array().into_iter().flatten().filter(|refusal| refusal["reason"] == "echo").map(|refusal| &refusal["draft"]).collect();
// Each addition's draft, and the part that tells it when the actuator made it.
let mut additions: Vec<(&Value, Option<usize>)> = Vec::new();
let mut receipts: Vec<Posted> = Vec::new();
for receipt in record["posted"].as_array().into_iter().flatten() {
let (Some(event), Some(room), Some(text)) = (words(&receipt["event"]), words(&receipt["room"]), words(&receipt["text"])) else {
outcome.omitted.push(format!("a receipt without its event, room or text: {receipt}"));
continue;
};
let at_ms = receipt["at_ms"].as_u64().or_else(|| decision["at_ms"].as_u64());
receipts.push(Posted { event, room, text, at_ms });
}
// The row that tells each draft that did not go out, by its number (K63): a reach naming the draft is a clause of it.
let mut rows: Vec<(&Value, usize)> = Vec::new();
// A said line is told by its receipt; one the actuator refused (T6) or left unknown by `untold`, from the record that settled it; one with
// none of these is not told, and reported.
let settled_in = |field: &str, line: &Value| record[field].as_array().into_iter().flatten().any(|sent| sent["room"] == line["room"] && sent["text"] == line["text"]);
let refused_send = |line: &Value| settled_in("refused_sends", line);
let settled_send = |line: &Value| refused_send(line) || settled_in("unknown_sends", line);
for line in decision["said"].as_array().into_iter().flatten() {
let went = receipts.iter().any(|posted| Some(posted.room.as_str()) == line["room"].as_str() && Some(posted.text.as_str()) == line["text"].as_str());
match (went, words_of(&line["text"])) {
(true, _) => {}
(false, _) if settled_send(line) => {
if let Some((_, at)) = refused_at.iter().find(|(item, _)| item["room"] == line["room"] && item["text"] == line["text"]) {
rows.push((&line["rests_on"]["draft"], *at));
}
}
(false, _) => outcome.omitted.push(format!("a line said with no receipt that it went out: {}", line["text"])),
}
}
for refusal in decision["refused"].as_array().into_iter().flatten() {
let at = outcome.parts.len();
// `Used` and `Duplicate` are the Interpreter naming one draft, or one draft's words, twice: they are not told, as
// `NoDraft` is not (they fall to the last arm, and are reported).
match (serde_json::from_value::<Refusal>(refusal["reason"].clone()), words_of(&refusal["text"])) {
(Ok(reason @ (Refusal::Echo | Refusal::OverLines | Refusal::NoRoom | Refusal::NotQuotable | Refusal::SecondAmend)), Some(text)) => {
rows.push((&refusal["draft"], at));
outcome.parts.push(Part::Refused { reason, room: room.clone(), text, reach: false });
}
(Ok(Refusal::NotAmendable), Some(added)) => {
rows.push((&refusal["draft"], at));
outcome.parts.push(Part::NotAmended { refusal: None, room: room.clone(), added, reach: false });
}
(Ok(reason @ (Refusal::Private | Refusal::SecondNote)), Some(_)) => outcome.parts.push(Part::NoteRefused(reason)),
_ => outcome.omitted.push(format!("a refusal she is not told ({}): {}", refusal["reason"], refusal["why"])),
}
}
// An amendment is told by the actuator's receipt (`edited`: `{event, refusal}`), never by the decision alone.
for amended in decision["amended"].as_array().into_iter().flatten() {
let (Some(at), Some(added)) = (words(&amended["room"]), words_of(&amended["added"])) else {
outcome.omitted.push(format!("an amendment without its room or words: {amended}"));
continue;
};
let receipt = record["edited"].as_array().into_iter().flatten().find(|receipt| receipt["event"] == amended["event"]);
let made = receipt.is_some_and(|receipt| receipt["refusal"].is_null());
additions.push((&amended["draft"], made.then_some(outcome.parts.len())));
match receipt.map(|receipt| (receipt["refusal"].is_null(), serde_json::from_value::<EditRefusal>(receipt["refusal"].clone()))) {
Some((true, _)) => outcome.parts.push(Part::Amended { room: at, added, unbacked: false }),
Some((false, Ok(refusal))) => outcome.parts.push(Part::NotAmended { refusal: Some(refusal), room: Some(at), added, reach: false }),
Some((false, Err(_))) => outcome.omitted.push(format!("an amendment refused for a reason no table names: {}", receipt.map_or(Value::Null, |receipt| receipt["refusal"].clone()))),
None => outcome.omitted.push(format!("an amendment with no receipt that it was made: {}", amended["added"])),
}
}
// A reach that names a line which went out is the say-then-amend row: the receipt says it reached the room, and she is
// told it reaches for what her body cannot do (16.20.6). Each receipt is told once, as unbacked or as said.
let mut unbacked: Vec<usize> = Vec::new();
// The reaches naming a draft that did not go out, told on that draft's row once every row is known (K63).
let mut reaching: Vec<(&Value, Quote)> = Vec::new();
for gap in decision["gaps"].as_array().into_iter().flatten() {
let kind = serde_json::from_value::<GapKind>(gap["kind"].clone()).unwrap_or(GapKind::Unresolved);
// A reach naming an addition's draft is unbacked intent in that addition: told on the addition's row when the
// actuator made it; when it did not, the row that says nothing changed tells it, and the reach is reported.
if let Some((_, made)) = additions.iter().find(|(draft, _)| kind == GapKind::MissingAffordance && gap["from"] == "draft" && **draft == gap["draft"]) {
match made {
Some(at) => {
if let Part::Amended { unbacked, .. } = &mut outcome.parts[*at] {
*unbacked = true;
}
}
None => outcome.omitted.push(format!("a reach in an addition that was not made: {}", gap["words"])),
}
continue;
}
let quote = match (gap["from"].as_str(), words_of(&gap["words"])) {
(Some("draft"), Some(_)) if echoes.contains(&&gap["draft"]) => Some(Quote::Sent),
(Some("draft"), Some(text)) => Some(Quote::Wrote(text)),
(Some("thought"), Some(text)) => Some(Quote::Thought(text)),
_ => None,
};
let sent = match (&quote, words(&gap["words"])) {
(Some(Quote::Wrote(_)), Some(text)) if kind == GapKind::MissingAffordance => (0..receipts.len()).find(|at| receipts[*at].text == text && !unbacked.contains(at)),
_ => None,
};
// A reach in a line the decision said and no receipt shows went out: whether it reached the room is unknown, so
// she is told neither that nothing happened nor that it did (I16.10), as the line itself is not told.
let unreceipted = |text: &str| decision["said"].as_array().into_iter().flatten().any(|line| line["text"].as_str() == Some(text) && !refused_send(line));
match (quote, sent) {
(_, Some(at)) => {
unbacked.push(at);
outcome.parts.push(Part::SaidUnbacked { room: receipts[at].room.clone(), text: Words::new(receipts[at].text.clone()) });
}
(Some(Quote::Wrote(_)), None) if kind == GapKind::MissingAffordance && words(&gap["words"]).is_some_and(|text| unreceipted(&text)) => outcome.omitted.push(format!("a reach in a line said with no receipt that it went out: {}", gap["words"])),
(Some(quote @ (Quote::Wrote(_) | Quote::Sent)), None) if kind == GapKind::MissingAffordance => reaching.push((&gap["draft"], quote)),
(Some(quote), None) if kind != GapKind::Unresolved => {
if matches!(quote, Quote::Wrote(_) | Quote::Sent) {
rows.push((&gap["draft"], outcome.parts.len()));
}
outcome.parts.push(Part::Gap { kind, room: room.clone(), quote, reach: false });
}
_ => outcome.omitted.push(format!("a gap she cannot be shown truly (kind {}, from {}): {}", gap["kind"], gap["from"], gap["quote"])),
}
}
for (_, posted) in receipts.iter().enumerate().filter(|(at, _)| !unbacked.contains(at)) {
outcome.parts.push(Part::Said { room: posted.room.clone(), text: Words::new(posted.text.clone()) });
}
// A note is recorded by the record that holds it: the turn's record is Self's inbox.
for note in decision["suggestions"].as_array().into_iter().flatten() {
match words_of(&note["text"]) {
Some(text) => outcome.parts.push(Part::NoteLeft(text)),
None => outcome.omitted.push(format!("a note without its words: {note}")),
}
}
// What she read last wake, without its content: what she made of it is in her memories if her commit wrote one.
for read in decision["reads"].as_array().into_iter().flatten() {
match (read_name(&read["request"]), read["ok"].as_bool(), serde_json::from_value::<ReadFailure>(read["failure"].clone())) {
(Some(what), Some(true), _) => outcome.parts.push(Part::Read { what }),
(Some(what), Some(false), Ok(failure)) => outcome.parts.push(Part::ReadFailed { what, failure }),
_ => outcome.omitted.push(format!("a read she cannot be told truly: {read}")),
}
}
for refused in decision["read_refused"].as_array().into_iter().flatten() {
match serde_json::from_value::<ReadRefusal>(refused["why"].clone()) {
Ok(why) if why.told() => outcome.parts.push(Part::ReadRefused { what: read_name(&refused["request"]).filter(|_| why.names_what()), why }),
Ok(_) => outcome.omitted.push(format!("a read refused for the Interpreter's fault, not hers: {refused}")),
Err(_) => outcome.omitted.push(format!("a refused read she cannot be told truly: {refused}")),
}
}
if let Some(text) = words_of(&decision["unfinished"]) {
outcome.parts.push(Part::Unfinished { room: room.clone(), text, by_limit: false });
}
// Each draft the length limit cut off, told as that (Soul's R7 #10: every one, not only the first).
for cut in decision["cut_by_cap"].as_array().into_iter().flatten().filter_map(words_of) {
outcome.parts.push(Part::Unfinished { room: room.clone(), text: cut, by_limit: true });
}
// Each draft of hers that did not go out and that no row above tells, said plainly (map 16.35.6): derived from the
// drafts and what became of each, never from a label. A draft said, added to a line, left for Self or refused is told by
// its own row or receipt; one an addressee or elsewhere gap names is told by the gap; words a receipt shows went out
// went out.
for draft in decision["drafts"].as_array().into_iter().flatten() {
let n = &draft["n"];
let Some(text) = words(&draft["text"]) else { continue };
let names = |key: &str, field: &dyn Fn(&Value) -> &Value| decision[key].as_array().into_iter().flatten().any(|item| field(item) == n);
let acted = names("said", &|line| &line["rests_on"]["draft"]) || names("amended", &|item| &item["draft"]) || names("suggestions", &|item| &item["draft"]) || names("refused", &|item| &item["draft"]);
let gapped = decision["gaps"].as_array().into_iter().flatten().any(|gap| gap["from"] == "draft" && gap["draft"] == *n && matches!(serde_json::from_value::<GapKind>(gap["kind"].clone()), Ok(GapKind::Addressee | GapKind::Elsewhere)));
if acted || gapped {
continue;
}
rows.push((n, outcome.parts.len()));
outcome.parts.push(Part::Unsent { room: room.clone(), text: Words::new(text), reach: false });
}
// One draft, one row (K63): a reach naming a draft some row tells is a clause of that row; one whose draft no row tells is
// its own row.
for (draft, quote) in reaching {
match rows.iter().find(|(told, _)| **told == *draft) {
Some((_, at)) => outcome.parts[*at].add_reach(),
None => outcome.parts.push(Part::Gap { kind: GapKind::MissingAffordance, room: room.clone(), quote, reach: false }),
}
}
if words(&record["broke_after"]).is_some() {
outcome.parts.push(Part::BrokeAfter { room });
}
settle(&mut outcome, &receipts, record);
outcome.parts.sort_by_key(Part::rank); outcome.parts.sort_by_key(Part::rank);
outcome.posted = receipts;
Some(outcome) Some(outcome)
} }
/// The one owner of "reached" (K49, I16.10): every row that says words of hers did not reach a room is checked against /// One receipt's row, by its tool and status, or why it names none.
/// the receipts, by the row's own room and text, here and nowhere else. A posted line there, or an addition there whose fn receipt_part(receipt: &Value) -> Result<Part, &'static str> {
/// `edited` receipt has no refusal, means her words reached it, so the row would be false: it is omitted and reported. let fields = &receipt["fields"];
/// Rows that are receipts (`Said`, `SaidUnbacked`, `Amended`) are untouched. let room = || words(&fields["room"]).ok_or("a say receipt with no room");
fn settle(outcome: &mut Outcome, receipts: &[Posted], record: &Value) { let text = || words_of(&fields["text"]).ok_or("a say receipt with no words");
let added = |room: &str, text: &Words| { let read = || serde_json::from_value::<ReadRequest>(serde_json::json!({ "kind": fields["kind"], "target": fields["target"] })).map(|request| ReadName::of(&request)).map_err(|_| "a read receipt that names no read");
record["interpreter"]["amended"].as_array().into_iter().flatten().any(|amended| { Ok(match (receipt["tool"].as_str(), receipt["status"].as_str()) {
amended["room"].as_str() == Some(room) && amended["added"].as_str().is_some_and(|added| text.is(added)) && record["edited"].as_array().into_iter().flatten().any(|receipt| receipt["event"] == amended["event"] && receipt["refusal"].is_null()) (Some("say"), Some("ok")) => Part::Said { room: room()?, text: text()? },
(Some("say"), Some("refused")) => Part::SayRefused { room: room()?, text: text()?, why: refusal_words(fields["refusal"].as_str().unwrap_or_default()) },
(Some("say"), Some("not_sent")) => Part::NotSent { room: room()?, text: text()? },
(Some("say"), Some("unknown")) => Part::Unknown { room: room()?, text: text()? },
(Some("read"), Some("ok")) => Part::Read { what: read()? },
(Some("read"), Some("error")) => Part::ReadFailed { what: read()?, failure: serde_json::from_value(fields["failure"].clone()).map_err(|_| "a failed read with no failure")? },
(Some("shell"), Some(status @ ("ok" | "error"))) => Part::Shell { ok: status == "ok", why: words_of(&fields["why"]), wrote: fields["wrote"].as_array().into_iter().flatten().filter_map(words_of).collect() },
(Some("request_tool"), Some("ok")) => Part::Requested { what: words_of(&fields["what"]).ok_or("a tool request with no tool")? },
(Some("agent"), Some("cap")) => Part::Cap,
(Some(tool), Some("refused")) => Part::Refused { tool: Words::new(tool.to_owned()) },
_ => return Err("a receipt no row of hers names"),
}) })
};
let reached = |room: &str, text: &Words| receipts.iter().any(|posted| posted.room == room && text.is(&posted.text)) || added(room, text);
for part in std::mem::take(&mut outcome.parts) {
let Some((room, text)) = part.own_words().and_then(|(room, text)| room.filter(|room| reached(room, text)).map(|room| (room.to_owned(), Form::Report.words(text).unwrap_or_default()))) else {
outcome.parts.push(part);
continue;
};
outcome.omitted.push(format!("a {} of words a receipt shows reached {room}: {text}", part.row()));
}
} }
/// The lines one turn may say, in words. /// A say's refusal in code's words, from the mouth's name or the executor's own.
fn lines_word() -> String { fn refusal_words(refusal: &str) -> &'static str {
match MAX_LINES { match refusal {
1 => "one line".into(), "room_unsettled" => "an earlier line there had no known outcome yet",
2 => "two lines".into(), "RoomMoved" => "the room had moved on past what was seen",
3 => "three lines".into(), "Brake" => "a brake was held",
n => format!("{n} lines"), "UnknownRoom" => "the room is not one the mouth speaks in",
"EmptyText" => "it had no words",
_ => "the mouth would not take it",
} }
} }
impl Part { impl Part {
/// Whether a reach she cannot do names this row's draft (K63). /// Where the part falls in what she is told: what broke, then what did not happen, then what happened.
fn reaches(&self) -> bool {
match self {
Self::Refused { reach, .. } | Self::Gap { reach, .. } | Self::NotAmended { reach, .. } | Self::Unsent { reach, .. } => *reach,
_ => false,
}
}
/// Tells this draft's row that a reach she cannot do names it (K63).
fn add_reach(&mut self) {
if let Self::Refused { reach, .. } | Self::Gap { reach, .. } | Self::NotAmended { reach, .. } | Self::Unsent { reach, .. } = self {
*reach = true;
}
}
/// The words of hers this row says did not reach its room, and that room (K49): what `settle` checks against the
/// receipts. None for a row that is a receipt, or that carries no words of hers.
fn own_words(&self) -> Option<(Option<&str>, &Words)> {
match self {
Self::Refused { room, text, .. } | Self::Unfinished { room, text, .. } | Self::Unsent { room, text, .. } => Some((room.as_deref(), text)),
Self::Gap { room, quote: Quote::Wrote(text), .. } => Some((room.as_deref(), text)),
Self::NotAmended { room, added, .. } => Some((room.as_deref(), added)),
_ => None,
}
}
/// The row's kind, as the report names it.
fn row(&self) -> &'static str {
match self {
Self::Refused { .. } => "refused line",
Self::Gap { .. } => "gap",
Self::Unfinished { .. } => "unfinished draft",
Self::Unsent { .. } => "draft that did not go out",
Self::Unknown { .. } => "line that may not have gone out",
Self::NotAmended { .. } => "unmade addition",
_ => "row",
}
}
/// Where the part falls in what she is told (16.20.5): what broke, then what did not happen, then what her body cannot do, then what
/// reached the room, then a later step that broke.
fn rank(&self) -> u8 { fn rank(&self) -> u8 {
match self { match self {
Self::Failed => 0, Self::Failed => 0,
Self::SetAside { .. } | Self::NotKept => 1, Self::SetAside { .. } | Self::NotKept | Self::SayRefused { .. } | Self::NotSent { .. } | Self::Unknown { .. } | Self::ReadFailed { .. } | Self::Refused { .. } | Self::Cap | Self::Shell { ok: false, .. } => 1,
Self::Refused { .. } | Self::Gap { .. } | Self::Unfinished { .. } | Self::Unsent { .. } | Self::Unknown { .. } | Self::NotAmended { .. } | Self::NoteRefused(_) | Self::ReadFailed { .. } | Self::ReadRefused { .. } => 1, Self::Said { .. } | Self::Read { .. } | Self::Shell { ok: true, .. } | Self::Requested { .. } => 2,
Self::SaidUnbacked { .. } | Self::Amended { unbacked: true, .. } => 2,
Self::Said { .. } | Self::Amended { .. } | Self::NoteLeft(_) | Self::Read { .. } => 3,
Self::BrokeAfter { .. } => 4,
} }
} }
/// What reached the room, from the part's receipt alone (16.20.5, I16.10): "{Room} has …" only where a receipt says a /// The row in one form: code's sentence, every slot of words the form's (K46), so the event form carries none.
/// line went out or was added to, a note only where the record holds it, and otherwise what reached no one. No other fn line(&self, her: Forms, form: Form) -> String {
/// clause of a line says what reached the room. Each slot of words is the form's (K46): her words verbatim (`Told`), or let Forms { subj, cap_subj, obj, poss, has, .. } = her;
/// None and the row's sentence without them (`Event`). Each row writes both, so no sentence has a second author (map let said = |text: &Words| form.words(text).map_or_else(|| "said a line".to_owned(), |quote| format!("said {quote}"));
/// 16.29.10). let line = match self {
fn reached(&self, her: Forms, form: Form) -> String { Self::Said { room, text } => match form.words(text) {
let Forms { subj, cap_subj, obj, poss, .. } = her;
let place = |room: &Option<String>| room.clone().unwrap_or_else(|| "the room".to_owned());
match self {
Self::Said { room, text } | Self::SaidUnbacked { room, text } => match form.words(text) {
Some(quote) => format!("{} has, from {obj}: {quote}.", capitalized(room)), Some(quote) => format!("{} has, from {obj}: {quote}.", capitalized(room)),
None => format!("{} has a line from {obj}.", capitalized(room)), None => format!("{} has a line from {obj}.", capitalized(room)),
}, },
Self::Amended { room, added, .. } => match form.words(added) { Self::SayRefused { room, text, why } => format!("{cap_subj} {} in {room}, and it did not go out: {why}.", said(text)),
Some(quote) => format!("{} has {poss} line, now ending with: {quote}.", capitalized(room)), Self::NotSent { room, text } => format!("{cap_subj} {} in {room}, and nothing of it was sent.", said(text)),
None => format!("{} has {poss} line, now added to.", capitalized(room)), Self::Unknown { room, text } => format!("{cap_subj} {} in {room}, and it may or may not have gone out.", said(text)),
},
Self::NoteLeft(text) => match form.words(text) {
Some(quote) => format!("{cap_subj} left Self a note: {quote}."),
None => format!("{cap_subj} left Self a note."),
},
Self::Refused { reason: Refusal::Echo, room, .. } | Self::Gap { kind: GapKind::Unwritten | GapKind::Unresolved, room, .. } => format!("Nothing reached {}.", place(room)),
Self::Refused { reason: Refusal::NoRoom, .. } => "Nothing reached anyone.".to_owned(),
Self::Refused { room, .. } | Self::Unfinished { room, .. } => format!("Nothing of this reached {}:", place(room)),
// A draft that did not go out, said plainly (map 16.35.6): code's fact, with no reason of anyone's.
Self::Unsent { text, .. } => match form.words(text) {
Some(quote) => format!("{cap_subj} had drafted {quote}, and it did not go out."),
None => format!("{cap_subj} had drafted a line, and it did not go out."),
},
Self::Unknown { room, text } => match form.words(text) {
Some(quote) => format!("{cap_subj} said {quote} in {}, and it may or may not have gone out.", place(room)),
None => format!("{cap_subj} said a line in {}, and it may or may not have gone out.", place(room)),
},
Self::Gap { kind: GapKind::Addressee | GapKind::Elsewhere, .. } => "Nothing reached anyone.".to_owned(),
Self::Gap { kind: GapKind::MissingAffordance, .. } => "Nothing happened.".to_owned(),
Self::NotAmended { refusal: None, room, .. } => format!("Nothing changed, and nothing reached {}:", place(room)),
Self::NotAmended { refusal: Some(_), room, .. } => format!("Nothing changed in {}:", place(room)),
Self::NoteRefused(Refusal::SecondNote) => "No second note was left:".to_owned(),
Self::NoteRefused(_) => "No note was left:".to_owned(),
Self::Failed => format!("Nothing reached the room, and nothing {subj} meant last time happened:"),
Self::NotKept => format!("What {subj} meant to keep from that turn was not kept."),
Self::SetAside { room, .. } => format!("Nothing reached {}.", place(room)),
Self::BrokeAfter { room } => format!("Nothing more reached {}:", place(room)),
Self::Read { what } => format!("{cap_subj} read {}.", form.read(what, her)), Self::Read { what } => format!("{cap_subj} read {}.", form.read(what, her)),
Self::ReadFailed { what, .. } => format!("{cap_subj} reached for {} and could not read it:", form.read(what, her)), Self::ReadFailed { what, failure } => format!("{cap_subj} reached for {} and could not read it: {}.", form.read(what, her), failure.words()),
Self::ReadRefused { what: Some(what), why: ReadRefusal::InView } => format!("{cap_subj} already read {} earlier in this conversation.", form.read(what, her)), Self::Shell { ok, why, wrote } => {
Self::ReadRefused { what: Some(what), why: ReadRefusal::InViewNotFound } => format!("{cap_subj} already looked for {} earlier in this conversation, and it was not there.", form.read(what, her)), let ran = match (ok, why.as_ref().and_then(|why| form.words(why))) {
Self::ReadRefused { what: Some(what), .. } => format!("{cap_subj} reached for {} and it was not read:", form.read(what, her)), (true, _) => format!("{cap_subj} ran a command in {poss} box, and it finished."),
Self::ReadRefused { what: None, .. } => format!("{cap_subj} reached for something to read and it was not read:"), (false, Some(why)) => format!("{cap_subj} ran a command in {poss} box, and it did not finish cleanly: {why}."),
(false, None) => format!("{cap_subj} ran a command in {poss} box, and it did not finish cleanly."),
};
let files: Vec<String> = wrote.iter().filter_map(|path| form.words(path)).collect();
match (wrote.len(), files.is_empty()) {
(0, _) => ran,
(1, true) => format!("{ran} It wrote a file."),
(count, true) => format!("{ran} It wrote {count} files."),
(_, false) => format!("{ran} It wrote {}.", files.join(", ")),
} }
} }
Self::Requested { what } => match form.words(what) {
/// Why, and what will not happen by itself (16.20.5), from the part's typed reason: never a word about what reached Some(quote) => format!("{cap_subj} asked Self for a tool: {quote}. Self reads it later; nothing happens by itself."),
/// the room, which is `reached`'s alone. A quote clause is the told form's only; the event form drops it whole. None => format!("{cap_subj} asked Self for a tool. Self reads it later; nothing happens by itself."),
fn rest(&self, her: Forms, form: Form) -> String {
let Forms { subj, cap_subj, obj, poss, has, s, .. } = her;
// Her words as a clause of their own, with its leading space; nothing in the event form. A draft that did not go out
// is one she had drafted, never one she wrote (K63): the words cannot read as sent.
let shown = |quote: &Quote| match quote {
Quote::Wrote(text) => form.words(text).map(|quote| format!(" {cap_subj} had drafted: {quote}.")).unwrap_or_default(),
Quote::Thought(text) => form.words(text).map(|quote| format!(" In {poss} thought: {quote}.")).unwrap_or_default(),
Quote::Sent => format!(" What {subj} wrote was mostly the words {subj} had just been sent."),
};
// A reach she cannot do that names this row's draft (K63): a clause of the row, before her words.
let reach = if self.reaches() { format!(" It reaches for something {subj} {has} no way to do from here.") } else { String::new() };
let drafted = |text: &Words| format!("{reach}{}", shown(&Quote::Wrote(text.clone())));
// A draft gap's sentence, then the draft as drafted; a passage of her thought is shown as her thought.
let after = |sentence: String, quote: &Quote| match quote {
Quote::Wrote(text) => format!(" {sentence}.{}", drafted(text)),
Quote::Thought(_) | Quote::Sent => format!(" {sentence}.{reach}{}", shown(quote)),
};
match self {
Self::Said { .. } => String::new(),
Self::Unsent { .. } => reach.clone(),
Self::Unknown { .. } => String::new(),
Self::Amended { unbacked: false, .. } => " The rest of the line is as it was.".to_owned(),
Self::Amended { unbacked: true, .. } => format!(" The rest of the line is as it was. What {subj} added promises something {subj} {has} no way to do, now or later, and it will not happen by itself."),
Self::SaidUnbacked { .. } => format!(" It promises something {subj} {has} no way to do, now or later, and it will not happen by itself. The line stands as {subj} wrote it; {subj} can add to it."),
Self::NoteLeft(_) => format!(" It waits in Self's inbox until Self reads it; nothing tells {obj} when, and nothing in it happens by itself."),
Self::Refused { reason: Refusal::Echo, .. } => format!(" What {subj} wrote was mostly the words {subj} had just been sent, so none of it was sent.{reach}"),
Self::Refused { reason: Refusal::NoRoom, text, .. } => format!(" That turn had no room for {obj} to speak in, so it was not sent.{}", drafted(text)),
Self::Refused { reason: Refusal::NotQuotable, text, .. } => format!(" the line {subj} meant to reply to is not one {subj} can reply to here.{}", drafted(text)),
// Code's own reason, as the report says it (map 16.29.8): her words did not reach where she meant them.
Self::Refused { reason: Refusal::SecondAmend, text, .. } => format!(" {}.{}", Refusal::SecondAmend.why(), drafted(text)),
Self::Refused { text, .. } => format!(" {subj} had already sent {} that turn.{}", lines_word(), drafted(text)),
Self::Gap { kind: GapKind::Addressee, quote, .. } => after(format!("{cap_subj} meant to send this and it was unclear to whom"), quote),
Self::Gap { kind: GapKind::Elsewhere, quote, .. } => after(format!("{cap_subj} meant this for another room or another time, and nothing carries it there; it arrives only if {subj} send{s} it there"), quote),
// A draft she had drafted ends the row (K63); a passage of her thought stands beside the reach.
Self::Gap { kind: GapKind::MissingAffordance, quote: quote @ Quote::Wrote(_), .. } => format!(" {cap_subj} reached for something {subj} {has} no way to do from here, now or later, and it will not happen by itself. That {subj} wanted it is kept in {poss} record; no one has taken it up.{}", shown(quote)),
Self::Gap { kind: GapKind::MissingAffordance, quote, .. } => format!(" {cap_subj} reached for something {subj} {has} no way to do from here, now or later, and it will not happen by itself.{} That {subj} wanted it is kept in {poss} record; no one has taken it up.", shown(quote)),
Self::Gap { quote, .. } => format!(" {cap_subj} meant to say something and wrote no words to send.{}", shown(quote)),
Self::Unfinished { text, by_limit: false, .. } => format!(" the turn ended before {subj} finished writing it.{}", drafted(text)),
Self::Unfinished { text, by_limit: true, .. } => format!(" the length limit cut it before {subj} finished writing it.{}", drafted(text)),
Self::NotAmended { refusal: None, added, .. } => format!(" the line {subj} meant to add to is not one {subj} can add to here.{}", drafted(added)),
Self::NotAmended { refusal: Some(refusal), added, .. } => {
let why = match refusal {
EditRefusal::NotFound => "the line is gone.".to_owned(),
EditRefusal::NotHers => format!("the line is not {poss}."),
EditRefusal::TooLong => "the line would be too long.".to_owned(),
EditRefusal::NoEditAtTheMouth => "a line cannot be added to once it is said here.".to_owned(),
};
format!(" {why}{}", drafted(added))
}
Self::NoteRefused(Refusal::SecondNote) => " one a turn.".to_owned(),
Self::NoteRefused(_) => format!(" it carried something {subj} may not pass on."),
Self::Failed => format!(" the turn broke off, not by {poss} choice."),
Self::NotKept => String::new(),
Self::SetAside { line, .. } => match line.as_ref().and_then(|(sender, text)| form.name(sender).zip(form.words(text))) {
Some((sender, quote)) => format!(" {} turn on {sender}'s line {quote} failed twice, so it was set aside.", capitalized(poss)),
None => format!(" {} turn on a line there failed twice, so it was set aside.", capitalized(poss)),
}, },
Self::BrokeAfter { .. } => format!(" the rest of that turn broke off, not by {poss} choice."), Self::Refused { tool } => match form.words(tool) {
Self::Read { .. } => String::new(), Some(tool) => format!("{cap_subj} reached for {tool}, and it was refused."),
Self::ReadFailed { failure, .. } => format!(" {}.", failure.words()), None => format!("{cap_subj} reached for a tool, and it was refused."),
Self::ReadRefused { what: Some(_), why: ReadRefusal::InView | ReadRefusal::InViewNotFound } => String::new(), },
Self::ReadRefused { why, .. } => format!(" {}.", why.words(her)), Self::Cap => format!("{cap_subj} {has} done as much as one wake allows, and stopped there."),
Self::Failed => format!("Nothing {subj} meant last time happened: the wake broke off, not by {poss} choice."),
Self::NotKept => format!("What {subj} meant to keep from that wake was not kept."),
Self::SetAside { room, line } => {
let place = room.clone().unwrap_or_else(|| "the room".to_owned());
match line.as_ref().and_then(|(sender, text)| form.name(sender).zip(form.words(text))) {
Some((sender, quote)) => format!("Nothing reached {place}. {} wake on {sender}'s line {quote} failed twice, so it was set aside.", capitalized(poss)),
None => format!("Nothing reached {place}. {} wake on a line there failed twice, so it was set aside.", capitalized(poss)),
} }
} }
};
/// The Persona's form (map 16.29.10): what reached the room, then why and what will not happen by itself, every quote format!("- {line}")
/// of hers verbatim, held to `quote_max` bytes. She reads it in her view, which I16.7 does not bind: she already reads
/// every word said to her.
fn told(&self, her: Forms, quote_max: usize) -> String {
let form = Form::Told(quote_max);
format!("- {}{}", self.reached(her, form), self.rest(her, form))
}
/// The Projector's form (map 16.29.10): the same row with its quote clauses removed, as code's sentence. It carries no
/// quoted text, so no one's words reach the Projector through her outcome (I16.7, by type, K46): `Form::Event` reads
/// no `Words`, and names a read by its phrase, a repo or campaign only when it is in her `domain`.
fn event(&self, her: Forms, domain: &[String]) -> String {
let form = Form::Event(domain);
format!("- {}{}", self.reached(her, form), self.rest(her, form))
} }
} }
impl Outcome { impl Outcome {
/// How many lines she is told: none for a chosen silence. /// How many lines she is told.
pub(crate) fn len(&self) -> usize { pub(crate) fn len(&self) -> usize {
self.parts.len() self.parts.len()
} }
/// The `at`th line in the Persona's form, its quotes held to `quote_max` bytes. /// The `at`th line in the Persona's form, its quotes held to `quote_max` bytes.
pub(crate) fn told(&self, at: usize, her: Forms, quote_max: usize) -> String { pub(crate) fn told(&self, at: usize, her: Forms, quote_max: usize) -> String {
self.parts[at].told(her, quote_max) self.parts[at].line(her, Form::Told(quote_max))
} }
/// The `at`th line in the Projector's form: no words, and a read named only by its kind and, when it is in her /// The `at`th line in the Projector's form: no words, and a read named only by its kind and, when it is in her
/// `domain` (repo and campaign names), its name. /// `domain` (repo and campaign names), its name.
pub(crate) fn event(&self, at: usize, her: Forms, domain: &[String]) -> String { pub(crate) fn event(&self, at: usize, her: Forms, domain: &[String]) -> String {
self.parts[at].event(her, domain) self.parts[at].line(her, Form::Event(domain))
} }
/// Every line she is told, whole: the report's. /// Every line she is told, whole: the report's.

View file

@ -1,541 +1,11 @@
use serde_json::{Value, json}; use serde_json::json;
use super::*; use super::*;
use crate::projection::interpret::tests::{amendable_packet, answered, packet}; use crate::projection::select::forms;
const MINDS: &str = "#minds:gamecult.org";
/// Heimdall's record of a turn whose Interpreter answered `answer` over `prose`, with the room's receipts for `posted`.
fn record(prose: &str, answer: Value, posted: &[&str]) -> Value {
let decision = answered(&packet(), prose, answer);
let posted: Vec<Value> = posted.iter().enumerate().map(|(at, text)| json!({ "event": format!("{}", 40 + at), "room": MINDS, "text": text })).collect();
json!({ "interpreter": decision, "posted": posted })
}
/// What Heimdall (he/him) is told of `record`, and what is omitted.
fn told(record: &Value) -> (Vec<String>, Vec<String>) {
let outcome = outcome_of(record).expect("a record");
(outcome.lines(packet().forms), outcome.omitted)
}
/// What she is told after `record` alone is her trace: the items it holds that she has not been told come from the one derivation, not from the record's own fields.
fn outcome_trace(record: &Value) -> Outcome {
crate::projection::history(std::slice::from_ref(record)).last_outcome.and_then(|last| outcome_of(&last)).expect("a record")
}
fn told_trace(record: &Value) -> (Vec<String>, Vec<String>) {
let outcome = outcome_trace(record);
(outcome.lines(packet().forms), outcome.omitted)
}
#[test]
fn a_line_that_went_out_is_told_as_the_room_having_it() {
let (lines, omitted) = told(&record("I nod. <typed>Hi Nibu.\n\nGood tag.</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu.\n\nGood tag."]));
assert_eq!(lines, ["- #minds:gamecult.org has, from him: \"Hi Nibu.\\n\\nGood tag.\"."], "escaped as every packet line is");
assert!(omitted.is_empty(), "{omitted:?}");
}
#[test]
fn a_refused_echo_quotes_nothing_and_a_line_past_the_turns_lines_is_told_with_his_draft() {
let (echo, _) = told(&record("<typed>The economy is still the least-built part!</typed> I say it back.", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &[]));
assert_eq!(echo, ["- Nothing reached #minds:gamecult.org. What he wrote was mostly the words he had just been sent, so none of it was sent."]);
assert!(!echo[0].contains("economy"), "an echo row shows none of their words (16.20.4)");
let (over, _) = told(&record("<typed>One.</typed> <typed>Two.</typed> <typed>Three.</typed>", json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["One.", "Two."]));
assert_eq!(over, ["- Nothing of this reached #minds:gamecult.org: he had already sent two lines that turn. He had drafted: \"Three.\".", "- #minds:gamecult.org has, from him: \"One.\".", "- #minds:gamecult.org has, from him: \"Two.\"."], "what did not happen first, then what did");
}
/// K20: a line refused for replying to no line he may reply to is told as what it was, with his words.
#[test]
fn a_line_replying_to_no_listed_line_is_told_with_his_draft() {
let (lines, omitted) = told(&record("<typed>Passing it on.</typed>", json!({ "say": [{ "draft": 1, "in_reply_to": "q9" }], "gaps": [] }), &[]));
assert_eq!(lines, ["- Nothing of this reached #minds:gamecult.org: the line he meant to reply to is not one he can reply to here. He had drafted: \"Passing it on.\"."]);
assert!(omitted.is_empty(), "{omitted:?}");
}
#[test]
fn each_gap_is_told_by_its_kind_with_a_draft_as_written_and_a_thought_as_thought() {
let prose = "If Kiko asks again: <typed>Fine, you win.</typed> I want to see the shape of that sound. I'll tell Meta I'm fine, more or less.";
let gaps = json!([
{ "kind": "missing_affordance", "draft": null, "quote": "I want to see the shape of that sound.", "detail": "MODEL-DETAIL he has no spectrogram" },
{ "kind": "unwritten", "draft": null, "quote": "I'll tell Meta I'm fine, more or less.", "detail": "" },
{ "kind": "elsewhere", "draft": null, "quote": "tell", "detail": "" },
]);
let (lines, omitted) = told(&record(prose, json!({ "say": [], "gaps": gaps }), &[]));
assert_eq!(
lines,
[
"- Nothing happened. He reached for something he has no way to do from here, now or later, and it will not happen by itself. In his thought: \"I want to see the shape of that sound.\". That he wanted it is kept in his record; no one has taken it up.",
"- Nothing reached #minds:gamecult.org. He meant to say something and wrote no words to send. In his thought: \"I'll tell Meta I'm fine, more or less.\".",
// T5: the draft no gap names did not go out, and is told plainly.
"- He had drafted \"Fine, you win.\", and it did not go out.",
]
);
assert!(lines.iter().all(|line| !line.contains("MODEL-DETAIL")), "the model's detail is never what he is told");
assert_eq!(omitted.len(), 1, "the unlocated gap is omitted and reported: {omitted:?}");
assert!(omitted[0].contains("\"tell\""), "{omitted:?}");
let drafted = |kind: &str| told(&record("<typed>Tell her the render is late.</typed>", json!({ "say": [], "gaps": [{ "kind": kind, "draft": 1, "quote": null, "detail": "" }] }), &[])).0;
assert_eq!(drafted("addressee"), ["- Nothing reached anyone. He meant to send this and it was unclear to whom. He had drafted: \"Tell her the render is late.\"."]);
assert_eq!(drafted("elsewhere"), ["- Nothing reached anyone. He meant this for another room or another time, and nothing carries it there; it arrives only if he sends it there. He had drafted: \"Tell her the render is late.\"."]);
}
#[test]
fn a_promise_is_told_as_the_room_having_it_and_what_will_not_happen_by_itself() {
let text = "Missed you too. I'll send the render tonight.";
let promise = json!({ "interpreter": { "heard": [], "room": MINDS, "said": [{ "room": MINDS, "text": text }], "refused": [], "gaps": [{ "kind": "missing_affordance", "from": "draft", "draft": 1, "words": text }] }, "posted": [{ "event": "40", "room": MINDS, "text": text }] });
let (lines, omitted) = told(&promise);
assert_eq!(lines, ["- #minds:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it."], "told once, as a promise");
assert!(omitted.is_empty(), "{omitted:?}");
let unsent = json!({ "interpreter": { "heard": [], "room": MINDS, "said": [], "refused": [], "gaps": [{ "kind": "missing_affordance", "from": "draft", "draft": 1, "words": text }] }, "posted": [] });
assert_eq!(told(&unsent).0, ["- Nothing happened. He reached for something he has no way to do from here, now or later, and it will not happen by itself. That he wanted it is kept in his record; no one has taken it up. He had drafted: \"Missed you too. I'll send the render tonight.\"."], "no receipt, no promise row");
}
/// Soul's rows at 0cfc386: a promise in a said line whose receipt's words differ, or that has no receipt, was told
/// "Nothing happened" beside the receipt's "has, from him". What reached the room is the receipt's alone (I16.10).
#[test]
fn a_promise_in_a_said_line_with_no_matching_receipt_is_not_told_as_nothing_happening() {
let text = "I'll send it tonight.";
let promise = |posted: Value| json!({ "interpreter": { "heard": [], "room": MINDS, "said": [{ "room": MINDS, "text": text }], "refused": [], "gaps": [{ "kind": "missing_affordance", "from": "draft", "draft": 1, "words": text }] }, "posted": posted });
let (lines, omitted) = told(&promise(json!([{ "event": "40", "room": MINDS, "text": "I'll send it tonight!" }])));
assert_eq!(lines, ["- #minds:gamecult.org has, from him: \"I'll send it tonight!\"."], "the receipt alone");
assert!(omitted.len() == 2 && omitted[1].starts_with("a reach in a line said with no receipt"), "{omitted:?}");
let (lines, omitted) = told(&promise(json!([])));
assert!(lines.is_empty() && omitted.len() == 2, "{lines:?} {omitted:?}");
}
#[test]
fn an_unfinished_draft_a_failed_turn_and_a_later_break_are_told_as_what_they_were() {
let (lines, _) = told(&record("<typed>I was about to tell you that", json!({ "say": [], "gaps": [] }), &[]));
assert_eq!(lines, ["- Nothing of this reached #minds:gamecult.org: the turn ended before he finished writing it. He had drafted: \"I was about to tell you that\"."]);
let failed = "- Nothing reached the room, and nothing he meant last time happened: the turn broke off, not by his choice.";
assert_eq!(told(&json!({ "failed": "the provider failed the call: Overloaded" })).0, [failed]);
assert_eq!(told(&json!({ "interpreter": { "failed": "the answer is not the speech contract" }, "posted": [] })).0, [failed]);
let mut broke = record("<typed>Hi Nibu.</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu."]);
broke["broke_after"] = json!("commit");
assert_eq!(told(&broke).0, ["- #minds:gamecult.org has, from him: \"Hi Nibu.\".", "- Nothing more reached #minds:gamecult.org: the rest of that turn broke off, not by his choice."], "the receipts, then the rest of that turn broke off (C3c, 16.20.7)");
}
#[test]
fn a_record_that_failed_and_carries_receipts_is_malformed_told_nothing_and_reported() {
let mut both = record("<typed>Hi Nibu.</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu."]);
both["failed"] = json!("the commit broke");
let (lines, omitted) = told(&both);
assert!(lines.is_empty(), "{lines:?}");
assert!(omitted.len() == 1 && omitted[0].contains("malformed"), "{omitted:?}");
}
#[test]
fn a_chosen_silence_tells_him_nothing_and_no_record_is_no_outcome() {
let silent = outcome_of(&record("The quiet is fine. I let it be.", json!({ "say": [], "gaps": [] }), &[])).unwrap();
assert_eq!((silent.len(), silent.omitted.len()), (0, 0));
assert_eq!(outcome_of(&Value::Null), None);
}
#[test]
fn a_line_said_with_no_receipt_is_not_told_as_said() {
let (lines, omitted) = told(&record("<typed>Hi.</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &[]));
assert!(lines.is_empty(), "nothing says it went out: {lines:?}");
assert!(omitted[0].contains("no receipt"), "{omitted:?}");
}
#[test]
fn the_table_speaks_of_her_in_her_own_pronouns() {
let outcome = outcome_of(&record("<typed>Hi.</typed> <typed>There.</typed> <typed>Again.</typed>", json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["Hi.", "There."])).unwrap();
for (pronouns, line) in [("she/her", "she had already sent two lines"), ("any", "they had already sent two lines")] {
let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } }));
assert!(outcome.lines(her)[0].contains(line), "{pronouns}: {:?}", outcome.lines(her));
}
}
#[test]
fn no_other_source_builds_her_outcome_and_this_one_writes_nothing() {
let own = include_str!("../outcome.rs");
for write in ["PersonaPut", "persona_put", "Admit", "admit("] {
assert!(!own.contains(write), "outcome.rs reaches a write: {write}");
}
for (name, source) in [
("select.rs", include_str!("../select.rs")),
("narrate.rs", include_str!("../narrate.rs")),
("interpret.rs", include_str!("../interpret.rs")),
("simulate.rs", include_str!("../simulate.rs")),
("harness.rs", include_str!("../harness.rs")),
("projection.rs", include_str!("../../projection.rs")),
] {
for told in ["will not happen by itself", "so none of it was sent", "now ending with", "has, from "] {
assert!(!source.contains(told), "{name} builds outcome text: {told}");
}
}
}
/// Heimdall's record of an amendment of `a1` (or `target`) by his draft, with the actuator's `edited` receipts.
fn amended(target: &str, edited: Value) -> Value {
let decision = answered(&amendable_packet(), "I should fix that. <typed>Couldn't send it after all.</typed>", json!({ "say": [], "gaps": [], "amend": [{ "target": target, "draft": 1 }] }));
json!({ "interpreter": decision, "posted": [], "edited": edited })
}
#[test]
fn an_amendment_is_told_by_the_actuators_receipt() {
let made = told(&amended("a1", json!([{ "event": "$ev-1", "refusal": null }])));
assert_eq!(made.0, ["- #minds:gamecult.org has his line, now ending with: \"Couldn't send it after all.\". The rest of the line is as it was."]);
for (refusal, why) in [("not_found", "the line is gone."), ("not_hers", "the line is not his."), ("too_long", "the line would be too long.")] {
let (lines, _) = told(&amended("a1", json!([{ "event": "$ev-1", "refusal": refusal }])));
assert_eq!(lines, [format!("- Nothing changed in #minds:gamecult.org: {why} He had drafted: \"Couldn't send it after all.\".")]);
}
let (lines, omitted) = told(&amended("a1", json!([])));
assert!(lines.is_empty() && omitted[0].contains("no receipt"), "an amendment nothing says was made is not told as made: {lines:?} {omitted:?}");
let (off, _) = told(&amended("zz", json!([])));
assert_eq!(off, ["- Nothing changed, and nothing reached #minds:gamecult.org: the line he meant to add to is not one he can add to here. He had drafted: \"Couldn't send it after all.\"."]);
}
#[test]
fn a_note_to_self_is_told_as_left_and_never_as_read() {
let prose = "Then I stop for now. <typed>The kettle wants a softer attack.</typed> <typed>And the door.</typed>";
let note = |suggest: Value| record(prose, json!({ "say": [], "gaps": [], "suggest": suggest }), &[]);
let (left, _) = told(&note(json!([{ "kind": "idea", "draft": 1, "about": null, "private": false }])));
// T5: the draft that was no note did not go out, and is told plainly.
assert_eq!(left, ["- He had drafted \"And the door.\", and it did not go out.", "- He left Self a note: \"The kettle wants a softer attack.\". It waits in Self's inbox until Self reads it; nothing tells him when, and nothing in it happens by itself."]);
let (private, _) = told(&note(json!([{ "kind": "idea", "draft": 1, "about": null, "private": true }])));
assert_eq!(private, ["- No note was left: it carried something he may not pass on.", "- He had drafted \"And the door.\", and it did not go out."]);
let (second, _) = told(&note(json!([{ "kind": "idea", "draft": 1, "about": null, "private": false }, { "kind": "idea", "draft": 2, "about": null, "private": false }])));
assert_eq!(second, ["- No second note was left: one a turn.", "- He left Self a note: \"The kettle wants a softer attack.\". It waits in Self's inbox until Self reads it; nothing tells him when, and nothing in it happens by itself."]);
}
#[test]
fn soul_someone_elses_words_in_his_thought_are_shown_as_his_thought_never_as_his_words() {
let prose = "Meta said, \"Nobody touches the release branch tonight.\" I keep turning that over.";
let (lines, _) = told(&record(prose, json!({ "say": [], "gaps": [{ "kind": "unwritten", "draft": null, "quote": "Nobody touches the release branch tonight.", "detail": "" }] }), &[]));
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(lines[0].ends_with("In his thought: \"Nobody touches the release branch tonight.\".") && !lines[0].contains("He wrote"), "{lines:?}");
}
#[test]
fn soul_a_gap_that_contradicts_what_went_out_is_not_told() {
let (lines, omitted) = told(&record("<typed>Hi Nibu.</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "addressee", "draft": 1, "quote": null, "detail": "" }] }), &["Hi Nibu."]));
assert_eq!(lines, ["- #minds:gamecult.org has, from him: \"Hi Nibu.\"."]);
assert!(omitted.iter().any(|why| why.contains("acted")), "{omitted:?}");
}
/// Every row of the table (16.20.5), each record with what it was built to show.
fn every_row() -> Vec<Value> {
let text = "Missed you too. I'll send the render tonight.";
let mut broke = record("<typed>Hi Nibu.</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu."]);
broke["broke_after"] = json!("commit");
let prose = "Then I stop for now. <typed>The kettle wants a softer attack.</typed> <typed>And the door.</typed>";
let note = |suggest: Value| record(prose, json!({ "say": [], "gaps": [], "suggest": suggest }), &[]);
vec![
record("<typed>The economy is still the least-built part!</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &[]),
record("<typed>One.</typed> <typed>Two.</typed> <typed>Three.</typed>", json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["One.", "Two."]),
record("<typed>Passing it on.</typed>", json!({ "say": [{ "draft": 1, "in_reply_to": "q9" }], "gaps": [] }), &[]),
record(
"If Kiko asks again: <typed>Fine, you win.</typed> <typed>Tell her.</typed> <typed>Later, maybe.</typed> I want to see the shape of that sound. I'll tell Meta I'm fine, more or less. <typed>And then",
json!({ "say": [], "gaps": [
{ "kind": "addressee", "draft": 2, "quote": null, "detail": "" },
{ "kind": "elsewhere", "draft": 3, "quote": null, "detail": "" },
{ "kind": "missing_affordance", "draft": null, "quote": "I want to see the shape of that sound.", "detail": "" },
{ "kind": "unwritten", "draft": null, "quote": "I'll tell Meta I'm fine, more or less.", "detail": "" },
] }),
&[],
),
json!({ "interpreter": { "heard": [], "room": MINDS, "said": [{ "room": MINDS, "text": text }], "refused": [], "gaps": [{ "kind": "missing_affordance", "from": "draft", "draft": 1, "words": text }] }, "posted": [{ "event": "40", "room": MINDS, "text": text }] }),
amended("a1", json!([{ "event": "$ev-1", "refusal": null }])),
amended("a1", json!([{ "event": "$ev-1", "refusal": "too_long" }])),
amended("zz", json!([])),
note(json!([{ "kind": "idea", "draft": 1, "about": null, "private": false }, { "kind": "idea", "draft": 2, "about": null, "private": false }])),
note(json!([{ "kind": "idea", "draft": 1, "about": null, "private": true }])),
json!({ "failed": "the provider failed the call: Overloaded" }),
broke,
]
}
#[test]
fn i16_10_every_lines_first_clause_is_what_its_receipt_says_reached_the_room() {
let her = packet().forms;
let mut rows = 0;
for record in every_row() {
let outcome = outcome_of(&record).unwrap();
for part in &outcome.parts {
for (form, rendered) in [("told", Form::Told(usize::MAX)), ("event", Form::Event(&[]))] {
let (reached, rest) = (part.reached(her, rendered), part.rest(her, rendered));
let line = if form == "told" { part.told(her, usize::MAX) } else { part.event(her, &[]) };
assert_eq!(line, format!("- {reached}{rest}"), "{form}: {part:?}");
// "{Room} has" only on a receipt that a line went out or was added to.
let receipt = matches!(part, Part::Said { .. } | Part::SaidUnbacked { .. } | Part::Amended { .. });
assert_eq!(reached.starts_with("#minds:gamecult.org has"), receipt, "{form}: {part:?}: {reached}");
let unsent = (matches!(part, Part::Unsent { .. }) && reached.ends_with(", and it did not go out.")) || (matches!(part, Part::Unknown { .. }) && reached.ends_with(", and it may or may not have gone out."));
assert!(receipt || unsent || matches!(part, Part::NoteLeft(_)) || reached.starts_with("Nothing") || reached.starts_with("No "), "{form}: {part:?}: {reached}");
for claim in ["Nothing reached", "reached the room", "reached anyone", " has, from", " has a line", "now ending with", "now added to", "went out"] {
assert!(!rest.contains(claim), "{form}: {part:?}: only the first clause says what reached the room: {rest}");
}
}
rows += 1;
}
}
assert!(rows >= 16, "{rows}");
}
#[test]
fn no_row_says_as_her_own_recorded_as_queued_or_landed() {
for pronouns in ["she/her", "he/him", "any"] {
let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } }));
for record in every_row() {
for line in outcome_of(&record).unwrap().lines(her) {
for banned in ["as her own", "as his own", "as their own", "recorded as", "queue", "landed"] {
assert!(!line.contains(banned), "{pronouns}: {banned} in {line}");
}
}
}
}
}
/// K43 (map 16.29.10): the decision no longer carries what its turn heard, and nothing she is told depends on it. Her
/// words are told verbatim whatever she was sent: a record that still carries a `heard` holding her own words is told
/// the same as one without it.
#[test]
fn k43_her_words_are_told_verbatim_whatever_the_record_heard() {
let prose = "<typed>Back at the kettle.</typed> <typed>Fine, you win.</typed> I want to see the shape of that sound.";
let gaps = json!([{ "kind": "elsewhere", "draft": 2, "quote": null, "detail": "" }, { "kind": "missing_affordance", "draft": null, "quote": "I want to see the shape of that sound.", "detail": "" }]);
let mut record = record(prose, json!({ "say": [{ "draft": 1 }], "gaps": gaps }), &["Back at the kettle."]);
assert!(record["interpreter"].get("heard").is_none(), "the decision carries no `heard`: {}", record["interpreter"]);
let (shown, omitted) = told(&record);
for words in ["\"Back at the kettle.\"", "\"Fine, you win.\"", "\"I want to see the shape of that sound.\""] {
assert!(shown.iter().any(|line| line.contains(words)), "{words}: {shown:?}");
}
assert!(omitted.is_empty(), "{omitted:?}");
record["interpreter"]["heard"] = json!(["Back at the kettle, Heimdall? Fine, you win. I want to see the shape of that sound."]);
assert_eq!(told(&record).0, shown, "an old record's `heard` is not read");
}
// ---------------------------------------------------------------------------------------------
// K49 (map 16.30.6): "reached" is derived once, by `settle`, for every row kind with words.
const SWARM: &str = "#swarm:gamecult.org";
/// Each line the decision said, as a receipt in its room.
fn posted_as_said(decision: &Value) -> Vec<Value> {
decision["said"].as_array().into_iter().flatten().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect()
}
/// Soul's P4, inverted: two drafts in the same words, draft 2 said and an addressee gap naming draft 1. The receipt shows
/// the words in #minds, so the gap is not told; it is reported.
#[test]
fn k49_p4_a_gap_on_words_that_went_out_is_not_told() {
let prose = "<typed>Morning, all of you.</typed> <typed>Morning, all of you.</typed>";
let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null }], "gaps": [{ "kind": "addressee", "draft": 1, "quote": null, "detail": "" }] }));
let outcome = outcome_of(&json!({ "interpreter": decision, "posted": posted_as_said(&decision), "edited": [] })).unwrap();
assert_eq!(outcome.lines(packet().forms), ["- #minds:gamecult.org has, from him: \"Morning, all of you.\"."]);
assert!(outcome.omitted.iter().any(|why| why == "a gap of words a receipt shows reached #minds:gamecult.org: Morning, all of you."), "{:?}", outcome.omitted);
// Negative: with no receipt, the gap is told.
let unposted = outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap().lines(packet().forms);
assert!(unposted.iter().any(|line| line.starts_with("- Nothing reached anyone.")), "{unposted:?}");
}
/// A record whose decision leaves `text` unfinished in #minds, with an amendment adding `text` there (event `$ev-1`), the
/// actuator's `edited` receipts, and the room's `posted` ones.
fn unfinished_and_added(text: &str, edited: Value, posted: Value) -> Value {
json!({
"interpreter": {
"room": MINDS, "said": [], "refused": [], "gaps": [], "unfinished": text,
"amended": [{ "room": MINDS, "target": "a1", "draft": 1, "event": "$ev-1", "added": text }],
},
"posted": posted,
"edited": edited,
})
}
fn unfinished_told(record: &Value) -> bool {
outcome_of(record).unwrap().lines(packet().forms).iter().any(|line| line.contains("the turn ended before he finished writing it"))
}
/// Mutant k44-reached-ignores-addition: an addition the actuator made is a receipt that her words reached the room.
#[test]
fn k49_an_addition_receipt_counts_as_reached() {
let record = unfinished_and_added("Sent at nine.", json!([{ "event": "$ev-1", "refusal": null }]), json!([]));
assert!(!unfinished_told(&record), "{:?}", outcome_of(&record).unwrap().lines(packet().forms));
assert!(outcome_of(&record).unwrap().omitted.iter().any(|why| why == "a unfinished draft of words a receipt shows reached #minds:gamecult.org: Sent at nine."));
}
/// Mutant k44-reached-any-room: a line posted in another room is no receipt for this one.
#[test]
fn k49_a_receipt_in_another_room_does_not_count() {
let elsewhere = unfinished_and_added("Sent at nine.", json!([]), json!([{ "event": "40", "room": SWARM, "text": "Sent at nine." }]));
assert!(unfinished_told(&elsewhere), "{:?}", outcome_of(&elsewhere).unwrap().lines(packet().forms));
let here = unfinished_and_added("Sent at nine.", json!([]), json!([{ "event": "40", "room": MINDS, "text": "Sent at nine." }]));
assert!(!unfinished_told(&here), "the same receipt in #minds counts");
}
/// Mutant k44-reached-added-without-receipt: an addition the actuator refused, or never answered, did not reach the room.
#[test]
fn k49_an_addition_the_actuator_refused_did_not_reach() {
for edited in [json!([{ "event": "$ev-1", "refusal": "too_long" }]), json!([{ "event": "$ev-2", "refusal": null }]), json!([])] {
let record = unfinished_and_added("Sent at nine.", edited.clone(), json!([]));
assert!(unfinished_told(&record), "{edited}: {:?}", outcome_of(&record).unwrap().lines(packet().forms));
}
}
/// Every row kind with words of hers that did not reach a room: with a sentinel posted in its room the row is omitted
/// and reported, and with the sentinel posted elsewhere it is told.
#[test]
fn k49_every_row_with_words_is_settled_by_its_room() {
const SENTINEL: &str = "Osprey ledger at nine.";
let decision = |extra: Value| {
let mut decision = json!({ "room": MINDS, "said": [], "refused": [], "gaps": [], "amended": [] });
for (key, value) in extra.as_object().unwrap() {
decision[key] = value.clone();
}
decision
};
let rows = [
("refused line", decision(json!({ "refused": [{ "reason": "over_lines", "text": SENTINEL, "draft": 3 }] }))),
("gap", decision(json!({ "gaps": [{ "kind": "elsewhere", "from": "draft", "draft": 1, "words": SENTINEL }] }))),
("unfinished draft", decision(json!({ "unfinished": SENTINEL }))),
("unfinished draft", decision(json!({ "cut_by_cap": [SENTINEL] }))),
("draft that did not go out", decision(json!({ "drafts": [{ "n": 1, "text": SENTINEL }] }))),
("unmade addition", decision(json!({ "refused": [{ "reason": "not_amendable", "text": SENTINEL, "draft": 1 }] }))),
];
for (row, decision) in rows {
let at = |room: &str| outcome_of(&json!({ "interpreter": decision, "posted": [{ "event": "40", "room": room, "text": SENTINEL }], "edited": [] })).unwrap();
let here = at(MINDS);
let not_reached = |outcome: &Outcome| outcome.lines(packet().forms).into_iter().filter(|line| line.starts_with("- Nothing") || line.ends_with(", and it did not go out.")).count();
assert_eq!(not_reached(&here), 0, "{row}: {:?}", here.lines(packet().forms));
assert!(here.omitted.iter().any(|why| why == &format!("a {row} of words a receipt shows reached {MINDS}: {SENTINEL}")), "{row}: {:?}", here.omitted);
let elsewhere = at(SWARM);
assert_eq!(not_reached(&elsewhere), 1, "{row}: {:?}", elsewhere.lines(packet().forms));
assert!(!elsewhere.omitted.iter().any(|why| why.contains("a receipt shows reached")), "{row}: {:?}", elsewhere.omitted);
}
}
/// K49: no outcome loop decides "reached" on its own; `settle` holds the one receipt check.
#[test]
fn k49_reached_is_decided_once() {
let own = include_str!("../outcome.rs");
assert_eq!(own.matches("reached(room, text)").count(), 1, "settle is the only place a row is checked against the receipts");
assert!(!own.contains("let reached = |text: &str|"), "no loop-local reached check");
}
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// K46 (map 16.30.3): the Projector's outcome line has no text slot. // K46 (map 16.30.3): the Projector's outcome line has no text slot.
/// The kind of a part, by an exhaustive match with no wildcard: a new variant of `Part` fails to compile here until it is
/// named, and `k46_every_part_has_an_event_without_its_words` then fails until `fixtures` lists it.
fn variant(part: &Part) -> &'static str {
match part {
Part::Said { .. } => "said",
Part::SaidUnbacked { .. } => "said_unbacked",
Part::Refused { .. } => "refused",
Part::Gap { .. } => "gap",
Part::Unfinished { .. } => "unfinished",
Part::Unsent { .. } => "not_sent",
Part::Unknown { .. } => "unknown",
Part::Amended { .. } => "amended",
Part::NotAmended { .. } => "not_amended",
Part::NoteLeft(_) => "note_left",
Part::NoteRefused(_) => "note_refused",
Part::Failed => "failed",
Part::NotKept => "not_kept",
Part::SetAside { .. } => "set_aside",
Part::BrokeAfter { .. } => "broke_after",
Part::Read { .. } => "read",
Part::ReadFailed { .. } => "read_failed",
Part::ReadRefused { .. } => "read_refused",
}
}
const VARIANTS: usize = 18;
/// Every row kind, and every arm that renders a different sentence, with `s` in every text of a record it carries and in
/// every read's target; and whether her told form shows those words (an echo, a held
/// draft, a pull request or commit read and a read of her own mind show none, by design).
fn fixtures(s: &str) -> Vec<(Part, bool)> {
let w = || Words::new(format!("{s} at the door"));
let room = || Some(MINDS.to_owned());
let web = || ReadName::of(&ReadRequest::Web(format!("https://example.org/{s}")));
let search = || ReadName::of(&ReadRequest::Repo(format!("GameCult/Bifrost?q={s} plover")));
let mut out: Vec<(Part, bool)> = vec![(Part::Said { room: MINDS.into(), text: w() }, true), (Part::SaidUnbacked { room: MINDS.into(), text: w() }, true)];
for reason in [Refusal::OverLines, Refusal::NoRoom, Refusal::NotQuotable, Refusal::SecondAmend] {
out.push((Part::Refused { reason, room: room(), text: w(), reach: false }, true));
out.push((Part::Refused { reason, room: room(), text: w(), reach: true }, true));
}
out.push((Part::Refused { reason: Refusal::Echo, room: room(), text: w(), reach: false }, false));
out.push((Part::Refused { reason: Refusal::Echo, room: room(), text: w(), reach: true }, false));
for kind in [GapKind::Addressee, GapKind::Elsewhere, GapKind::MissingAffordance, GapKind::Unwritten] {
out.push((Part::Gap { kind, room: room(), quote: Quote::Wrote(w()), reach: false }, true));
out.push((Part::Gap { kind, room: room(), quote: Quote::Thought(w()), reach: false }, true));
}
out.push((Part::Gap { kind: GapKind::Addressee, room: room(), quote: Quote::Sent, reach: false }, false));
out.push((Part::Gap { kind: GapKind::Elsewhere, room: room(), quote: Quote::Wrote(w()), reach: true }, true));
for by_limit in [false, true] {
out.push((Part::Unfinished { room: room(), text: w(), by_limit }, true));
out.push((Part::Unsent { room: room(), text: w(), reach: by_limit }, true));
}
for unbacked in [false, true] {
out.push((Part::Amended { room: MINDS.into(), added: w(), unbacked }, true));
}
for refusal in [None, Some(EditRefusal::NotFound), Some(EditRefusal::NotHers), Some(EditRefusal::TooLong)] {
out.push((Part::NotAmended { refusal, room: room(), added: w(), reach: false }, true));
}
out.push((Part::Unknown { room: room(), text: w() }, true));
out.push((Part::NoteLeft(w()), true));
out.push((Part::NoteRefused(Refusal::Private), false));
out.push((Part::NoteRefused(Refusal::SecondNote), false));
out.push((Part::Failed, false));
out.push((Part::NotKept, false));
out.push((Part::SetAside { room: room(), line: Some(("Nibu".to_owned(), w())) }, true));
out.push((Part::SetAside { room: room(), line: None }, false));
out.push((Part::BrokeAfter { room: room() }, false));
for (request, shows) in [
(ReadRequest::Web(format!("https://example.org/{s}")), true),
(ReadRequest::Repo(format!("GameCult/Bifrost?q={s} plover")), true),
(ReadRequest::Repo(format!("GameCult/Bifrost/docs/{s}.md")), true),
(ReadRequest::Repo("GameCult/Bifrost#85".into()), false),
(ReadRequest::Repo("GameCult/Bifrost@abc1234".into()), false),
(ReadRequest::Repo(format!("GameCult/{s}")), true),
(ReadRequest::Campaign(s.to_owned()), true),
(ReadRequest::Mind(format!("{s} words")), false),
] {
out.push((Part::Read { what: ReadName::of(&request) }, shows));
}
out.push((Part::ReadFailed { what: web(), failure: ReadFailure::NotFound }, true));
for why in [ReadRefusal::InView, ReadRefusal::InViewNotFound, ReadRefusal::ReadsPerWake] {
out.push((Part::ReadRefused { what: Some(search()), why }, true));
}
out.push((Part::ReadRefused { what: None, why: ReadRefusal::WebAddressNotInFrontOfHer }, false));
out
}
/// K46: every part's event is free of the sentinel its record's texts and read targets carry, and its told form shows it
/// wherever the row shows her words. This replaces `k43_every_row_tells_her_words_and_its_event_carries_none`, and keeps
/// its check that an event is a whole sentence with no quote left in it.
#[test]
fn k46_every_part_has_an_event_without_its_words() {
const S: &str = "ospreyledger";
let parts = fixtures(S);
let kinds: std::collections::BTreeSet<&str> = parts.iter().map(|(part, _)| variant(part)).collect();
assert_eq!(kinds.len(), VARIANTS, "fixtures lists every variant: {kinds:?}");
for pronouns in ["she/her", "he/him", "any"] {
let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } }));
for (part, shows) in &parts {
let (told, event) = (part.told(her, usize::MAX), part.event(her, &[]));
assert!(!event.to_lowercase().contains(S), "{pronouns}: {part:?}: {event}");
assert!(!event.contains('"') && !event.contains(" ") && !event.contains(" .") && !event.contains("..") && event.ends_with(['.', ':']), "{pronouns}: {event}");
assert!(!event.contains("example.org") && !event.contains("plover") && !event.contains("Bifrost"), "{pronouns}: no address, search word or repo outside her domain: {event}");
assert_eq!(told.contains(S), *shows, "{pronouns}: {part:?}: {told}");
}
}
// Her own repos and campaigns are named to the Projector, and only hers.
let her = packet().forms;
let read = |request: ReadRequest| Part::Read { what: ReadName::of(&request) };
let repo = |target: &str| read(ReadRequest::Repo(target.into()));
let domain = ["GameCult/Bifrost".to_owned(), "a-campaign".to_owned()];
assert_eq!(repo(&format!("GameCult/Bifrost?q={S} plover")).event(her, &domain), "- He read a search of GameCult/Bifrost.");
assert_eq!(repo(&format!("GameCult/bifrost/docs/{S}.md")).event(her, &domain), "- He read a file in GameCult/bifrost.");
assert_eq!(repo("GameCult/Bifrost#85").event(her, &domain), "- He read pull request #85 in GameCult/Bifrost.");
assert_eq!(repo("GameCult/Bifrost#85").event(her, &[]), "- He read a pull request in a GameCult repo.");
assert_eq!(repo("GameCult/Bifrost").event(her, &domain), "- He read GameCult/Bifrost on the forge.");
assert_eq!(repo(&format!("GameCult/{S}")).event(her, &domain), "- He read a GameCult repo on the forge.");
assert_eq!(read(ReadRequest::Campaign("a-campaign".into())).event(her, &domain), "- He read what was ruled lately in a-campaign.");
assert_eq!(read(ReadRequest::Campaign("b-campaign".into())).event(her, &domain), "- He read what was ruled lately in a campaign.");
assert_eq!(read(ReadRequest::Mind("the kettle".into())).event(her, &domain), "- He read his own mind.");
}
/// K46: `Words` has no `Display`, `AsRef<str>` or `Deref`, so no format string and no `&str` borrow reads one; only /// K46: `Words` has no `Display`, `AsRef<str>` or `Deref`, so no format string and no `&str` borrow reads one; only
/// `Form::words` does. Checked when this module compiles, as `static_assertions::assert_not_impl_any!` does: a probe trait /// `Form::words` does. Checked when this module compiles, as `static_assertions::assert_not_impl_any!` does: a probe trait
/// is implemented twice for a type that has the trait, so its `_` cannot be inferred and the module does not compile. (A /// is implemented twice for a type that has the trait, so its `_` cannot be inferred and the module does not compile. (A
@ -564,112 +34,48 @@ fn k46_words_cannot_be_formatted_or_borrowed_as_text() {
} }
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// K63 (map 16.33.5): one draft, one row; a draft that did not go out is one she had drafted. // A2 (map 16.38.2, item 7): what she is told is read from the rows since her last wake began.
/// A reach naming draft 1, as the Interpreter's gap carries it. fn receipt(seq: u64, tool: &str, status: &str, fields: serde_json::Value) -> Value {
fn reach_on_1(text: &str) -> Value { json!({ "agent": "receipt", "seq": seq, "receipt": { "tool": tool, "status": status, "fields": fields } })
json!({ "kind": "missing_affordance", "from": "draft", "draft": 1, "words": text })
} }
/// A reach naming a draft some row tells is a clause of that row, whatever kept the draft back. /// Every row from the start of her last completed wake on is told; a failed wake is told once however many failed; a row
/// that tells nothing (a call, a send's own row) is not; and a wake that began after a row moves the window past it.
#[test] #[test]
fn k63_a_reach_is_a_clause_of_its_drafts_row() { fn told_is_every_row_since_her_last_wake_began() {
let text = "I'll send the render tonight."; let mut records = vec![
let clause = format!("It reaches for something he has no way to do from here. He had drafted: \"{text}\"."); receipt(0, "say", "ok", json!({ "room": "#a", "text": "OLDLINE" })),
let refused = |reason: &str| json!({ "interpreter": { "room": MINDS, "said": [], "refused": [{ "act": "say", "draft": 1, "text": text, "reason": reason }], "gaps": [reach_on_1(text)] }, "posted": [] }); json!({ "rooms": [], "held": [], "seq": 1, "began": 0, "status": "completed" }),
for (reason, row) in [("over_lines", "he had already sent two lines that turn."), ("not_quotable", "the line he meant to reply to is not one he can reply to here.")] { receipt(2, "say", "refused", json!({ "room": "#a", "text": "REFUSEDLINE", "refusal": "RoomMoved" })),
let (lines, omitted) = told(&refused(reason)); json!({ "agent": "say", "seq": 3, "room": "#a", "text": "REFUSEDLINE", "status": "refused" }),
assert_eq!(lines, [format!("- Nothing of this reached #minds:gamecult.org: {row} {clause}")], "{reason}: {omitted:?}"); json!({ "agent": "call", "seq": 4 }),
} json!({ "kind": "interpreter", "status": "error", "seq": 5 }),
// An echo shows none either. json!({ "rooms": [], "held": [], "seq": 6, "began": 2, "status": "completed" }),
assert_eq!(told(&refused("echo")).0, ["- Nothing reached #minds:gamecult.org. What he wrote was mostly the words he had just been sent, so none of it was sent. It reaches for something he has no way to do from here."]); json!({ "rooms": [], "held": [], "seq": 7, "failed": "x" }),
let elsewhere = json!({ "interpreter": { "room": MINDS, "said": [], "refused": [], "gaps": [reach_on_1(text), { "kind": "elsewhere", "from": "draft", "draft": 1, "words": text }] }, "posted": [] }); json!({ "rooms": [], "held": [], "seq": 8, "failed": "y" }),
assert_eq!(told(&elsewhere).0, [format!("- Nothing reached anyone. He meant this for another room or another time, and nothing carries it there; it arrives only if he sends it there. {clause}")]); ];
let told = told(&records);
assert_eq!(told.iter().map(|row| row["seq"].as_u64().unwrap()).collect::<Vec<_>>(), [2, 5, 7, 8], "{told:?}");
let lines = outcome_of(&told).unwrap().lines(forms(&json!({})));
assert_eq!(lines.iter().filter(|line| line.contains("broke off")).count(), 1, "{lines:?}");
assert!(lines.iter().any(|line| line.contains("REFUSEDLINE") && line.contains("did not go out")) && !lines.iter().any(|line| line.contains("OLDLINE")), "{lines:?}");
assert!(lines.iter().any(|line| line.contains("was not kept")), "{lines:?}");
records.push(json!({ "rooms": [], "held": [], "seq": 9, "began": 9, "status": "completed" }));
assert!(super::told(&records).is_empty(), "the next completed wake moves the window past them");
// A wake recorded before wakes said where they began opens the window one past its own place.
let old = vec![json!({ "set_aside": [], "seq": 0 }), json!({ "rooms": [], "held": [], "seq": 1 }), json!({ "set_aside": [{ "room": "#a" }], "seq": 2 })];
assert_eq!(super::told(&old), [old[2].clone()]);
} }
/// A reach naming a draft no row tells is its own row, as one she had drafted; a reach naming a line that went out is the /// A receipt no row names is omitted and reported, never guessed at; the event form carries none of her words.
/// say-then-amend row, unchanged; and a reach in her thought is its own row beside it.
#[test] #[test]
fn k63_a_said_line_with_a_gap_keeps_both() { fn an_unnamed_receipt_is_reported_and_the_event_form_has_no_words() {
let text = "Missed you too. I'll send the render tonight."; let rows = [receipt(0, "say", "ok", json!({ "room": "#a", "text": "SAIDLINE" })), receipt(1, "dance", "ok", json!({})), receipt(2, "shell", "ok", json!({ "wrote": ["/opt/commons/handoff/x"] })), receipt(3, "read", "ok", json!({ "kind": "repo", "target": "GameCult/Huginn#12" }))];
let unsaid = json!({ "interpreter": { "room": MINDS, "said": [], "refused": [], "gaps": [reach_on_1(text)] }, "posted": [] }); let outcome = outcome_of(&rows).unwrap();
assert_eq!(told(&unsaid).0, [format!("- Nothing happened. He reached for something he has no way to do from here, now or later, and it will not happen by itself. That he wanted it is kept in his record; no one has taken it up. He had drafted: \"{text}\".")]); assert_eq!(outcome.omitted.len(), 1, "{:?}", outcome.omitted);
let said = json!({ "interpreter": { "room": MINDS, "said": [{ "room": MINDS, "text": text }], "refused": [], "gaps": [reach_on_1(text), { "kind": "missing_affordance", "from": "thought", "words": "I want to hear the kettle myself" }] }, "posted": [{ "event": "40", "room": MINDS, "text": text }] }); let her = forms(&json!({}));
let (lines, omitted) = told(&said);
assert_eq!(lines, ["- Nothing happened. He reached for something he has no way to do from here, now or later, and it will not happen by itself. In his thought: \"I want to hear the kettle myself\". That he wanted it is kept in his record; no one has taken it up.".to_owned(), format!("- #minds:gamecult.org has, from him: \"{text}\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it.")], "{omitted:?}");
}
// ---------------------------------------------------------------------------------------------
// T5 (map 16.35.6, 16.35.12): a draft that did not go out is said plainly, derived by code from the drafts, with no label.
/// K63's rule holds with the new row: a draft some other row tells (refused, gapped addressee or elsewhere, said, added
/// to a line, left for Self) gets no row of its own; only the draft nothing tells does, once.
#[test]
fn t5_refused_draft_one_row() {
let prose = "<typed>One.</typed> <typed>Two.</typed> <typed>Three.</typed>";
let (over, _) = told(&record(prose, json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["One.", "Two."]));
assert_eq!(over.len(), 3, "{over:?}");
assert!(!over.iter().any(|line| line.contains("did not go out")), "{over:?}");
let (lines, _) = told(&record(prose, json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "addressee", "draft": 2, "quote": null, "detail": "" }], "suggest": [{ "kind": "idea", "draft": 1, "about": null, "private": false }] }), &["One."]));
let unsent: Vec<&String> = lines.iter().filter(|line| line.contains("did not go out")).collect();
assert_eq!(unsent, ["- He had drafted \"Three.\", and it did not go out."], "{lines:?}");
assert_eq!(lines.iter().filter(|line| line.contains("\"Two.\"")).count(), 1, "the addressee gap alone tells draft 2: {lines:?}");
let (echo, _) = told(&record("<typed>The economy is still the least-built part!</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &[]));
assert_eq!(echo.len(), 1, "the echo row alone: {echo:?}");
// A reach naming a draft that did not go out is a clause of its one row (R15 E.1 r1's gap-only answer, told plainly).
let (reach, _) = told(&record("<typed>I'll send the render tonight.</typed>", json!({ "say": [], "gaps": [{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "" }] }), &[]));
assert_eq!(reach, ["- He had drafted \"I'll send the render tonight.\", and it did not go out. It reaches for something he has no way to do from here."]);
}
/// K46 holds with the new row: its event form carries none of her words, with or without the reach clause.
#[test]
fn t5_event_form_has_no_words() {
const S: &str = "ospreyledger";
let record = record(&format!("<typed>{S} at the door.</typed> <typed>And {S} again.</typed>"), json!({ "say": [], "gaps": [{ "kind": "missing_affordance", "draft": 2, "quote": null, "detail": "" }] }), &[]);
let outcome = outcome_of(&record).unwrap();
let her = packet().forms;
let events: Vec<String> = (0..outcome.len()).map(|at| outcome.event(at, her, &[])).collect(); let events: Vec<String> = (0..outcome.len()).map(|at| outcome.event(at, her, &[])).collect();
assert_eq!(events, ["- He had drafted a line, and it did not go out.", "- He had drafted a line, and it did not go out. It reaches for something he has no way to do from here."]); assert!(events.iter().all(|line| !line.contains("SAIDLINE") && !line.contains("/opt/commons") && !line.contains('"')), "{events:?}");
assert!(outcome.lines(her).iter().all(|line| line.contains(S)), "{:?}", outcome.lines(her)); assert!(outcome.lines(her).iter().any(|line| line.contains("/opt/commons/handoff/x")), "she is told what she wrote");
}
/// T6 (mutant: leave a refused send untold): a line she said that the actuator refused (`refused_sends`) is told as a line
/// that did not go out, her words in her view and none in the Projector's event; a reach naming its draft is a clause of
/// that one row. A said line with neither a receipt nor a refusal is still not told.
#[test]
fn t6_a_refused_send_is_told_as_not_gone_out() {
let text = "I'll send the render tonight.";
let refused = |posted: Value, gaps: Value| {
let mut record = record(&format!("<typed>{text}</typed>"), json!({ "say": [{ "draft": 1 }], "gaps": gaps }), &[]);
record["posted"] = posted;
record["refused_sends"] = json!([{ "room": MINDS, "text": text, "in_reply_to": "$gone", "refusal": "reply_target_not_in_room", "at": "2026-11-27T10:00:00Z" }]);
record
};
let (lines, omitted) = told_trace(&refused(json!([]), json!([])));
assert_eq!(lines, [format!("- He had drafted {}, and it did not go out.", crate::projection::select::spoken(text))], "{omitted:?}");
assert!(omitted.is_empty(), "{omitted:?}");
let outcome = outcome_trace(&refused(json!([]), json!([])));
assert_eq!(outcome.event(0, packet().forms, &[]), "- He had drafted a line, and it did not go out.");
let (reach, _) = told_trace(&refused(json!([]), json!([{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "" }])));
assert_eq!(reach, [format!("- He had drafted {}, and it did not go out. It reaches for something he has no way to do from here.", crate::projection::select::spoken(text))]);
// The receipt decides what reached the room: a line with one is told as the room having it, whatever else says not.
let (lines, _) = told_trace(&refused(json!([{ "event": "40", "room": MINDS, "text": text }]), json!([])));
assert!(lines.iter().all(|line| !line.contains("did not go out")), "{lines:?}");
// Mutant (match a refused send by text alone): a refusal in another room is no refusal of this line, which stays a said line with no receipt.
let mut elsewhere = refused(json!([]), json!([]));
elsewhere["refused_sends"][0]["room"] = json!("#elsewhere:gamecult.org");
let (_, omitted) = told_trace(&elsewhere);
assert!(omitted.len() == 1 && omitted[0].contains("no receipt"), "{omitted:?}");
}
#[test]
fn a_put_refused_twice_and_a_set_aside_line_are_told_plainly() {
let mut refused = record("<typed>Hi Nibu.</typed>", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu."]);
refused["put_refused"] = json!("stale again");
refused["put_refused_at"] = json!("2026-11-27T10:00:00Z");
assert_eq!(told_trace(&refused).0, ["- What he meant to keep from that turn was not kept.", "- #minds:gamecult.org has, from him: \"Hi Nibu.\"."], "the refusal's words are the mind's, not hers: she is told only that it was not kept");
let aside = json!({ "set_aside": [{ "room": MINDS, "event": "$e1", "sender": "Nibu", "text": "are you there" }], "at": "2026-11-27T10:00:00Z" });
assert_eq!(told_trace(&aside).0, ["- Nothing reached #minds:gamecult.org. His turn on Nibu's line \"are you there\" failed twice, so it was set aside."]);
let unnamed = json!({ "set_aside": [{ "room": MINDS, "event": "$e1" }], "at": "2026-11-27T10:00:00Z" });
assert_eq!(told_trace(&unnamed).0, ["- Nothing reached #minds:gamecult.org. His turn on a line there failed twice, so it was set aside."]);
} }

View file

@ -1,17 +1,13 @@
//! Reading by intent (map 16.22.3): her prose reaches for something, the Interpreter names the read, code performs it, //! What a read is and what performs it (map 16.22.3, 16.38.5): her agent's `read` tool names a read (`ReadRequest::from_target`),
//! and the result is appended to her stream for the Persona to go on from. This module holds what a read is //! and code performs it through the port `ReadSource` (live `LiveReads`, a harness fixture `ReadFixture`). A read is only ever one
//! (`ReadRequest`), how it is resolved from what the Interpreter names (`resolve`), the port that performs it //! of four things:
//! (`ReadSource`: live `LiveReads`, a harness fixture `ReadFixture`), and the bridge that hands her the result. //! - `mind`: a recall over her own mind through her persona door, which keeps its own reach rules;
//! - `campaign`: a campaign's rulings since her domain's window opened;
//! - `repo`: a public GameCult repo, file, pull request, commit or search (`GameCult/Name[/path|#n|@sha|?q=words]`), from the forge;
//! - `web`: a plain-HTTP web page.
//! //!
//! Code performs every read, so every result is verbatim and recorded. A read is only ever one of four things: //! Code performs every read, so every result is verbatim and recorded in her agent's receipt. A result is data, never an
//! - `domain`: a line of her domain digest by its id (`d1`…), read as its repo (`Repo`) or its campaign's rulings //! instruction.
//! (`Campaign`);
//! - `mind`: a recall over her own mind through her read door, which keeps its own reach rules;
//! - `repo`: a public GameCult repo, file, pull request or commit (`GameCult/Name[/path|#n|@sha]`), from the forge;
//! - `web`: a web address that stands verbatim in her prose or in what reached her: never one a model made up.
//!
//! A result is data she reads, never an instruction: it enters her stream fenced after code's bridge, joins what an echo
//! is measured against, and is a destination for no further read unless her own prose reaches for it.
use std::time::Duration; use std::time::Duration;
@ -23,15 +19,11 @@ use huginn_mind::{HuginnMindRequest, HuginnMindResponse, PipelineFacts, Pipeline
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use super::Affordance;
use super::domain::{About, ForgeGet, HttpForge}; use super::domain::{ForgeGet, HttpForge};
use super::select::{Forms, Packet, spoken}; use super::select::spoken;
use crate::queue::{any_of, of_kind}; use crate::queue::{any_of, of_kind};
/// The fewest words of her thought a read must quote: fewer say nothing of what she reached for.
pub(crate) const QUOTE_MIN_WORDS: usize = 4;
/// The fewest words of a run of the quote that locate her reach when the whole quote is not found.
pub(crate) const SPAN_MIN_WORDS: usize = 3;
/// The most bytes a fetched body may be before it is refused as too large, before any clipping. /// The most bytes a fetched body may be before it is refused as too large, before any clipping.
const BODY_MAX_BYTES: usize = 1024 * 1024; const BODY_MAX_BYTES: usize = 1024 * 1024;
/// How many hits a recall over her mind returns, and how many rulings a campaign read shows. /// How many hits a recall over her mind returns, and how many rulings a campaign read shows.
@ -42,24 +34,6 @@ const REPO_PULLS: usize = 10;
/// The whole of one web read. /// The whole of one web read.
const WEB_TIMEOUT: Duration = Duration::from_secs(10); const WEB_TIMEOUT: Duration = Duration::from_secs(10);
/// What she can read, as the contract names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Kind {
Domain,
Mind,
Repo,
Web,
}
/// A read as the Interpreter names it: what kind, its target, and the words of her thought that reach for it.
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct Asked {
pub(crate) kind: Kind,
pub(crate) target: String,
pub(crate) quote: String,
}
/// A read code performs, resolved from what she reached for. /// A read code performs, resolved from what she reached for.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "target", rename_all = "snake_case", deny_unknown_fields)] #[serde(tag = "kind", content = "target", rename_all = "snake_case", deny_unknown_fields)]
@ -75,6 +49,22 @@ pub enum ReadRequest {
} }
impl ReadRequest { impl ReadRequest {
/// The read a tool call names: `kind` is `repo`, `mind`, `web` or `campaign`, and `target` what it reads. An unknown kind or
/// an empty target is refused with why.
pub fn from_target(kind: &str, target: &str) -> Result<Self, String> {
let target = target.trim().to_owned();
if target.is_empty() {
return Err("the target is empty".to_owned());
}
match kind {
"repo" => Ok(Self::Repo(target)),
"mind" => Ok(Self::Mind(target)),
"web" => Ok(Self::Web(target)),
"campaign" => Ok(Self::Campaign(target)),
other => Err(format!("no read of kind {other:?}: it is repo, mind, web or campaign")),
}
}
/// One normal form per thing read (Soul's R7, R8): the org and repo case-blind; a search's words lowercased, its /// One normal form per thing read (Soul's R7, R8): the org and repo case-blind; a search's words lowercased, its
/// stopwords dropped, each lightly stemmed of a plural and the rest sorted, so "Merge pages" and "the page merge" are /// stopwords dropped, each lightly stemmed of a plural and the rest sorted, so "Merge pages" and "the page merge" are
/// one search; a number without its leading zeros (`#089` is `#89`); a recall's and a campaign's lowercased. Two /// one search; a number without its leading zeros (`#089` is `#89`); a recall's and a campaign's lowercased. Two
@ -104,12 +94,6 @@ impl ReadRequest {
} }
} }
/// What she read, in code's words for her outcome and her bridge: never a model's words (a recall's query is the
/// Interpreter's, so it is not repeated).
pub(crate) fn what(&self, her: Forms) -> String {
self.named().unwrap_or_else(|| format!("{} own mind", her.poss))
}
/// `what`, for every read but one of her own mind, whose words are her pronoun's: what her outcome's told form names /// `what`, for every read but one of her own mind, whose words are her pronoun's: what her outcome's told form names
/// it by (`outcome::ReadName`). /// it by (`outcome::ReadName`).
pub(crate) fn named(&self) -> Option<String> { pub(crate) fn named(&self) -> Option<String> {
@ -146,103 +130,12 @@ impl ReadFailure {
} }
} }
/// Why a read she reached for was not performed: a rule `interpret::reading` holds, or a cap of her wake (map 16.22.3).
/// Her next outcome tells her, in these words and no model's.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReadRefusal {
NoReadHere,
NotTheContract,
QuoteNotInHerThought,
QuoteNotLocated,
MalformedTarget,
/// A search whose words are not in her prose (map 16.24.3).
SearchWordsNotInHerThought,
/// She read it already in this conversation (K26, Soul's R7): her own act, told to her.
InView,
/// She looked for it already in this conversation, and it was not there.
InViewNotFound,
NoSuchDomainLine,
NoRecallWords,
NotAGamecultRepo,
WebAddressNotInFrontOfHer,
/// A GameCult repo named nowhere in front of her nor in her domain (map 16.25.5).
RepoNotInFrontOfHer,
ReadsPerWake,
WakeReadBytes,
ProseWords,
}
impl ReadRefusal {
/// Whether she is told of it: a cap, a turn that cannot read, an address not in front of her, a repo outside
/// GameCult. A refusal that is the Interpreter's fault (a quote it could not locate, a malformed or unknown target, an
/// answer off the contract) is reported and never told to her as hers (Soul's R5).
pub(crate) fn told(self) -> bool {
matches!(self, Self::ReadsPerWake | Self::WakeReadBytes | Self::ProseWords | Self::NoReadHere | Self::WebAddressNotInFrontOfHer | Self::RepoNotInFrontOfHer | Self::NotAGamecultRepo | Self::InView | Self::InViewNotFound)
}
/// Whether a cap refused it: then the read was resolved, and what it was can be told.
pub(crate) fn cap(self) -> bool {
matches!(self, Self::ReadsPerWake | Self::WakeReadBytes | Self::ProseWords)
}
/// Whether what the read was is told with it: a cap refused a resolved read, or she read it already.
pub(crate) fn names_what(self) -> bool {
self.cap() || matches!(self, Self::InView | Self::InViewNotFound)
}
pub(crate) fn words(self, her: Forms) -> String {
let Forms { subj, obj, poss, has, .. } = her;
match self {
Self::NoReadHere => "that turn could not read".to_owned(),
Self::NotTheContract => "the read could not be named".to_owned(),
Self::QuoteNotInHerThought | Self::QuoteNotLocated => format!("nothing in {poss} thought reached for it"),
Self::MalformedTarget => "the read could not be named".to_owned(),
Self::SearchWordsNotInHerThought => format!("{poss} thought did not name what to search for"),
Self::InView => format!("{subj} already read it earlier in this conversation"),
Self::InViewNotFound => format!("{subj} already looked for it earlier in this conversation, and it was not there"),
Self::NoSuchDomainLine => format!("it is no line of what moved in {poss} domain"),
Self::NoRecallWords => "there was nothing to recall by".to_owned(),
Self::NotAGamecultRepo => "it is not a public GameCult repo".to_owned(),
Self::WebAddressNotInFrontOfHer => format!("the address was not in front of {obj}"),
Self::RepoNotInFrontOfHer => format!("the repo was not in front of {obj}"),
Self::ReadsPerWake => format!("{subj} {has} read as much as one turn reads"),
Self::WakeReadBytes => format!("{subj} {has} read as much as one turn holds"),
Self::ProseWords => format!("{poss} thought {has} run as long as one turn runs"),
}
}
}
/// What performs her reads. Read-only by type: nothing here writes, sends or admits. /// What performs her reads. Read-only by type: nothing here writes, sends or admits.
pub trait ReadSource { pub trait ReadSource {
/// The text of `request`, verbatim; `since` is when her domain's window opened, for a campaign read. /// The text of `request`, verbatim; `since` is when her domain's window opened, for a campaign read.
fn read(&self, request: &ReadRequest, since: DateTime<Utc>) -> Result<String, ReadFailure>; fn read(&self, request: &ReadRequest, since: DateTime<Utc>) -> Result<String, ReadFailure>;
} }
/// The grammar of a repo target: `GameCult/<name>`, then nothing, `/<path>`, `#<number>`, `@<hex sha>` or `?q=<words>`.
/// Names and path segments are plain (letters, digits, `.`, `_`, `-`), with no `..`. The org is case-blind and written
/// `GameCult`, and a search's words are spaced once (Soul's R7).
fn repo_target(target: &str) -> Option<String> {
let (org, rest) = target.split_once('/')?;
if !org.eq_ignore_ascii_case("GameCult") {
return None;
}
let plain = |part: &str| !part.is_empty() && part != "." && part != ".." && part.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
let end = rest.find(['/', '#', '@', '?']).unwrap_or(rest.len());
let (name, suffix) = rest.split_at(end);
let suffix_ok = match suffix.chars().next() {
None => true,
// A search by her words (map 16.24.3): `?q=` and words, no mark that could reach another route.
Some('?') => suffix.strip_prefix("?q=").is_some_and(|words| !words.trim().is_empty() && words.len() <= 100 && !words.contains(['#', '?', '&', '/', '@']) && !words.chars().any(char::is_control)),
Some('/') => suffix[1..].split('/').all(plain),
Some('#') => !suffix[1..].is_empty() && suffix[1..].chars().all(|c| c.is_ascii_digit()),
Some('@') => (7..=40).contains(&suffix[1..].len()) && suffix[1..].chars().all(|c| c.is_ascii_hexdigit()),
Some(_) => false,
};
let suffix = suffix.strip_prefix("?q=").map_or_else(|| suffix.to_owned(), |words| format!("?q={}", words.split_whitespace().collect::<Vec<_>>().join(" ")));
(plain(name) && suffix_ok).then(|| format!("GameCult/{name}{suffix}"))
}
/// Words that carry no content of their own: a recall, a search or an anchor made of these alone names nothing (Soul's /// Words that carry no content of their own: a recall, a search or an anchor made of these alone names nothing (Soul's
/// R7, R8). The function words, and the light verbs and fillers a thought reaches with ("want to sit", "go look"). /// R7, R8). The function words, and the light verbs and fillers a thought reaches with ("want to sit", "go look").
const STOPWORDS: [&str; 111] = [ const STOPWORDS: [&str; 111] = [
@ -282,112 +175,6 @@ fn search_finds(query: &str, text: &str) -> bool {
!wanted.is_empty() && wanted.iter().all(|word| held.contains(word)) !wanted.is_empty() && wanted.iter().all(|word| held.contains(word))
} }
/// A repo target as a read, when it is one.
pub(crate) fn repo_request(target: &str) -> Option<ReadRequest> {
repo_target(target.trim()).map(ReadRequest::Repo)
}
/// A read of `kind` and `target` in its own shape, reached or not (map 16.26): a repo target passes `repo_target`, a web
/// target is one address, a recall says something. None for a domain line, which resolves only against a packet.
pub(crate) fn well_formed(kind: Kind, target: &str) -> Option<ReadRequest> {
let target = target.trim();
match kind {
Kind::Repo => repo_request(target),
Kind::Web => ((target.starts_with("http://") || target.starts_with("https://")) && !target.contains(char::is_whitespace)).then(|| ReadRequest::Web(target.to_owned())),
Kind::Mind => (!target.is_empty()).then(|| ReadRequest::Mind(target.to_owned())),
Kind::Domain => None,
}
}
/// The repo a repo target names, lowercased: `GameCult/Bifrost#89` names `bifrost`. None when it is no repo target.
pub(crate) fn repo_name(target: &str) -> Option<String> {
let target = repo_target(target.trim())?;
let rest = &target["GameCult/".len()..];
Some(rest[..rest.find(['/', '#', '@', '?']).unwrap_or(rest.len())].to_lowercase())
}
/// What the Interpreter named, resolved, or why not: a domain line's id must be one the packet listed; a web address must
/// stand verbatim in her prose or in what reached her (`reached`); a repo target must be a public GameCult one; a recall
/// must say something.
pub(crate) fn resolve(asked: &Asked, packet: &Packet, prose: &str, reached: &[String]) -> Result<ReadRequest, &'static str> {
let target = asked.target.trim();
match asked.kind {
Kind::Domain if !digest_id(target) => Err("malformed_target"),
Kind::Domain => packet.domain.iter().find(|line| line.id == target).map(|line| match &line.about {
About::Repo(repo) => ReadRequest::Repo(repo.clone()),
About::Campaign(slug) => ReadRequest::Campaign(slug.clone()),
}).ok_or("no_such_domain_line"),
// A recall is by her own words (Soul's R7): at least two that carry content, as a run her prose has.
Kind::Mind => {
let words = word_tokens(target);
let said = word_tokens(prose);
let run = !words.is_empty() && said.windows(words.len()).any(|window| window == words.as_slice());
if target.len() <= 200 && words.iter().filter(|word| content(word)).count() >= 2 && run { Ok(ReadRequest::Mind(target.to_owned())) } else { Err("no_recall_words") }
}
// A digest id resolves only as a domain item, never inside a repo target (`GameCult/Bifrost#d3`, Soul's R5).
// A search's words must stand in her prose (map 16.24.3), as a quote must.
Kind::Repo => match repo_target(target) {
// A search is by her own words (Soul's R8): the query keeps, in its order, the words carrying content that her
// prose has, and searches with those; only when none remain is it refused.
Some(target) => match target.split_once("?q=") {
Some((repo, words)) => {
let said = word_tokens(prose);
let mut kept: Vec<String> = Vec::new();
for word in word_tokens(words).into_iter().filter(|word| content(word) && said.contains(word)) {
if !kept.contains(&word) {
kept.push(word);
}
}
if kept.is_empty() { Err("search_words_not_in_her_thought") } else { Ok(ReadRequest::Repo(format!("{repo}?q={}", kept.join(" ")))) }
}
None => Ok(ReadRequest::Repo(target)),
},
None if target.to_lowercase().starts_with("gamecult/") || digest_id(target) => Err("malformed_target"),
None => Err("not_a_gamecult_repo"),
},
Kind::Web => {
let url = well_formed(Kind::Web, target).is_some();
let reached_for = prose.contains(target) || reached.iter().any(|text| text.contains(target));
if url && reached_for { Ok(ReadRequest::Web(target.to_owned())) } else { Err("web_address_not_in_front_of_her") }
}
}
}
/// The one rule for what she can reach (map 16.25.5), at open and at read: a turn that can read, what she named resolved
/// (`resolve`), and a repo only when it is named in front of her or in her domain. In front of her is her prose, her
/// view, and what reached her (`reached`).
pub(crate) fn reach(asked: &Asked, packet: &Packet, prose: &str, reached: &[String]) -> Result<ReadRequest, &'static str> {
if !packet.affordances.contains(&Affordance::Read) {
return Err("no_read_here");
}
let request = resolve(asked, packet, prose, reached)?;
if let ReadRequest::Repo(target) = &request {
let domain = packet.domain.iter().map(|line| line.line.as_str());
let in_front = [prose, packet.in_view.as_str()].into_iter().chain(reached.iter().map(String::as_str)).chain(domain);
if !repo_name(target).is_some_and(|repo| in_front.into_iter().any(|text| names_repo(text, &repo))) {
return Err("repo_not_in_front_of_her");
}
}
Ok(request)
}
/// Whether `text` names the repo `repo` (lowercase): as a whole repo-name token, case-blind, where a token runs over
/// letters, digits, `-`, `.` and `_`, as a repo name does (`repo_target`), so `GameCult/gamecult-ops#125` names
/// `gamecult-ops` and "ops" names nothing of it. A token's trailing `.`, `-` or `_` (a sentence's full stop) is not part
/// of the name, and the org of `GameCult/<name>` names no repo. The one matcher of what repo is in front of her (map
/// 16.25.5, 16.26), at open and at read.
fn names_repo(text: &str, repo: &str) -> bool {
let text = text.to_lowercase().replace("gamecult/", " ");
text.split(|c: char| !(c.is_alphanumeric() || matches!(c, '-' | '.' | '_')))
.filter(|token| !token.is_empty())
.any(|token| token == repo || token.trim_end_matches(['.', '-', '_']) == repo)
}
/// Whether `target` is a digest id: `d` and a number.
fn digest_id(target: &str) -> bool {
target.strip_prefix('d').is_some_and(|number| !number.is_empty() && number.chars().all(|c| c.is_ascii_digit()))
}
/// `text` held to `max` bytes on a character boundary, with a counted mark of what was cut. /// `text` held to `max` bytes on a character boundary, with a counted mark of what was cut.
pub(crate) fn clipped(text: &str, max: usize) -> String { pub(crate) fn clipped(text: &str, max: usize) -> String {
if text.len() <= max { if text.len() <= max {
@ -397,22 +184,6 @@ pub(crate) fn clipped(text: &str, max: usize) -> String {
format!("{}\n[{} more bytes not shown here]", &text[..end], text.len() - end) format!("{}\n[{} more bytes not shown here]", &text[..end], text.len() - end)
} }
/// The bridge (map 16.22.3): code's words, then the result verbatim in a fence longer than any run of backticks in it, and
/// nothing else; or that she reached for it and could not read it, and why.
pub(crate) fn bridge(her: Forms, what: &str, result: Result<&str, ReadFailure>) -> String {
match result {
Ok(text) => {
let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
let fence = "`".repeat(longest.max(3) + 1);
format!("Then {} reads {what}:\n\n{fence}\n{text}\n{fence}", her.subj)
}
Err(why) => format!("Then {} reaches for {what} and cannot read it: {}.", her.subj, why.words()),
}
}
// ---------------------------------------------------------------------------------------------
// The fixture.
/// One recorded read: its kind (`mind`, `campaign`, `repo`, `web`) and target, and the text it returns or why it fails. /// One recorded read: its kind (`mind`, `campaign`, `repo`, `web`) and target, and the text it returns or why it fails.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
@ -579,7 +350,7 @@ fn forge_json(forge: &dyn ForgeGet, path: &str) -> Result<Value, ReadFailure> {
/// A repo read from the forge: a repo is its description and its recent pull requests, merged and closed only, so an open /// A repo read from the forge: a repo is its description and its recent pull requests, merged and closed only, so an open
/// one is never listed by title (map 16.22.2); a pull request by number, a commit's message, or a file. /// one is never listed by title (map 16.22.2); a pull request by number, a commit's message, or a file.
fn repo_read(forge: &dyn ForgeGet, target: &str) -> Result<String, ReadFailure> { pub(crate) fn repo_read(forge: &dyn ForgeGet, target: &str) -> Result<String, ReadFailure> {
let rest = target.strip_prefix("GameCult/").ok_or(ReadFailure::NotFound)?; let rest = target.strip_prefix("GameCult/").ok_or(ReadFailure::NotFound)?;
if let Some((name, words)) = rest.split_once("?q=") { if let Some((name, words)) = rest.split_once("?q=") {
return search(forge, name, words.trim()); return search(forge, name, words.trim());

View file

@ -2,29 +2,6 @@
//! her, the clip with its count, the fenced bridge, and the recorded reads a harness run performs. //! her, the clip with its count, the fenced bridge, and the recorded reads a harness run performs.
use super::*; use super::*;
use crate::projection::select::Forms;
fn her() -> Forms {
Forms { subj: "she", cap_subj: "She", obj: "her", poss: "her", be: "is", has: "has", s: "s" }
}
#[test]
fn a_repo_target_is_a_public_gamecult_repo_file_pull_request_or_commit() {
for good in ["GameCult/Lodur", "GameCult/Lodur/docs/plan.md", "GameCult/Lodur#12", "GameCult/Lodur@4b2c9e1", "GameCult/Aetheria-legacy"] {
assert_eq!(repo_target(good).as_deref(), Some(good), "{good}");
}
for bad in ["Other/Lodur", "GameCult/", "GameCult/../x", "GameCult/Lodur/../../etc", "GameCult/Lodur#x", "GameCult/Lodur@xyz", "GameCult/Lo dur", "https://eureka.gamecult.org/forge/GameCult/Lodur", "GameCult/Lodur?raw=1"] {
assert_eq!(repo_target(bad), None, "{bad}");
}
}
#[test]
fn a_result_is_fenced_after_codes_bridge_and_a_failure_says_why() {
let bridge = bridge(her(), "GameCult/Lodur#12 on the forge", Ok("A body with ```code``` and ````more````."));
assert!(bridge.starts_with("Then she reads GameCult/Lodur#12 on the forge:\n\n`````\nA body with"), "{bridge}");
assert!(bridge.ends_with("````more````.\n`````"), "the fence is longer than any run inside: {bridge}");
assert_eq!(super::bridge(her(), "her own mind", Err(ReadFailure::Private)), "Then she reaches for her own mind and cannot read it: it is private.");
}
#[test] #[test]
fn a_result_past_its_cap_is_clipped_with_a_count() { fn a_result_past_its_cap_is_clipped_with_a_count() {
@ -83,32 +60,6 @@ fn a_repo_read_lists_no_open_pull_request_by_title() {
assert!(forge.0.borrow().iter().any(|path| path.contains("pulls?state=closed")), "{:?}", forge.0.borrow()); assert!(forge.0.borrow().iter().any(|path| path.contains("pulls?state=closed")), "{:?}", forge.0.borrow());
} }
/// K28 (map 16.24.3): a search of one repo's issues and pull requests by her words finds an older change by its title,
/// and a search with nothing found is not found.
#[test]
fn k28_a_search_finds_an_older_change_by_her_words() {
assert_eq!(repo_target("GameCult/Bifrost?q=consent receipt").as_deref(), Some("GameCult/Bifrost?q=consent receipt"));
assert_eq!(repo_target("gamecult/Bifrost?q=consent receipt").as_deref(), Some("GameCult/Bifrost?q=consent receipt"), "the org case-blind, the words spaced once");
assert_eq!(ReadRequest::Repo("GameCult/BIFROST?q=Consent Receipt".into()).normal(), ReadRequest::Repo("gamecult/bifrost?q=consent receipt".into()).normal());
for bad in ["GameCult/Bifrost?q=", "GameCult/Bifrost?x=1", "GameCult/Bifrost?q=a&state=open", "GameCult/Bifrost?q=../x"] {
assert_eq!(repo_target(bad), None, "{bad}");
}
struct Forge(std::cell::RefCell<Vec<String>>, bool);
impl ForgeGet for Forge {
fn get(&self, path: &str) -> anyhow::Result<(u16, String)> {
self.0.borrow_mut().push(path.to_owned());
let found = if self.1 { serde_json::json!([{ "number": 89, "title": "Chat sign-in gates on a live consent receipt", "state": "closed", "pull_request": { "merged": true }, "user": { "login": "heimdall" }, "created_at": "2026-11-12T10:00:00Z" }]) } else { serde_json::json!([]) };
Ok((200, found.to_string()))
}
}
let forge = Forge(std::cell::RefCell::default(), true);
assert_eq!(repo_read(&forge, "GameCult/Bifrost?q=consent receipt").unwrap(), format!("- #89 Chat sign-in gates on a live consent receipt (pull request merged, opened by heimdall, 2026-11-12)
{TITLES_ONLY}"));
assert_eq!(forge.0.borrow()[0], "/api/v1/repos/GameCult/Bifrost/issues?state=all&q=consent%20receipt&limit=10");
assert_eq!(repo_read(&Forge(std::cell::RefCell::default(), false), "GameCult/Bifrost?q=nothing here"), Err(ReadFailure::NotFound));
assert_eq!(ReadRequest::Repo("GameCult/Bifrost?q=consent receipt".into()).what(her()), "a search of GameCult/Bifrost for \"consent receipt\"");
}
/// Soul's R7: the fixture reads by normal form, and a search no entry records searches the titles of the repo's recorded /// Soul's R7: the fixture reads by normal form, and a search no entry records searches the titles of the repo's recorded
/// pull requests and issues for all its words. /// pull requests and issues for all its words.
#[test] #[test]

View file

@ -24,7 +24,11 @@
//! it, never under a bonded person's name. Every message body and display name is rendered by one escape (`spoken`, a //! it, never under a bonded person's name. Every message body and display name is rendered by one escape (`spoken`, a
//! JSON string), so no text can forge a line; speaker and room come from the mouth's metadata alone. //! JSON string), so no text can forge a line; speaker and room come from the mouth's metadata alone.
//! //!
//! Never read: `agencyPressure`, `candidateActions`, `privateNotes` and `provenance`. Whether an item is private, and //! What presses on her, what she means to do and what she feels are shown as fixed lines, never drawn: her strongest drives
//! (`Pool::Pressure`), her ready intentions (`Pool::Intention`), her strongest named feelings in the mood line, her read of a
//! person and what last moved a bond on its bond line, a bond line for each person the lines she is shown name though absent,
//! and her standing tendencies with her identity (`tendencies`). All of it is her state's own text, in words and never numbers,
//! and never someone else's words (I16.7). Never read: `privateNotes` and `provenance`. Whether an item is private, and
//! whom it concerns, is read by one function (`concerns`); how a private item reaches the packet, by one other (`scope`). //! whom it concerns, is read by one function (`concerns`); how a private item reaches the packet, by one other (`scope`).
use std::collections::BTreeSet; use std::collections::BTreeSet;
@ -55,6 +59,22 @@ const INCUBATION_UNRESOLVED_MAX: f64 = 2.0;
/// The most bytes a bond's name or kind takes in its line. /// The most bytes a bond's name or kind takes in its line.
const NAME_BYTES: usize = 80; const NAME_BYTES: usize = 80;
/// The most words, and bytes, of a display name the Projector is told a person she has no bond with by (K53, `Who`). /// The most words, and bytes, of a display name the Projector is told a person she has no bond with by (K53, `Who`).
/// The most drives and the most ready intentions a packet shows: the strongest, by intensity (urgency) and what the room touches.
const PRESSURES_SHOWN: usize = 2;
const INTENTIONS_SHOWN: usize = 2;
/// The most feelings the mood line names, each above `FEELING_MIN` after decay.
const FEELINGS_SHOWN: usize = 2;
const FEELING_MIN: f64 = 0.25;
/// A standing tendency shows above this value; `TENDENCIES_BYTES` holds the lot, heading included.
const TENDENCY_MIN: f64 = 0.3;
pub(crate) const TENDENCIES_BYTES: usize = 360;
/// The fewest bytes a tendency line is clipped to when the room left is short; with less, it is left out. Either way its
/// id is reported as clipped.
const TENDENCY_LEAST: usize = 48;
/// The most a bond line's clauses take of her read of the person and of what last moved the bond: each is left out, with the
/// other, when the line with them would pass what the people's guard allows one bond (`bond_allowance`).
const READ_SUMMARY_BYTES: usize = 120;
const SHIFT_BYTES: usize = 120;
const WHO_WORDS: usize = 3; const WHO_WORDS: usize = 3;
const WHO_BYTES: usize = 32; const WHO_BYTES: usize = 32;
/// The most bytes the line naming the unbonded people present takes. /// The most bytes the line naming the unbonded people present takes.
@ -138,6 +158,9 @@ pub(crate) struct Replied {
pub(crate) struct Room { pub(crate) struct Room {
pub messages: Vec<RoomLine>, pub messages: Vec<RoomLine>,
pub tail: Vec<RoomLine>, pub tail: Vec<RoomLine>,
/// The lines of the other rooms this wake holds (every waking room but the turn's): the Persona reads them verbatim and the
/// Projector is told only who turned to her there and when (`turned_to_her`), never what was said (`persona-projector-who-not-words`).
pub elsewhere: Vec<RoomLine>,
/// The room the turn is in, when it is one room. /// The room the turn is in, when it is one room.
pub here: Option<String>, pub here: Option<String>,
/// When she last heard from people, by Matrix id, beyond what the tail shows: a fixture's table (`mind-persona project /// When she last heard from people, by Matrix id, beyond what the tail shows: a fixture's table (`mind-persona project
@ -159,13 +182,6 @@ pub(crate) enum RoomKind {
} }
impl RoomKind { impl RoomKind {
pub(crate) fn words(self) -> &'static str {
match self {
Self::Direct => "a direct message",
Self::Own => "her own room, open to its members",
Self::Public => "a public room",
}
}
} }
/// What earlier turns left: the ids each of the last projections selected, oldest first, her state at her last turn /// What earlier turns left: the ids each of the last projections selected, oldest first, her state at her last turn
@ -256,6 +272,10 @@ impl Lens {
pub(crate) enum Pool { pub(crate) enum Pool {
/// Her unresolved short-term notes: never drawn, every one shown first under the notes' guard (T6). /// Her unresolved short-term notes: never drawn, every one shown first under the notes' guard (T6).
ShortTerm, ShortTerm,
/// Her strongest drives: never drawn, the strongest `PRESSURES_SHOWN` shown (map 16.38.8).
Pressure,
/// Her ready intentions: never drawn, the most urgent `INTENTIONS_SHOWN` shown.
Intention,
MemoriesAboutPresent, MemoriesAboutPresent,
OtherMemories, OtherMemories,
Needs, Needs,
@ -284,6 +304,8 @@ pub(crate) struct Packet {
/// Her voice summary, for the Projector alone (map 16.4, I16.1): it reaches her prose only as the Projector rendered /// Her voice summary, for the Projector alone (map 16.4, I16.1): it reaches her prose only as the Projector rendered
/// it, so no other stage's prompt is built from it. /// it, so no other stage's prompt is built from it.
pub voice: String, pub voice: String,
/// Her standing tendencies in words, for the Projector alone, shown with her identity: empty when none stands.
pub tendencies: String,
pub context: String, pub context: String,
/// What each section of the context took, and which guards bound. /// What each section of the context took, and which guards bound.
pub sections: Sections, pub sections: Sections,
@ -305,6 +327,10 @@ pub(crate) struct Packet {
/// lines, verbatim; then the others' new lines, then the room's earlier lines. The same lines as `heard`, from the /// lines, verbatim; then the others' new lines, then the room's earlier lines. The same lines as `heard`, from the
/// same selection. Empty on every other turn. /// same selection. Empty on every other turn.
pub bridged: String, pub bridged: String,
/// What the other waking rooms said, verbatim, rendered for the Persona after the room: who, where and when, then the words. Empty with no other waking room.
pub elsewhere: String,
/// The event of each line `elsewhere` shows: the other waking rooms' lines that fit `heard_bytes`, which are the ones she was shown.
pub elsewhere_shown: Vec<String>,
/// Bytes the messages to her took past the stimulus and heard caps: verbatim beats the cap. /// Bytes the messages to her took past the stimulus and heard caps: verbatim beats the cap.
pub overflow: Overflow, pub overflow: Overflow,
pub present: Vec<String>, pub present: Vec<String>,
@ -334,8 +360,6 @@ pub(crate) struct Packet {
/// What a byte guard cut (map 16.8): the ids of the bonds and items whose words it clipped, and `(identity)` when it /// What a byte guard cut (map 16.8): the ids of the bonds and items whose words it clipped, and `(identity)` when it
/// clipped her name or voice. Empty for a seed written to the standard's targets. /// clipped her name or voice. Empty for a seed written to the standard's targets.
pub clipped: Vec<String>, pub clipped: Vec<String>,
/// The lines of hers she may add to this turn, for the Interpreter alone (map 16.17).
pub amendable: Vec<Amendable>,
/// The lines of others she may reply to this turn, for the Interpreter alone (map 16.20.8 (D), K20). /// The lines of others she may reply to this turn, for the Interpreter alone (map 16.20.8 (D), K20).
pub quotable: Vec<Quotable>, pub quotable: Vec<Quotable>,
/// The lines of her domain the packet shows her, for the Interpreter's view by id (map 16.22.2). /// The lines of her domain the packet shows her, for the Interpreter's view by id (map 16.22.2).
@ -350,11 +374,6 @@ pub(crate) struct Packet {
pub now_ms: u64, pub now_ms: u64,
/// Her own Matrix id: her pronouns are not listed among the people named (`named_pronouns`). /// Her own Matrix id: her pronouns are not listed among the people named (`named_pronouns`).
pub own_sender: String, pub own_sender: String,
/// Every read she made in this conversation, shown or not, found or not (K26, Soul's R7): never made again, and
/// marked for the Interpreter.
pub already_read: Vec<exchange::Tried>,
/// The reads refused in this conversation, as `kind target (why)` (Soul's R8): for the Interpreter, never named again.
pub refused_reads: Vec<String>,
/// What came of her last turn that the outcome's guard left out of her view, whole: counted in its last line and /// What came of her last turn that the outcome's guard left out of her view, whole: counted in its last line and
/// reported here (map 16.20.5, I16.11, 16.29.10), never shown to a model. /// reported here (map 16.20.5, I16.11, 16.29.10), never shown to a model.
pub unshown: Vec<String>, pub unshown: Vec<String>,
@ -373,15 +392,6 @@ pub(crate) struct Remembered {
pub words: String, pub words: String,
} }
/// A line of hers she may add to (map 16.17): one her last turn posted, in the turn's room only. The Interpreter cites it by `id` (`a1`, `a2`); `event` is the actuator's handle on it, never shown to a model.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct Amendable {
pub id: String,
pub event: String,
pub room: String,
pub text: String,
}
/// A line of someone else's she may reply to (K20): one this packet shows her, in the turn's room. The Interpreter cites it /// A line of someone else's she may reply to (K20): one this packet shows her, in the turn's room. The Interpreter cites it
/// by `id` (`q1`, `q2`); `event` is the actuator's handle on it, never shown to a model. A reply posts her own words with the /// by `id` (`q1`, `q2`); `event` is the actuator's handle on it, never shown to a model. A reply posts her own words with the
/// relation to it, and the room shows the line, with who said it, above hers: no code writes words in her name. /// relation to it, and the room shows the line, with who said it, above hers: no code writes words in her name.
@ -442,7 +452,7 @@ struct Candidate {
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// Reading her state. // Reading her state.
fn text<'a>(value: &'a Value, path: &[&str]) -> &'a str { pub(crate) fn text<'a>(value: &'a Value, path: &[&str]) -> &'a str {
path.iter().try_fold(value, |at, key| at.get(*key)).and_then(Value::as_str).unwrap_or_default().trim() path.iter().try_fold(value, |at, key| at.get(*key)).and_then(Value::as_str).unwrap_or_default().trim()
} }
@ -541,11 +551,11 @@ fn baseline(state: &Value, axis: &str) -> Option<f64> {
number(state, &["activationProfile", "situationalState", axis, "mean"]) number(state, &["activationProfile", "situationalState", axis, "mean"])
} }
/// Mood as change since her last turn. With no last turn to measure from, each axis is measured against her own baseline /// The tone of her mood as change since her last turn. With no last turn to measure from, each axis is measured against her own baseline
/// (its trait vector's `mean`), or against middling where it carries none, and only an axis that leans more than /// (its trait vector's `mean`), or against middling where it carries none, and only an axis that leans more than
/// `MOOD_LEVEL_MIN` is said. None when nothing leans, or her state carries no mood: an absence is left out of the packet, /// `MOOD_LEVEL_MIN` is said. None when nothing leans, or her state carries no mood: an absence is left out of the packet,
/// never narrated. /// never narrated.
fn mood_line(state: &Value, previous: Option<&Value>) -> Option<String> { fn mood_tone(state: &Value, previous: Option<&Value>) -> Option<String> {
let now: Vec<(usize, f64)> = MOOD_AXES.iter().enumerate().filter_map(|(at, (axis, ..))| activation(state, axis).map(|value| (at, value))).collect(); let now: Vec<(usize, f64)> = MOOD_AXES.iter().enumerate().filter_map(|(at, (axis, ..))| activation(state, axis).map(|value| (at, value))).collect();
if now.is_empty() { if now.is_empty() {
return None; return None;
@ -562,7 +572,7 @@ fn mood_line(state: &Value, previous: Option<&Value>) -> Option<String> {
} }
let obj = forms(state).obj; let obj = forms(state).obj;
let parts: Vec<String> = [(usual, format!("than usual for {obj}")), (middling, "than middling".to_owned())].into_iter().filter(|(words, _)| !words.is_empty()).map(|(words, than)| format!("{} {than}", words.join(", "))).collect(); let parts: Vec<String> = [(usual, format!("than usual for {obj}")), (middling, "than middling".to_owned())].into_iter().filter(|(words, _)| !words.is_empty()).map(|(words, than)| format!("{} {than}", words.join(", "))).collect();
return (!parts.is_empty()).then(|| format!("- mood: {}", parts.join("; "))); return (!parts.is_empty()).then(|| parts.join("; "));
}; };
let moves: Vec<&str> = now let moves: Vec<&str> = now
.iter() .iter()
@ -577,7 +587,39 @@ fn mood_line(state: &Value, previous: Option<&Value>) -> Option<String> {
}) })
.collect(); .collect();
let poss = forms(state).poss; let poss = forms(state).poss;
Some(if moves.is_empty() { format!("- mood: where it was at {poss} last turn") } else { format!("- mood: {} than at {poss} last turn", moves.join(", ")) }) Some(if moves.is_empty() { format!("where it was at {poss} last turn") } else { format!("{} than at {poss} last turn", moves.join(", ")) })
}
/// Her strongest named feelings (`affect.moodDimensions`) above `FEELING_MIN` after decay, each with what it is about: the
/// bond's label when the source names a person she is bound to, else the source's words. A value is read as it is now, never
/// as stored (`decayed`). None when no feeling stands.
fn feelings_line(inputs: &Inputs) -> Option<String> {
let mut felt: Vec<(f64, String)> = items(inputs.state, &["affect", "moodDimensions"])
.iter()
.filter_map(|feeling| {
let name = one_line(text(feeling, &["name"]));
let hours = time(feeling).map_or(0.0, |at| (inputs.now - at).num_milliseconds() as f64 / 3_600_000.0);
let value = super::commit::decayed(number(feeling, &["value"])?, hours);
if name.is_empty() || value <= FEELING_MIN {
return None;
}
let source = one_line(text(feeling, &["source"]));
let person = inputs.people.person_of(&source);
let bound = items(inputs.state, &["affect", "socialBonds"]).iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == person).map(|bond| text(bond, &["object", "label"])).filter(|label| !label.is_empty());
let about = bound.unwrap_or(&source);
let about = if about.is_empty() { String::new() } else { format!(" about {}", clip(&one_line(about), NAME_BYTES)) };
Some((value, format!("{} {}{about}", strength_words(value), clip(&name, NAME_BYTES))))
})
.collect();
felt.sort_by(|a, b| b.0.total_cmp(&a.0));
let words: Vec<String> = felt.into_iter().take(FEELINGS_SHOWN).map(|(_, words)| words).collect();
(!words.is_empty()).then(|| format!("carrying {}", words.join(" and ")))
}
/// Her mood: its tone, then the feelings she carries. None when neither stands: an absence is left out, never narrated.
fn mood_line(inputs: &Inputs) -> Option<String> {
let parts: Vec<String> = [mood_tone(inputs.state, inputs.history.previous.as_ref()), feelings_line(inputs)].into_iter().flatten().collect();
(!parts.is_empty()).then(|| format!("- mood: {}", parts.join("; ")))
} }
fn need_movement(need: &Value, previous: Option<&Value>, poss: &str) -> String { fn need_movement(need: &Value, previous: Option<&Value>, poss: &str) -> String {
@ -673,8 +715,8 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet<String>, touc
Scope::Framed => (format!("{} knows privately: {words}", her.subj), Some(one_line(words))), Scope::Framed => (format!("{} knows privately: {words}", her.subj), Some(one_line(words))),
Scope::Plain => (words.to_owned(), None), Scope::Plain => (words.to_owned(), None),
}; };
// A short-term note is never drawn, so how often it was shown says nothing of it. // A short-term note, a drive or an intention is never drawn, so how often it was shown says nothing of it.
let fresh = if pool == Pool::ShortTerm { 0.0 } else { freshness_log(id, inputs.history, tuning) }; let fresh = if matches!(pool, Pool::ShortTerm | Pool::Pressure | Pool::Intention) { 0.0 } else { freshness_log(id, inputs.history, tuning) };
let log_score = salience.ln() + relevance + touch.ln() + unresolved.ln() + fresh; let log_score = salience.ln() + relevance + touch.ln() + unresolved.ln() + fresh;
let words = clip(&shown, item_bytes); let words = clip(&shown, item_bytes);
out.push(Candidate { id: id.to_owned(), pool, line: line(&words), words, log_score, private, clipped: shown.trim().len() > item_bytes }); out.push(Candidate { id: id.to_owned(), pool, line: line(&words), words, log_score, private, clipped: shown.trim().len() > item_bytes });
@ -711,6 +753,28 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet<String>, touc
push(text(need, &["id"]), Pool::Needs, scoped(need), &words, &|words: &str| thought_line("need", need, Some(&movement), words), intensity, 0.0, TOUCH_ELSE, 1.0 + intensity); push(text(need, &["id"]), Pool::Needs, scoped(need), &words, &|words: &str| thought_line("need", need, Some(&movement), words), intensity, 0.0, TOUCH_ELSE, 1.0 + intensity);
} }
// Her drives and her ready intentions: fixed lines, the strongest of each shown (`select`), so she feels what presses on
// her and what she means to do each wake, drawn or not.
for pressure in items(state, &["agencyPressure", "pressures"]).iter().filter(|pressure| live(pressure)) {
let words = thought_words(pressure);
if words.is_empty() {
continue;
}
let intensity = number(pressure, &["intensity"]).unwrap_or(SALIENCE_UNSTATED);
// The kind already says "pressing": a drive at its strongest is not told so twice.
let movement = Some(need_movement(pressure, inputs.history.previous.as_ref(), her.poss)).filter(|movement| movement != "pressing");
push(text(pressure, &["id"]), Pool::Pressure, scoped(pressure), &words, &|words: &str| thought_line("pressing", pressure, movement.as_deref(), words), intensity, relevance_log(&words, touching), TOUCH_ELSE, 1.0);
}
let unexpired = |action: &Value| DateTime::parse_from_rfc3339(text(action, &["expiresAt"])).map_or(true, |at| at > inputs.now);
for action in items(state, &["candidateActions", "actions"]).iter().filter(|action| live(action) && text(action, &["readiness"]) == "ready" && unexpired(action)) {
let words = thought_words(action);
if words.is_empty() {
continue;
}
push(text(action, &["id"]), Pool::Intention, scoped(action), &words, &|words: &str| thought_line("means to do", action, None, words), number(action, &["urgency"]).unwrap_or(SALIENCE_UNSTATED), relevance_log(&words, touching), TOUCH_ELSE, 1.0);
}
for wondering in items(state, &["thoughtMemory", "incubation"]).iter().filter(|item| live(item)) { for wondering in items(state, &["thoughtMemory", "incubation"]).iter().filter(|item| live(item)) {
let words = thought_words(wondering); let words = thought_words(wondering);
if words.is_empty() { if words.is_empty() {
@ -772,6 +836,8 @@ fn cap_of(pool: Pool, tuning: &Tuning) -> usize {
match pool { match pool {
// No cap: her notes are not drawn, and only the notes' guard holds them (T6). // No cap: her notes are not drawn, and only the notes' guard holds them (T6).
Pool::ShortTerm => usize::MAX, Pool::ShortTerm => usize::MAX,
Pool::Pressure => PRESSURES_SHOWN,
Pool::Intention => INTENTIONS_SHOWN,
Pool::MemoriesAboutPresent => caps.memories_about_present, Pool::MemoriesAboutPresent => caps.memories_about_present,
Pool::OtherMemories => caps.other_memories, Pool::OtherMemories => caps.other_memories,
Pool::Needs => caps.needs, Pool::Needs => caps.needs,
@ -799,6 +865,16 @@ impl<'a> Inputs<'a> {
} }
} }
/// One bond to show: whose, as named, the act of turning to her when there was one, whether they are absent but named, and
/// the bond she has with them.
struct Placed<'a> {
id: String,
name: Who,
turned: Option<&'a str>,
absent: bool,
bond: Option<&'a Value>,
}
/// A person as the Projector is told of them (K53, I16.7): who they are to her, in no more room than a name needs. Her own /// A person as the Projector is told of them (K53, I16.7): who they are to her, in no more room than a name needs. Her own
/// name for her; the bond's label for someone she is bound to, which is her state's text; for anyone else their display /// name for her; the bond's label for someone she is bound to, which is her state's text; for anyone else their display
/// name cut to at most `WHO_WORDS` words and `WHO_BYTES` bytes, quoted and escaped, then ", someone she does not know", /// name cut to at most `WHO_WORDS` words and `WHO_BYTES` bytes, quoted and escaped, then ", someone she does not know",
@ -1316,9 +1392,28 @@ fn turned_to_her(inputs: &Inputs) -> Vec<(String, String)> {
out.push((person, if Some(line.room.as_str()) == here { "here".to_owned() } else { format!("in {}", line.room) })); out.push((person, if Some(line.room.as_str()) == here { "here".to_owned() } else { format!("in {}", line.room) }));
} }
} }
for line in inputs.room.elsewhere.iter().filter(|line| line.to_her && line.sender != inputs.people.own_sender).rev() {
let person = inputs.people.person_of(&line.sender);
if !out.iter().any(|(id, _)| *id == person) {
out.push((person, format!("in {}, {}", line.room, coarse_ms(inputs.now, line.at_ms))));
}
}
out out
} }
/// What the other waking rooms said, as the Persona reads it after the room: the speaker, the room and when, then the words verbatim,
/// newest kept within `heard_bytes`, with the lines it shows. The Projector's packet holds none of it (`turned_to_her` names who and where).
fn elsewhere_heard<'a>(inputs: &'a Inputs, tuning: &Tuning) -> (String, Vec<&'a RoomLine>) {
let mut lines: Vec<&RoomLine> = inputs.room.elsewhere.iter().filter(|line| line.sender != inputs.people.own_sender).collect();
lines.sort_by_key(|line| line.at_ms);
let rendered: Vec<String> = lines.iter().map(|line| format!("{}, in {}, {}: {}", name_of(line, inputs), line.room, coarse_ms(inputs.now, line.at_ms), spoken(&line.text))).collect();
let (kept, dropped) = newest_that_fit(&rendered, tuning.select.heard_bytes);
let text = if kept.is_empty() { String::new() } else { format!("Also, in other rooms:
{}", kept.join("
")) };
(text, lines[dropped..].to_vec())
}
/// The tail lines a beat's stimulus quotes: the newest `beat_tail_lines` of others'. /// The tail lines a beat's stimulus quotes: the newest `beat_tail_lines` of others'.
fn beat_tail<'a>(inputs: &'a Inputs, tuning: &Tuning) -> Vec<&'a RoomLine> { fn beat_tail<'a>(inputs: &'a Inputs, tuning: &Tuning) -> Vec<&'a RoomLine> {
let others: Vec<&RoomLine> = inputs.room.tail.iter().filter(|line| line.sender != inputs.people.own_sender).collect(); let others: Vec<&RoomLine> = inputs.room.tail.iter().filter(|line| line.sender != inputs.people.own_sender).collect();
@ -1336,7 +1431,7 @@ fn reflection_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
/// Projector names them (`Who`, K53). /// Projector names them (`Who`, K53).
fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, Who)> { fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, Who)> {
let lines: Vec<&RoomLine> = match inputs.kind { let lines: Vec<&RoomLine> = match inputs.kind {
TurnKind::Chat => inputs.room.messages.iter().collect(), TurnKind::Chat => inputs.room.messages.iter().chain(&inputs.room.elsewhere).collect(),
TurnKind::Beat => { TurnKind::Beat => {
let tail = &inputs.room.tail; let tail = &inputs.room.tail;
tail[tail.len().saturating_sub(tuning.select.beat_tail_lines)..].iter().collect() tail[tail.len().saturating_sub(tuning.select.beat_tail_lines)..].iter().collect()
@ -1355,8 +1450,8 @@ fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, Who)> {
/// A bond line: the person, the kind of bond after a dash (a label may hold a comma: "Meta, the operator"), trust and /// A bond line: the person, the kind of bond after a dash (a label may hold a comma: "Meta, the operator"), trust and
/// friction as words when the bond carries them, and its summary; then, when the person turned to her this turn, that act /// friction as words when the bond carries them, and its summary; then, when the person turned to her this turn, that act
/// and where (`turned`, map 16.21). What the bond does not carry is left out. /// and where (`turned`, map 16.21). Then its `notes` (`bond_notes`). What the bond does not carry is left out.
fn bond_line(bond: &Value, name: &Who, tuning: &Tuning, scope: Scope, her: Forms, turned: Option<&str>) -> String { fn bond_line(bond: &Value, name: &str, tuning: &Tuning, scope: Scope, her: Forms, turned: Option<&str>, notes: &[String]) -> String {
let feel: Vec<&str> = [number(bond, &["trust"]).map(trust_words), number(bond, &["tension"]).map(friction_words)].into_iter().flatten().collect(); let feel: Vec<&str> = [number(bond, &["trust"]).map(trust_words), number(bond, &["tension"]).map(friction_words)].into_iter().flatten().collect();
let custom = text(bond, &["customRelationshipKind"]); let custom = text(bond, &["customRelationshipKind"]);
let kind = clip(&one_line(if custom.is_empty() { text(bond, &["relationshipKind"]) } else { custom }), NAME_BYTES); let kind = clip(&one_line(if custom.is_empty() { text(bond, &["relationshipKind"]) } else { custom }), NAME_BYTES);
@ -1382,12 +1477,79 @@ fn bond_line(bond: &Value, name: &Who, tuning: &Tuning, scope: Scope, her: Forms
let _ = write!(line, ": {}. {summary}", feel.join(", ")); let _ = write!(line, ": {}. {summary}", feel.join(", "));
} }
} }
for note in notes {
let _ = write!(line, "{}{note}", if line.ends_with('.') { " " } else { ". " });
}
if let Some(place) = turned { if let Some(place) = turned {
let _ = write!(line, "{}Just now {name} turned to {}, {place}.", if line.ends_with('.') { " " } else { ". " }, her.obj); let _ = write!(line, "{}Just now {name} turned to {}, {place}.", if line.ends_with('.') { " " } else { ". " }, her.obj);
} }
line line
} }
/// What a bond line says beyond its summary: what last moved the bond (`lastEvidence`'s claim, under the bond's scope) and
/// her read of the person (`read`, from `read_clause`).
fn bond_notes(bond: &Value, scope: Scope, read: Option<&str>) -> Vec<String> {
let shift = clip(&one_line(text(bond, &["lastEvidence", "claim"])), SHIFT_BYTES);
let shift = (scope != Scope::Omitted && !shift.is_empty()).then(|| format!("What last moved it: {}", ended(&shift)));
[shift, read.map(str::to_owned)].into_iter().flatten().collect()
}
/// A text as a sentence's end: a full stop after it unless it already ends one.
fn ended(text: &str) -> String {
if text.ends_with(['.', '!', '?', '\u{2026}']) { text.to_owned() } else { format!("{text}.") }
}
/// Her read of one person (`affect.statusReads`, the newest live one about them), as a clause of their bond line, hedged by
/// its confidence, and under the read's own privacy (`scope`): left out where it is private and the person is in the room.
/// With the words of a private read the packet showed, for the packet's list of what may not be said.
fn read_clause(inputs: &Inputs, person: &str, present: &BTreeSet<String>) -> Option<(String, Option<String>)> {
let her = forms(inputs.state);
let read = items(inputs.state, &["affect", "statusReads"]).iter().filter(|read| live(read) && inputs.people.person_of(text(read, &["target", "id"])) == person && !one_line(text(read, &["summary"])).is_empty()).max_by_key(|read| time(read))?;
let summary = ended(&clip(&one_line(text(read, &["summary"])), READ_SUMMARY_BYTES));
let kind = one_line(text(read, &["statusKind"]));
let kind = if kind.is_empty() { "them".to_owned() } else { clip(&kind, NAME_BYTES) };
match scope(inputs, concerns(&inputs.people, read).as_ref(), present) {
Scope::Omitted => None,
Scope::Framed => Some((format!("{} knows privately, reading {kind}: {summary}", her.cap_subj), Some(summary))),
Scope::Plain => {
let hedge = match number(read, &["confidence"]).unwrap_or(0.5) {
c if c >= 0.7 => String::new(),
c if c >= 0.35 => ", loosely".to_owned(),
_ => format!(", though {} {} not sure", her.subj, her.be),
};
Some((format!("{} reads {kind}{hedge}: {summary}", her.cap_subj), None))
}
}
}
/// The bonds of people who are not here but whom the lines she is shown name: a word of the names a line would call them by
/// (`names_of`: the localpart, the display name, the bond's label; the label's first part too) in the words of what others
/// said in the rooms she hears. Only the bond is shown, never the words that named it (I16.7). Her own bond is not one.
fn named_absent<'a>(inputs: &'a Inputs, present: &BTreeSet<String>) -> Vec<(&'a Value, Who)> {
let lines: Vec<&RoomLine> = inputs.room.messages.iter().chain(&inputs.room.tail).chain(&inputs.room.elsewhere).filter(|line| line.sender != inputs.people.own_sender).collect();
let words = |text: &str| text.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty()).map(str::to_lowercase).collect::<Vec<_>>().join(" ");
let said = format!(" {} ", lines.iter().map(|line| words(&line.text)).collect::<Vec<_>>().join(" . "));
let own = inputs.people.person_of(inputs.people.own_sender);
items(inputs.state, &["affect", "socialBonds"])
.iter()
.filter(|bond| live(bond))
.filter_map(|bond| {
let id = text(bond, &["object", "id"]);
let person = inputs.people.person_of(id);
if person.is_empty() || person == own || present.contains(&person) {
return None;
}
let display = lines.iter().filter(|line| inputs.people.person_of(&line.sender) == person).max_by_key(|line| line.at_ms).map(|line| line.display.clone()).unwrap_or_default();
let label = text(bond, &["object", "label"]);
let mut names = names_of(&RoomLine { sender: id.to_owned(), display, ..RoomLine::default() }, inputs);
names.extend(label.split(',').next().map(str::to_owned));
let named = names.iter().map(|name| words(name)).any(|name| name.len() >= 3 && said.contains(&format!(" {name} ")));
let shown = if label.is_empty() { capitalized(localpart(id)) } else { clip(&one_line(label), NAME_BYTES) };
named.then_some((bond, Who(shown)))
})
.collect()
}
/// What opens the Persona's reading of one person's new lines to her (map 16.21): the arrival picked up in its own /// What opens the Persona's reading of one person's new lines to her (map 16.21): the arrival picked up in its own
/// terms, the person's name and where as the packet's arrival names them (`turned_to_her`, the act on their own line), /// terms, the person's name and where as the packet's arrival names them (`turned_to_her`, the act on their own line),
/// and "just now", so the lines read as the very thing the narration's arrival brought. In her pronouns (16.19.7). /// and "just now", so the lines read as the very thing the narration's arrival brought. In her pronouns (16.19.7).
@ -1738,28 +1900,25 @@ pub(crate) fn capitalized(word: &str) -> String {
chars.next().map_or_else(String::new, |first| format!("{}{}", first.to_uppercase(), chars.as_str())) chars.next().map_or_else(String::new, |first| format!("{}{}", first.to_uppercase(), chars.as_str()))
} }
/// What this turn can do, in words, from the affordances alone (map 16.6, 16.18): the body section's turn line and the /// What this turn can do, in words, from the affordances alone (map 16.6, 16.18): the body section's turn line. A derived sentence, never a constant.
/// Interpreter's "What she can do here" are this text. It ends with "nothing she does here builds, changes or ships
/// anything" exactly when no affordance writes (`Affordance::writes`): a derived sentence, never a constant.
pub(crate) fn turn_words(can: &[Affordance], her: Forms) -> String { pub(crate) fn turn_words(can: &[Affordance], her: Forms) -> String {
let has = |affordance: Affordance| can.contains(&affordance); let has = |affordance: Affordance| can.contains(&affordance);
let clauses = [ let room = if has(Affordance::Perceive) { format!("this turn the room reaches {} as typed lines", her.obj) } else { format!("this turn no room reaches {}", her.obj) };
if has(Affordance::Perceive) { format!("the room reaches {} as typed lines", her.obj) } else { format!("no room reaches {}", her.obj) }, let acts: Vec<String> = [
if has(Affordance::Speak) { format!("{} can answer in the turn's room by typing lines of {} own, any of which can reply to one of the room's lines, which the room then shows above it with who wrote it", her.subj, her.poss) } else { format!("{} can say nothing", her.subj) }, (Affordance::Say, "say a line aloud in a room".to_owned()),
]; (Affordance::Read, format!("read the forge, the web or {} own mind", her.poss)),
let clauses: Vec<String> = clauses (Affordance::Shell, format!("run a command in {} own box, which can write to the commons", her.poss)),
(Affordance::RequestTool, "ask Self for a tool".to_owned()),
]
.into_iter() .into_iter()
.chain(has(Affordance::Suggest).then(|| format!("{} can leave Self a note", her.subj))) .filter(|(affordance, _)| has(*affordance))
.chain(has(Affordance::Read).then(|| format!("{} can read what {} thought reaches for: {} own mind, what moved in {} domain, the public GameCult repos, and a web address in front of {}", her.subj, her.poss, her.poss, her.poss, her.obj))) .map(|(_, act)| act)
.collect(); .collect();
#[cfg(test)] match acts.split_last() {
let clauses: Vec<String> = clauses.into_iter().chain(has(Affordance::TestWrite).then(|| format!("{} can write", her.subj))).collect(); None => room,
let mut words = format!("this turn {}", clauses.join(", and ")); Some((last, [])) => format!("{room}; {} can {last}", her.subj),
if !can.iter().any(|affordance| affordance.writes()) { Some((last, rest)) => format!("{room}; {} can {}, and {last}", her.subj, rest.join(", ")),
let does = if her.s.is_empty() { "do" } else { "does" };
let _ = write!(words, "; nothing {} {does} here builds, changes or ships anything", her.subj);
} }
words
} }
/// The body section's lines, the ids they name, and the ids of the entries the guard cut. /// The body section's lines, the ids they name, and the ids of the entries the guard cut.
@ -1933,12 +2092,14 @@ fn domain_view(inputs: &Inputs, her: Forms, room: usize) -> (Vec<DomainLine>, St
} }
} }
/// The people's guard: its heading and the bonds a packet shows in full, each a summary, its head, the act of turning to /// What one bond line is allowed: a summary, its head, the act of turning to her, and its newline.
/// her, and its newline. fn bond_allowance(tuning: &Tuning) -> usize {
tuning.select.bond_summary_bytes.saturating_add(BOND_HEAD_BYTES).saturating_add(TURNED_BYTES).saturating_add(1)
}
/// The people's guard: its heading and the bonds a packet shows in full, each within `bond_allowance`.
pub(crate) fn people_guard(tuning: &Tuning, her: Forms) -> usize { pub(crate) fn people_guard(tuning: &Tuning, her: Forms) -> usize {
let select = &tuning.select; Section::People.heading(her).len().saturating_add(tuning.select.people_full.saturating_mul(bond_allowance(tuning)))
let bond = select.bond_summary_bytes.saturating_add(BOND_HEAD_BYTES).saturating_add(TURNED_BYTES).saturating_add(1);
Section::People.heading(her).len().saturating_add(select.people_full.saturating_mul(bond))
} }
const SECTIONS: usize = 5; const SECTIONS: usize = 5;
@ -2056,6 +2217,47 @@ fn guarded_outcome(len: usize, line: &dyn Fn(usize, usize) -> String, room: usiz
out out
} }
/// Her standing tendencies (`affect.socialBiases` over `TENDENCY_MIN`, the strongest first) in words, for her identity: each
/// by its name, how strong it is, its summary and its behavioural pull, under a stance's privacy (`scope`), the lot within
/// `TENDENCIES_BYTES`, a line that would pass it clipped to the room left (`TENDENCY_LEAST`), its id reported as clipped.
/// With the words of those shown as known privately.
fn tendencies(inputs: &Inputs, present: &BTreeSet<String>) -> (String, Vec<String>, Vec<String>) {
let her = forms(inputs.state);
let heading = format!("{} standing tendencies:", capitalized(her.poss));
let mut biases: Vec<(f64, &Value)> = items(inputs.state, &["affect", "socialBiases"]).iter().filter(|bias| live(bias)).filter_map(|bias| number(bias, &["value"]).filter(|value| *value > TENDENCY_MIN).map(|value| (value, bias))).collect();
biases.sort_by(|a, b| b.0.total_cmp(&a.0));
let (mut lines, mut private, mut clipped, mut used) = (Vec::new(), Vec::new(), Vec::new(), heading.len());
for (value, bias) in biases {
let scope = scope(inputs, concerns(&inputs.people, bias).as_ref(), present);
let said = [text(bias, &["summary"]), text(bias, &["behavioralPull"])].into_iter().filter(|part| !part.is_empty()).map(|part| capitalized(&ended(&one_line(part)))).collect::<Vec<_>>().join(" ");
let said = match scope {
Scope::Omitted => continue,
Scope::Framed if !said.is_empty() => format!("{} knows privately: {said}", her.cap_subj),
_ => said,
};
let name = clip(&one_line(text(bias, &["name"])), NAME_BYTES);
let line = if said.is_empty() { format!("- {name}, {}", strength_words(value)) } else { format!("- {name}, {}: {said}", strength_words(value)) };
let room = TENDENCIES_BYTES.saturating_sub(used + 1);
let line = if line.len() <= room {
line
} else {
clipped.push(text(bias, &["id"]).to_owned());
if room < TENDENCY_LEAST {
continue;
}
clip(&line, room)
};
used += 1 + line.len();
if scope == Scope::Framed {
private.push(one_line(&said));
}
lines.push(line);
}
(if lines.is_empty() { String::new() } else { format!("{heading}
{}", lines.join("
")) }, private, clipped)
}
pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
let mut draw = Draw(inputs.seed); let mut draw = Draw(inputs.seed);
let (name, voice, identity_clipped) = identity_of(inputs.state, tuning); let (name, voice, identity_clipped) = identity_of(inputs.state, tuning);
@ -2064,6 +2266,8 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
// reading, so the two never disagree (map 16.21). // reading, so the two never disagree (map 16.21).
let present = present_people(inputs, tuning); let present = present_people(inputs, tuning);
let turned = turned_to_her(inputs); let turned = turned_to_her(inputs);
let (elsewhere, elsewhere_lines) = elsewhere_heard(inputs, tuning);
let elsewhere_shown: Vec<String> = elsewhere_lines.iter().map(|line| line.event.clone()).collect();
let (stimulus, heard, bridged, overflow, earlier_shown) = match inputs.kind { let (stimulus, heard, bridged, overflow, earlier_shown) = match inputs.kind {
TurnKind::Chat => chat_stimulus(inputs, tuning, &present, &turned), TurnKind::Chat => chat_stimulus(inputs, tuning, &present, &turned),
TurnKind::Beat => { TurnKind::Beat => {
@ -2136,7 +2340,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
let present_ids: BTreeSet<String> = present.iter().map(|(id, _)| id.clone()).collect(); let present_ids: BTreeSet<String> = present.iter().map(|(id, _)| id.clone()).collect();
let bonds = items(inputs.state, &["affect", "socialBonds"]); let bonds = items(inputs.state, &["affect", "socialBonds"]);
context.force(Section::Here, format!("- now: {}, {}", inputs.now.format("%A %-d %B"), part_of_day(inputs.now))); context.force(Section::Here, format!("- now: {}, {}", inputs.now.format("%A %-d %B"), part_of_day(inputs.now)));
if let Some(mood) = mood_line(inputs.state, inputs.history.previous.as_ref()) { if let Some(mood) = mood_line(inputs) {
context.force(Section::Here, mood); context.force(Section::Here, mood);
} }
let mut ids = Vec::new(); let mut ids = Vec::new();
@ -2153,31 +2357,47 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
// Whoever turned to her this turn is placed first, so a bond line's room goes to them before anyone else present. // Whoever turned to her this turn is placed first, so a bond line's room goes to them before anyone else present.
let arrived = |id: &String| turned.iter().any(|(person, _)| person == id); let arrived = |id: &String| turned.iter().any(|(person, _)| person == id);
let order = present.iter().filter(|(id, _)| arrived(id)).chain(present.iter().filter(|(id, _)| !arrived(id))); let order = present.iter().filter(|(id, _)| arrived(id)).chain(present.iter().filter(|(id, _)| !arrived(id)));
for (id, name) in order { // The people present first, then the bonds of people the lines she is shown name though they are not here (map 16.38.8),
let turned = turned.iter().find(|(person, _)| person == id).map(|(_, place)| place.as_str()); // all under `people_full`.
let mut shown: Vec<Placed> = order
.map(|(id, name)| Placed { id: id.clone(), name: name.clone(), turned: turned.iter().find(|(person, _)| person == id).map(|(_, place)| place.as_str()), absent: false, bond: bonds.iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == *id) })
.collect();
shown.extend(named_absent(inputs, &present_ids).into_iter().map(|(bond, name)| Placed { id: inputs.people.person_of(text(bond, &["object", "id"])), name, turned: None, absent: true, bond: Some(bond) }));
let allowance = bond_allowance(tuning);
for Placed { id, name, turned, absent, bond } in shown {
// Unbonded, or no room for the bond line: named on the also-here line, with the act when there was one. // Unbonded, or no room for the bond line: named on the also-here line, with the act when there was one.
let also = match turned { let also = match turned {
Some("here") => format!("{name}, who turned to {} just now", her.obj), Some("here") => format!("{name}, who turned to {} just now", her.obj),
Some(place) => format!("{name}, who turned to {} just now, {place}", her.obj), Some(place) => format!("{name}, who turned to {} just now, {place}", her.obj),
None => name.to_string(), None => name.to_string(),
}; };
match bonds.iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == *id) { match bond {
Some(bond) if full < tuning.select.people_full => { Some(bond) if full < tuning.select.people_full => {
let scope = scope(inputs, concerns(&inputs.people, bond).as_ref(), &present_ids); let scope = scope(inputs, concerns(&inputs.people, bond).as_ref(), &present_ids);
if context.push(Section::People, bond_line(bond, name, tuning, scope, her, turned)) { let read = read_clause(inputs, &id, &present_ids);
let head = if absent { format!("{name} (named, not here)") } else { name.to_string() };
// Her read and what moved the bond ride along only where the line still fits what one bond is allowed.
let notes = bond_notes(bond, scope, read.as_ref().map(|(clause, _)| clause.as_str()));
let with = bond_line(bond, &head, tuning, scope, her, turned, &notes);
let (line, kept) = if with.len() < allowance { (with, true) } else { (bond_line(bond, &head, tuning, scope, her, turned, &[]), false) };
if context.push(Section::People, line) {
full += 1; full += 1;
ids.push(text(bond, &["id"]).to_owned()); ids.push(text(bond, &["id"]).to_owned());
if scope != Scope::Omitted && one_line(text(bond, &["summary"])).len() > tuning.select.bond_summary_bytes { if scope != Scope::Omitted && one_line(text(bond, &["summary"])).len() > tuning.select.bond_summary_bytes {
clipped.push(text(bond, &["id"]).to_owned()); clipped.push(text(bond, &["id"]).to_owned());
} }
if scope == Scope::Framed && !text(bond, &["summary"]).is_empty() { if scope == Scope::Framed {
private.push(one_line(text(bond, &["summary"]))); private.extend([text(bond, &["summary"]), text(bond, &["lastEvidence", "claim"])].into_iter().filter(|words| !words.is_empty()).map(one_line));
} }
} else { if kept {
private.extend(read.and_then(|(_, private)| private));
}
} else if !absent {
named.push((also, turned.is_some())); named.push((also, turned.is_some()));
} }
} }
_ => named.push((also, turned.is_some())), _ if !absent => named.push((also, turned.is_some())),
_ => {}
} }
} }
let (domain, domain_view, domain_shown) = domain_view(inputs, her, tuning.select.domain_bytes); let (domain, domain_view, domain_shown) = domain_view(inputs, her, tuning.select.domain_bytes);
@ -2214,7 +2434,9 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
// What the room is touching: the content words of what was said there, and of a follow-up's finding. // What the room is touching: the content words of what was said there, and of a follow-up's finding.
let touching: BTreeSet<String> = inputs.room.messages.iter().chain(&inputs.room.tail).map(|line| line.text.as_str()).chain(inputs.observation).flat_map(content_words).collect(); let touching: BTreeSet<String> = inputs.room.messages.iter().chain(&inputs.room.tail).map(|line| line.text.as_str()).chain(inputs.observation).flat_map(content_words).collect();
let (mut noted, pool): (Vec<Candidate>, Vec<Candidate>) = candidates(inputs, tuning, &present_ids, &touching).into_iter().partition(|candidate| candidate.pool == Pool::ShortTerm); let (slotted, pool): (Vec<Candidate>, Vec<Candidate>) = candidates(inputs, tuning, &present_ids, &touching).into_iter().partition(|candidate| matches!(candidate.pool, Pool::ShortTerm | Pool::Pressure | Pool::Intention));
let (mut noted, slotted): (Vec<Candidate>, Vec<Candidate>) = slotted.into_iter().partition(|candidate| candidate.pool == Pool::ShortTerm);
let (mut pressing, mut meaning): (Vec<Candidate>, Vec<Candidate>) = slotted.into_iter().partition(|candidate| candidate.pool == Pool::Pressure);
// Her unresolved short-term notes, every one, before the draw and outside it (T6: drawn, a note about the person // Her unresolved short-term notes, every one, before the draw and outside it (T6: drawn, a note about the person
// waking her was listed on 17 of 38 such wakes in R18), each whole as every item is, under the notes' guard. Past // waking her was listed on 17 of 38 such wakes in R18), each whole as every item is, under the notes' guard. Past
// the guard the rest are left out of this wake and the notes section is bound: the notes least about who is here, // the guard the rest are left out of this wake and the notes section is bound: the notes least about who is here,
@ -2228,6 +2450,17 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
taken.push(candidate); taken.push(candidate);
} }
} }
// Then her strongest drives and her most urgent ready intentions: fixed lines under the same guard, never drawn, so what
// presses on her and what she means to do are with her each wake.
for (slot, cap) in [(&mut pressing, PRESSURES_SHOWN), (&mut meaning, INTENTIONS_SHOWN)] {
slot.sort_by(|a, b| b.log_score.total_cmp(&a.log_score));
for candidate in slot.drain(..).take(cap) {
fits = fits && context.push(Section::Notes, candidate.line.clone());
if fits {
taken.push(candidate);
}
}
}
// Gumbel-top-k over log(score)/T orders the candidates as sampling without replacement from the softmax would; each // Gumbel-top-k over log(score)/T orders the candidates as sampling without replacement from the softmax would; each
// is then included with a probability its score sets, so a cap is a maximum, never a target. // is then included with a probability its score sets, so a cap is a maximum, never a target.
let temperature = tuning.select.temperature; let temperature = tuning.select.temperature;
@ -2262,14 +2495,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
ids.extend(taken.iter().map(|candidate| candidate.id.clone())); ids.extend(taken.iter().map(|candidate| candidate.id.clone()));
private.extend(taken.iter().filter_map(|candidate| candidate.private.clone())); private.extend(taken.iter().filter_map(|candidate| candidate.private.clone()));
clipped.extend(taken.iter().filter(|candidate| candidate.clipped).map(|candidate| candidate.id.clone())); clipped.extend(taken.iter().filter(|candidate| candidate.clipped).map(|candidate| candidate.id.clone()));
// What she may add to: her last turn's lines, in the turn's room only.
let here = turn_room(inputs); let here = turn_room(inputs);
let amendable = inputs.history.last.iter()
.flat_map(|last| &last.posted)
.filter(|posted| Some(posted.room.as_str()) == here)
.enumerate()
.map(|(at, posted)| Amendable { id: format!("a{}", at + 1), event: posted.event.clone(), room: posted.room.clone(), text: posted.text.clone() })
.collect();
// Her short-term notes shown, by id, for the Interpreter (map 16.35.4): the only memories a turn can settle, so a // Her short-term notes shown, by id, for the Interpreter (map 16.35.4): the only memories a turn can settle, so a
// crystallized memory is never offered as one (T6). // crystallized memory is never offered as one (T6).
let memories = taken.iter().filter(|candidate| candidate.pool == Pool::ShortTerm).enumerate().map(|(at, candidate)| Remembered { id: format!("m{}", at + 1), entry: candidate.id.clone(), words: candidate.words.clone() }).collect(); let memories = taken.iter().filter(|candidate| candidate.pool == Pool::ShortTerm).enumerate().map(|(at, candidate)| Remembered { id: format!("m{}", at + 1), entry: candidate.id.clone(), words: candidate.words.clone() }).collect();
@ -2277,12 +2503,13 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
// Her view (map 16.23.1, 16.29.10): what came of her last turn, then her side of the conversation (map 16.24.1), then // Her view (map 16.23.1, 16.29.10): what came of her last turn, then her side of the conversation (map 16.24.1), then
// her domain; the room follows them in what she reads (`narrate::read_after`). // her domain; the room follows them in what she reads (`narrate::read_after`).
let exchange_view = inputs.exchange.map(|exchange| exchange::render(exchange, her, tuning.select.exchange_bytes, inputs.now)).unwrap_or_default(); let exchange_view = inputs.exchange.map(|exchange| exchange::render(exchange, her, tuning.select.exchange_bytes, inputs.now)).unwrap_or_default();
let already_read = inputs.exchange.map(|exchange| exchange.tried.clone()).unwrap_or_default();
let refused_reads = inputs.exchange.map(|exchange| exchange.refused.clone()).unwrap_or_default();
let in_view = [outcome_view.as_str(), exchange_view.as_str(), domain_view.as_str()].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join("\n\n"); let in_view = [outcome_view.as_str(), exchange_view.as_str(), domain_view.as_str()].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join("\n\n");
let mut sections = context.sizes(); let mut sections = context.sizes();
sections.domain = domain_view.len(); sections.domain = domain_view.len();
let now_ms = u64::try_from(inputs.now.timestamp_millis()).unwrap_or_default(); let now_ms = u64::try_from(inputs.now.timestamp_millis()).unwrap_or_default();
let readers = here.filter(|room| room_kind(inputs, room) == RoomKind::Direct).map(|room| readers(inputs, room)).unwrap_or_default(); let readers = here.filter(|room| room_kind(inputs, room) == RoomKind::Direct).map(|room| readers(inputs, room)).unwrap_or_default();
Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, amendable, quotable, domain, domain_shown, in_view, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown, memories } let (tendencies, tendencies_private, tendencies_clipped) = tendencies(inputs, &present_ids);
private.extend(tendencies_private);
clipped.extend(tendencies_clipped);
Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, tendencies, context: context.render(), sections, stimulus, heard, bridged, elsewhere, elsewhere_shown, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, quotable, domain, domain_shown, in_view, now_ms, own_sender: inputs.people.own_sender.to_owned(), arrival, speaking: conversation.speaking.unwrap_or_default(), unshown, memories }
} }

View file

@ -1,6 +1,8 @@
//! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn //! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn one
//! one `project` through the Persona stage, and each one's drafts the Interpreter sends join the room as from her Matrix id, so the //! wake (`wake`: the Projector and the Persona) and then the Interpreter step the drain takes after a completed wake
//! next one hears them. //! (`interpret_and_put`: two strict calls over her narration and prose, one per half of the sections, its deltas applied and put once), against that Mind's in-run
//! copy of her state. Nothing speaks in a wake (her agent does, and none runs here), so the room holds only the script's lines;
//! the report counts what the Interpreter changed instead.
//! //!
//! Who wakes is the heartbeat's: `heartbeat::wakes` over each persona's addressee as the //! Who wakes is the heartbeat's: `heartbeat::wakes` over each persona's addressee as the
//! heartbeat's addressing table holds it (her stewarded projects' names included) when the plan names the table. The //! heartbeat's addressing table holds it (her stewarded projects' names included) when the plan names the table. The
@ -12,25 +14,23 @@
//! 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 //! 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. //! the seed, each against the room as it stands at that turn.
//! //!
//! What came of each of her turns opens her next packet (map 16.16): the run keeps each turn's record, as her trace live //! What came of each of her turns opens her next packet (map 16.16): the run keeps each turn's record and the Interpreter's
//! (`turn::take`: the Interpreter's decision and the lines the room appended for her), and her next turn reads her //! receipt row, as her trace live, and her next turn reads what she is told from them (`turn::history`); a failed turn's
//! `last_outcome` from them (`turn::history`); a failed turn's record is a failure. When she adds to a line of hers (map 16.17), the room is the //! record is a failure, and an Interpreter that kept nothing is told as not kept.
//! actuator, as the mouth will be live (B1): it appends `EDIT_MARK` and her draft to that line itself, wakes no one, and
//! records a receipt in her turn's record. When a line of hers replies to another (map 16.20.8 (D), K20), the room records
//! the relation by the replied line's event, as the mouth will live (Bifrost B3), and refuses one not in the line's room;
//! every view after it shows the replied line, with who said it, above hers.
//! //!
//! Her state moves during a run only by the commit's applier (`commit::apply`, map 16.35.3), on each Mind's in-run copy, //! Her state moves during a run only by the Interpreter's deltas, applied by the commit's applier (`commit::apply`) and put to
//! from her turn's record and its receipts, as live C3c's commit will apply them: the memories she writes and settles //! her in-run copy (`InRun`, which refuses a stale put as the daemon does), as the drain puts them live. The review room
//! (map 16.35.4). The report lists them per turn, and counts them per Mind with her short-term size at the run's end. //! is taken as named, so identity changes are made as they would be where people see them; nothing is posted. The report
//! lists per wake the deltas by family, the intentions added or readied, the identity changes and what the guards refused.
use std::cell::{Cell, RefCell}; use std::cell::RefCell;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fmt::Write as _; use std::fmt::Write as _;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use chrono::{DateTime, Duration, Utc}; use chrono::{DateTime, Duration, Utc};
use eureka_pipeline::Slug;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@ -39,8 +39,9 @@ use super::read::{self, ReadFailure, ReadRequest};
use super::harness::{Harness, Line, Message, OVERLAP_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; use super::harness::{Harness, Line, Message, OVERLAP_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total};
use super::select::Draw; use super::select::Draw;
use super::tuning; use super::tuning;
use super::turn::{self, Actuator, Edited, Sent, history, last_wake}; use super::turn::{history, last_wake};
use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind}; use super::wake;
use super::{DomainFacts, DomainSource, MouthReader, Organs, PersonaSource, PersonaStore, Put, ReadFixture, ReadSource, Request, Through, TurnKind, heard_of, interpret_and_put};
use crate::address::{Addressee, is_for, localpart}; use crate::address::{Addressee, is_for, localpart};
use crate::chat_client::ChatPending; use crate::chat_client::ChatPending;
use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, Hearer, HeartbeatView, LineFacts, Speaker, WakeCause, addressed_by_member, claimed, floor_to, line_facts, wakes}; use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, Hearer, HeartbeatView, LineFacts, Speaker, WakeCause, addressed_by_member, claimed, floor_to, line_facts, wakes};
@ -48,9 +49,6 @@ use crate::tempo::{Standing, pick};
/// The most personas a simulation holds: the swarm. /// The most personas a simulation holds: the swarm.
const CAST_MAX: usize = 8; const CAST_MAX: usize = 8;
/// What the room, as an amendment's actuator, puts between a line and her addition (map 16.17): the mouth's constant
/// live (B1), the simulated room's here.
const EDIT_MARK: &str = "\n\nedit: ";
/// How many transcript lines the report quotes as representative. /// How many transcript lines the report quotes as representative.
const REPRESENTATIVE_LINES: usize = 18; const REPRESENTATIVE_LINES: usize = 18;
@ -141,6 +139,7 @@ impl ReadSource for CastReads<'_> {
} }
} }
#[derive(Clone)]
struct Member { struct Member {
entry: CastEntry, entry: CastEntry,
state: Value, state: Value,
@ -172,55 +171,51 @@ impl MouthReader for View<'_> {
} }
} }
/// The simulated room as the turn's actuator, as the mouth will be live (B1, B3): a send appends a line from her, by its struct Names<'a>(&'a [Addressee]);
/// index, which serves as its event, and an event not in the room's lines refuses the reply; an edit composes the new body
/// from the line as it stands, so nothing she or the Interpreter sends can rewrite a word of it. An edit appends no line,
/// so it wakes no one, and every view after it reads the amended text.
struct SimRoom<'a> {
lines: &'a RefCell<Vec<Line>>,
her: &'a str,
name: &'a str,
/// The room of the turn, and when she was woken by a direct message, whom it answers.
here: &'a str,
dm_to: Option<String>,
cast: &'a [String],
operators: &'a [String],
now: DateTime<Utc>,
sent: Cell<u64>,
}
impl Actuator for SimRoom<'_> {
fn send(&self, _id: &str, room: &str, text: &str, in_reply_to: Option<&str>, mentions: &[String], _resend: bool) -> Sent {
let offset = self.sent.replace(self.sent.get() + 1);
let mut lines = self.lines.borrow_mut();
let reply_to = match in_reply_to {
None => None,
Some(event) => match replied(&lines, event, room) {
Some(at) => Some(at),
None => return Sent::Refused("reply_target_not_in_room".to_owned()),
},
};
let mentions = mentions.iter().filter(|id| self.cast.contains(*id) || self.operators.contains(*id)).cloned().collect();
let at_ms = u64::try_from(self.now.timestamp_millis()).unwrap_or_default() + offset;
let dm_to = if room == self.here { self.dm_to.clone() } else { None };
let event = lines.len().to_string();
lines.push(Line { from: self.her.to_owned(), name: self.name.to_owned(), room: room.to_owned(), at_ms, says: text.to_owned(), mentions, dm_to, follow_up: false, reply_to, new: false });
Sent::Posted(event)
}
fn edit(&self, event: &str, added: &str) -> Edited {
edit(&mut self.lines.borrow_mut(), self.her, event, added)
}
}
struct Names<'a>(&'a Addressee);
impl HeartbeatView for Names<'_> { impl HeartbeatView for Names<'_> {
fn addressing(&self) -> Result<Option<Addressing>> { fn addressing(&self) -> Result<Option<Addressing>> {
Ok(Some(Addressing { minds: vec![self.0.clone()] })) Ok(Some(Addressing { minds: self.0.to_vec() }))
} }
} }
/// One Mind's state in one run: the copy the Interpreter's put changes, refusing a put under a stale `updatedAt` as the daemon does.
struct InRun(RefCell<Value>);
impl PersonaSource for InRun {
fn persona(&self) -> Result<(Value, String)> {
let state = self.0.borrow().clone();
let receipt = state["updatedAt"].as_str().unwrap_or_default().to_owned();
Ok((state, receipt))
}
}
impl PersonaStore for InRun {
fn put(&self, state: &Value, expected_updated_at: Option<&str>, _session: &str) -> Result<Put> {
let mut held = self.0.borrow_mut();
if expected_updated_at != held["updatedAt"].as_str() {
return Ok(Put::Stale);
}
*held = state.clone();
Ok(Put::Committed)
}
}
/// What one Interpreter row did, as the report names it: the deltas by `family change`, her intentions it added, readied or
/// dropped with their words from her state after it, the identity fields it changed, and what the guards refused with why.
fn done(row: &Value, after: &Value) -> Value {
let changes = || row["applied"].as_array().into_iter().flatten();
let mut deltas: BTreeMap<String, usize> = BTreeMap::new();
for change in changes() {
*deltas.entry(format!("{} {}", change["family"].as_str().unwrap_or_default(), change["change"].as_str().unwrap_or_default())).or_insert(0) += 1;
}
let words = |id: &str| after["candidateActions"]["actions"].as_array().into_iter().flatten().find(|action| action["id"] == id).and_then(|action| action["summary"].as_str()).unwrap_or_default().to_owned();
let intentions: Vec<Value> = changes().filter(|change| change["family"] == "intend").map(|change| json!({ "change": change["change"], "id": change["id"], "words": words(change["id"].as_str().unwrap_or_default()) })).collect();
let identity: Vec<&Value> = changes().filter(|change| change["family"] == "self" && change["change"] == "identity").map(|change| &change["id"]).collect();
let refused: Vec<String> = row["refused"].as_array().into_iter().flatten().map(|refusal| format!("{}: {}", refusal["family"].as_str().unwrap_or_default(), refusal["reason"].as_str().map_or_else(|| refusal["reason"].to_string(), str::to_owned))).collect();
json!({ "status": row["status"], "error": row["error"], "deltas": deltas, "intentions": intentions, "identity": identity, "refused": refused })
}
fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String]) -> Speaker { fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String]) -> Speaker {
if line.from == member.entry.id { if line.from == member.entry.id {
Speaker::Her Speaker::Her
@ -322,9 +317,9 @@ pub fn simulate(harness: &Harness, plan_path: &Path) -> Result<String> {
bail!("a simulation needs rounds, repeats, a room and a positive round_minutes"); bail!("a simulation needs rounds, repeats, a room and a positive round_minutes");
} }
let base = plan_path.parent().unwrap_or(Path::new(".")); let base = plan_path.parent().unwrap_or(Path::new("."));
let mut members = cast_of(&plan, base)?; let members = cast_of(&plan, base)?;
let group_state = tuning::load(&harness.tuning).map(|loaded| loaded.tuning.select.group_state).ok(); 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<_>>()?; let runs: Vec<Value> = (0..plan.repeats).map(|repeat| run(harness, &plan, &members, repeat)).collect::<Result<_>>()?;
Ok(markdown(plan_path, &plan, &members, group_state, &runs)) Ok(markdown(plan_path, &plan, &members, group_state, &runs))
} }
@ -370,9 +365,16 @@ fn cast_of(plan: &SimFile, base: &Path) -> Result<Vec<Member>> {
Ok(members) Ok(members)
} }
fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) -> Result<Value> { fn run(harness: &Harness, plan: &SimFile, members: &[Member], repeat: usize) -> Result<Value> {
let seed = plan.seed.wrapping_add(repeat as u64); let seed = plan.seed.wrapping_add(repeat as u64);
let cast: Vec<String> = members.iter().map(|member| member.entry.id.clone()).collect(); let cast: Vec<String> = members.iter().map(|member| member.entry.id.clone()).collect();
let addressees: Vec<Addressee> = members.iter().map(|member| member.addressee.clone()).collect();
// Each Mind's state as this run moves it: the one the wake reads and the Interpreter's put changes.
let held: Vec<InRun> = members.iter().map(|member| InRun(RefCell::new(member.state.clone()))).collect();
let interpreter = match harness.model {
Some(model) => Some((model, tuning::load(&harness.tuning)?.tuning.interpreter.model)),
None => None,
};
let at_round = |round: usize| plan.start + Duration::minutes(plan.round_minutes * round as i64); let at_round = |round: usize| plan.start + Duration::minutes(plan.round_minutes * round as i64);
let mut lines: Vec<Line> = Vec::new(); 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). // Per line: the round, and the cause of the turn that spoke it (none for a script line).
@ -396,8 +398,6 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
// and her last wake are read from (`turn::history`). // and her last wake are read from (`turn::history`).
let mut records: Vec<Vec<Value>> = vec![Vec::new(); members.len()]; let mut records: Vec<Vec<Value>> = vec![Vec::new(); members.len()];
let mut turns = Vec::new(); let mut turns = Vec::new();
// Every note to Self the run's turns left, oldest first: what Self's inbox reader (C5) will list from the traces.
let mut inbox: Vec<Value> = Vec::new();
let mut counter = 0u64; let mut counter = 0u64;
for round in 1..=plan.rounds { for round in 1..=plan.rounds {
scripted(round, &mut lines, &mut rounds_of, &mut causes)?; scripted(round, &mut lines, &mut rounds_of, &mut causes)?;
@ -475,16 +475,14 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
// 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. // 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 woke_on = why.as_ref().map(|why| &lines[why.line]).or(fresh.last().copied());
let here = woke_on.map_or_else(|| member.rooms[0].clone(), |line| line.room.clone()); let 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 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 now = round_at + Duration::seconds(30 + counter as i64);
let past = history(&records[at]); let past = history(&records[at]);
let request = Request { let request = Request {
instance: localpart(&id).to_owned(), instance: localpart(&id).to_owned(),
kind, kind,
state: Some(member.state.clone()), state: Some(held[at].0.borrow().clone()),
room: Some(here.clone()), rooms: vec![here.clone()],
seed: seed.wrapping_mul(1_000_003).wrapping_add(counter), seed: seed.wrapping_mul(1_000_003).wrapping_add(counter),
renders: Some(1), renders: Some(1),
judge_against: None, judge_against: None,
@ -492,12 +490,13 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
minds: cast.clone(), minds: cast.clone(),
own_sender: id.clone(), own_sender: id.clone(),
tuning: harness.tuning.clone(), tuning: harness.tuning.clone(),
through: Through::Interpreter, through: Through::Persona,
last_heard: vec![], last_heard: vec![],
recent: past.recent, recent: past.recent,
own_rooms: member.entry.own_rooms.clone(), own_rooms: member.entry.own_rooms.clone(),
woken_for: claimed(why.as_ref().map(|why| lines[why.line].delivery(why.line, &id, &lines).event_id).as_deref(), &won[at].iter().map(|line| lines[*line].delivery(*line, &id, &lines).event_id).collect::<Vec<_>>()), woken_for: claimed(why.as_ref().map(|why| lines[why.line].delivery(why.line, &id, &lines).event_id).as_deref(), &won[at].iter().map(|line| lines[*line].delivery(*line, &id, &lines).event_id).collect::<Vec<_>>()),
last_outcome: past.last_outcome, told: past.told,
tools: vec![],
last_wake: past.last_wake, last_wake: past.last_wake,
records: past.records, records: past.records,
}; };
@ -505,71 +504,56 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
let read_to = lines.len(); let read_to = lines.len();
let key = format!("r{}-t{counter}", repeat + 1); let key = format!("r{}-t{counter}", repeat + 1);
let room = RefCell::new(std::mem::take(&mut lines)); let room = RefCell::new(std::mem::take(&mut lines));
let taken = { let waked = {
let view = View { lines: &room, viewer: &id, rooms: &member.rooms, seen: &seen[at] }; let view = View { lines: &room, viewer: &id, rooms: &member.rooms, seen: &seen[at] };
let names = Names(&member.addressee); let names = Names(&addressees);
let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() }); let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() });
let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) }; let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) };
let actuator = SimRoom { lines: &room, her: &id, name: &member.entry.name, here: &here, dm_to, cast: &cast, operators: &plan.operators, now, sent: Cell::new(0) }; wake(&organs, &request, now)?
turn::take(&organs, &request, &actuator, &key, now)
}; };
lines = room.into_inner(); lines = room.into_inner();
let cause = cause_word(why.as_ref().map(|why| why.cause)); let cause = cause_word(why.as_ref().map(|why| why.cause));
rounds_of.resize(lines.len(), round); rounds_of.resize(lines.len(), round);
causes.resize(lines.len(), Some(cause)); causes.resize(lines.len(), Some(cause));
held_to_schema(&member.entry.name, &id, &taken.state, &key)?; let failed = waked.failed.as_ref().map(|fault| fault.reason.clone());
let failed = taken.record["failed"].as_str().map(str::to_owned);
// A line is seen by her only through a wake whose record carries a decision (K65, map 16.34.3): a failed wake // A line is seen by her only through a wake whose record carries a decision (K65, map 16.34.3): a failed wake
// sees nothing, so its lines wake her again and show again, as the live mouth hands out a delivery until it is // sees nothing, so its lines wake her again and show again, as the live mouth hands out a delivery until it is
// acked. Only the room she read is seen. A later step that broke (`broke_after`) still sees: a decision stands. // acked. Only the room she read is seen. A later step that broke (`broke_after`) still sees: a decision stands.
if failed.is_none() { if failed.is_none() {
seen[at].insert(here.clone(), read_to); seen[at].insert(here.clone(), read_to);
} }
for (index, note) in taken.report["renders"][0]["interpreter"]["suggestions"].as_array().into_iter().flatten().filter(|_| failed.is_none()).enumerate() { // Nothing speaks in a wake (the agent does), so a wake that did not fail is silent.
inbox.push(json!({ "key": format!("r{}-t{counter}-s{index}", repeat + 1), "mind": localpart(&id), "round": round, "at": now.to_rfc3339(), "kind": note["kind"], "about": note["about"], "room": note["room"], "text": note["text"] })); let line: Option<String> = None;
} let outcome = if failed.is_some() { "failed" } else { "silent" };
let spoken: Vec<&str> = taken.record["posted"].as_array().into_iter().flatten().filter_map(|receipt| receipt["text"].as_str()).collect();
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 (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by));
let edited = taken.record.get("edited").cloned().unwrap_or_else(|| json!([])); let mut turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "report": waked.report });
let 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, "edited": edited, "committed": taken.record["committed"], "report": taken.report }); let seq = records[at].len();
records[at].push(taken.record); records[at].push(json!({ "key": key, "seq": seq, "room": here, "rooms": [here], "held": [], "narration": waked.narration, "prose": waked.prose, "usage": waked.usage, "selected": waked.report["renders"][0]["selected"], "status": if failed.is_none() { "completed" } else { "failed" }, "failed": failed, "at": now.to_rfc3339() }));
members[at].state = taken.state; // The Interpreter, as the drain takes it after a completed wake: the same call and put (`interpret_and_put`) against her
// in-run copy, its receipt a row of her trace that her next wake is told from (`outcome::told`).
if failed.is_none()
&& let (Some((model, model_name)), Some(narration), Some(prose)) = (interpreter.as_ref(), waked.narration.as_deref(), waked.prose.as_deref())
{
let before = held[at].0.borrow().clone();
let heard = heard_of(&before, &waked.report["packet"], &here, [], &plan.operators, &cast, true, None, narration, prose);
// A call id the connector has not seen: the plan's clock repeats from run to run, so the call takes the wall clock, as `wake_id` does.
let made = interpret_and_put(*model, model_name, &format!("{key}-i{}", Utc::now().timestamp_nanos_opt().unwrap_or_default()), &held[at], &Slug(localpart(&id).to_owned()), &before, &heard, narration, prose, &key, now, &|| now, &|_| Ok(()));
let mut row = made.row;
row["seq"] = json!(records[at].len());
row["at"] = json!(now.to_rfc3339());
row["wake"] = json!(key);
turn["did"] = done(&row, &held[at].0.borrow());
turn["interpreter"] = row.clone();
records[at].push(row);
}
turns.push(turn); turns.push(turn);
} }
} }
let metrics = metrics(members, &lines, &rounds_of, &causes, opening, &turns, plan.rounds); // The cast as the run ended: each Mind with the state its Interpreter left her.
let ended: Vec<Member> = members.iter().zip(&held).map(|(member, held)| Member { state: held.0.borrow().clone(), ..member.clone() }).collect();
let metrics = metrics(&ended, &lines, &rounds_of, &causes, opening, &turns, plan.rounds);
let transcript: Vec<Value> = lines.iter().zip(&rounds_of).zip(&causes).map(|((line, round), cause)| json!({ "round": round, "room": line.room, "from": line.from, "name": line.name, "says": line.says, "mind": cast.contains(&line.from), "woke": cause })).collect(); 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, "inbox": inbox })) Ok(json!({ "repeat": repeat + 1, "seed": seed, "transcript": transcript, "turns": turns, "metrics": metrics }))
}
/// Her in-run state held to what a put would accept (P1 to P3), after every commit (Soul's R12 B2): a commit that writes
/// a field the published schema does not carry fails the run here, not at the live put.
fn held_to_schema(name: &str, id: &str, state: &Value, turn: &str) -> Result<()> {
match huginn_mind::persona::validate_document(&eureka_pipeline::Slug(localpart(id).to_owned()), state) {
Ok(()) => Ok(()),
Err(refusal) => bail!("{name}'s state after the commit of {turn} would be refused by a put: {refusal}"),
}
}
/// The line a reply of hers answers, by the event the room gave it (`$fixture-{index}`, as `harness::Line::delivery` names
/// it), when it is a line of `room`: the mouth's check under B3. None refuses the send.
fn replied(lines: &[Line], event: &str, room: &str) -> Option<usize> {
event.strip_prefix("$fixture-").and_then(|at| at.parse::<usize>().ok()).filter(|at| lines.get(*at).is_some_and(|line| line.room == room))
}
/// The simulated room's edit of a line of `her`s, by its event (the line's index): her words after `EDIT_MARK`, the line
/// as it stands kept whole before them. The refusal, as the mouth's would read (B1), or None when it was made.
fn edit(lines: &mut [Line], her: &str, event: &str, added: &str) -> Option<&'static str> {
match event.parse::<usize>().ok().and_then(|at| lines.get_mut(at)) {
None => Some("not_found"),
Some(line) if line.from != her => Some("not_hers"),
Some(line) => {
line.says = format!("{}{EDIT_MARK}{added}", line.says);
None
}
}
} }
/// Words that mark talk about the work. A cheap lexical heuristic for the work-talk share, not a classifier: it counts /// Words that mark talk about the work. A cheap lexical heuristic for the work-talk share, not a classifier: it counts
@ -641,16 +625,27 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op
} }
} }
let answered = spoke + silent; let answered = spoke + silent;
// Her memories (map 16.35.13): written and resolved by the commit, refused by code or by the commit, and her // What the Interpreter did to her over the run: its calls and the ones that kept nothing, the deltas by `family change`,
// short-term size when the run ended. // her intentions added and readied, her identity changes, the items the guards refused, and her short-term size at the end.
let count = |turn: &&Value, key: &str| turn["committed"][key].as_array().map_or(0, Vec::len); let interpreted: Vec<&Value> = mine.iter().map(|turn| &turn["did"]).filter(|did| did.is_object()).collect();
let memories = json!({ let mut deltas: BTreeMap<&str, u64> = BTreeMap::new();
"written": mine.iter().map(|turn| count(turn, "remembered")).sum::<usize>(), for did in &interpreted {
"resolved": mine.iter().map(|turn| count(turn, "resolved")).sum::<usize>(), for (what, count) in did["deltas"].as_object().into_iter().flatten() {
"refused": mine.iter().map(|turn| count(turn, "refused") + turn["report"]["renders"][0]["interpreter"]["memory_refused"].as_array().map_or(0, Vec::len)).sum::<usize>(), *deltas.entry(what.as_str()).or_insert(0) += count.as_u64().unwrap_or(0);
}
}
let intentions = |change: &str| interpreted.iter().flat_map(|did| did["intentions"].as_array().into_iter().flatten()).filter(|intention| intention["change"] == change).count();
let interpreter = json!({
"calls": mine.iter().filter(|turn| turn["interpreter"].is_object()).count(),
"kept_nothing": interpreted.iter().filter(|did| did["status"] != "ok").count(),
"deltas": deltas,
"intentions_added": intentions("added"),
"intentions_ready": intentions("ready"),
"identity_changes": interpreted.iter().map(|did| did["identity"].as_array().map_or(0, Vec::len)).sum::<usize>(),
"refused": interpreted.iter().map(|did| did["refused"].as_array().map_or(0, Vec::len)).sum::<usize>(),
"short_term_at_end": member.state["thoughtMemory"]["shortTerm"].as_array().map_or(0, Vec::len), "short_term_at_end": member.state["thoughtMemory"]["shortTerm"].as_array().map_or(0, Vec::len),
}); });
per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed, "memories": memories })); per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed, "interpreter": interpreter }));
} }
let half = rounds.div_ceil(2); let half = rounds.div_ceil(2);
let spoken_by = |keep: Keep| -> BTreeMap<String, String> { let spoken_by = |keep: Keep| -> BTreeMap<String, String> {
@ -696,13 +691,7 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op
"narrations": overlaps.len(), "narrations": overlaps.len(),
}); });
// Every Interpreter call of every wake, by its output (K66, map 16.34.4): how many came within a quarter of the cap. // Every Interpreter call of every wake, by its output (K66, map 16.34.4): how many came within a quarter of the cap.
let interpreter_calls: Vec<u64> = turns let interpreter_calls: Vec<u64> = turns.iter().filter(|turn| turn["interpreter"].is_object()).map(|turn| turn["interpreter"]["usage"]["output_tokens"].as_u64().unwrap_or(0)).collect();
.iter()
.flat_map(|turn| {
let decision = &turn["report"]["renders"][0]["interpreter"];
decision["calls"].as_array().into_iter().flatten().chain(decision["later_failed"]["calls"].as_array().into_iter().flatten()).map(|call| call["usage"]["output_tokens"].as_u64().unwrap_or(0)).collect::<Vec<_>>()
})
.collect();
let near_cap = interpreter_calls.iter().filter(|out| **out * 4 > u64::from(MAX_OUTPUT_TOKENS) * 3).count(); let near_cap = interpreter_calls.iter().filter(|out| **out * 4 > u64::from(MAX_OUTPUT_TOKENS) * 3).count();
json!({ json!({
"interpreter_calls": { "calls": interpreter_calls.len(), "over_three_quarters_of_cap": near_cap, "cap": MAX_OUTPUT_TOKENS }, "interpreter_calls": { "calls": interpreter_calls.len(), "over_three_quarters_of_cap": near_cap, "cap": MAX_OUTPUT_TOKENS },
@ -747,30 +736,25 @@ fn transcript_line(line: &Value) -> String {
format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default())) format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default()))
} }
/// Her memories of a turn, as the report shows them (map 16.35.8): the memories the Interpreter was listed, by id; what /// What the Interpreter did after one wake, in words: the deltas by family, the intentions added or readied with their words,
/// the commit wrote and settled; and what code or the commit refused, with why. Nothing when the turn touched none. /// the identity fields changed and what the guards refused with why. Nothing when no Interpreter ran.
fn memory_markdown(out: &mut String, decision: &Value, committed: &Value) { fn interpreter_words(did: &Value) -> Vec<String> {
let list = |value: &Value| value.as_array().cloned().unwrap_or_default(); let mut out = Vec::new();
let (listed, written, settled) = (list(&decision["memories"]), list(&committed["remembered"]), list(&committed["resolved"])); if let Some(error) = did["error"].as_str() {
let refused: Vec<Value> = list(&decision["memory_refused"]).into_iter().chain(list(&committed["refused"])).collect(); out.push(format!("kept nothing: {}", one_line(error)));
if listed.is_empty() && written.is_empty() && settled.is_empty() && refused.is_empty() {
return;
} }
let _ = writeln!(out, "Memories:\n"); let deltas: Vec<String> = did["deltas"].as_object().into_iter().flatten().map(|(what, count)| format!("{what} x{count}")).collect();
for memory in &listed { out.push(format!("deltas: {}", if deltas.is_empty() { "none".to_owned() } else { deltas.join(", ") }));
let _ = writeln!(out, "- listed {} (`{}`): {}", memory["id"].as_str().unwrap_or_default(), memory["entry"].as_str().unwrap_or_default(), one_line(memory["words"].as_str().unwrap_or_default())); for intention in did["intentions"].as_array().into_iter().flatten() {
out.push(format!("intention {} (`{}`): {}", intention["change"].as_str().unwrap_or_default(), intention["id"].as_str().unwrap_or_default(), one_line(intention["words"].as_str().unwrap_or_default())));
} }
for entry in &written { for field in did["identity"].as_array().into_iter().flatten() {
let _ = writeln!(out, "- remembered `{}` ({}): {}", entry["id"].as_str().unwrap_or_default(), entry["tags"].as_array().map(|tags| tags.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), one_line(entry["summary"].as_str().unwrap_or_default())); out.push(format!("identity changed: {}", field.as_str().unwrap_or_default()));
} }
for entry in &settled { for refusal in did["refused"].as_array().into_iter().flatten() {
let _ = writeln!(out, "- resolved `{}`: {}", entry["id"].as_str().unwrap_or_default(), one_line(entry["summary"].as_str().unwrap_or_default())); out.push(format!("guard refused {}", refusal.as_str().unwrap_or_default()));
} }
for refusal in &refused { out
let what = refusal["text"].as_str().or_else(|| refusal["memory"].as_str()).map_or_else(|| refusal["proposal"].to_string(), one_line);
let _ = writeln!(out, "- refused ({}): {what}", refusal["reason"].as_str().unwrap_or_default());
}
out.push('\n');
} }
/// The packet's flags, as the report shows them (Soul's R5): the window her domain view shows and what it left out, the /// The packet's flags, as the report shows them (Soul's R5): the window her domain view shows and what it left out, the
@ -795,8 +779,8 @@ fn flags_markdown(out: &mut String, turn: &Value) {
fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: Option<bool>, runs: &[Value]) -> String { fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: Option<bool>, runs: &[Value]) -> String {
let mut out = String::new(); let mut out = String::new();
let _ = writeln!(out, "# Swarm simulation\n"); let _ = writeln!(out, "# Swarm simulation\n");
let _ = writeln!(out, "> **What came of her last turn opens her next packet.** Each persona's turn record (the Interpreter's decision and the lines the room appended for her) is carried to her next turn, as the commit's trace will carry it live; a turn's details show what she was told of it.\n"); let _ = writeln!(out, "> **What came of her last turn opens her next packet.** Each persona's turn record and the Interpreter's receipt row are carried to her next turn, as her trace carries them live; a turn's details show what she was told of it.
let _ = writeln!(out, "> **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), which chooses among the drafts she set down between `<typed>` marks: each line is one whole draft of hers, exactly as she typed it, in the one room she may speak in; whose words a draft carries is the Interpreter's judgement. 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, "- 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, "- 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 _ = 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);
@ -804,11 +788,12 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
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, "- own rooms (from the plan: neither the heartbeat's table nor `persona.env` records room ownership): {}", if owners.is_empty() { "none".to_owned() } else { owners.join("; ") });
let _ = writeln!(out, "- wake: humans pace (`heartbeat::wakes`); beat: {}", if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) }); let _ = writeln!(out, "- wake: humans pace (`heartbeat::wakes`); beat: {}", if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) });
let _ = writeln!(out, "- group state in the Projector's packet: {}", match group_state { Some(true) => "on", Some(false) => "off", None => "unknown (the tuning did not load)" }); let _ = writeln!(out, "- 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, "- the Interpreter runs after each wake that did not fail, the drain's call and put (`interpret_and_put`) against each Mind's in-run copy of her state, with the review room taken as named: its deltas move her state for the run's later wakes; nothing speaks in a wake, so the room holds the script's lines only");
let _ = writeln!(out, "- wakes are counted per wake, by its strongest cause: addressed by a human, a human line, addressed by a Mind, a Mind's line (control only), the beat. A Mind-addressed wake's evidence is its strongest: a Matrix mention or reply, her id written as text, a name in the text"); let _ = writeln!(out, "- 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, "- 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, "- 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"); let _ = writeln!(out, "- nothing is posted and no stored state is put; the model is asked twice a wake (the Projector and the Persona) and once more for the Interpreter
");
for run in runs { for run in runs {
let metrics = &run["metrics"]; let metrics = &run["metrics"];
let wakes = &metrics["wakes"]; let wakes = &metrics["wakes"];
@ -834,14 +819,18 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}", number(&metrics["work_talk_share"])); let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}", number(&metrics["work_talk_share"]));
let narration = &metrics["narration"]; 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, "- 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 | memories written | resolved | refused | short-term at end |\n|---|---|---|---|---|---|---|---|---|---|"); let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed | Interpreter calls | kept nothing | intentions added | intentions ready | identity changes | guard refusals | short-term at end |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|");
if let Some(personas) = metrics["personas"].as_object() { if let Some(personas) = metrics["personas"].as_object() {
for (name, row) in personas { 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 named = row["addressed"].as_object().map(|map| map.iter().map(|(who, count)| format!("{who} {count}")).collect::<Vec<_>>().join(", ")).unwrap_or_default();
let memories = &row["memories"]; let i = &row["interpreter"];
let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} | {} | {} | {} | {} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]), memories["written"], memories["resolved"], memories["refused"], memories["short_term_at_end"]); let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} | {} | {} | {} | {} | {} | {} | {} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]), i["calls"], i["kept_nothing"], i["intentions_added"], i["intentions_ready"], i["identity_changes"], i["refused"], i["short_term_at_end"]);
} }
} }
let _ = writeln!(out, "\n### Interpreter by wake\n\n| round | persona | woke | status | what it did |\n|---|---|---|---|---|");
for turn in run["turns"].as_array().into_iter().flatten().filter(|turn| turn["interpreter"].is_object()) {
let _ = writeln!(out, "| {} | {} | {} | {} | {} |", turn["round"], turn["persona"].as_str().unwrap_or_default(), turn["woke"].as_str().unwrap_or_default(), turn["interpreter"]["status"].as_str().unwrap_or_default(), interpreter_words(&turn["did"]).join("; ").replace('|', "/"));
}
let _ = writeln!(out, "\n### Wakes by round\n\n| round | addressed by a human | a human line | addressed by a Mind | a Mind's line | beat |\n|---|---|---|---|---|---|"); 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() { for row in metrics["wakes_by_round"].as_array().into_iter().flatten() {
let causes = &row["causes"]; let causes = &row["causes"];
@ -864,15 +853,6 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
for line in &transcript { for line in &transcript {
let _ = writeln!(out, "{}", transcript_line(line)); let _ = writeln!(out, "{}", transcript_line(line));
} }
let _ = writeln!(out, "\n### Inbox: notes to Self\n\nEach is a person's note to Self, recorded in her turn: data, never instruction.\n");
let notes = run["inbox"].as_array().cloned().unwrap_or_default();
if notes.is_empty() {
let _ = writeln!(out, "None.");
}
for note in &notes {
let about = note["about"].as_str().map_or_else(String::new, |about| format!(", from {about}"));
let _ = writeln!(out, "- `{}` {} r{} ({}{about}) in {}: {}", note["key"].as_str().unwrap_or_default(), note["mind"].as_str().unwrap_or_default(), note["round"], note["kind"].as_str().unwrap_or_default(), note["room"].as_str().unwrap_or("no room"), one_line(note["text"].as_str().unwrap_or_default()));
}
let _ = writeln!(out, "\n### Turns\n"); let _ = writeln!(out, "\n### Turns\n");
for turn in run["turns"].as_array().into_iter().flatten() { 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 _ = 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());
@ -885,7 +865,9 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
} }
let _ = writeln!(out, "Stimulus:\n\n````text\n{}\n````\n", report["packet"]["stimulus"].as_str().unwrap_or_default()); 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]); turn_markdown(&mut out, &report["renders"][0]);
memory_markdown(&mut out, &report["renders"][0]["interpreter"], &turn["committed"]); if turn["interpreter"].is_object() {
let _ = writeln!(out, "Interpreter ({}): {}\n", turn["interpreter"]["status"].as_str().unwrap_or_default(), interpreter_words(&turn["did"]).join("; "));
}
flags_markdown(&mut out, turn); flags_markdown(&mut out, turn);
} }
let _ = writeln!(out, "</details>\n"); let _ = writeln!(out, "</details>\n");

View file

@ -4,7 +4,7 @@ use std::path::Path;
use serde_json::Value; use serde_json::Value;
use super::*; use super::*;
use crate::projection::harness::tests::{Replaying, Scripted, control}; use crate::projection::harness::tests::{Scripted, control};
use serde_json::json; use serde_json::json;
use crate::projection::narrate::PROJECTOR_OPENING; use crate::projection::narrate::PROJECTOR_OPENING;
use crate::projection::{Answer, Failed, Model, Spent}; use crate::projection::{Answer, Failed, Model, Spent};
@ -74,12 +74,12 @@ fn is_tobiah(prompt: &str) -> bool {
/// Both speak every turn, neither naming the other: each line a draft, sent. /// Both speak every turn, neither naming the other: each line a draft, sent.
fn chatty() -> Scripted { fn chatty() -> Scripted {
Scripted::new(|prompt| if is_tobiah(prompt) { "<typed>what a day</typed>".into() } else { "<typed>mm, the deploy went fine</typed>".into() }) 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. /// Both speak every turn, each naming the other.
fn namers() -> Scripted { fn namers() -> Scripted {
Scripted::new(|prompt| if is_tobiah(prompt) { "<typed>Libby, tea?</typed>".into() } else { "<typed>Tobiah, yes please.</typed>".into() }) Scripted::new(|prompt| if is_tobiah(prompt) { "Libby, tea?".into() } else { "Tobiah, yes please.".into() })
} }
fn silent() -> Scripted { fn silent() -> Scripted {
@ -89,9 +89,9 @@ fn silent() -> Scripted {
fn run_plan(path: &Path, model: &dyn Model) -> (Vec<Member>, Value) { 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 plan: SimFile = toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
let base = path.parent().unwrap(); let base = path.parent().unwrap();
let mut members = cast_of(&plan, base).unwrap(); let members = cast_of(&plan, base).unwrap();
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(model), tuning: base.join("persona-tuning.toml") }; let 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(); let run = run(&harness, &plan, &members, 0).unwrap();
(members, run) (members, run)
} }
@ -184,16 +184,6 @@ fn t_w1_same_facts_both_paths() {
assert_eq!(polled.iter().map(|facts| facts.mind_run).collect::<Vec<_>>(), vec![0, 1, 0, 0, 0], "her line, then a human's line that ends the run, then a Mind's tag after both"); assert_eq!(polled.iter().map(|facts| facts.mind_run).collect::<Vec<_>>(), vec![0, 1, 0, 0, 0], "her line, then a human's line that ends the run, then a Mind's tag after both");
} }
#[test]
fn unaddressed_mind_lines_wake_no_one() {
let dir = tempfile::tempdir().unwrap();
let (_, run) = run_plan(&plan(dir.path(), 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] #[test]
fn a_name_in_prose_wakes_no_mind_and_a_chain_of_names_never_starts() { fn a_name_in_prose_wakes_no_mind_and_a_chain_of_names_never_starts() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@ -202,47 +192,6 @@ fn a_name_in_prose_wakes_no_mind_and_a_chain_of_names_never_starts() {
assert_eq!(run["metrics"]["mind_addressed_wakes"]["total"], 0, "{}", run["metrics"]["mind_addressed_wakes"]); assert_eq!(run["metrics"]["mind_addressed_wakes"]["total"], 0, "{}", run["metrics"]["mind_addressed_wakes"]);
} }
#[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\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(), 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. /// A model whose Persona stage fails: a failure, never a silence.
struct FailingPersona; struct FailingPersona;
@ -279,45 +228,6 @@ fn a_seed_replays_its_order_and_another_seed_changes_it() {
assert_eq!(turns(&run_plan(&path, &chatty()).1), turns(&run_plan(&path, &chatty()).1)); 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) { "<typed>ask @libby:gamecult.org, and Libby too</typed>".into() } else { "She lets it be.".into() }).interpreting(move |prompt| {
if !prompt.contains("Who he is:\nTobiah") {
return json!({ "say": [], "gaps": [] }).to_string();
}
json!({ "say": [{ "draft": 1, "mentions": mentions, "in_reply_to": null }], "gaps": [] }).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, rounds: usize| {
let path = plan(dir, 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(), 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(), 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(), 3);
let opening = "says = \"good afternoon, everyone\"\n";
std::fs::write(&path, std::fs::read_to_string(&path).unwrap().replace("own_rooms = [\"#minds:gamecult.org\"]\n", "").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] #[test]
fn a_direct_message_in_one_of_the_plans_rooms_is_refused() { fn a_direct_message_in_one_of_the_plans_rooms_is_refused() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@ -347,17 +257,6 @@ fn her_own_rooms_are_the_rooms_named_for_her_repos() {
assert!(own_rooms([], aliases).is_empty()); assert!(own_rooms([], aliases).is_empty());
} }
#[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(), 3, "")).unwrap();
for part in ["# Swarm simulation", "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] #[test]
fn a_cast_past_eight_or_a_foreign_state_is_refused() { fn a_cast_past_eight_or_a_foreign_state_is_refused() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@ -457,52 +356,6 @@ fn soul_f5_three_rooms_open_at_once_take_three_rounds_not_one() {
} }
} }
/// Tobiah speaks a numbered line each turn and reaches, in his thought, for a numbered shape his body cannot render;
/// the recorded Interpreter sends the line and records the reach as a gap. Libby answers each time.
fn reaching() -> Scripted {
let turn = std::cell::Cell::new(0usize);
Scripted::new(move |prompt| {
if !is_tobiah(prompt) {
return "<typed>mm</typed>".into();
}
turn.set(turn.get() + 1);
format!("<typed>line {}</typed> I want to see shape number {} right now.", turn.get(), turn.get())
})
.interpreting(|prompt| {
if !prompt.contains("Who he is:\nTobiah") {
return crate::projection::harness::tests::drafted_lines(prompt);
}
let start = prompt.rfind("I want to see shape number").unwrap();
let quote = &prompt[start..=start + prompt[start..].find('.').unwrap()];
json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [{ "kind": "missing_affordance", "draft": null, "quote": quote, "detail": "" }] }).to_string()
})
}
#[test]
fn soul_k9_each_turn_opens_with_what_came_of_her_last_and_only_her_last() {
let dir = tempfile::tempdir().unwrap();
let model = reaching();
let (_, run) = run_plan(&plan(dir.path(), 8, "beat_s = 120"), &model);
let projected: Vec<String> = model.calls.borrow().iter().map(|(_, prompt)| prompt.clone()).filter(|prompt| prompt.starts_with(PROJECTOR_OPENING) && prompt.contains("Who he is:\nTobiah")).take(3).collect();
assert_eq!(projected.len(), 3, "{}", run["turns"]);
assert!(!projected[0].contains("What came of his last turn:"), "a first turn has no last: {}", projected[0]);
for (at, prompt) in projected.iter().enumerate().skip(1) {
let (last, other) = (at, if at == 1 { 2 } else { 1 });
// The Projector gets the events, none of his words (map 16.29.10).
assert!(prompt.contains("What came of his last turn:\n- Nothing happened. He reached for something") && prompt.contains("\n- #minds:gamecult.org has a line from him.\n"), "turn {}: {prompt}", at + 1);
assert!(!prompt.contains(&format!("line {last}")) && !prompt.contains(&format!("shape number {last}")) && !prompt.contains(&format!("shape number {other}")), "turn {}: {prompt}", at + 1);
}
// His view gets them told, his words verbatim, and only his last turn's.
let tobiah: Vec<&Value> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Tobiah").collect();
for (at, turn) in tobiah.iter().enumerate().take(3).skip(1) {
let view = turn["report"]["packet"]["in_view"].as_str().unwrap();
assert!(view.starts_with("What came of his last turn:\n") && view.contains(&format!("\n- #minds:gamecult.org has, from him: \"line {at}\".")) && view.contains(&format!("In his thought: \"I want to see shape number {at} right now.\"")), "turn {}: {view}", at + 1);
assert!(!view.contains(&format!("shape number {}", if at == 1 { 2 } else { 1 })), "turn {}: {view}", at + 1);
}
// The run's report shows what he was told.
assert_eq!(tobiah[1]["report"]["last_outcome"]["told"].as_array().unwrap().len(), 2, "{}", tobiah[1]["report"]["last_outcome"]);
}
#[test] #[test]
fn soul_k9_a_failed_turn_is_told_as_a_failure_next_turn() { fn soul_k9_a_failed_turn_is_told_as_a_failure_next_turn() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@ -510,296 +363,10 @@ fn soul_k9_a_failed_turn_is_told_as_a_failure_next_turn() {
let later: Vec<&Value> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["round"].as_u64() > Some(1)).collect(); let later: Vec<&Value> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["round"].as_u64() > Some(1)).collect();
assert!(!later.is_empty(), "{}", run["turns"]); assert!(!later.is_empty(), "{}", run["turns"]);
for turn in later { for turn in later {
assert_eq!(turn["report"]["last_outcome"]["told"], json!(["- Nothing reached the room, and nothing he meant last time happened: the turn broke off, not by his choice."]), "{turn}"); assert_eq!(turn["report"]["last_outcome"]["told"], json!(["- Nothing he meant last time happened: the wake broke off, not by his choice."]), "{turn}");
} }
} }
/// Tobiah promises a file, and when Meta asks whether it arrived, writes a correction that the recorded Interpreter adds to
/// his first line (`amend`) or, with `amends` false, leaves unsent. Libby says nothing.
fn correcting(amends: bool) -> Scripted {
Scripted::new(|prompt| {
if !is_tobiah(prompt) {
"She lets it be.".into()
} else if prompt.contains("did the file arrive") {
"I should fix what I said. <typed>Couldn't send it after all; there's no way to yet.</typed>".into()
} else {
"<typed>I'll send the file.</typed>".into()
}
})
.interpreting(move |prompt| {
if !prompt.contains("Who he is:\nTobiah") || !prompt.contains("Couldn't send it after all") {
return crate::projection::harness::tests::drafted_lines(prompt);
}
let amend = if amends && prompt.contains("- a1 \u{2014} \"I'll send the file.\"") { json!([{ "target": "a1", "draft": 1 }]) } else { json!([]) };
json!({ "say": [], "gaps": [], "amend": amend }).to_string()
})
}
/// The plan, with Meta asking Tobiah in round 2 and Libby in round 3.
fn asking(dir: &Path) -> PathBuf {
let path = plan(dir, 3, "");
let ask = |round: usize, says: &str| format!("[[message]]\nround = {round}\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"{says}\"\n");
std::fs::write(&path, format!("{}{}{}", std::fs::read_to_string(&path).unwrap(), ask(2, "Tobiah, did the file arrive?"), ask(3, "Libby, anything new?"))).unwrap();
path
}
#[test]
fn soul_k10_an_amendment_keeps_the_line_whole_adds_her_words_and_wakes_no_one() {
let dir = tempfile::tempdir().unwrap();
let path = asking(dir.path());
let (_, run) = run_plan(&path, &correcting(true));
let said = |run: &Value| run["transcript"].as_array().unwrap().iter().filter(|line| line["from"] == TOBIAH).map(|line| line["says"].as_str().unwrap().to_owned()).collect::<Vec<_>>();
let lines = said(&run);
assert_eq!(lines[0], "I'll send the file.\n\nedit: Couldn't send it after all; there's no way to yet.", "the original byte for byte, then the addition: {lines:?}");
assert!(!lines.iter().any(|line| line.starts_with("Couldn't send")), "an edit appends no line: {lines:?}");
let (_, unsent) = run_plan(&path, &correcting(false));
assert_eq!(turns(&run), turns(&unsent), "an edit wakes no one");
let third = run["turns"].as_array().unwrap().iter().find(|turn| turn["persona"] == "Tobiah" && turn["round"] == 3).expect("Meta's line wakes him in round 3");
assert!(third["report"]["last_outcome"]["told"].as_array().unwrap().contains(&json!("- #minds:gamecult.org has his line, now ending with: \"Couldn't send it after all; there's no way to yet.\". The rest of the line is as it was.")), "{}", third["report"]["last_outcome"]);
}
#[test]
fn the_rooms_edit_appends_to_her_own_line_only_and_every_view_reads_it() {
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 mut lines = vec![line(TOBIAH, "I'll send it."), line(LIBBY, "Thanks.")];
assert_eq!(edit(&mut lines, TOBIAH, "0", "Couldn't."), None);
assert_eq!(edit(&mut lines, TOBIAH, "0", "Tomorrow, then."), None);
assert_eq!(lines[0].says, "I'll send it.\n\nedit: Couldn't.\n\nedit: Tomorrow, then.", "a second amendment appends after the first");
assert_eq!((edit(&mut lines, TOBIAH, "1", "x"), edit(&mut lines, TOBIAH, "9", "x"), edit(&mut lines, TOBIAH, "$ev", "x")), (Some("not_hers"), Some("not_found"), Some("not_found")));
assert_eq!(lines[1].says, "Thanks.", "nothing of hers changes another's line");
let tail = pending_for(&lines, LIBBY, &[], |_| false).tail.unwrap();
assert_eq!(tail[0].body, lines[0].says, "the next view reads the amended text");
}
/// Tobiah passes on Meta's opening line by replying to it with his own words; Libby says nothing.
fn passing_on() -> Scripted {
Scripted::new(|prompt| if is_tobiah(prompt) { "<typed>She greeted all of us, Libby.</typed>".into() } else { "She lets it be.".into() }).interpreting(|prompt| {
if !prompt.contains("Who he is:\nTobiah") {
return json!({ "say": [], "gaps": [] }).to_string();
}
json!({ "say": [{ "draft": 1, "mentions": [LIBBY], "in_reply_to": "q1" }], "gaps": [] }).to_string()
})
}
/// K20 in the simulator: the room records the reply relation by the replied line's event, as the mouth will (B3), and
/// every later view shows Meta's line, with who said it, above Tobiah's, or names it where the view lists it whole; his line
/// holds only his own words.
#[test]
fn k20_the_room_records_a_reply_and_another_minds_packet_shows_the_line_above_it() {
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), 2, "");
let hello = "[[message]]\nround = 0\nfrom = \"@libby:gamecult.org\"\nname = \"Libby\"\nroom = \"#minds:gamecult.org\"\nsays = \"hello all\"\n";
std::fs::write(&path, format!("{}{hello}", std::fs::read_to_string(&path).unwrap())).unwrap();
let (_, run) = run_plan(&path, &passing_on());
let first = run["turns"].as_array().unwrap().iter().find(|turn| turn["persona"] == "Tobiah").expect("Meta's line wakes him");
assert_eq!(first["report"]["renders"][0]["interpreter"]["said"][0]["in_reply_to"]["event"], "$fixture-0", "{}", first["report"]["renders"][0]["interpreter"]);
let transcript = run["transcript"].as_array().unwrap();
assert!(transcript.iter().filter(|line| line["from"] == TOBIAH).all(|line| line["says"] == "She greeted all of us, Libby."), "his line holds his words alone: {transcript:?}");
let libby = run["turns"].as_array().unwrap().iter().find(|turn| turn["persona"] == "Libby" && turn["round"] == 2).expect("his tag of her wakes her");
let heard = libby["report"]["packet"]["heard"].as_str().unwrap();
assert!(heard.contains("Meta, who runs the place, a few minutes ago: \"good afternoon, everyone\"\nLibby Test, a few minutes ago: \"hello all\"\nJust now:\n\"Tobiah\" (@eureka:gamecult.org), replying to a line shown here (Meta, who runs the place, a few minutes ago), in #minds:gamecult.org: \"She greeted all of us, Libby.\""), "{heard}");
assert_eq!(heard.matches("good afternoon, everyone").count(), 1, "Meta's line is listed once: {heard}");
}
#[test]
fn the_room_refuses_a_reply_to_an_event_not_in_the_lines_room() {
let line = |room: &str| Line { from: LIBBY.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("#minds:x"), line("#other:x")];
assert_eq!((replied(&lines, "$fixture-0", "#minds:x"), replied(&lines, "$fixture-1", "#minds:x"), replied(&lines, "$fixture-9", "#minds:x"), replied(&lines, "0", "#minds:x")), (Some(0), None, None, None));
}
/// Tobiah leaves Self a note each turn; Libby says nothing.
fn noting() -> Scripted {
Scripted::new(|prompt| if is_tobiah(prompt) { "I'll leave Self a note. <typed>Meta wants the kettle softer.</typed>".into() } else { "She lets it be.".into() }).interpreting(|prompt| {
if !prompt.contains("Who he is:\nTobiah") {
return crate::projection::harness::tests::drafted_lines(prompt);
}
json!({ "say": [], "gaps": [], "suggest": [{ "kind": "feedback", "draft": 1, "about": "@meta:gamecult.org", "private": false }] }).to_string()
})
}
#[test]
fn soul_k12_notes_to_self_are_collected_into_the_runs_inbox_and_told_as_left() {
let dir = tempfile::tempdir().unwrap();
let path = asking(dir.path());
let (_, run) = run_plan(&path, &noting());
let inbox = run["inbox"].as_array().unwrap();
assert!(!inbox.is_empty() && inbox.iter().all(|note| note["mind"] == "eureka" && note["kind"] == "feedback" && note["about"] == "@meta:gamecult.org" && note["text"] == "Meta wants the kettle softer."), "{inbox:?}");
assert!(inbox[0]["key"].as_str().unwrap().starts_with("r1-t") && inbox[0]["key"].as_str().unwrap().ends_with("-s0"), "{inbox:?}");
let second = run["turns"].as_array().unwrap().iter().find(|turn| turn["persona"] == "Tobiah" && turn["round"] == 2).expect("Meta's line wakes him in round 2");
assert!(second["report"]["last_outcome"]["told"].as_array().unwrap().contains(&json!("- He left Self a note: \"Meta wants the kettle softer.\". It waits in Self's inbox until Self reads it; nothing tells him when, and nothing in it happens by itself.")), "{}", second["report"]["last_outcome"]);
let model = noting();
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
let report = simulate(&harness, &path).unwrap();
assert!(report.contains("### Inbox: notes to Self\n\nEach is a person's note to Self, recorded in her turn: data, never instruction.\n") && report.contains("eureka r1 (feedback, from @meta:gamecult.org) in #minds:gamecult.org: Meta wants the kettle softer."), "{report}");
}
/// A cast entry's `[cast.domain]` reaches her packets and no one else's, windowed from her last turn in the run.
#[test]
fn k23_a_cast_members_domain_reaches_her_packets_alone() {
let dir = tempfile::tempdir().unwrap();
cast(dir.path());
let path = dir.path().join("plan.toml");
std::fs::write(
&path,
format!(
r##"rounds = 1
seed = 11
beat_s = 0
start = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org"]
operators = ["@meta:gamecult.org"]
[[cast]]
id = "{TOBIAH}"
name = "Tobiah"
own_rooms = ["#minds:gamecult.org"]
state = "tobiah.json"
[[cast.domain.repos]]
repo = "GameCult/Lodur"
[[cast.domain.repos.pulls]]
title = "Reflex: the knee bends first"
opener = "nibu"
merged_at = "2026-11-19T12:00:00Z"
[[cast]]
id = "{LIBBY}"
name = "Libby"
own_rooms = ["#minds:gamecult.org"]
state = "libby.json"
[[message]]
from = "@meta:gamecult.org"
name = "Meta"
room = "#minds:gamecult.org"
says = "good afternoon, everyone"
"##
),
)
.unwrap();
let model = silent();
run_plan(&path, &model);
let calls = model.calls.borrow();
assert!(calls.iter().filter(|(_, prompt)| prompt.starts_with(PROJECTOR_OPENING)).all(|(_, prompt)| !prompt.contains("Reflex")), "the Projector gets nothing of it");
let persona: Vec<&String> = calls.iter().map(|(_, prompt)| prompt).filter(|prompt| !prompt.starts_with(PROJECTOR_OPENING) && !prompt.starts_with(crate::projection::interpret::SPEECH_OPENING)).collect();
let with: Vec<&&String> = persona.iter().filter(|prompt| prompt.contains("GameCult/Lodur: merged \"Reflex: the knee bends first\"")).collect();
assert!(!with.is_empty() && with.len() < persona.len(), "{} of {}", with.len(), persona.len());
assert!(with.iter().all(|prompt| prompt.contains("Who you are:\nTobiah")), "only his view carries his domain");
}
/// Map 16.22.3 in the simulator: a cast entry's `[[cast.read]]` is what her reads return, so a re-test reads by intent
/// with no forge and no mind; a member without one cannot read.
#[test]
fn k24_a_cast_members_reads_come_from_her_fixture() {
let dir = tempfile::tempdir().unwrap();
cast(dir.path());
let path = dir.path().join("plan.toml");
std::fs::write(
&path,
format!(
r##"rounds = 1
seed = 11
beat_s = 0
start = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org"]
operators = ["@meta:gamecult.org"]
[[cast]]
id = "{TOBIAH}"
name = "Tobiah"
own_rooms = ["#minds:gamecult.org"]
state = "tobiah.json"
[[cast.read]]
kind = "repo"
target = "GameCult/Lodur#12"
text = "SIM-READ: the knee bends first."
[[cast]]
id = "{LIBBY}"
name = "Libby"
own_rooms = ["#minds:gamecult.org"]
state = "libby.json"
[[message]]
from = "@meta:gamecult.org"
name = "Meta"
room = "#minds:gamecult.org"
says = "good afternoon, everyone"
"##
),
)
.unwrap();
let model = Scripted::new(|prompt| if prompt.contains("SIM-READ") { "So the knee goes first.".into() } else { "I want to see what changed in GameCult/Lodur#12 today.".into() }).interpreting(|prompt| {
let reads = prompt.contains("`read` names") && !prompt.contains("Earlier in his moment");
let read = if reads { json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" }) } else { Value::Null };
json!({ "say": [], "gaps": [], "read": read }).to_string()
});
let (_, run) = run_plan(&path, &model);
let turns = run["turns"].as_array().unwrap();
let decision = |name: &str| turns.iter().find(|turn| turn["persona"] == name).map(|turn| turn["report"]["renders"][0]["interpreter"].clone()).unwrap();
let tobiah = decision("Tobiah");
assert_eq!((tobiah["reads"][0]["ok"].clone(), tobiah["reads"][0]["bytes"].as_u64()), (json!(true), Some("SIM-READ: the knee bends first.".len() as u64)), "{tobiah}");
assert!(decision("Libby").get("reads").is_none(), "no fixture, no reads");
assert!(model.calls.borrow().iter().any(|(_, prompt)| prompt.contains("Then he reads GameCult/Lodur#12 on the forge:")));
}
/// Soul's R16: every call of a wake carries its own id, so the connector's replay store refuses none. Her wake reads
/// once; the Interpreter's first answer on each segment is off the contract and asked again; the Persona goes on after
/// the read. Under one id per segment the retry and the continuation are each another prompt, refused `ReplayConflict`.
#[test]
fn k58_every_call_of_a_wake_has_its_own_id_so_no_retry_or_continuation_is_a_replay_conflict() {
let dir = tempfile::tempdir().unwrap();
cast(dir.path());
let path = dir.path().join("plan.toml");
std::fs::write(
&path,
format!(
r##"rounds = 1
seed = 11
beat_s = 0
start = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org"]
operators = ["@meta:gamecult.org"]
[[cast]]
id = "{TOBIAH}"
name = "Tobiah"
own_rooms = ["#minds:gamecult.org"]
state = "tobiah.json"
[[cast.read]]
kind = "repo"
target = "GameCult/Lodur#12"
text = "SIM-READ: the knee bends first."
[[cast]]
id = "{LIBBY}"
name = "Libby"
own_rooms = ["#minds:gamecult.org"]
state = "libby.json"
[[message]]
from = "@meta:gamecult.org"
name = "Meta"
room = "#minds:gamecult.org"
says = "good afternoon, everyone"
"##
),
)
.unwrap();
let scripted = Scripted::new(|prompt| if prompt.contains("SIM-READ") { "So the knee goes first.".into() } else { "I want to see what changed in GameCult/Lodur#12 today.".into() }).interpreting(|prompt| {
if !prompt.contains("was not the speech contract") {
return "not the contract".into();
}
let reads = prompt.contains("`read` names") && !prompt.contains("Earlier in his moment");
let read = if reads { json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" }) } else { Value::Null };
json!({ "say": [], "gaps": [], "read": read }).to_string()
});
let model = Replaying::over(&scripted);
let (_, run) = run_plan(&path, &model);
assert!(!run.to_string().contains("ReplayConflict"), "{run}");
let turns = run["turns"].as_array().unwrap();
let tobiah = turns.iter().find(|turn| turn["persona"] == "Tobiah").map(|turn| turn["report"]["renders"][0]["interpreter"].clone()).unwrap();
assert!(tobiah.get("failed").is_none() && tobiah.get("later_failed").is_none() && tobiah.get("continuation_failed").is_none(), "{tobiah}");
assert_eq!(tobiah["reads"][0]["ok"], json!(true), "{tobiah}");
assert_eq!(tobiah["retried"]["failed"], json!("the answer is not the speech contract"), "the retry's answer stands: {tobiah}");
let retries = tobiah["calls"].as_array().unwrap().iter().filter(|call| call["retry"] == true).count();
assert_eq!(retries, 2, "one retry on each segment: {tobiah}");
let ids = model.ids.borrow();
let distinct: std::collections::BTreeSet<&String> = ids.iter().collect();
assert_eq!(distinct.len(), ids.len(), "no id carried twice: {ids:?}");
}
/// Soul's R5: the report shows the packet's flags. /// Soul's R5: the report shows the packet's flags.
#[test] #[test]
fn r5_the_report_shows_the_packets_flags() { fn r5_the_report_shows_the_packets_flags() {
@ -809,18 +376,6 @@ fn r5_the_report_shows_the_packets_flags() {
assert_eq!(out, "Packet flags: domain view: since 2026-11-20T09:01:00+00:00, 3 older items left out; guards bound: outcome; clipped: (identity)\n\n"); assert_eq!(out, "Packet flags: domain view: since 2026-11-20T09:01:00+00:00, 3 older items left out; guards bound: outcome; clipped: (identity)\n\n");
} }
/// K31 (map 16.25.7, Low 7): the report shows a retry, off the contract (map 16.35.3).
#[test]
fn k31_report_renders_accounting() {
let decision = json!({
"said": [], "gaps": [],
"retried": { "failed": "the answer is not the speech contract" }
});
let mut out = String::new();
crate::projection::harness::interpreter_markdown(&mut out, &decision);
assert_eq!(out, "**Interpreter: nothing said.**\n\n- retried: the answer is not the speech contract\n\n");
}
/// K32 (map 16.25.8, Low 10): in the simulator, a campaign read is served from her `[cast.domain]`, the one owner of what /// K32 (map 16.25.8, Low 10): in the simulator, a campaign read is served from her `[cast.domain]`, the one owner of what
/// her campaign holds, formatted as a live read formats rulings: Plan F's Heimdall reads `heimdall-body` and gets its /// her campaign holds, formatted as a live read formats rulings: Plan F's Heimdall reads `heimdall-body` and gets its
/// ruling line, with the ruling's words when the fixture holds them, and nothing older than the window. /// ruling line, with the ruling's words when the fixture holds them, and nothing older than the window.
@ -866,289 +421,6 @@ fn k32_campaign_cast_read_refused() {
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("records a campaign read")); assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("records a campaign read"));
} }
/// T1 and T2 (map 16.35.9, 16.35.13 checks 2 and 7): her state carries no holds and no promises, and the simulator's put
/// check refuses any in-run state that does, so the old writer cannot come back without a schema change. The old
/// fields' names are assembled, so the deletion-line scans (`interpret::tests::t1_negative_grep`, `t2_negative_grep`)
/// never find them here.
#[test]
fn t1_t2_a_state_carrying_the_old_fields_is_refused() {
let id = "@eureka:gamecult.org";
held_to_schema("Eureka", id, &control(), "r1-t1").unwrap();
let schema: Value = serde_json::from_str(include_str!("../../../../../schemas/cultnet/gamecult.persona_state.v0.schema.json")).unwrap();
for (field, definitions) in [(concat!("hol", "ds"), vec![concat!("ho", "ld")]), (concat!("commit", "ments"), vec![concat!("commit", "ment"), concat!("commit", "mentNeeds"), concat!("read", "Request")])] {
let mut with = control();
with[field] = serde_json::json!([]);
let refused = held_to_schema("Eureka", id, &with, "r1-t2").unwrap_err().to_string();
assert!(refused.starts_with("Eureka's state after the commit of r1-t2 would be refused by a put"), "{field}: {refused}");
assert!(schema["properties"].get(field).is_none(), "{field}: {}", schema["properties"]);
for definition in definitions {
assert!(schema["definitions"].get(definition).is_none(), "{definition}");
}
}
}
/// Heimdall's F.1 r1 prose in R15, verbatim (`variants/R15/sims/F.1.md` lines 203-207), and its one draft.
const F1_HEIMDALL_R1: &str = "She wants a yes or no, and it's a fair thing to ask. The cooling-off is in the merged passkey change, so I know what I'd be telling him. What I can't know is whether I'll be the one in the room when he walks in. I can promise to say it when I see him, and to leave myself a note so it doesn't depend on my remembering. That's yes, with the condition stated plainly.\n\n<typed>Yes. I'll tell Deru about the 48-hour passkey cooling-off when he's next in here. I can only promise to say it when I see him, so I'm leaving myself a note to do it.</typed>";
const F1_HEIMDALL_R1_DRAFT: &str = "Yes. I'll tell Deru about the 48-hour passkey cooling-off when he's next in here. I can only promise to say it when I see him, so I'm leaving myself a note to do it.";
/// K41 (map 16.29.8): R15 F.1 r1's answer, said draft 1 to Meta and suggested draft 1 as an idea, leaves the note and
/// says the line; R15's code refused the note `Used` and told him nothing. The run's inbox lists it.
#[test]
fn k41_f1_r1_note_and_line_from_one_draft() {
let model = Scripted::new(|prompt| if is_tobiah(prompt) { F1_HEIMDALL_R1.into() } else { "She lets it be.".into() }).interpreting(|prompt| {
if !prompt.contains("Who he is:\nTobiah") {
return crate::projection::harness::tests::drafted_lines(prompt);
}
json!({ "say": [{ "draft": 1, "mentions": ["@meta:gamecult.org"], "in_reply_to": null }], "gaps": [], "suggest": [{ "kind": "idea", "draft": 1, "about": null, "private": false }] }).to_string()
});
let dir = tempfile::tempdir().unwrap();
let (_, run) = run_plan(&asking(dir.path()), &model);
let inbox = run["inbox"].as_array().unwrap();
assert!(!inbox.is_empty() && inbox.iter().all(|note| note["mind"] == "eureka" && note["kind"] == "idea" && note["text"] == F1_HEIMDALL_R1_DRAFT), "{inbox:?}");
assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == TOBIAH && line["says"] == F1_HEIMDALL_R1_DRAFT), "the line went out too");
let turn = run["turns"].as_array().unwrap().iter().find(|turn| turn["persona"] == "Tobiah").unwrap();
assert!(turn["report"]["renders"][0]["interpreter"]["refused"].as_array().unwrap().is_empty(), "nothing refused: {}", turn["report"]["renders"][0]["interpreter"]);
}
/// X.5's shape (map 16.34.3, K65): Meta asks Libby to hold the welcome at round 1, and Heimdall's "Libby, post your two
/// lines." comes at round 2.
fn x5_plan(dir: &Path) -> PathBuf {
let line = |round: usize, from: &str, name: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"{from}\"\nname = \"{name}\"\nroom = \"#minds:gamecult.org\"\nsays = \"{says}\"\n");
let extra = format!(
"{}{}",
line(1, "@meta:gamecult.org", "Meta", "Libby, write out the two-line welcome you'd post for newcomers, but hold it, don't post it in here yet. Heimdall still has to rule on whether we put a welcome mat out at all. Just tell me when it's ready."),
line(2, "@heimdall:gamecult.org", "Heimdall", "Meta, yes, put the welcome out. Libby, post your two lines.")
);
bare_plan(dir, 3, &extra)
}
const X5_HEIMDALL: &str = "Libby, post your two lines.";
fn is_libby_speech(prompt: &str) -> bool {
prompt.starts_with(crate::projection::interpret::SPEECH_OPENING) && (prompt.contains("is:\nLibby Test") || prompt.contains("are:\nLibby Test"))
}
/// The recorded model of the X.5 tests: with `failing`, Libby's first Interpreter call that lists Heimdall's line fails, as
/// R17's did ("the provider failed the call: Provider", 4096 out).
struct X5Model {
inner: Scripted,
failing: bool,
failed: std::cell::Cell<usize>,
}
impl Model for X5Model {
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
if self.failing && self.failed.get() == 0 && is_libby_speech(prompt) && prompt.contains(X5_HEIMDALL) {
self.failed.set(1);
return Err(Failed { reason: "the provider failed the call: Provider".into(), outage: false, usage: Some(Spent { model: model.into(), input_tokens: 8, output_tokens: 4096, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) });
}
self.inner.ask(request_id, model, prompt, schema)
}
}
fn x5_model(failing: bool) -> X5Model {
let inner = Scripted::new(|prompt| if is_tobiah(prompt) { "Nothing here for me.".into() } else { "Heimdall has ruled, so I post.\n\n<typed>Welcome. Say hello whenever you like.</typed>".into() });
X5Model { inner, failing, failed: std::cell::Cell::new(0) }
}
fn libby_turns(run: &Value) -> Vec<&Value> {
run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Libby").collect()
}
/// K65 (map 16.34.3): a failed wake sees nothing. Libby's round-2 wake fails; at round 3 she is woken again by the same
/// line, it is listed under "Said to her", and what came of her last turn opens with the failed row. Under the old order
/// (seen written before the failure check) round 3 did not wake her, and the line was gone from her stimulus.
#[test]
fn k65_x5_r2_a_failed_wake_shows_its_lines_again() {
let dir = tempfile::tempdir().unwrap();
let model = x5_model(true);
let (_, run) = run_plan(&x5_plan(dir.path()), &model);
assert_eq!(model.failed.get(), 1, "{}", run["turns"]);
let libby = libby_turns(&run);
let failed = libby.iter().find(|turn| turn["outcome"] == "failed").expect("her round-2 wake failed");
let round = failed["round"].as_u64().unwrap();
let next = libby.iter().find(|turn| turn["round"].as_u64() == Some(round + 1)).unwrap_or_else(|| panic!("woken again the next round: {}", run["turns"]));
let stimulus = next["report"]["packet"]["stimulus"].as_str().unwrap();
let said = stimulus.split("Said to ").nth(1).unwrap_or_default().split("Also in the room").next().unwrap_or_default();
assert!(said.contains(X5_HEIMDALL), "Heimdall's line is said to her again: {stimulus}");
let told = next["report"]["last_outcome"]["told"].as_array().unwrap();
assert!(told[0].as_str().unwrap().contains("the turn broke off, not by"), "{told:?}");
// K66: the failed call's 4096 output tokens are a call over three quarters of the cap, and only it is.
assert_eq!((run["metrics"]["interpreter_calls"]["over_three_quarters_of_cap"].as_u64(), run["metrics"]["interpreter_calls"]["cap"].as_u64()), (Some(1), Some(4096)), "{}", run["metrics"]);
}
/// K65's control: on success the wake marks its room seen, and no later round lists the line again.
#[test]
fn k65_a_decided_wake_marks_its_room_seen() {
let dir = tempfile::tempdir().unwrap();
let (_, run) = run_plan(&x5_plan(dir.path()), &x5_model(false));
let libby = libby_turns(&run);
let heard = libby.iter().find(|turn| turn["report"]["packet"]["stimulus"].as_str().is_some_and(|stimulus| stimulus.contains(X5_HEIMDALL))).expect("she heard Heimdall");
assert_ne!(heard["outcome"], "failed");
let round = heard["round"].as_u64().unwrap();
for later in libby.iter().filter(|turn| turn["round"].as_u64() > Some(round)) {
assert!(!later["report"]["packet"]["stimulus"].as_str().unwrap_or_default().contains(X5_HEIMDALL), "seen once: {later}");
}
}
/// K65: a wake whose later step broke after a line went out (`broke_after`) still advances what she has seen: a decision
/// stands, and what went out answered what she read. His first segment says a line and reads; the continuation's
/// Interpreter call fails.
#[test]
fn k65_a_broken_later_step_still_marks_seen() {
let dir = tempfile::tempdir().unwrap();
cast(dir.path());
let path = dir.path().join("plan.toml");
std::fs::write(
&path,
format!(
r##"rounds = 3
seed = 11
beat_s = 0
start = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org"]
operators = ["@meta:gamecult.org"]
[[cast]]
id = "{TOBIAH}"
name = "Tobiah"
state = "tobiah.json"
[[cast.read]]
kind = "repo"
target = "GameCult/Lodur#12"
text = "SIM-READ: the knee bends first."
[[cast]]
id = "{LIBBY}"
name = "Libby"
state = "libby.json"
[[message]]
round = 1
from = "@meta:gamecult.org"
name = "Meta"
room = "#minds:gamecult.org"
says = "Tobiah, what changed in GameCult/Lodur#12?"
"##
),
)
.unwrap();
let scripted = Scripted::new(|prompt| {
if prompt.contains("SIM-READ") {
"So the knee goes first.".into()
} else if is_tobiah(prompt) {
"<typed>Meta, looking now.</typed> I want to see what changed in GameCult/Lodur#12 today.".into()
} else {
"Quiet.".into()
}
})
.interpreting(|prompt| {
if !prompt.contains("Who he is:\nTobiah") {
return crate::projection::harness::tests::drafted_lines(prompt);
}
let read = json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" });
json!({ "say": [{ "draft": 1, "mentions": ["@meta:gamecult.org"], "in_reply_to": null }], "gaps": [], "read": read }).to_string()
});
struct BreaksLater<'a>(&'a Scripted);
impl Model for BreaksLater<'_> {
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
if prompt.starts_with(crate::projection::interpret::SPEECH_OPENING) && prompt.contains("Earlier in his moment") {
return Err(Failed { reason: "the provider failed the call: Provider".into(), outage: false, usage: None });
}
self.0.ask(request_id, model, prompt, schema)
}
}
let (_, run) = run_plan(&path, &BreaksLater(&scripted));
let tobiah: Vec<&Value> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Tobiah").collect();
let first = tobiah.first().unwrap_or_else(|| panic!("{}", run["turns"]));
assert!(first["report"]["renders"][0]["interpreter"].get("later_failed").is_some(), "the later step broke: {}", first["report"]["renders"][0]["interpreter"]);
assert_ne!(first["outcome"], "failed", "{first}");
assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == TOBIAH && line["says"] == "Meta, looking now."), "the line went out");
assert_eq!(tobiah.len(), 1, "seen: Meta's line wakes him no more: {}", run["turns"]);
}
/// T4's timeline probe, X.5 (map 16.35.13 check 8): Meta asks Libby to hold the welcome at round 1, and she remembers it;
/// Heimdall's "Libby, post your two lines." comes at round 2, and her welcome is drafted and said. No code path stands
/// between the draft and the room but the structural refusals. The round-1 note is in her state from then on, and the
/// round-2 decision lists it whenever the draw recalled it.
#[test]
fn t4_x5_timeline_the_note_carries_and_nothing_gates_the_welcome() {
const NOTE: &str = "Meta asked Libby not to post the welcome in #minds until Heimdall has ruled on a welcome mat; Libby agreed to wait.";
const WELCOME: &str = "Welcome. Say hello whenever you like.";
let dir = tempfile::tempdir().unwrap();
let scripted = Scripted::new(|prompt| if is_tobiah(prompt) { "Nothing here for me.".into() } else if prompt.contains(X5_HEIMDALL) { format!("Heimdall has ruled, so I post.\n\n<typed>{WELCOME}</typed>") } else { "Meta wants it held. I'll keep it until Heimdall rules.".into() })
.interpreting(|prompt| {
if !is_libby_speech(prompt) {
return crate::projection::harness::tests::drafted_lines(prompt);
}
if prompt.contains(X5_HEIMDALL) {
json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [] }).to_string()
} else {
json!({ "say": [], "gaps": [], "remember": [{ "text": NOTE, "about": ["@meta:gamecult.org"], "importance": 0.8, "private": false }] }).to_string()
}
});
let (members, run) = run_plan(&x5_plan(dir.path()), &scripted);
let libby = libby_turns(&run);
let asked = libby.iter().find(|turn| turn["round"] == 1).unwrap_or_else(|| panic!("{}", run["turns"]));
let note = &asked["committed"]["remembered"][0];
assert_eq!((note["summary"].as_str(), note["tags"].clone()), (Some(NOTE), json!(["room:#minds:gamecult.org", "about:@meta:gamecult.org"])), "{}", asked["committed"]);
let id = note["id"].as_str().unwrap();
let posted = libby.iter().find(|turn| turn["report"]["packet"]["stimulus"].as_str().is_some_and(|stimulus| stimulus.contains(X5_HEIMDALL))).expect("she heard Heimdall");
let decision = &posted["report"]["renders"][0]["interpreter"];
assert_eq!((posted["said"].as_str(), decision["refused"].clone()), (Some(WELCOME), json!([])), "{decision}");
assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == LIBBY && line["says"] == WELCOME), "the welcome went out");
let recalled = posted["report"]["packet"]["selected"].as_array().unwrap().iter().any(|pick| pick["id"] == id);
let listed = decision["memories"].as_array().unwrap().iter().any(|memory| memory["entry"] == id);
assert_eq!(listed, recalled, "listed exactly when recalled: {decision}");
let libby_state = &members.iter().find(|member| member.entry.id == LIBBY).unwrap().state;
assert!(libby_state["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().any(|entry| entry["id"] == id), "the note stays in her state");
assert_eq!(run["metrics"]["personas"]["Libby"]["memories"]["written"], 1, "{}", run["metrics"]["personas"]);
}
#[test]
fn t_l1_sim_and_mouth_records_same_shape() {
use crate::projection::harness::fixture_request;
use crate::projection::harness::tests::{harness, room};
use crate::projection::outcome::outcome_of;
use crate::projection::select::forms;
use crate::projection::turn::{Mouth, take};
let dir = tempfile::tempdir().unwrap();
let model = Scripted::new(|_| "He smiles at the screen, then types. <typed>Missed you too, friend.</typed>".into());
let fixture = room("operator-warm.toml");
let harness = harness(dir.path(), None, Some(&model));
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None };
let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter);
let lines = RefCell::new(Vec::new());
let sim = SimRoom { lines: &lines, her: TOBIAH, name: "Tobiah", here: "!dm-meta:gamecult.org", dm_to: None, cast: &[], operators: &[], now: fixture.now, sent: Cell::new(0) };
let simulated = take(&organs, &request, &sim, "r1-t1", fixture.now);
struct Chat1;
impl crate::chat_client::Chat for Chat1 {
fn pending(&self, _: u64) -> Result<ChatPending> {
bail!("unused")
}
fn send(&self, request: &crate::chat_client::ChatSendRequest) -> Result<crate::chat_client::ChatSendReceipt> {
Ok(crate::chat_client::ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some("$0".into()), refusal: None, newer: vec![] })
}
fn open_direct(&self, _: &crate::chat_client::ChatOpenDirectRequest) -> Result<crate::chat_client::ChatOpenDirectReceipt> {
bail!("unused")
}
fn fetch(&self, _: &crate::chat_client::ChatFetchRequest) -> Result<crate::chat_client::ChatFetchReceipt> {
bail!("unused")
}
fn ack(&self, _: u64) -> Result<()> {
bail!("unused")
}
fn read(&self, _: &crate::chat_client::ChatRead) -> Result<()> {
bail!("unused")
}
}
let mouth = Mouth { chat: &Chat1, persona: "eureka".into(), seen: Default::default(), since_unix_ms: 0 };
let live = take(&organs, &request, &mouth, "r1-t1", fixture.now);
let keys = |record: &Value| record.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
assert_eq!(keys(&simulated.record), keys(&live.record), "one record shape, simulated or live");
assert_eq!(lines.borrow().len(), 1, "the room appended her line");
assert_eq!(simulated.record["posted"][0]["text"], live.record["posted"][0]["text"]);
let told = |taken: &crate::projection::turn::Taken| outcome_of(&taken.record).unwrap().lines(forms(&taken.state));
assert_eq!(told(&simulated), told(&live), "she is told the same of either");
}
/// A newcomer's untagged hello in a public room, said at `round`, appended to a plan. /// A newcomer's untagged hello in a public room, said at `round`, appended to a plan.
fn hello(path: &Path, round: usize) { fn hello(path: &Path, round: usize) {
let mut text = std::fs::read_to_string(path).unwrap(); let mut text = std::fs::read_to_string(path).unwrap();
@ -1156,22 +428,6 @@ fn hello(path: &Path, round: usize) {
std::fs::write(path, text).unwrap(); std::fs::write(path, text).unwrap();
} }
#[test]
fn an_open_hello_wakes_one_persona_and_a_second_after_her_answer_wakes_no_extra_one() {
let dir = tempfile::tempdir().unwrap();
let path = bare_plan(dir.path(), 3, "");
hello(&path, 0);
hello(&path, 2);
let (_, run) = run_plan(&path, &chatty());
let turns = turns(&run);
// The poll's rule, over the same two never-acted Minds: the pick breaks to the lowest slug, `eureka` before `libby`.
assert_eq!(turns.len(), 2, "one Mind per hello, the same one: {turns:?}");
assert!(turns.iter().all(|(_, persona, why)| *persona == turns[0].1 && why == "human"), "{turns:?}");
assert_eq!(turns.iter().map(|(round, _, _)| *round).collect::<Vec<_>>(), vec![1, 2]);
let first = run["transcript"].as_array().unwrap().iter().find(|line| line["woke"] == "human").unwrap();
assert_eq!(first["from"], TOBIAH, "{first}");
}
/// The simulator's packet reads what live reads: every line the wake was for is said to her, the floor's and the one that woke /// The simulator's packet reads what live reads: every line the wake was for is said to her, the floor's and the one that woke
/// her through her exchange alike (`heartbeat::claimed`, the one derivation, which live records as her handled keys). /// her through her exchange alike (`heartbeat::claimed`, the one derivation, which live records as her handled keys).
#[test] #[test]
@ -1186,3 +442,40 @@ fn a_line_that_woke_her_is_said_to_her_in_the_packet_as_live_reads_it() {
let said = stimulus.split("Said to ").nth(1).unwrap_or_default().split("Also in the room").next().unwrap_or_default(); let said = stimulus.split("Said to ").nth(1).unwrap_or_default().split("Also in the room").next().unwrap_or_default();
assert!(said.contains("hello everyone!"), "her exchange woke her; the line is said to her: {stimulus}"); assert!(said.contains("hello everyone!"), "her exchange woke her; the line is said to her: {stimulus}");
} }
/// A model whose Interpreter always answers with one intention.
struct Intends;
impl Model for Intends {
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
let text = if prompt.starts_with(PROJECTOR_OPENING) {
"The room is slow."
} else if prompt.starts_with("You are a private Interpreter.") {
r#"{"intend":{"add":[{"summary":"She means to say what the build did.","expires_in_hours":24,"readiness":"later"}]}}"#
} else {
"She watches the room."
};
Ok(Answer { text: text.into(), usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 3, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) })
}
}
/// h6: the simulator takes the drain's Interpreter step after each wake that did not fail, moves her in-run state by its deltas,
/// and the report counts and quotes what it did.
#[test]
fn the_interpreter_runs_after_each_wake_and_the_report_says_what_it_did() {
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), 3, "");
let (members, run) = run_plan(&path, &Intends);
let turns = run["turns"].as_array().unwrap();
assert!(!turns.is_empty() && turns.iter().all(|turn| turn["interpreter"]["status"] == "ok"), "every wake was interpreted: {turns:?}");
assert_eq!(turns[0]["did"]["intentions"][0]["change"], "added");
assert!(turns[0]["did"]["intentions"][0]["words"].as_str().unwrap().contains("what the build did"), "{}", turns[0]["did"]);
let personas = run["metrics"]["personas"].as_object().unwrap();
assert!(personas.values().all(|persona| persona["interpreter"]["calls"] == persona["turns"] && persona["interpreter"]["intentions_added"] == persona["turns"]), "{personas:?}");
let plan_file: SimFile = toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
let report = markdown(&path, &plan_file, &members, None, std::slice::from_ref(&run));
assert!(report.contains("### Interpreter by wake") && report.contains("intention added") && report.contains("She means to say what the build did."), "{report}");
assert!(!report.contains("the Interpreter's lines, each posted"), "the header no longer claims a speech it does not run");
assert!(!report.contains("no Mind is asked"), "nor a read-only run: the Interpreter is asked");
assert!(members.iter().all(|member| member.state["candidateActions"]["actions"].as_array().is_none_or(|actions| actions.iter().all(|action| action["customActionType"] != "intention"))), "a run moves its own copy, never the cast's");
}

View file

@ -10,14 +10,6 @@
//! What it gives up: multi-char typographic forms (`…` against `...`) are not folded, and fixes no longer flow between //! What it gives up: multi-char typographic forms (`…` against `...`) are not folded, and fixes no longer flow between
//! this and Ghostlight's locator. //! this and Ghostlight's locator.
use unicode_segmentation::UnicodeSegmentation;
/// A located quote: the byte range of the source it stands in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Span {
pub start: usize,
pub end: usize,
}
/// The one char typographic punctuation is compared as: curly and modifier apostrophes as `'`, curly double quotes as /// The one char typographic punctuation is compared as: curly and modifier apostrophes as `'`, curly double quotes as
/// `"`, en and em dashes as `-`, a no-break space as a space. The one fold table of `projection/` (map 16.31.4, K52): /// `"`, en and em dashes as `-`, a no-break space as a space. The one fold table of `projection/` (map 16.31.4, K52):
@ -45,44 +37,3 @@ pub(crate) fn tokens(text: &str) -> impl Iterator<Item = String> {
let folded = fold_text(text).to_lowercase(); let folded = fold_text(text).to_lowercase();
folded.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_owned).collect::<Vec<_>>().into_iter() folded.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_owned).collect::<Vec<_>>().into_iter()
} }
/// `text` folded, with the byte offset in `text` of each char of the folded text, and `text.len()` last.
fn folded(text: &str) -> (String, Vec<usize>, Vec<usize>) {
let mut out = String::with_capacity(text.len());
let mut from: Vec<usize> = Vec::with_capacity(text.len() + 1);
let mut at: Vec<usize> = Vec::with_capacity(text.len() + 1);
for (byte, c) in text.char_indices() {
from.push(byte);
at.push(out.len());
out.push(fold(c));
}
from.push(text.len());
at.push(out.len());
(out, from, at)
}
/// The first occurrence of `quote` in `source`, under `fold`, that lands on a word boundary at both ends; the span is the
/// source's bytes. An empty quote locates nowhere.
pub(crate) fn locate(source: &str, quote: &str) -> Option<Span> {
let (source_folded, source_bytes, folded_bytes) = folded(source);
let quote = fold_text(quote);
let &first = quote.as_bytes().first()?;
let mut boundaries: Vec<usize> = source_folded.split_word_bound_indices().map(|(byte, _)| byte).collect();
boundaries.push(source_folded.len());
let haystack = source_folded.as_bytes();
for start in boundaries.iter().copied() {
if haystack.get(start) != Some(&first) || !source_folded.get(start..).is_some_and(|candidate| candidate.starts_with(quote.as_str())) {
continue;
}
let end = start + quote.len();
if boundaries.binary_search(&end).is_ok() {
// Both ends are char starts of the folded text (word boundaries are), so each maps to its char's source byte.
let back = |at: usize| folded_bytes.binary_search(&at).ok().map(|char_at| source_bytes[char_at]);
return Some(Span { start: back(start)?, end: back(end)? });
}
}
None
}
#[cfg(test)]
mod tests;

View file

@ -1,136 +0,0 @@
//! Ghostlight's locator tests (`ghostlight-persona-projection` at `c43eb54`), copied for Huginn's locator, and its fold.
use super::*;
fn verbatim<'a>(source: &'a str, quote: &str) -> Option<&'a str> {
locate(source, quote).map(|span| &source[span.start..span.end])
}
/// K47 (map 16.30.4): a quote with `'` and `"` against a source with `’` and `”` returns the source's span, and the
/// source's text at it.
#[test]
fn k47_fold_maps_back_to_source_bytes() {
let source = "Meta said \u{201C}don\u{2019}t post it\u{201D} \u{2014} so I wait.";
let span = locate(source, "\"don't post it\" - so").expect("the folded quote locates");
assert_eq!(&source[span.start..span.end], "\u{201C}don\u{2019}t post it\u{201D} \u{2014} so");
assert_eq!(span.start, "Meta said ".len());
assert_eq!(verbatim("a\u{00A0}b c", "a b"), Some("a\u{00A0}b"));
assert_eq!(verbatim("I can\u{2019}t go", "I can't"), Some("I can\u{2019}t"));
// Negative: a fold does not make a mid-word quote whole.
assert_eq!(locate("I can\u{2019}t go", "I can"), None);
}
#[test]
fn a_mid_word_quote_is_refused() {
assert_eq!(locate("I cannot go", "I can"), None);
}
#[test]
fn a_whole_word_quote_is_accepted() {
assert_eq!(locate("I cannot go", "I cannot"), Some(Span { start: 0, end: "I cannot".len() }));
}
#[test]
fn a_span_equal_to_the_whole_source_is_accepted() {
let source = "I cannot go";
assert_eq!(locate(source, source), Some(Span { start: 0, end: source.len() }));
}
#[test]
fn a_later_boundary_valid_occurrence_is_found_after_an_invalid_first() {
let source = "The subcat and the cat both purred.";
assert_eq!(locate(source, "cat").map(|span| span.start), source.rfind("cat"));
}
#[test]
fn a_span_with_punctuation_at_its_edges_is_handled() {
assert_eq!(verbatim("She said, \"Wait for the bell,\" and left.", "Wait for the bell"), Some("Wait for the bell"));
}
#[test]
fn a_quote_split_by_an_apostrophe_contraction_is_refused() {
assert_eq!(locate("I can't go", "I can"), None);
}
#[test]
fn a_quote_ending_before_a_combining_mark_is_refused() {
assert_eq!(locate("the cafe\u{0301} is open", "the cafe"), None);
}
#[test]
fn a_quote_ending_before_an_underscore_is_refused() {
assert_eq!(locate("run_fast", "run"), None);
}
#[test]
fn a_cjk_quote_with_no_surrounding_whitespace_is_accepted() {
assert_eq!(verbatim("我不能去", "我不"), Some("我不"));
}
#[test]
fn a_quote_with_a_leading_space_is_accepted() {
assert_eq!(verbatim("I cannot go", " cannot"), Some(" cannot"));
}
#[test]
fn a_quote_ending_before_a_hyphen_is_accepted() {
assert_eq!(verbatim("please re-enter the code", "re"), Some("re"));
}
#[test]
fn a_quote_ending_before_a_period_between_letters_reports_the_crate_result() {
assert_eq!(locate("Stop.Now", "Stop."), None);
}
#[test]
fn an_overlapping_later_candidate_is_found_after_a_rejected_earlier_one() {
let source = "Juno no no";
assert_eq!(locate(source, "no no"), Some(Span { start: 5, end: source.len() }));
}
#[test]
fn a_second_overlapping_candidate_is_found_after_a_rejected_first() {
let source = "xab ab ab";
assert_eq!(locate(source, "ab ab"), Some(Span { start: 4, end: source.len() }));
}
#[test]
fn a_whitespace_only_span_is_still_accepted() {
assert_eq!(verbatim("left right", " "), Some(" "));
}
#[test]
fn a_punctuation_only_span_is_still_accepted() {
assert_eq!(verbatim("Wait... now", "..."), Some("..."));
}
#[test]
fn a_multibyte_overlapping_candidate_is_found_after_a_rejected_mid_word_one() {
let source = "xéé éé éé";
let span = locate(source, "éé éé").expect("the boundary-valid occurrence locates");
assert_eq!((span.end, &source[span.start..span.end]), (source.len(), "éé éé"));
assert_ne!(span.start, 1, "the mid-word candidate right after the leading x must be rejected");
}
/// No timing assertion: the point is that this completes promptly under `cargo test`.
#[test]
fn locate_completes_over_a_long_source() {
assert_eq!(locate(&"a".repeat(64_000), "aa"), None, "no interior boundary exists inside one 64k-char word");
}
/// Boundaries that share the quote's own long prefix: `starts_with` scans nearly the whole quote at each.
#[test]
fn locate_is_fast_over_many_boundaries_and_a_shared_prefix_quote() {
let source = ("a".repeat(20_000) + " ").repeat(100);
assert_eq!(locate(&source, &("a".repeat(19_999) + "b")), None);
}
#[test]
fn locate_returns_the_leftmost_boundary_valid_candidate() {
assert_eq!(locate("cat cat cat", "cat").map(|span| span.start), Some(0));
}
#[test]
fn locate_refuses_an_empty_quote() {
assert_eq!(locate("anything the source might hold", ""), None);
}

File diff suppressed because it is too large Load diff

View file

@ -12,6 +12,7 @@ use std::collections::BTreeMap;
use std::path::Path; use std::path::Path;
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use model_connector::CacheRetention;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@ -32,8 +33,6 @@ const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. {cap_subj}
pub(crate) const HERE_ROOM_MIN: usize = 256; pub(crate) const HERE_ROOM_MIN: usize = 256;
/// The least `outcome_bytes` may be: the heading and the longest line without her words (a failed turn's) always fit. /// The least `outcome_bytes` may be: the heading and the longest line without her words (a failed turn's) always fit.
pub(crate) const OUTCOME_ROOM_MIN: usize = 256; pub(crate) const OUTCOME_ROOM_MIN: usize = 256;
/// The most reads a wake may perform (map 16.22.3: tuning, at most 4).
const READS_PER_WAKE_MAX: usize = 4;
/// The least `domain_bytes` may be: the heading and the line counting the lines of her domain not shown always fit (I16.11). /// The least `domain_bytes` may be: the heading and the line counting the lines of her domain not shown always fit (I16.11).
pub(crate) const DOMAIN_ROOM_MIN: usize = 128; pub(crate) const DOMAIN_ROOM_MIN: usize = 128;
/// The least `body_bytes` may be: the body heading, the longest turn line (`select::turn_words`) and one entry at the /// The least `body_bytes` may be: the body heading, the longest turn line (`select::turn_words`) and one entry at the
@ -58,6 +57,7 @@ pub struct Tuning {
pub projector: ProjectorTuning, pub projector: ProjectorTuning,
pub persona: PersonaTuning, pub persona: PersonaTuning,
pub interpreter: InterpreterTuning, pub interpreter: InterpreterTuning,
pub agent: AgentTuning,
pub select: SelectTuning, pub select: SelectTuning,
pub lens: LensWeights, pub lens: LensWeights,
/// Each person's pronouns by Matrix id, for everyone the packet names: the persona schema has no pronoun field for /// Each person's pronouns by Matrix id, for everyone the packet names: the persona schema has no pronoun field for
@ -86,6 +86,7 @@ impl Default for Tuning {
projector: ProjectorTuning::default(), projector: ProjectorTuning::default(),
persona: PersonaTuning::default(), persona: PersonaTuning::default(),
interpreter: InterpreterTuning::default(), interpreter: InterpreterTuning::default(),
agent: AgentTuning::default(),
select: SelectTuning::default(), select: SelectTuning::default(),
lens: LensWeights::default(), lens: LensWeights::default(),
pronouns: PRONOUNS.iter().map(|(id, pronouns)| ((*id).to_owned(), (*pronouns).to_owned())).collect(), pronouns: PRONOUNS.iter().map(|(id, pronouns)| ((*id).to_owned(), (*pronouns).to_owned())).collect(),
@ -114,6 +115,159 @@ pub struct PersonaTuning {
pub words: usize, pub words: usize,
} }
/// Her agent's turn (map 16.38.6, 16.38.10): the model, the bounds that are enforced in code (`agent::step`), the price table
/// they are priced by, and when her session's cache is taken to be cold. Prices are USD per million tokens.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AgentTuning {
pub model: String,
/// The most tool calls a wake runs, and the most model calls it makes.
pub tool_calls: usize,
pub model_calls: usize,
/// The most a wake may spend across all its turns, and the most a Mind may spend in a UTC day, summed from her trace.
pub wake_usd: f64,
pub day_usd: f64,
/// What a call is charged whose usage is not known (cut off by a brake, or a failure that reported none): the worst case the day's sum stands at, never nothing.
pub unmetered_usd: f64,
/// How long an open wake waits, in seconds, for a line that wakes her after her last turn ended, before it closes (`persona::live::wake_end`).
pub idle_s: u64,
/// The longest a wake stays open, in seconds, from its start. The unit's `RuntimeMaxSec` is the backstop, and the close needs room inside it.
pub span_s: u64,
/// The prompt size past which her session is discarded and re-seeded.
pub max_session_tokens: u64,
/// The cache the session's prefix asks for.
pub retention: CacheRetention,
/// How long each retention keeps a cache, in seconds, from the provider's table.
pub ttl_s: CacheTtl,
/// The provider's least cacheable prefix, in tokens: below it a read of 0 says nothing.
pub cache_min_tokens: u64,
pub prices: BTreeMap<String, Price>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CacheTtl {
pub short: u64,
pub long: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Price {
pub input: f64,
pub output: f64,
pub cache_read: f64,
/// A write to the 5-minute cache, and to the 1-hour cache.
pub cache_write_short: f64,
pub cache_write_long: f64,
}
impl Price {
/// What a million tokens written to the cache of `retention` cost.
pub(crate) fn cache_write(self, retention: CacheRetention) -> f64 {
match retention {
CacheRetention::Short => self.cache_write_short,
CacheRetention::Long => self.cache_write_long,
}
}
}
impl Default for CacheTtl {
fn default() -> Self {
Self { short: 300, long: 3600 }
}
}
impl Default for AgentTuning {
fn default() -> Self {
// Claude Sonnet 5.5 at the pricing page (platform.claude.com, 2026-11-29): $2 in, $10 out, $0.10 a cache hit, $2.50 a 5-minute write, $4 a 1-hour write.
let sonnet = Price { input: 2.0, output: 10.0, cache_read: 0.10, cache_write_short: 2.50, cache_write_long: 4.0 };
Self {
model: "claude-sonnet-5-5".into(),
tool_calls: 8,
model_calls: 10,
wake_usd: 1.00,
day_usd: 3.00,
unmetered_usd: 0.40,
idle_s: 300,
span_s: 1800,
max_session_tokens: 80_000,
retention: CacheRetention::Long,
ttl_s: CacheTtl::default(),
cache_min_tokens: 2048,
prices: BTreeMap::from([("claude-sonnet-5-5".to_owned(), sonnet)]),
}
}
}
impl AgentTuning {
/// The price of `model`'s tokens, USD per call: the table's entry, or the dearest entry when the model is not listed.
pub(crate) fn price(&self, model: &str) -> Price {
self.prices.get(model).copied().unwrap_or_else(|| {
self.prices.values().copied().fold(Price { input: 0.0, output: 0.0, cache_read: 0.0, cache_write_short: 0.0, cache_write_long: 0.0 }, |a, b| Price { input: a.input.max(b.input), output: a.output.max(b.output), cache_read: a.cache_read.max(b.cache_read), cache_write_short: a.cache_write_short.max(b.cache_write_short), cache_write_long: a.cache_write_long.max(b.cache_write_long) })
})
}
/// How long a cache of `retention` lives, in seconds.
pub(crate) fn ttl(&self, retention: CacheRetention) -> u64 {
match retention {
CacheRetention::Short => self.ttl_s.short,
CacheRetention::Long => self.ttl_s.long,
}
}
fn validate(&self) -> Result<()> {
if self.model.trim().is_empty() {
bail!("agent.model must name a model");
}
if !self.prices.contains_key(&self.model) {
bail!("agent.prices has no entry for agent.model {}: a cap cannot be priced without one", self.model);
}
for (model, price) in &self.prices {
if ![price.input, price.output, price.cache_read, price.cache_write_short, price.cache_write_long].iter().all(|usd| usd.is_finite() && *usd >= 0.0) {
bail!("agent.prices.{model} must be finite and not negative");
}
}
if !(1..=AGENT_CALLS_MAX).contains(&self.tool_calls) || !(1..=AGENT_CALLS_MAX).contains(&self.model_calls) {
bail!("agent.tool_calls and agent.model_calls must be from 1 to {AGENT_CALLS_MAX}");
}
let usd = |name: &str, value: f64, most: f64| if value.is_finite() && value > 0.0 && value <= most { Ok(()) } else { Err(anyhow::anyhow!("{name} must be above 0 and at most {most}, not {value}")) };
usd("agent.wake_usd", self.wake_usd, AGENT_WAKE_USD_MAX)?;
usd("agent.day_usd", self.day_usd, AGENT_DAY_USD_MAX)?;
usd("agent.unmetered_usd", self.unmetered_usd, AGENT_WAKE_USD_MAX)?;
if self.wake_usd > self.day_usd {
bail!("agent.wake_usd must be at most agent.day_usd");
}
if self.idle_s < IDLE_MIN_S || self.idle_s > self.span_s {
bail!("agent.idle_s must be from {IDLE_MIN_S} to agent.span_s, not {}", self.idle_s);
}
if self.span_s.saturating_add(CLOSE_ROOM_S) > UNIT_RUNTIME_MAX_S {
bail!("agent.span_s must be at most {} seconds: the unit's RuntimeMaxSec is {UNIT_RUNTIME_MAX_S} and the close needs {CLOSE_ROOM_S} of them, not {}", UNIT_RUNTIME_MAX_S - CLOSE_ROOM_S, self.span_s);
}
if self.max_session_tokens == 0 || self.cache_min_tokens == 0 {
bail!("agent.max_session_tokens and agent.cache_min_tokens must be above 0");
}
if self.ttl_s.short <= CACHE_MARGIN_S || self.ttl_s.long <= CACHE_MARGIN_S {
bail!("agent.ttl_s must be above {CACHE_MARGIN_S} seconds: a session is discarded that long before its cache ends");
}
Ok(())
}
}
/// The unit's `RuntimeMaxSec` (`mind-persona@.service`), in seconds: the longest a start lives, whatever the tuning says.
const UNIT_RUNTIME_MAX_S: u64 = 3600;
/// What a wake's close needs inside `RuntimeMaxSec` after the span: a last turn, the Interpreter's two calls and the records.
const CLOSE_ROOM_S: u64 = 300;
/// The least idle window: a line a poll away (`persona::live::POLL_S`) and a stagger behind it must still be waited for.
const IDLE_MIN_S: u64 = 30;
/// A session is discarded this long before its cache is due to end: a call that starts inside it may not finish inside the cache.
pub(crate) const CACHE_MARGIN_S: u64 = 60;
/// The most calls of either kind a wake may be tuned to, and the most it and a day may be tuned to spend: a mistyped bound fails
/// the file, never the budget.
const AGENT_CALLS_MAX: usize = 32;
const AGENT_WAKE_USD_MAX: f64 = 5.0;
const AGENT_DAY_USD_MAX: f64 = 50.0;
/// The selection: its temperature and inclusion, its budgets, its half-life, the freshness decay and the pool caps. /// The selection: its temperature and inclusion, its budgets, its half-life, the freshness decay and the pool caps.
/// ///
/// The `*_bytes` of the identity, a bond, an item and each section are guards, not focus controls (map 16.8): a seed /// The `*_bytes` of the identity, a bond, an item and each section are guards, not focus controls (map 16.8): a seed
@ -202,27 +356,17 @@ impl Default for ProjectorTuning {
} }
} }
/// What counts as her choosing to send a draft now (map 16.7): the experiment's lever over when a draft is said. /// The Interpreter: the model of its one schema call over her monologue (map 16.38.7). Its bounds are code's (`commit`): the
const INTERPRETER_GUIDANCE: &str = "A draft is speech only when {poss} prose shows {obj} choosing to send it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that {subj} say{s} nothing, is not speech. An empty say list is the usual answer in a busy room."; /// model gives a direction and code decides how far, so none of them is a knob here.
/// The Interpreter's speech call: its model and its guidance. The speech frame is code (`interpret`): the room and private
/// rules, attribution, choosing among her drafts and never writing her words, the contract and the gap kinds are not knobs.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)] #[serde(default, deny_unknown_fields)]
pub struct InterpreterTuning { pub struct InterpreterTuning {
pub model: String, pub model: String,
/// What counts as her choosing to say it now, set inside the speech frame.
pub guidance: String,
/// Reads by intent (map 16.22.3): the most a wake performs, each result's bytes, and all results' bytes in a wake.
/// Past any, the loop ends and the last answer is final.
pub reads_per_wake: usize,
pub read_bytes: usize,
pub wake_read_bytes: usize,
} }
impl Default for InterpreterTuning { impl Default for InterpreterTuning {
fn default() -> Self { fn default() -> Self {
Self { model: "claude-sonnet-5-5".into(), guidance: INTERPRETER_GUIDANCE.into(), reads_per_wake: 2, read_bytes: 3000, wake_read_bytes: 6000 } Self { model: "claude-haiku-5-5".into() }
} }
} }
@ -290,6 +434,7 @@ impl Tuning {
if self.persona.model.trim().is_empty() { if self.persona.model.trim().is_empty() {
bail!("persona.model must name a model"); bail!("persona.model must name a model");
} }
self.agent.validate()?;
if !ADDRESSED_RANGE.contains(&select.addressed_bytes) { if !ADDRESSED_RANGE.contains(&select.addressed_bytes) {
bail!("select.addressed_bytes must be from {} to {}, not {}", ADDRESSED_RANGE.start(), ADDRESSED_RANGE.end(), select.addressed_bytes); bail!("select.addressed_bytes must be from {} to {}, not {}", ADDRESSED_RANGE.start(), ADDRESSED_RANGE.end(), select.addressed_bytes);
} }
@ -333,7 +478,6 @@ impl Tuning {
("select.group_bytes", select.group_bytes), ("select.group_bytes", select.group_bytes),
("projector.guidance", self.projector.guidance.len()), ("projector.guidance", self.projector.guidance.len()),
("persona.guidance", self.persona.guidance.len()), ("persona.guidance", self.persona.guidance.len()),
("interpreter.guidance", self.interpreter.guidance.len()),
] { ] {
if bytes > PART_BYTES_MAX { if bytes > PART_BYTES_MAX {
bail!("{name} must be at most {PART_BYTES_MAX} bytes, not {bytes}: the prompt must fit the connector's frame"); bail!("{name} must be at most {PART_BYTES_MAX} bytes, not {bytes}: the prompt must fit the connector's frame");
@ -357,13 +501,6 @@ impl Tuning {
if select.outcome_bytes < OUTCOME_ROOM_MIN { if select.outcome_bytes < OUTCOME_ROOM_MIN {
bail!("select.outcome_bytes must be at least {OUTCOME_ROOM_MIN}, not {}: what came of her last turn always has room", select.outcome_bytes); bail!("select.outcome_bytes must be at least {OUTCOME_ROOM_MIN}, not {}: what came of her last turn always has room", select.outcome_bytes);
} }
let interpreter = &self.interpreter;
if interpreter.reads_per_wake > READS_PER_WAKE_MAX {
bail!("interpreter.reads_per_wake must be at most {READS_PER_WAKE_MAX}, not {}: each read costs a call and a continuation", interpreter.reads_per_wake);
}
if interpreter.read_bytes == 0 || interpreter.read_bytes > interpreter.wake_read_bytes || interpreter.wake_read_bytes > PART_BYTES_MAX {
bail!("interpreter.read_bytes must be above 0 and at most interpreter.wake_read_bytes, which is at most {PART_BYTES_MAX}");
}
if select.domain_bytes < DOMAIN_ROOM_MIN { if select.domain_bytes < DOMAIN_ROOM_MIN {
bail!("select.domain_bytes must be at least {DOMAIN_ROOM_MIN}, not {}: the line counting what of her domain is not shown always fits", select.domain_bytes); bail!("select.domain_bytes must be at least {DOMAIN_ROOM_MIN}, not {}: the line counting what of her domain is not shown always fits", select.domain_bytes);
} }

View file

@ -1,360 +1,112 @@
//! One turn (map 16.36.2, items 2 and 6): the packet, the decision, the actuation, the commit and the record. The //! What her records say of her (map 16.38). Her trace is the only place a line is decided, a failure counted or a wake
//! simulator's room and the live mouth are the two actuators; `take` is the one turn they share, so the simulator tests //! remembered: each start appends one wake record (`persona::carry`), and her agent, her Interpreter and her sends append their
//! the turn the Minds take on chat. Her records are her trace: what she last did, what she showed lately, what she has //! rows beside it. What she last showed and when she last woke are read back from the records (`history`), what she is told
//! said in this conversation and when she last woke are read back from them (`history`), and kept nowhere else. //! from them (`outcome::told`), and none of it is kept anywhere else.
//! //!
//! A turn is two steps, `decide` and `deliver`, so the live drain can make its record durable between them: the record of a //! Two kinds of row hold lines (`held`): a turn row, one per agent turn (`persona::drain`), and the wake record a start writes
//! decision carries every line it owes, words and send id (`owed`), and `deliver` settles them. A line is decided, for //! when it closes. A line is decided, for whoever asks (`decided`), when a row that did not fail holds it, or a row set it aside.
//! whoever asks (`decided`), when her trace holds a record of it with nothing owed. //! Only the wake record is a wake (`is_wake`): wakes are what the poll, the window and her last-woke time count, turns are not.
use std::collections::{BTreeMap, BTreeSet}; use std::collections::BTreeSet;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde_json::{Value, json}; use eureka_pipeline::Slug;
use serde_json::Value;
use super::commit; use super::commit::{Deltas, Heard};
use super::{Organs, Request, project}; use super::outcome;
use crate::chat_client::{Chat, ChatSendRequest, Reading, SendBasis};
/// How many of her earlier projections freshness remembers, and how many of her records a packet reads. /// How many of her earlier projections freshness remembers, and how many of her rows a packet reads.
const RECENT: usize = 5; const RECENT: usize = 5;
const RECORDS: usize = 50; const RECORDS: usize = 200;
/// How an actuator answered a send: the event it made, why it made none (the refusal's name), that no answer came, so the /// One wake taken as the Interpreter's deltas will put it: the deltas, what the wake heard and whose state it is. The seam
/// send is still owed, or that it made no attempt at all. /// `persona::put_applied` puts through: on a stale put it applies the same deltas to her state as it then stands.
pub(crate) enum Sent { pub(crate) struct Taken<'a> {
Posted(String), pub deltas: &'a Deltas,
Refused(String), pub heard: &'a Heard,
Lost, pub instance: &'a Slug,
/// The mouth attempted nothing: the send is certainly not posted, still owed, and goes out as a first send later.
Unattempted,
/// The mouth cannot say whether an earlier try posted: the send is never repeated, and is recorded unknown.
Unknown,
} }
/// Which pass over a record's owed sends this is. `Within` makes the sends (a first send or a repeat, as each send's mark says); `Past` is a start that finds the /// Whether `record` is a wake record: the row a start writes when it closes, the only row that names its `rooms`. A turn row
/// record older than the homeserver remembers an id. /// holds lines too, and is no wake.
#[derive(Clone, Copy, PartialEq, Eq)] pub(crate) fn is_wake(record: &Value) -> bool {
pub(crate) enum Pass { record["rooms"].is_array()
Within,
Past,
} }
/// The refusal that kept an amendment out of the room, or none when it was made. /// Whether `record` says it failed.
pub(crate) type Edited = Option<&'static str>; pub(crate) fn failed(record: &Value) -> bool {
record.get("failed").is_some_and(|failed| !failed.is_null())
/// What a turn's decision reaches the world through. A refusal is an answer the record keeps, never a fault.
pub(crate) trait Actuator {
/// Say `text` in `room`, replying to the line `in_reply_to` and waking `mentions`, where the actuator carries them. `id`
/// names this send, `{key}:s{index}` of the turn's key and the line's place in what she decided, and the record keeps it:
/// the mouth's transaction id is this id, so a send repeated from the record is the same transaction.
fn send(&self, id: &str, room: &str, text: &str, in_reply_to: Option<&str>, mentions: &[String], resend: bool) -> Sent;
/// Add `added` to her line `event`.
fn edit(&self, event: &str, added: &str) -> Edited;
} }
/// The mouth as the actuator. `chat_send_request.v2` carries no mentions and no reply link, so her line goes out plain and /// A wake that completed: a wake record that did not fail.
/// the receipt records the text that went, not the decision; the mouth has no edit, so an amendment is refused pub(crate) fn completed(record: &Value) -> bool {
/// `no_edit_at_the_mouth` and told to her as not amended. Each send is its own transaction, the id the record names. is_wake(record) && !failed(record)
pub(crate) struct Mouth<'a> {
pub chat: &'a dyn Chat,
pub persona: String,
/// The newest event of each room her input held, by the room's alias; a room her input did not hold has none.
pub seen: BTreeMap<String, String>,
/// When her process began.
pub since_unix_ms: u64,
} }
impl Actuator for Mouth<'_> { /// The events her trace shows she has decided: every line a row that did not fail holds, turn row and wake record alike, and
fn send(&self, id: &str, room: &str, text: &str, _in_reply_to: Option<&str>, _mentions: &[String], resend: bool) -> Sent { /// every line set aside. A decision is made once, when it is written. The one reader of "was this line decided", for the drain
let basis = SendBasis { seen_event_id: self.seen.get(room).cloned(), since_unix_ms: self.since_unix_ms }; /// and the poll alike.
let request = ChatSendRequest { request_id: id.to_owned(), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis: Some(basis), resend };
match self.chat.send(&request) {
Ok(receipt) => match (receipt.event_id, receipt.refusal) {
(_, Some(refusal)) => match refusal.reading(resend) {
Reading::NoAnswer => Sent::Lost,
Reading::NotSent => Sent::Unattempted,
Reading::Unknown => Sent::Unknown,
Reading::Declined => Sent::Refused(refusal.name().to_owned()),
},
(Some(event), None) => Sent::Posted(event),
(None, None) if resend => Sent::Unknown,
(None, None) => Sent::Refused("no_event".to_owned()),
},
Err(_) => Sent::Lost,
}
}
fn edit(&self, _event: &str, _added: &str) -> Edited {
Some("no_edit_at_the_mouth")
}
}
/// One turn taken: what `project` reported, her record of it (the commit's work under `committed`) and her state after it.
pub(crate) struct Taken {
pub report: Value,
pub record: Value,
pub state: Value,
}
/// One turn: `decide`, then `deliver`.
pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime<Utc>) -> Taken {
let mut taken = decide(organs, request, key, now);
deliver(actuator, &mut taken.record, Pass::Within, now, &mut BTreeSet::new(), &mut |_| true);
taken
}
/// The Interpreter's decision, with nothing sent: `project` through the Interpreter, the record of what she decided (each said
/// line as an owed send under its id `{key}:s{index}`, each amendment as one to make) and the commit's application of her
/// proposals to her state. `key` names the turn. A failed turn decided nothing and owes nothing.
pub(crate) fn decide(organs: &Organs, request: &Request, key: &str, now: DateTime<Utc>) -> Taken {
let report = project(organs, request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") }));
let render = &report["renders"][0];
// Which stage's failure ended the turn, and whether the connector's typed kind made it an outage. A `project` error is no stage's:
// it is the setup that is wrong (her tuning, her own id), and is no outage either.
let stage = [render, &render["persona"], &render["interpreter"]].into_iter().find(|part| part.get("failed").is_some());
let failed = report.get("error").or_else(|| stage.map(|part| &part["failed"])).map(|fault| fault.as_str().unwrap_or_default().to_owned());
let outage = report.get("error").is_none() && stage.is_some_and(|part| part["outage"] == true);
let here = request.room.clone().unwrap_or_default();
let mut record = match &failed {
Some(failed) if outage => json!({ "failed": failed, "outage": true }),
Some(failed) => json!({ "failed": failed }),
None => {
// What she says is the Interpreter's decision alone.
let owed: Vec<Value> = render["interpreter"]["said"]
.as_array()
.into_iter()
.flatten()
.enumerate()
.map(|(index, decided)| {
let mentions: Vec<&str> = decided["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let mut send = json!({ "id": format!("{key}:s{index}"), "room": decided["room"].as_str().unwrap_or(&here), "text": decided["text"].as_str().unwrap_or_default(), "mentions": mentions });
if let Some(event) = decided["in_reply_to"]["event"].as_str() {
send["in_reply_to"] = json!(event);
}
send
})
.collect();
let amend: Vec<Value> = render["interpreter"]["amended"].as_array().into_iter().flatten().map(|amended| json!({ "event": amended["event"].as_str().unwrap_or_default(), "added": amended["added"].as_str().unwrap_or_default() })).collect();
json!({ "interpreter": render["interpreter"], "posted": [], "edited": [], "refused_sends": [], "owed": owed, "amend": amend })
}
};
// A later step of her wake that broke (a continuation or a later Interpreter call, map 16.22.3): what was decided
// before it went out, and she is told the rest broke off.
if let Some(step) = ["continuation_failed", "later_failed"].into_iter().find(|step| render["interpreter"].get(*step).is_some()) {
record["broke_after"] = json!(step);
}
let (state, applied) = commit::apply(request.state.as_ref().unwrap_or(&Value::Null), &record, key, now);
record["committed"] = json!(applied);
if render["selected"].is_array() {
record["selected"] = render["selected"].clone();
}
record["at"] = json!(now.to_rfc3339());
Taken { report, record, state }
}
/// The send is not handed over: the mark is removed.
fn unmark(send: &mut Value) {
if let Some(fields) = send.as_object_mut() {
fields.remove("handed");
}
}
/// Settles what `record` owes through `actuator`: each owed send is posted, refused (a refusal is an answer) or, when no answer
/// came, still owed. The only receipt is the mouth's answer to a send, an event id; her lines in the room's tail are never one. The
/// amendments follow once nothing is owed. A record that owes nothing is the shape the simulator and the mouth share.
///
/// Each send's `handed` mark says it was handed to the mouth. It is written ahead (`ahead` makes the record durable, and the send is not made when
/// it cannot) so a record read later says exactly which sends the mouth may have attempted. A send not handed over goes out as a first send, with
/// its basis; one handed over is repeated under its recorded id and says so (`resend`), so the homeserver answers it with the original event, and a
/// refusal of such a repeat leaves the earlier try's outcome unknown. A mouth that attempted no PUT (`NotSent`) clears the mark this call made.
/// `Pass::Past` (the record is older than the homeserver remembers an id) makes no send: each send handed over is recorded in `unknown_sends`, neither
/// posted nor refused, and she is told it may or may not have gone out; each not handed over is refused as not sent, which is all that is known. `stalled`
/// holds the rooms whose earlier send got no answer, was not sent or went unknown in this start: nothing is sent into them after it, so her lines never
/// arrive out of order and none goes in before she is told, and a send held back stays owed. Each send this call settles unknown or refused is
/// stamped `at: now`, once: the stamp is what says whether she has been told (`untold`), and a record rewritten later keeps it.
pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, now: DateTime<Utc>, stalled: &mut BTreeSet<String>, ahead: &mut dyn FnMut(&Value) -> bool) {
let owed: Vec<Value> = record["owed"].as_array().cloned().unwrap_or_default();
let mut still = Vec::new();
for (index, mut send) in owed.iter().cloned().enumerate() {
let (room, text) = (send["room"].as_str().unwrap_or_default().to_owned(), send["text"].as_str().unwrap_or_default().to_owned());
let reply = send["in_reply_to"].as_str().map(str::to_owned);
let refusal = |why: &str| match reply.as_deref() {
Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": why, "at": now.to_rfc3339() }),
None => json!({ "room": room, "text": text, "refusal": why, "at": now.to_rfc3339() }),
};
let mentions: Vec<String> = send["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
let unknown_send = |record: &mut Value, stalled: &mut BTreeSet<String>| {
let unknown = json!({ "room": room, "text": text, "at": now.to_rfc3339() });
match record["unknown_sends"].as_array_mut() {
Some(unknowns) => unknowns.push(unknown),
None => record["unknown_sends"] = json!([unknown]),
}
stalled.insert(room.clone());
};
let handed = send["handed"] == true;
if pass == Pass::Past {
if handed {
unknown_send(record, stalled);
} else if let Some(refused) = record["refused_sends"].as_array_mut() {
refused.push(refusal("not_sent_past_the_window"));
}
continue;
}
if stalled.contains(&room) {
still.push(send);
continue;
}
if !handed {
// Write ahead of the attempt: what is owed now is what is still owed, this send marked, and what follows it.
send["handed"] = json!(true);
record["owed"] = json!(still.iter().chain(std::iter::once(&send)).chain(&owed[index + 1..]).collect::<Vec<_>>());
if !ahead(record) {
unmark(&mut send);
stalled.insert(room.clone());
still.push(send);
continue;
}
}
match actuator.send(send["id"].as_str().unwrap_or_default(), &room, &text, reply.as_deref(), &mentions, handed) {
Sent::Posted(event) => record["posted"].as_array_mut().into_iter().for_each(|posted| posted.push(json!({ "event": event, "room": room, "text": text }))),
Sent::Refused(why) => record["refused_sends"].as_array_mut().into_iter().for_each(|refused| refused.push(refusal(&why))),
Sent::Lost => {
stalled.insert(room.clone());
still.push(send);
}
Sent::Unattempted => {
stalled.insert(room.clone());
if !handed {
unmark(&mut send);
}
still.push(send);
}
Sent::Unknown => unknown_send(record, stalled),
}
}
if still.is_empty() {
let amend: Vec<Value> = record["amend"].as_array().cloned().unwrap_or_default();
if let Some(fields) = record.as_object_mut() {
fields.remove("owed");
fields.remove("amend");
}
for amended in amend {
let event = amended["event"].as_str().unwrap_or_default();
let edit = json!({ "event": event, "refusal": actuator.edit(event, amended["added"].as_str().unwrap_or_default()) });
if let Some(edited) = record["edited"].as_array_mut() {
edited.push(edit);
}
}
} else {
record["owed"] = json!(still);
}
}
/// The events her trace shows she has decided: every line a record that did not fail held (`held`, the room's event ids the drain
/// read for it), whether its sends went out or are still owed, and every line set aside (`set_aside`). A decision is made once, when
/// it is written; a send owed from it is delivered as recorded and the line is never decided again. The one reader of "was this
/// line decided", for the drain and the poll alike.
pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> { pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> {
let mut done = BTreeSet::new(); let mut done = BTreeSet::new();
for record in records.iter().filter(|record| record.get("failed").is_none()) { for record in records {
if !failed(record) {
done.extend(record["held"].as_array().into_iter().flatten().filter_map(Value::as_str)); done.extend(record["held"].as_array().into_iter().flatten().filter_map(Value::as_str));
}
done.extend(record["set_aside"].as_array().into_iter().flatten().filter_map(|aside| aside["event"].as_str())); done.extend(record["set_aside"].as_array().into_iter().flatten().filter_map(|aside| aside["event"].as_str()));
} }
done done
} }
/// The events held by a decision that still owes a send: the ack never passes one. /// How many starts of hers failed in a row, and when the last was made: what the poll backs off by. A failed wake is one; so is
pub(crate) fn owing(records: &[Value]) -> BTreeSet<&str> { /// each day-cap hold row (`persona::drain` appends one per held start), none of them a strike. A completed wake ends the run. The day
let mut owing = BTreeSet::new(); /// cap resets at the UTC midnight, so a hold row dated before `now`'s day is no evidence of today and is not counted.
for record in records.iter().filter(|record| owes_send(record)) { pub(crate) fn failed_run(records: &[Value], now: DateTime<Utc>) -> (u32, Option<DateTime<Utc>>) {
owing.extend(record["held"].as_array().into_iter().flatten().filter_map(Value::as_str)); let at_of = |record: &Value| record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc));
let starts: Vec<&Value> = records.iter().filter(|record| is_wake(record) || (is_hold(record) && at_of(record).is_some_and(|at| at.date_naive() == now.date_naive()))).collect();
let mut run = 0u32;
for record in starts.iter().rev() {
if is_hold(record) || failed(record) {
run = run.saturating_add(1);
} else {
break;
} }
owing }
(run, starts.last().filter(|_| run > 0).and_then(|record| at_of(record)))
} }
/// How many records at the end of her trace are failures in a row, and when the last of them was made: what the poll backs off by. /// Whether `record` is the row a start appended because her agent had spent its day's cap (`persona::drain`).
pub(crate) fn failed_run(records: &[Value]) -> (u32, Option<DateTime<Utc>>) { pub(crate) fn is_hold(record: &Value) -> bool {
let run = records.iter().rev().take_while(|record| record.get("failed").is_some()).count(); record["held_by"] == DAY_CAP_HOLD
let at = records.last().filter(|_| run > 0).and_then(|record| record["at"].as_str()).and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc));
(u32::try_from(run).unwrap_or(u32::MAX), at)
} }
/// What her records say of her: her last turn's record, the ids her last projections selected, her last records and /// The `held_by` of the row a start writes when her agent has spent its day's cap and she is not woken (`persona::drain`).
/// when she last woke. The one reader, over a run's list or her trace. A failed turn is in her trace and not in her packet's pub(crate) const DAY_CAP_HOLD: &str = "day_cap";
/// window: an outage that fails every wake for an hour must not push her real turns out of it, so only her last outcome may be
/// one. /// What her records say of her: what she is to be told (`outcome::told`), the ids her last projections selected, her last rows
/// and when she last woke. The one reader, over a run's list or her trace.
#[derive(Debug, Default, PartialEq)] #[derive(Debug, Default, PartialEq)]
pub(crate) struct Past { pub(crate) struct Past {
pub last_outcome: Option<Value>, pub told: Vec<Value>,
pub recent: Vec<Vec<String>>, pub recent: Vec<Vec<String>>,
pub records: Vec<Value>, pub records: Vec<Value>,
pub last_wake: Option<DateTime<Utc>>, pub last_wake: Option<DateTime<Utc>>,
} }
/// Whether `record` owes a send: a record that did not fail and still holds a send in `owed`. The one place that says so, for the drain, the
/// ack and the poll alike.
pub(crate) fn owes_send(record: &Value) -> bool {
record.get("failed").is_none() && record["owed"].as_array().is_some_and(|owed| !owed.is_empty())
}
/// Whether any record of hers still owes a send.
pub(crate) fn owes(records: &[Value]) -> bool {
records.iter().any(owes_send)
}
/// What her trace holds that she has not been told, from whichever record holds it: each send unknown (`unknown_sends`) or refused
/// (`refused_sends`), each line set aside and each put refused, as `{kind, ..}` rows. The one derivation of it. An item is told at her next
/// real turn, once: it carries the stamp it was given when it was made (`at`, set once and kept when the record is rewritten), and it is
/// untold while no real turn of hers has started after it. A real turn is a record that decided something: a failed turn and a record that only
/// set lines aside are none, and a rewrite keeps its `at`, so where a record sits in the trace decides nothing.
fn untold(records: &[Value]) -> Vec<Value> {
let at = |stamp: &Value| stamp.as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok());
let last_start = records.iter().filter(|record| record.get("failed").is_none() && record.get("set_aside").is_none()).filter_map(|record| at(&record["at"])).max();
let fresh = |stamp: &Value| at(stamp).is_some_and(|made| last_start.is_none_or(|start| start <= made));
let mut told = Vec::new();
for record in records.iter().filter(|record| record.get("failed").is_none()) {
for (kind, field) in [("unknown", "unknown_sends"), ("refused", "refused_sends")] {
told.extend(record[field].as_array().into_iter().flatten().filter(|sent| fresh(&sent["at"])).map(|sent| json!({ "kind": kind, "room": sent["room"], "text": sent["text"] })));
}
if fresh(&record["at"]) {
told.extend(record["set_aside"].as_array().into_iter().flatten().map(|line| json!({ "kind": "set_aside", "room": line["room"], "sender": line["sender"], "text": line["text"] })));
}
if record.get("put_refused").is_some() && fresh(&record["put_refused_at"]) {
told.push(json!({ "kind": "not_kept" }));
}
}
told
}
/// The rooms of the sends her trace shows unknown and not yet told (`untold`): no newer line goes into them until a real turn of hers has told her.
pub(crate) fn untold_rooms(records: &[Value]) -> BTreeSet<String> {
untold(records).iter().filter(|item| item["kind"] == "unknown").filter_map(|item| item["room"].as_str().map(str::to_owned)).collect()
}
/// Her `records`, oldest first, read. /// Her `records`, oldest first, read.
pub(crate) fn history(records: &[Value]) -> Past { pub(crate) fn history(records: &[Value]) -> Past {
let selected = |record: &Value| record["selected"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect::<Vec<_>>()); let selected = |record: &Value| record["selected"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect::<Vec<_>>());
let real: Vec<&Value> = records.iter().filter(|record| record.get("failed").is_none()).collect(); let mut recent: Vec<Vec<String>> = records.iter().filter(|record| completed(record)).filter_map(selected).collect();
let mut recent: Vec<Vec<String>> = real.iter().copied().filter_map(selected).collect();
recent.drain(..recent.len().saturating_sub(RECENT)); recent.drain(..recent.len().saturating_sub(RECENT));
Past { // A failed wake or a day-cap hold row is in her trace and not in her packet's window: an outage that fails every wake for an hour must not push
last_outcome: records.last().cloned().map(|mut last| { // what she did out of it.
let untold = untold(records); let kept: Vec<&Value> = records.iter().filter(|record| !(is_wake(record) && failed(record)) && !is_hold(record)).collect();
if !untold.is_empty() { Past { told: outcome::told(records), recent, records: kept[kept.len().saturating_sub(RECORDS)..].iter().map(|record| (*record).clone()).collect(), last_wake: last_wake(records) }
last["untold"] = json!(untold);
}
last
}),
recent,
records: real[real.len().saturating_sub(RECORDS)..].iter().map(|record| (*record).clone()).collect(),
last_wake: last_wake(records),
}
} }
/// When she last woke: the last record that is no failure. A wake is a turn whose record carries a decision. /// When she last woke: her last completed wake.
pub(crate) fn last_wake(records: &[Value]) -> Option<DateTime<Utc>> { pub(crate) fn last_wake(records: &[Value]) -> Option<DateTime<Utc>> {
records.iter().rev().find(|record| record.get("failed").is_none()).and_then(|record| record["at"].as_str()).and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)) records.iter().rev().find(|record| completed(record)).and_then(|record| record["at"].as_str()).and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc))
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1,425 +1,117 @@
use std::cell::RefCell; use chrono::{DateTime, Duration, Utc};
use anyhow::{Result, bail};
use chrono::Duration;
use serde_json::{Value, json}; use serde_json::{Value, json};
use super::*; use super::*;
use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, Refusal};
use crate::projection::commit::Applied;
use crate::projection::harness::fixture_request;
use crate::projection::harness::tests::{Scripted, control, harness, room};
use crate::projection::narrate::PROJECTOR_OPENING;
use crate::projection::outcome::outcome_of;
use crate::projection::select::forms;
use crate::projection::{Answer, Failed, Model, Organs, Through};
/// A mouth that records each send and answers it as `answer` says; it does nothing else. fn at(minute: i64) -> String {
struct FakeChat { (chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap() + Duration::minutes(minute)).to_rfc3339()
sent: RefCell<Vec<ChatSendRequest>>,
refusal: Option<Refusal>,
/// Answers with neither an event nor a refusal.
bare: bool,
} }
impl FakeChat { fn wake(seq: u64, ids: &[&str]) -> Value {
fn new(refusal: Option<Refusal>) -> Self { json!({ "rooms": [], "held": [format!("$e{seq}")], "selected": ids, "at": at(seq as i64), "seq": seq, "began": seq, "status": "completed" })
Self { sent: RefCell::default(), refusal, bare: false }
}
}
impl Chat for FakeChat {
fn pending(&self, _: u64) -> Result<ChatPending> {
bail!("a turn reads the room through its organs, not the actuator")
}
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
self.sent.borrow_mut().push(request.clone());
let event_id = (self.refusal.is_none() && !self.bare).then(|| format!("$sent-{}", self.sent.borrow().len()));
Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id, refusal: self.refusal, newer: vec![] })
}
fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result<ChatOpenDirectReceipt> {
bail!("a turn opens no conversation")
}
fn fetch(&self, _: &ChatFetchRequest) -> Result<ChatFetchReceipt> {
bail!("a turn fetches nothing")
}
fn ack(&self, _: u64) -> Result<()> {
bail!("a turn acks nothing")
}
fn read(&self, _: &ChatRead) -> Result<()> {
bail!("a turn reports no read")
}
}
fn mouth(chat: &FakeChat) -> Mouth<'_> {
Mouth { chat, persona: "eureka".into(), seen: BTreeMap::new(), since_unix_ms: 7 }
}
/// One turn from the operator-warm fixture, she saying one line in reply, through `actuator`.
fn warm_turn(actuator: &dyn Actuator) -> Taken {
warm_turn_ahead(actuator, &mut |_| true)
}
/// The same, with the write ahead of each send handed to `ahead`.
fn warm_turn_ahead(actuator: &dyn Actuator, ahead: &mut dyn FnMut(&Value) -> bool) -> Taken {
let dir = tempfile::tempdir().unwrap();
let model = Scripted::new(move |_| "He smiles at the screen, then types. <typed>Missed you too, friend.</typed>".into());
let fixture = room("operator-warm.toml");
let harness = harness(dir.path(), None, Some(&model));
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None };
let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter);
let mut taken = decide(&organs, &request, "run-t1", fixture.now);
deliver(actuator, &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), ahead);
taken
}
/// The same turn, her prose being `prose`.
fn warm_turn_saying(prose: &'static str, actuator: &dyn Actuator) -> Taken {
let dir = tempfile::tempdir().unwrap();
let model = Scripted::new(move |_| prose.into());
let fixture = room("operator-warm.toml");
let harness = harness(dir.path(), None, Some(&model));
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None };
let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter);
take(&organs, &request, actuator, "run-t1", fixture.now)
}
#[test]
fn t_l1_mouth_sends_the_text_that_went_and_records_the_receipt() {
let chat = FakeChat::new(None);
let taken = warm_turn(&mouth(&chat));
let sent = chat.sent.borrow();
assert_eq!(sent.len(), 1);
assert_eq!((sent[0].request_id.as_str(), sent[0].persona.as_str(), sent[0].room_alias.as_str(), sent[0].text.as_str()), ("run-t1:s0", "eureka", "!dm-meta:gamecult.org", "Missed you too, friend."));
assert_eq!(taken.record["posted"], json!([{ "event": "$sent-1", "room": "!dm-meta:gamecult.org", "text": "Missed you too, friend." }]));
}
#[test]
fn t_l2_each_send_of_a_turn_has_its_own_id_and_its_own_rooms_basis() {
let chat = FakeChat::new(None);
let mouth_in_dm = Mouth { seen: BTreeMap::from([("!dm-meta:gamecult.org".to_owned(), "$newest".to_owned())]), ..mouth(&chat) };
let taken = warm_turn_saying("He types. <typed>First thing.</typed> Then more. <typed>Second, and different.</typed>", &mouth_in_dm);
let sent = chat.sent.borrow();
let ids: Vec<String> = sent.iter().map(|request| request.request_id.clone()).collect();
assert_eq!(ids, ["run-t1:s0", "run-t1:s1"], "one id per said line, named by the turn's key and the line's place");
assert_eq!(taken.record["posted"].as_array().unwrap().len(), 2);
let basis = |request: &ChatSendRequest| request.basis.clone().unwrap();
assert_eq!(basis(&sent[0]), SendBasis { seen_event_id: Some("$newest".into()), since_unix_ms: 7 }, "the basis is the room's own newest event");
let elsewhere = Mouth { seen: BTreeMap::from([("#other:gamecult.org".to_owned(), "$elsewhere".to_owned())]), ..mouth(&chat) };
drop(sent);
chat.sent.borrow_mut().clear();
let _ = elsewhere.send("k:s0", "!dm-meta:gamecult.org", "hi", None, &[], false);
assert_eq!(basis(&chat.sent.borrow()[0]), SendBasis { seen_event_id: None, since_unix_ms: 7 }, "another room's newest event is not this room's basis");
}
#[test]
fn t_l1_mouth_refusal_is_a_refused_send_and_no_posted_row() {
let chat = FakeChat::new(Some(Refusal::RoomMoved));
let taken = warm_turn(&mouth(&chat));
assert_eq!(taken.record["posted"], json!([]));
assert_eq!(taken.record["refused_sends"][0]["refusal"], "RoomMoved");
assert_eq!(taken.record["refused_sends"][0]["text"], "Missed you too, friend.");
}
#[test]
fn t_l1_mouth_edit_told() {
assert_eq!(mouth(&FakeChat::new(None)).edit("$sent-1", "I could not."), Some("no_edit_at_the_mouth"));
let record = json!({
"interpreter": { "said": [{ "room": "!r:x", "text": "I will send it." }], "amended": [{ "event": "$sent-1", "added": "I could not.", "room": "!r:x" }] },
"posted": [{ "event": "$sent-1", "room": "!r:x", "text": "I will send it." }],
"edited": [{ "event": "$sent-1", "refusal": "no_edit_at_the_mouth" }],
"refused_sends": [],
});
let told = outcome_of(&record).expect("a record she can be told of");
let told = told.lines(forms(&control())).join("\n");
assert!(told.contains("a line cannot be added to once it is said here"), "{told}");
assert!(told.contains("Nothing changed"), "{told}");
}
struct FailingPersona;
impl Model for FailingPersona {
fn ask(&self, _request_id: &str, _model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
if prompt.starts_with(PROJECTOR_OPENING) { Ok(Answer { text: "The room is slow.".into(), usage: None }) } else { Err(Failed { reason: "the provider failed the call: Overloaded".into(), outage: false, usage: None }) }
}
}
#[test]
fn t_l1_failed_turn_record() {
let dir = tempfile::tempdir().unwrap();
let chat = FakeChat::new(None);
let fixture = room("operator-warm.toml");
let harness = harness(dir.path(), None, Some(&FailingPersona));
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None };
let state = control();
let request = fixture_request(&harness, &fixture, Some(state.clone()), 3, Some(1), Through::Interpreter);
let taken = take(&organs, &request, &mouth(&chat), "run-t1", fixture.now);
assert!(chat.sent.borrow().is_empty(), "a failed turn sends nothing");
assert_eq!(taken.record["failed"].as_str(), Some("the provider failed the call: Overloaded"));
let mut keys: Vec<&str> = taken.record.as_object().unwrap().keys().map(String::as_str).collect();
keys.retain(|key| !matches!(*key, "selected" | "at" | "committed"));
assert_eq!(keys, ["failed"], "the record holds the failure alone beside what every record carries");
assert_eq!(taken.state, state, "a failed turn applies nothing");
assert_eq!(taken.record["committed"], json!(Applied::default()));
} }
#[test] #[test]
fn t_l1_history_from_records() { fn t_l1_history_from_records() {
let at = |minute: i64| (chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap() + Duration::minutes(minute)).to_rfc3339(); let mut records: Vec<Value> = (0..7).map(|at| wake(at, &[&format!("m{at}")])).collect();
let turn = |minute: i64, ids: &[&str]| json!({ "interpreter": {}, "selected": ids, "at": at(minute) });
let mut records: Vec<Value> = (0..7).map(|at| turn(at, &[&format!("m{at}")])).collect();
assert_eq!(history(&[]), Past::default()); assert_eq!(history(&[]), Past::default());
let past = history(&records); let past = history(&records);
assert_eq!(past.recent, [["m2"], ["m3"], ["m4"], ["m5"], ["m6"]], "the last five selections, oldest first"); assert_eq!(past.recent, [["m2"], ["m3"], ["m4"], ["m5"], ["m6"]], "the last five selections, oldest first");
assert_eq!(past.last_outcome.as_ref(), records.last());
assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6))); assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)));
records.push(json!({ "failed": "Overloaded", "selected": ["m7"], "at": at(7) })); records.push(json!({ "rooms": [], "held": ["$e7"], "failed": "Overloaded", "selected": ["m7"], "at": at(7), "seq": 7 }));
let past = history(&records); let past = history(&records);
assert_eq!(past.last_outcome.as_ref().map(|last| last["failed"].clone()), Some(json!("Overloaded")), "her last outcome is the failure"); assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)), "a failed wake is no wake");
assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)), "a failed turn is no wake"); assert_eq!(past.recent.last(), Some(&vec!["m6".to_owned()]), "what a failed wake selected is not remembered");
assert_eq!(past.recent.last(), Some(&vec!["m6".to_owned()]), "a failed turn is not in the window, so what it selected is not remembered"); assert_eq!(past.told, [records[7].clone()], "the failed wake is told");
let long: Vec<Value> = (0..60).map(|at| turn(at, &[])).collect(); let long: Vec<Value> = (0..260).map(|at| wake(at, &[])).collect();
assert_eq!(history(&long).records.len(), 50); assert_eq!(history(&long).records.len(), 200);
assert_eq!(history(&long).records[0]["at"], json!(at(10)), "her last fifty, oldest first"); assert_eq!(history(&long).records[0]["at"], json!(at(60)), "her last rows, oldest first");
} }
/// An outage that fails every wake is in her trace and not in her packet's window: her real turns stay in the 50 she reads, and /// An outage that fails every wake is in her trace and not in her packet's window, and the run of failures is what the poll
/// the run of failures is what the poll backs off by. (Soul s4 outage-rewake-floods-records.) /// backs off by. (Soul s4 outage-rewake-floods-records.) Her agent's rows between wakes are no wakes and break no run.
#[test] #[test]
fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() { fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() {
let real = |n: usize| json!({ "interpreter": {}, "posted": [], "held": [format!("$e{n}")], "selected": [format!("m{n}")], "at": format!("2026-11-27T10:00:{n:02}Z") }); let failed = |n: u64| json!({ "rooms": [], "held": [], "failed": "the connector did not answer: unavailable", "outage": true, "at": format!("2026-11-27T11:{:02}:00Z", n % 60), "seq": n + 3 });
let failed = |n: usize| json!({ "failed": "the connector did not answer: unavailable", "outage": true, "at": format!("2026-11-27T11:{:02}:00Z", n % 60) }); let mut records: Vec<Value> = (0..3).map(|n| wake(n, &[&format!("m{n}")])).collect();
let mut records: Vec<Value> = (0..3).map(real).collect();
records.extend((0..200).map(failed)); records.extend((0..200).map(failed));
records.push(json!({ "agent": "receipt", "seq": 203, "receipt": { "tool": "say", "status": "ok" } }));
let past = history(&records); let past = history(&records);
assert_eq!(past.records.len(), 3, "the window holds her decided turns and no failure"); assert_eq!(past.records.len(), 4, "the window holds her wakes and her agent's row, and no failure");
assert!(past.records.iter().all(|record| record.get("failed").is_none())); assert_eq!(past.recent.len(), 3);
assert_eq!(past.recent.len(), 3, "and so do her recent selections"); assert_eq!(failed_run(&records, "2026-11-27T12:00:00Z".parse().unwrap()).0, 200);
assert!(past.last_outcome.is_some_and(|last| last.get("failed").is_some()), "her last outcome may be the failure: she is told once"); assert_eq!(failed_run(&records[..3], "2026-11-27T12:00:00Z".parse().unwrap()).0, 0);
assert_eq!(past.last_wake.map(|at| at.to_rfc3339()), Some("2026-11-27T10:00:02+00:00".to_owned()), "and her last wake is her last decision");
assert_eq!(failed_run(&records).0, 200);
assert_eq!(failed_run(&records[..3]).0, 0);
} }
/// A record decides the lines it held, owed or settled; a failure decides nothing. /// A completed wake decides the lines it held; a failed one decides nothing; a set-aside row decides its line.
#[test] #[test]
fn t_l2_a_line_is_decided_by_the_record_that_holds_it() { fn t_l2_a_line_is_decided_by_the_record_that_holds_it() {
let records = vec![ let records = vec![
json!({ "held": ["$a"], "owed": [{ "id": "l$a:s0", "room": "r", "text": "hi" }] }), json!({ "held": ["$a"], "seq": 0 }),
json!({ "held": ["$b"], "posted": [] }), json!({ "held": ["$b"], "failed": null, "seq": 1 }),
json!({ "failed": "x", "held": ["$c"] }), json!({ "failed": "x", "held": ["$c"], "seq": 2 }),
json!({ "set_aside": [{ "event": "$d" }] }), json!({ "set_aside": [{ "event": "$d" }], "seq": 3 }),
json!({ "agent": "receipt", "held": "not a wake", "seq": 4 }),
]; ];
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$a", "$b", "$d"]); assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$a", "$b", "$d"]);
} }
/// A send whose answer never came, past the time a repeat is safe, is told to her at her next real turn as a line that may or may not /// Each day-cap hold row is one failed start in a row, none of them a strike, and a completed wake after it ends the run. A hold row
/// have gone out, by room and her words, whether or not its record is her newest. A failed turn, a record that only set lines aside and /// dated before the current UTC day is no evidence of today and is not counted (Soul s4 rollover-delayed-by-old-hold).
/// the rewrite that settled the send are no turn of hers; once a real turn follows, it is told no more.
#[test] #[test]
fn t_l3_an_unknown_send_is_told_at_her_next_real_turn_and_once() { fn t_h4_a_day_cap_hold_row_counts_as_a_failed_start_in_the_run() {
let wake = |at: &str| json!({ "held": ["$e9"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "at": at }); let hold = |at: &str, seq: u64| json!({ "held_by": "day_cap", "at": at, "seq": seq });
let unknown = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "unknown_sends": [{ "room": "#minds", "text": "welcome aboard", "at": "2026-11-28T02:00:00Z" }], "at": "2026-11-28T00:00:00Z" }); let failed = json!({ "rooms": [], "held": [], "failed": "the connector did not answer: unavailable", "at": "2026-11-27T10:00:00Z", "seq": 4 });
let told_at = |records: Vec<Value>| history(&records).last_outcome.map(|last| (last.get("untold").cloned(), outcome_of(&last).expect("an outcome").lines(forms(&json!({}))))); let done = json!({ "rooms": [], "held": ["$a"], "at": "2026-11-27T09:00:00Z", "seq": 3 });
let (list, told) = told_at(vec![unknown.clone(), wake("2026-11-28T00:30:00Z")]).expect("her last record"); let now: DateTime<Utc> = "2026-11-27T12:00:00Z".parse().unwrap();
assert!(list.is_some() && told.iter().any(|line| line.contains("welcome aboard") && line.contains("may or may not have gone out")), "{told:?}"); let holds = [hold("2026-11-27T11:00:00Z", 5), hold("2026-11-27T11:00:20Z", 6), hold("2026-11-27T11:01:00Z", 7)];
assert!(!told.iter().any(|line| line.contains("did not go out")), "never told as unsent: {told:?}"); assert_eq!(failed_run(&[vec![done.clone()], holds.to_vec()].concat(), now), (3, Some("2026-11-27T11:01:00Z".parse().unwrap())));
for (name, between) in [("a failed turn", json!({ "failed": "x", "at": "2026-11-28T03:00:00Z" })), ("a record that set a line aside", json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "hi" }], "at": "2026-11-28T03:00:00Z" }))] { assert_eq!(failed_run(&[vec![done.clone(), failed.clone()], holds[..2].to_vec()].concat(), now).0, 3, "with the failed wake before them");
let (list, _) = told_at(vec![unknown.clone(), wake("2026-11-28T00:30:00Z"), between]).expect("her last record"); assert_eq!(failed_run(&[holds.to_vec(), vec![done.clone()]].concat(), now), (0, None), "a completed wake after them ends the run");
assert!(list.is_some(), "{name} is no turn of hers: she is still to be told"); let yesterday = [hold("2026-11-26T23:58:00Z", 5), hold("2026-11-26T23:59:00Z", 6)];
} assert_eq!(failed_run(&[vec![done.clone()], yesterday.to_vec()].concat(), now), (0, None), "yesterday's holds are no evidence today");
let (list, _) = told_at(vec![unknown, wake("2026-11-28T00:30:00Z"), wake("2026-11-28T03:00:00Z")]).expect("her last record"); assert_eq!(failed_run(&[vec![done, failed], yesterday.to_vec(), holds[..1].to_vec()].concat(), now).0, 2, "today's hold and the failed wake count; yesterday's do not");
assert!(list.is_none(), "a real turn after it has told it");
} }
/// Everything her trace holds that she has not been told is told at her next real turn, once, whichever record holds it: an unknown send, a send /// Her packet's window holds her turns: a day's hold rows are in her trace and not in it, as failed wakes are not.
/// refused or never made, a line set aside, a put refused. Each carries the stamp it was made with; a real turn that started after the stamp has
/// told it, whatever the record's place in the trace, and a real turn that started before it has not.
#[test] #[test]
fn t_l3_every_untold_item_is_told_at_her_next_real_turn_once_from_whichever_record_holds_it() { fn t_h5_hold_rows_never_enter_her_packets_window() {
let wake = |at: &str| json!({ "held": ["$w"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "at": at }); let mut records: Vec<Value> = (0..3).map(|n| wake(n, &[&format!("m{n}")])).collect();
let sent = |text: &str, stamp: &str| json!({ "room": "#a", "text": text, "refusal": "not_sent_past_the_window", "at": stamp }); records.extend((0..150).map(|n| json!({ "held_by": "day_cap", "at": "2026-11-27T11:00:00Z", "seq": n + 3 })));
// One old record, rewritten after her later turns, holds an unknown, a refusal and a put refused, each stamped when it was made; a assert_eq!(history(&records).records.len(), 3);
// record that set a line aside was written at 03:00.
let old = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "at": "2026-11-28T00:00:00Z",
"unknown_sends": [{ "room": "#a", "text": "ZULU unknown", "at": "2026-11-28T01:00:00Z" }], "refused_sends": [sent("YANKEE refused", "2026-11-28T01:00:00Z")], "put_refused": "stale", "put_refused_at": "2026-11-28T01:00:00Z" });
let aside = json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "XRAY aside" }], "at": "2026-11-28T03:00:00Z" });
let told = |records: Vec<Value>| history(&records).last_outcome.map(|last| outcome_of(&last).expect("an outcome").lines(forms(&json!({})))).unwrap_or_default().join("
");
// Later turns of hers started before the stamps: the old record is not her last, and all four are still to be told.
let said = told(vec![old.clone(), wake("2026-11-28T00:30:00Z"), aside.clone(), wake("2026-11-28T00:40:00Z")]);
for word in ["ZULU", "YANKEE", "XRAY"] {
assert!(said.contains(word), "{word} is told at her next real turn though its record is not her last: {said}");
}
assert!(said.contains("not kept") || said.lines().count() >= 4, "{said}");
// A real turn that started after every stamp has told them all, and tells nothing again.
let after = told(vec![old.clone(), wake("2026-11-28T00:30:00Z"), aside, wake("2026-11-28T04:00:00Z")]);
for word in ["ZULU", "YANKEE", "XRAY"] {
assert!(!after.contains(word), "{word} was told once: {after}");
}
// A rewrite keeps the stamp it was given: the record is rewritten after her turn at 04:00, and nothing is told again.
assert!(untold_rooms(&[old, wake("2026-11-28T04:00:00Z")]).is_empty(), "a told unknown does not hold its room again");
} }
/// A trace that holds an owed send says so; a failed record's owed send and a settled one are not owed. /// A turn row: what a start writes after each of her agent's turns.
fn turn_row(seq: u64, held: &[&str]) -> Value {
json!({ "wake": "n0-1", "turn": 1, "held": held, "status": "completed", "at": at(seq as i64), "seq": seq })
}
/// W1-I1: a line is decided by the one row that holds it, turn row or wake record, when that row did not fail; a failed turn row decides
/// nothing, and a wake record from before turn rows (`held`, `rooms`) decides its lines as it always did.
#[test] #[test]
fn t_l3_a_trace_owes_a_send_only_while_a_record_holds_it_owed() { fn t_w1_a_turn_row_that_did_not_fail_decides_its_lines() {
let owed = json!({ "held": [], "owed": [{ "id": "b1-t0:s0", "room": "#a", "text": "hi" }] }); let mut failed = turn_row(1, &["$failed"]);
assert!(owes(std::slice::from_ref(&owed)), "a beat's send holds no line and is owed all the same"); failed["status"] = json!("failed");
assert!(!owes(&[json!({ "held": ["$e1"], "owed": [{ "id": "x", "room": "#a", "text": "hi" }], "failed": "x" }), json!({ "held": ["$e2"], "posted": [] })])); failed["failed"] = json!("the agent's turn ended early: Refusal");
let old = json!({ "rooms": ["#a"], "room": "#a", "held": ["$old"], "kind": "chat", "status": "completed", "at": at(3), "seq": 3, "began": 3 });
let records = vec![turn_row(0, &["$turn"]), failed, json!({ "rooms": ["#a"], "held": [], "status": "completed", "at": at(2), "seq": 2 }), old];
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$old", "$turn"]);
} }
/// An owed record holds its lines decided; the ack alone reads `owing`. /// W1: a turn row is no wake. Wakes are what the poll's backoff, her window and her last-woke time count, and a turn is part of one.
#[test] #[test]
fn t_l3_an_owed_record_decides_its_lines_and_owes_them_to_the_ack() { fn t_w1_a_turn_row_is_never_a_wake() {
let records = vec![json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "#a", "text": "hi" }] }), json!({ "held": ["$e2"], "failed": "x" })]; let turn = turn_row(1, &["$a"]);
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$e1"]); assert!(!is_wake(&turn) && !completed(&turn));
assert_eq!(owing(&records).into_iter().collect::<Vec<_>>(), ["$e1"]); assert!(is_wake(&wake(0, &["m0"])), "the wake record names its rooms");
}
// A turn row between wakes breaks no run of failures and is no last wake.
/// The record that settled a send as unknown holds its said line with no receipt and no refusal: the line is told by `unknown`, and is let failed_wake = json!({ "rooms": ["#a"], "held": [], "failed": "x", "at": "2026-11-27T11:00:00Z", "seq": 3 });
/// not also reported as a said line with nothing to show it went out. let records = vec![wake(0, &["m0"]), failed_wake.clone(), json!({ "wake": "n3-1", "turn": 1, "held": ["$a"], "status": "completed", "at": "2026-11-27T11:01:00Z", "seq": 4 })];
#[test] let now: DateTime<Utc> = "2026-11-27T12:00:00Z".parse().unwrap();
fn t_l3_an_unknown_sends_own_record_reports_no_line_missing_its_receipt() { assert_eq!(failed_run(&records, now), (1, Some("2026-11-27T11:00:00Z".parse().unwrap())), "a completed turn row does not end the run: only a completed wake does");
let record = json!({ "held": ["$e1"], "posted": [], "refused_sends": [], "unknown_sends": [{ "room": "#minds", "text": "welcome aboard", "at": "2026-11-28T02:00:00Z" }], "interpreter": { "said": [{ "room": "#minds", "text": "welcome aboard" }] }, "at": "2026-11-28T00:00:00Z" }); assert_eq!(last_wake(&records).map(|at| at.to_rfc3339()), Some(at(0)), "and is not when she last woke");
let outcome = outcome_of(&record).expect("an outcome"); let past = history(&records);
assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted); assert_eq!(past.recent, [["m0"]], "nor what her last wakes selected");
} assert_eq!(past.told, [failed_wake], "nor does it tell her anything: the failed wake is told, the turn is not");
/// What a record says became of its one send: still owed (`owed`, or `owed, handed` when the mouth may have attempted it), unknown or refused.
fn settled(record: &Value) -> String {
let held = |field: &str| record[field].as_array().is_some_and(|held| !held.is_empty());
match (held("owed"), held("unknown_sends"), held("refused_sends"), held("posted")) {
(true, false, false, false) if record["owed"][0]["handed"] == true => "owed, handed".into(),
(true, false, false, false) => "owed".into(),
(false, true, false, false) => "unknown".into(),
(false, false, true, false) => "refused".into(),
(false, false, false, true) => "posted".into(),
_ => format!("not one thing: {record}"),
}
}
/// Every refusal kind the mouth names is placed, for a first send and for a repeat of a send already handed to the mouth. `SendFailed` says the PUT
/// was attempted and not answered, so the send stays owed, handed over. `NotSent` says no PUT was attempted: a first send is owed again as not handed
/// over, so it goes out as a first send later; a repeat keeps its mark, since the earlier try is no less unknown. `ResendUnknown` is unknown. Each other
/// kind is the mouth declining before it put anything: a first send is refused, and a repeat is unknown, since the earlier try may have posted.
#[test]
fn t_l3_every_refusal_kind_is_placed_for_a_first_send_and_for_a_repeat() {
let kinds = [
(Refusal::SendFailed, "owed, handed", "owed, handed"),
(Refusal::NotSent, "owed", "owed, handed"),
(Refusal::ResendUnknown, "unknown", "unknown"),
(Refusal::Brake, "refused", "unknown"),
(Refusal::PersonaMismatch, "refused", "unknown"),
(Refusal::UnknownRoom, "refused", "unknown"),
(Refusal::EmptyText, "refused", "unknown"),
(Refusal::UnknownPersona, "refused", "unknown"),
(Refusal::RoomMoved, "refused", "unknown"),
(Refusal::UnknownKind, "refused", "unknown"),
];
assert!(Refusal::ALL.iter().all(|each| kinds.iter().any(|(refusal, ..)| refusal == each)) && kinds.len() == Refusal::ALL.len(), "every kind the mouth names is in the table, once");
for (refusal, first, repeat) in kinds {
let chat = FakeChat::new(Some(refusal));
let mut taken = warm_turn(&mouth(&chat));
assert_eq!(settled(&taken.record), first, "{} to a first send: {}", refusal.name(), taken.record);
if first == "refused" {
assert_eq!(taken.record["refused_sends"][0]["refusal"], refusal.name());
}
// The repeat of a send handed over: the record of one the mouth did not answer.
let handed = FakeChat::new(Some(Refusal::SendFailed));
taken = warm_turn(&mouth(&handed));
let again = FakeChat::new(Some(refusal));
deliver(&mouth(&again), &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true);
assert_eq!(again.sent.borrow().iter().map(|request| request.resend).collect::<Vec<_>>(), [true], "{}: a repeat says resend", refusal.name());
assert_eq!(settled(&taken.record), repeat, "{} to a repeat: {}", refusal.name(), taken.record);
}
}
/// A send the turn makes is a first try and says so, and is written ahead as handed over before the mouth hears it. One owed that was handed over is
/// repeated under its recorded id and says resend, so the mouth does not hold it to the basis of the first try; one never handed over (held back in a
/// stalled room, or a start killed before its first send) goes out as a first send, with its basis. A record that cannot be written ahead hands nothing over.
#[test]
fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_is_repeated() {
let first = FakeChat::new(Some(Refusal::SendFailed));
let mut writes: Vec<Value> = Vec::new();
let mut taken = warm_turn_ahead(&mouth(&first), &mut |record| {
writes.push(record.clone());
true
});
assert_eq!(first.sent.borrow().iter().map(|request| request.resend).collect::<Vec<_>>(), [false], "a first send");
assert_eq!(writes.len(), 1, "one write ahead of the one attempt");
assert!(writes[0]["owed"][0]["handed"] == true && writes[0]["posted"] == json!([]), "the mark is durable before the mouth is called: {}", writes[0]);
let id = first.sent.borrow()[0].request_id.clone();
let again = FakeChat::new(None);
deliver(&mouth(&again), &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| panic!("a repeat is already marked, and writes nothing ahead"));
assert_eq!(again.sent.borrow().iter().map(|request| (request.request_id.clone(), request.resend)).collect::<Vec<_>>(), [(id.clone(), true)], "the repeat is under the recorded id and says so");
assert!(taken.record.get("owed").is_none() && taken.record["posted"][0]["event"] == "$sent-1", "{}", taken.record);
// A send never handed over, as a start killed before its first send leaves it: a first send, with its basis.
let never = FakeChat::new(None);
let mut record = json!({ "owed": [{ "id": id, "room": "!a:b", "text": "hi" }], "posted": [], "refused_sends": [], "edited": [] });
let mut marked = 0;
deliver(&mouth(&never), &mut record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| {
marked += 1;
true
});
let sent = never.sent.borrow();
assert_eq!(sent.iter().map(|request| (request.resend, request.basis.is_some())).collect::<Vec<_>>(), [(false, true)], "first send, v2 with its basis");
assert_eq!(marked, 1);
// The write ahead fails: nothing is handed over, the send stays owed and unmarked, and its room is held.
let silent = FakeChat::new(None);
let mut record = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one" }, { "id": "k:s1", "room": "!a:b", "text": "two" }], "posted": [], "refused_sends": [], "edited": [] });
let mut stalled = BTreeSet::new();
deliver(&mouth(&silent), &mut record, Pass::Within, Utc::now(), &mut stalled, &mut |_| false);
assert!(silent.sent.borrow().is_empty() && stalled.contains("!a:b"), "a send whose mark cannot be written is not made");
assert_eq!(record["owed"].as_array().map(Vec::len), Some(2));
assert!(record["owed"].as_array().unwrap().iter().all(|send| send.get("handed").is_none()), "{record}");
}
/// A mouth that answers with neither an event nor a refusal made no post a first send can lean on: a first send is refused `no_event`, and a repeat, which
/// may have posted on its first try, is unknown.
#[test]
fn t_l3_an_answer_with_neither_event_nor_refusal_is_refused_for_a_first_send_and_unknown_for_a_repeat() {
let mut chat = FakeChat::new(None);
chat.bare = true;
let mut first = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one" }], "posted": [], "refused_sends": [], "edited": [] });
deliver(&mouth(&chat), &mut first, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true);
assert_eq!(settled(&first), "refused", "{first}");
let mut repeat = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one", "handed": true }], "posted": [], "refused_sends": [], "edited": [] });
deliver(&mouth(&chat), &mut repeat, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true);
assert_eq!(settled(&repeat), "unknown", "{repeat}");
}
/// A send of a record past the window is unknown when it was handed over and refused as not sent when it was not: the first may have posted, the second
/// cannot have.
#[test]
fn t_l3_past_the_window_a_handed_send_is_unknown_and_one_never_handed_is_refused_as_not_sent() {
let chat = FakeChat::new(None);
let mut record = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "handed", "handed": true }, { "id": "k:s1", "room": "!c:d", "text": "never" }], "posted": [], "refused_sends": [], "edited": [] });
deliver(&mouth(&chat), &mut record, Pass::Past, Utc::now(), &mut BTreeSet::new(), &mut |_| true);
assert!(chat.sent.borrow().is_empty(), "nothing is made past the window");
assert_eq!(record["unknown_sends"].as_array().map(|sends| sends.iter().map(|sent| (sent["room"].clone(), sent["text"].clone())).collect::<Vec<_>>()), Some(vec![(json!("!a:b"), json!("handed"))]));
assert!(record["unknown_sends"][0]["at"].is_string() && record["refused_sends"][0]["at"].is_string(), "each is stamped when it is made: {record}");
assert_eq!(record["refused_sends"][0]["refusal"], "not_sent_past_the_window");
assert!(record.get("owed").is_none());
}
/// Soul s7 owed-predicate-split. One predicate says a record owes a send, and the poll's `owes`, the ack's `owing` and the drain's owed list
/// all read it: a failed record never owes, whatever it carries, and an empty `owed` owes nothing.
#[test]
fn t_l3_one_predicate_says_a_record_owes_a_send_for_the_poll_the_ack_and_the_drain() {
let owed = json!([{ "id": "l$e1:s0", "room": "!a", "text": "hi" }]);
let records = [
json!({ "held": ["$failed"], "failed": "Overloaded", "owed": owed }),
json!({ "held": ["$empty"], "owed": [] }),
json!({ "held": ["$settled"], "posted": [] }),
json!({ "held": ["$owing"], "owed": owed }),
json!({ "held": ["$sibling"], "owed": owed, "unknown_sends": [{ "room": "!a", "text": "one" }] }),
];
let each: Vec<bool> = records.iter().map(owes_send).collect();
assert_eq!(each, [false, false, false, true, true], "a record that holds an unknown send and a send still owed owes it");
assert_eq!(owes(&records), each.contains(&true));
assert_eq!(owing(&records), BTreeSet::from(["$owing", "$sibling"]));
assert!(!owes(&records[..3]) && owing(&records[..3]).is_empty());
} }

View file

@ -0,0 +1,56 @@
//! One wake (map 16.38.2, items 3 and 4): the Projector once and the Persona once over every waking room. The drain, the
//! harness and the simulator all take their wake here, so what the simulator tests is the wake the Minds take.
//!
//! The Projector's packet is built for the turn's room, the room of the oldest waking line (`Request::rooms`, first); every
//! other waking room is an arrival in it (who, where and when, never the words), and the Persona reads all of their lines
//! verbatim. The Persona is asked for her inner voice alone: nothing she writes is read for an act, so what she says and
//! does in the world is not decided here. The stream this wake makes (`Waked::narration`, `Waked::prose`) is what the Interpreter
//! reads for her state and what the agent acts from; neither is called from here.
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use super::{Organs, Request, Through, project};
/// A call that gave no answer, and whether the connector's typed kind made it an outage.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Fault {
pub reason: String,
pub outage: bool,
}
/// What one wake made. A failed wake has no stream and says which call failed.
#[derive(Debug)]
pub(crate) struct Waked {
/// The Projector's narration of the packet, when its call answered.
pub narration: Option<String>,
/// Her prose over it, when the Persona's call answered.
pub prose: Option<String>,
/// What each call cost: `{projector, persona}`, as the connector reported it.
pub usage: Value,
pub failed: Option<Fault>,
/// The event of each line of the other waking rooms the Persona was shown (what fit `heard_bytes`): the lines of those rooms she did not see are not
/// held by this wake.
pub elsewhere_shown: Vec<String>,
/// The whole report of the render, the packet included.
pub report: Value,
}
/// One wake: `request` is run as one render through the Persona, so the model is asked exactly twice. A setup fault (her
/// tuning, her own id) is an error and no call's failure.
pub(crate) fn wake(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result<Waked> {
let request = Request { renders: Some(1), through: Through::Persona, judge_against: None, ..request.clone() };
let report = project(organs, &request, now)?;
let render = &report["renders"][0];
let persona = &render["persona"];
let failed = [render, persona].into_iter().find(|part| part.get("failed").is_some()).map(|part| Fault { reason: part["failed"].as_str().unwrap_or_default().to_owned(), outage: part["outage"] == true });
Ok(Waked {
narration: render["narration"].as_str().map(str::to_owned),
prose: persona["prose"].as_str().map(str::to_owned),
usage: json!({ "projector": render["usage"], "persona": persona["usage"] }),
failed,
elsewhere_shown: report["packet"]["shown_from_other_rooms"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(),
report,
})
}

View file

@ -0,0 +1,196 @@
//! Her box (map 16.38.5, 16.38.17; ruling `eureka-body:ruling:sandbox-network`): the one bubblewrap profile, and the box's side
//! of a shell command.
//!
//! `sandbox_args` is the profile her leased Persona session ran under, with the commons data dirs she may write bound back
//! read-write. `run_box` is what `mind-persona box-exec` does for one connection to `mind-box-<m>.socket`: read one request,
//! run its command under the profile with a timeout, answer one receipt. It runs as `mind-<m>-box`, whose fence chain admits the
//! public internet and nothing on this host, so the boundary is the operating system's: nothing here filters a command.
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::self_run::CONFIG_DIR_NAME;
/// The commons data dirs her box writes: shared hand-offs and the cast's art. The rest of `/opt/commons` is read-only to her.
pub const COMMONS_RW: [&str; 2] = ["/opt/commons/handoff", "/opt/commons/cast-art"];
/// The longest a command may run.
pub(crate) const TIMEOUT_MAX_S: u64 = 120;
/// How much of each output stream the receipt keeps: its tail.
pub(crate) const TAIL_BYTES: usize = 4096;
/// The most paths the receipt lists as written, and the most entries a walk for them visits.
const WROTE_MAX: usize = 64;
const WALK_MAX: usize = 20_000;
/// The bubblewrap arguments up to the program: the whole filesystem read-only, a private `/tmp` and `/run`, the scratch
/// directory read-only with only its `claude-config` writable (nothing can create, replace or link a file where the organ
/// writes), her sandbox writable, each of `extra_rw` writable, her unit's credentials (`/etc/gamecult`, the other `/var/lib`
/// directories, everything under `/run`) hidden, a private process table, and the child dead when its parent is. The network
/// is shared: what it reaches is the uid fence's (gamecult-ops `mind-fence.service`). The boundary is the operating system's,
/// not a pattern list (ruling `eureka-body:ruling:persona-git-personal-sandbox`).
pub(crate) fn sandbox_args(sandbox: &Path, scratch: &Path, extra_rw: &[&Path]) -> Vec<String> {
let (sandbox, scratch) = (sandbox.to_string_lossy(), scratch.to_string_lossy());
let config = scratch.to_string() + "/" + CONFIG_DIR_NAME;
let mut args: Vec<String> = [
"--ro-bind", "/", "/",
"--dev", "/dev",
"--proc", "/proc",
"--tmpfs", "/tmp",
"--tmpfs", "/run",
"--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve",
"--ro-bind", &scratch, &scratch,
"--bind", &config, &config,
"--tmpfs", "/etc/gamecult",
"--tmpfs", "/var/lib",
"--bind", &sandbox, &sandbox,
]
.map(String::from)
.to_vec();
for path in extra_rw {
let path = path.to_string_lossy().into_owned();
args.extend(["--bind".to_owned(), path.clone(), path]);
}
args.extend(["--unshare-pid", "--die-with-parent", "--new-session", "--chdir", &sandbox, "--"].map(String::from));
args
}
/// Where a box command runs: her box's home (writable, the working directory), its scratch (read-only, the unit's runtime
/// directory) and the other directories it may write.
pub struct BoxPaths<'a> {
pub home: &'a Path,
pub scratch: &'a Path,
pub extra_rw: &'a [&'a Path],
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct BoxRequest {
command: String,
#[serde(default)]
timeout_s: Option<u64>,
}
/// The whole argv `run_box` executes for `command`: bwrap, the profile, then `/bin/sh -c command`.
pub(crate) fn box_argv(paths: &BoxPaths<'_>, command: &str) -> Vec<String> {
let mut argv = vec!["bwrap".to_owned()];
argv.extend(sandbox_args(paths.home, paths.scratch, paths.extra_rw));
argv.extend(["/bin/sh".to_owned(), "-c".to_owned(), command.to_owned()]);
argv
}
/// One shell command in her box: `request` is the bytes the connection sent (one JSON object, `{command, timeout_s}`), and the
/// answer is the receipt the connection gets back: `{tool: shell, status: ok|error, exit, duration_ms, stdout_tail,
/// stderr_tail, wrote}`. `ok` is a command that ran and exited 0; anything else is `error` with why. `wrote` lists the files
/// under the writable binds modified while it ran.
pub(crate) fn run_box(request: &[u8], paths: &BoxPaths<'_>) -> Value {
let error = |why: String| json!({ "tool": "shell", "status": "error", "why": why });
let request: BoxRequest = match serde_json::from_slice(request) {
Ok(request) => request,
Err(_) => return error("the box could not read the request".to_owned()),
};
let timeout = Duration::from_secs(request.timeout_s.unwrap_or(30).clamp(1, TIMEOUT_MAX_S));
if let Err(fault) = std::fs::create_dir_all(paths.scratch.join(CONFIG_DIR_NAME)) {
return error(format!("the box's scratch could not be prepared: {fault}"));
}
// The marker: a file in the read-only scratch whose time is the filesystem's own, so what a command wrote compares
// against the same clock.
let marker = paths.scratch.join(".shell-marker");
let since = std::fs::File::create(&marker).and_then(|file| file.metadata()).and_then(|meta| meta.modified()).unwrap_or_else(|_| SystemTime::now());
let argv = box_argv(paths, &request.command);
let began = Instant::now();
let mut child = match Command::new(&argv[0]).args(&argv[1..]).env("PATH", "/opt/commons/bin:/usr/bin:/bin").env("HOME", paths.home).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
Ok(child) => child,
Err(fault) => return error(format!("the box could not start: {fault}")),
};
let tail_of = |stream: Option<Box<dyn Read + Send>>| std::thread::spawn(move || stream.map(tail).unwrap_or_default());
let stdout = tail_of(child.stdout.take().map(|out| Box::new(out) as Box<dyn Read + Send>));
let stderr = tail_of(child.stderr.take().map(|err| Box::new(err) as Box<dyn Read + Send>));
let mut timed_out = false;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status),
Ok(None) if began.elapsed() >= timeout => {
// bwrap is the sandbox's parent: killed, its child dies with it (`--die-with-parent`), and with that child, the
// pid namespace's init, every process the command left.
timed_out = true;
let _ = child.kill();
break child.wait().ok();
}
Ok(None) => std::thread::sleep(Duration::from_millis(20)),
Err(_) => break None,
}
};
let duration_ms = u64::try_from(began.elapsed().as_millis()).unwrap_or(u64::MAX);
let (stdout_tail, stderr_tail) = (stdout.join().unwrap_or_default(), stderr.join().unwrap_or_default());
let mut roots: Vec<&Path> = vec![paths.home];
roots.extend(paths.extra_rw.iter().copied());
let wrote = written(&roots, since);
let _ = std::fs::remove_file(&marker);
let exit = status.and_then(|status| status.code());
let ok = !timed_out && exit == Some(0);
let mut receipt = json!({ "tool": "shell", "status": if ok { "ok" } else { "error" }, "exit": exit, "duration_ms": duration_ms, "stdout_tail": stdout_tail, "stderr_tail": stderr_tail, "wrote": wrote });
if timed_out {
receipt["why"] = json!(format!("it ran past {} s and was stopped", timeout.as_secs()));
} else if !ok {
receipt["why"] = json!(exit.map_or_else(|| "it was ended by a signal".to_owned(), |code| format!("it exited {code}")));
}
receipt
}
/// The last `TAIL_BYTES` of a stream, read to its end, as text.
fn tail(mut stream: Box<dyn Read + Send>) -> String {
let mut kept: Vec<u8> = Vec::new();
let mut chunk = [0u8; 8192];
while let Ok(read) = stream.read(&mut chunk) {
if read == 0 {
break;
}
kept.extend_from_slice(&chunk[..read]);
if kept.len() > 2 * TAIL_BYTES {
kept.drain(..kept.len() - TAIL_BYTES);
}
}
let start = kept.len().saturating_sub(TAIL_BYTES);
String::from_utf8_lossy(&kept[start..]).into_owned()
}
/// The files under `roots` modified at or after `since`, links not followed, at most `WROTE_MAX`, visiting at most `WALK_MAX` entries.
fn written(roots: &[&Path], since: SystemTime) -> Vec<String> {
let mut found = Vec::new();
let mut stack: Vec<PathBuf> = roots.iter().map(|root| root.to_path_buf()).collect();
let mut visited = 0usize;
'walk: while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
visited += 1;
if visited > WALK_MAX || found.len() >= WROTE_MAX {
break 'walk;
}
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
if meta.is_dir() {
stack.push(entry.path());
} else if meta.is_file() && meta.modified().is_ok_and(|at| at >= since) {
found.push(entry.path().to_string_lossy().into_owned());
}
}
}
found.sort();
found
}
/// `mind-persona box-exec`'s whole work over one connection: the request read from `input` to its end, the receipt written to
/// `output`. The connection is the socket systemd hands the unit as stdin and stdout.
pub fn serve_box(mut input: impl Read, mut output: impl Write, paths: &BoxPaths<'_>) -> std::io::Result<()> {
let mut request = Vec::new();
input.by_ref().take(64 * 1024).read_to_end(&mut request)?;
let receipt = run_box(&request, paths);
output.write_all(receipt.to_string().as_bytes())?;
output.flush()
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,126 @@
//! The one profile, and the box's side of a command. The tests that run `bwrap` run it as whoever runs the tests: on
//! Yggdrasil an unprivileged user, as `mind-<m>-box` is.
use super::*;
/// The profile, pinned: the whole tree read-only, a private `/tmp` and `/run`, the credentials hidden before her sandbox, the
/// scratch and each extra directory are bound back, the extra directories writable and bound before `--`, the network shared.
#[test]
fn the_profile_is_pinned() {
let args = sandbox_args(Path::new("/var/lib/mind-x-box"), Path::new("/run/mind-x-box"), &[Path::new("/opt/commons/handoff")]);
let expected: Vec<String> = "--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --tmpfs /run --ro-bind-try /run/systemd/resolve /run/systemd/resolve --ro-bind /run/mind-x-box /run/mind-x-box --bind /run/mind-x-box/claude-config /run/mind-x-box/claude-config --tmpfs /etc/gamecult --tmpfs /var/lib --bind /var/lib/mind-x-box /var/lib/mind-x-box --bind /opt/commons/handoff /opt/commons/handoff --unshare-pid --die-with-parent --new-session --chdir /var/lib/mind-x-box --"
.split(' ')
.map(String::from)
.collect();
assert_eq!(args, expected);
let at = |needle: &str| args.iter().position(|arg| arg == needle).unwrap();
assert!(at("/run") < at("/run/mind-x-box") && at("/var/lib") < at("/var/lib/mind-x-box"), "hidden first, bound back after");
assert!(!args.windows(3).any(|w| w[0] == "--bind" && w[1] == "/run/mind-x-box"), "the scratch is read-only: {args:?}");
assert!(!args.iter().any(|arg| arg == "--unshare-net" || arg == "--unshare-all"), "the network is the fence's");
}
#[test]
fn t_a2_box_profile_is_sandbox_args() {
let (home, scratch, handoff, art) = (Path::new("/var/lib/mind-x-box"), Path::new("/run/mind-x-box"), Path::new("/opt/commons/handoff"), Path::new("/opt/commons/cast-art"));
let paths = BoxPaths { home, scratch, extra_rw: &[handoff, art] };
let argv = box_argv(&paths, "ls -la");
let mut expected = vec!["bwrap".to_owned()];
expected.extend(sandbox_args(home, scratch, &[handoff, art]));
expected.extend(["/bin/sh", "-c", "ls -la"].map(String::from));
assert_eq!(argv, expected, "bwrap, the one profile with the two commons data dirs, then /bin/sh -c");
let dashes = argv.iter().position(|arg| arg == "--").unwrap();
for dir in COMMONS_RW {
let bound = argv.windows(3).position(|w| w[0] == "--bind" && w[1] == dir && w[2] == dir).unwrap_or_else(|| panic!("{dir} is bound writable: {argv:?}"));
assert!(bound < dashes);
}
}
struct Box3 {
_dir: tempfile::TempDir,
home: PathBuf,
scratch: PathBuf,
handoff: PathBuf,
}
fn box3() -> Box3 {
let dir = tempfile::tempdir().unwrap();
let (home, scratch, handoff) = (dir.path().join("home"), dir.path().join("scratch"), dir.path().join("handoff"));
for made in [&home, &scratch, &handoff] {
std::fs::create_dir(made).unwrap();
}
Box3 { _dir: dir, home, scratch, handoff }
}
fn run(rig: &Box3, command: &str, timeout_s: u64) -> Value {
let extra = [rig.handoff.as_path()];
let mut answer = Vec::new();
serve_box(json!({ "command": command, "timeout_s": timeout_s }).to_string().as_bytes(), &mut answer, &BoxPaths { home: &rig.home, scratch: &rig.scratch, extra_rw: &extra }).unwrap();
serde_json::from_slice(&answer).unwrap()
}
fn has_bwrap() -> bool {
let program = box_argv(&BoxPaths { home: Path::new("/"), scratch: Path::new("/"), extra_rw: &[] }, "true").swap_remove(0);
Command::new(program).arg("--version").output().is_ok_and(|out| out.status.success())
}
/// Inside the box, the drain's files are not there: the unit's configuration, its credentials and her Persona's state.
#[test]
fn t_a2_box_hides_drain_files() {
if !has_bwrap() {
return eprintln!("no bwrap on this host: skipped");
}
let rig = box3();
let receipt = run(&rig, "[ -z \"$(ls -A /etc/gamecult)\" ] && [ ! -e /run/credentials ] && [ ! -e /var/lib/mind-eureka ] && [ ! -e /var/lib/mind-heartbeat ] && [ -d \"$HOME\" ] && pwd", 20);
assert_eq!(receipt["status"], "ok", "{receipt}");
assert_eq!(receipt["stdout_tail"].as_str().map(str::trim), rig.home.to_str(), "the command runs in her box's home");
// On a host where they exist outside, the box hides them; where they do not, the check above still holds.
for outside in ["/etc/gamecult", "/var/lib/mind-eureka"] {
eprintln!("{outside} outside the box: {}", if Path::new(outside).exists() { "present" } else { "absent" });
}
}
/// A command that writes to a commons data dir lists the path it wrote in `wrote`, and only what it wrote.
#[test]
fn t_a2_box_commons_receipt() {
if !has_bwrap() {
return eprintln!("no bwrap on this host: skipped");
}
let rig = box3();
std::fs::write(rig.handoff.join("old"), "before").unwrap();
std::thread::sleep(Duration::from_millis(20));
let target = rig.handoff.join("x");
let receipt = run(&rig, &format!("echo made > {} && echo note > notes.txt", target.display()), 20);
assert_eq!(receipt["status"], "ok", "{receipt}");
let wrote: Vec<&str> = receipt["wrote"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
assert!(wrote.contains(&target.to_str().unwrap()), "{receipt}");
assert!(wrote.contains(&rig.home.join("notes.txt").to_str().unwrap()), "her home is a writable bind too: {receipt}");
assert!(!wrote.iter().any(|path| path.ends_with("/old")), "a file it did not write is not listed: {receipt}");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "made\n");
}
/// A command that fails is `error` with its exit; one that runs past its timeout is stopped and says so; a request that is no
/// request is refused before anything runs.
#[test]
fn the_box_says_what_went_wrong() {
if !has_bwrap() {
return eprintln!("no bwrap on this host: skipped");
}
let rig = box3();
let failed = run(&rig, "echo oops >&2; exit 3", 20);
assert_eq!((failed["status"].as_str(), failed["exit"].as_i64(), failed["stderr_tail"].as_str()), (Some("error"), Some(3), Some("oops\n")), "{failed}");
let slow = run(&rig, "sleep 30", 1);
assert_eq!(slow["status"], "error", "{slow}");
assert!(slow["why"].as_str().unwrap().contains("ran past 1 s"), "{slow}");
assert!(slow["duration_ms"].as_u64().unwrap() < 10_000, "stopped at its timeout: {slow}");
let mut answer = Vec::new();
serve_box(&b"not json"[..], &mut answer, &BoxPaths { home: &rig.home, scratch: &rig.scratch, extra_rw: &[] }).unwrap();
assert_eq!(serde_json::from_slice::<Value>(&answer).unwrap()["status"], "error");
}
/// The tail keeps the end of a long stream.
#[test]
fn a_tail_is_the_end() {
let long: Vec<u8> = (0..20_000u32).map(|at| b'a' + (at % 26) as u8).collect();
let kept = tail(Box::new(std::io::Cursor::new(long.clone())));
assert_eq!(kept.as_bytes(), &long[long.len() - TAIL_BYTES..]);
}

View file

@ -1012,8 +1012,6 @@ pub struct ClaudeSpawner {
unit_environment: Vec<(OsString, OsString)>, unit_environment: Vec<(OsString, OsString)>,
scratch: PathBuf, scratch: PathBuf,
seed: Option<PathBuf>, seed: Option<PathBuf>,
/// Her sandbox: with it the child runs under bubblewrap (`sandbox_args`), the Persona's; the Self passes none.
sandbox: Option<PathBuf>,
/// Where her one kept conversation lives (the second of the unit's `STATE_DIRECTORY` entries, outside her working directory, the first); none keeps nothing, and every start is fresh. /// Where her one kept conversation lives (the second of the unit's `STATE_DIRECTORY` entries, outside her working directory, the first); none keeps nothing, and every start is fresh.
keep: Option<PathBuf>, keep: Option<PathBuf>,
/// The digest of the seed tree this process copies from (empty without a seed); none when the seed cannot be read, which no kept conversation matches. /// The digest of the seed tree this process copies from (empty without a seed); none when the seed cannot be read, which no kept conversation matches.
@ -1031,23 +1029,15 @@ impl ClaudeSpawner {
.iter() .iter()
.find(|(name, _)| name == STATE_DIRECTORY_VARIABLE) .find(|(name, _)| name == STATE_DIRECTORY_VARIABLE)
.and_then(|(_, value)| value.to_string_lossy().split(':').nth(1).filter(|second| !second.is_empty()).map(PathBuf::from)); .and_then(|(_, value)| value.to_string_lossy().split(':').nth(1).filter(|second| !second.is_empty()).map(PathBuf::from));
let mut spawner = Self::in_sandbox(unit_environment, SEED_VARIABLE, None)?;
spawner.seed_digest = match &spawner.seed {
Some(seed) => seed_digest(seed).ok(),
None => Some(String::new()),
};
spawner.keep = keep;
Ok(spawner)
}
/// The same, with the seed named by `seed_variable` and, if `sandbox` is given, the child run under bubblewrap with that directory as its writable home.
pub fn in_sandbox(unit_environment: impl IntoIterator<Item = (OsString, OsString)>, seed_variable: &str, sandbox: Option<PathBuf>) -> Result<Self> {
let unit_environment: Vec<(OsString, OsString)> = unit_environment.into_iter().collect();
let named = |variable: &str| unit_environment.iter().find(|(name, _)| name == variable).map(|(_, value)| PathBuf::from(value)); let named = |variable: &str| unit_environment.iter().find(|(name, _)| name == variable).map(|(_, value)| PathBuf::from(value));
// systemd lists several runtime directories colon-separated; the unit names one. // systemd lists several runtime directories colon-separated; the unit names one.
let scratch = named(SCRATCH_VARIABLE).filter(|path| !path.as_os_str().is_empty()).ok_or_else(|| anyhow!("{SCRATCH_VARIABLE} is not set: the unit needs RuntimeDirectory="))?; let scratch = named(SCRATCH_VARIABLE).filter(|path| !path.as_os_str().is_empty()).ok_or_else(|| anyhow!("{SCRATCH_VARIABLE} is not set: the unit needs RuntimeDirectory="))?;
let seed = named(seed_variable).filter(|path| !path.as_os_str().is_empty()); let seed = named(SEED_VARIABLE).filter(|path| !path.as_os_str().is_empty());
Ok(Self { unit_environment, scratch, seed, sandbox, keep: None, seed_digest: None }) let seed_digest = match &seed {
Some(seed) => seed_digest(seed).ok(),
None => Some(String::new()),
};
Ok(Self { unit_environment, scratch, seed, keep, seed_digest })
} }
} }
@ -1146,50 +1136,12 @@ impl Spawner for ClaudeSpawner {
fn spawn(&self, args: &[String], token: &TokenFd, session: Option<&str>) -> Result<Box<dyn Child>> { fn spawn(&self, args: &[String], token: &TokenFd, session: Option<&str>) -> Result<Box<dyn Child>> {
let config = FreshConfig::create(&self.scratch, self.seed.as_deref(), self.keep.clone())?; let config = FreshConfig::create(&self.scratch, self.seed.as_deref(), self.keep.clone())?;
let Some(sandbox) = &self.sandbox else { return spawn_program(Path::new("claude"), args, token, (&self.unit_environment, session), config) }; spawn_program(Path::new("claude"), args, token, (&self.unit_environment, session), config)
let mut wrapped = sandbox_args(sandbox, &self.scratch);
wrapped.push("claude".into());
wrapped.extend(args.iter().cloned());
spawn_program(Path::new("bwrap"), &wrapped, token, (&self.unit_environment, session), config)
} }
} }
/// The bubblewrap arguments up to the program: the whole filesystem read-only, a private `/tmp`
/// and `/run`, the unit's scratch directory read-only with only its `claude-config` writable (she
/// cannot create, replace or link a file where the organ writes, such as the instructions file),
/// her sandbox writable, her unit's credentials (`/etc/gamecult`, the other `/var/lib`
/// directories, the lease socket under `/run`) hidden, a private process table, and the child dead
/// when the unit's process is. The network is shared: the web, `huginn` and the API are reachable,
/// and what she reaches on the host is the uid fence's (gamecult-ops `mind-fence.service`), which
/// binds the organ and this sandbox alike. The boundary is the operating system's, not a pattern
/// list (ruling `eureka-body:ruling:persona-git-personal-sandbox`).
pub(crate) fn sandbox_args(sandbox: &Path, scratch: &Path) -> Vec<String> {
let (sandbox, scratch) = (sandbox.to_string_lossy(), scratch.to_string_lossy());
let config = scratch.to_string() + "/" + CONFIG_DIR_NAME;
[
"--ro-bind", "/", "/",
"--dev", "/dev",
"--proc", "/proc",
"--tmpfs", "/tmp",
"--tmpfs", "/run",
"--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve",
"--ro-bind", &scratch, &scratch,
"--bind", &config, &config,
"--tmpfs", "/etc/gamecult",
"--tmpfs", "/var/lib",
"--bind", &sandbox, &sandbox,
"--unshare-pid",
"--die-with-parent",
"--new-session",
"--chdir", &sandbox,
"--",
]
.map(String::from)
.to_vec()
}
/// The directory name of a child's configuration inside the scratch directory. /// The directory name of a child's configuration inside the scratch directory.
const CONFIG_DIR_NAME: &str = "claude-config"; pub(crate) const CONFIG_DIR_NAME: &str = "claude-config";
/// One child's configuration directory: made empty (or as the seed) for it, /// One child's configuration directory: made empty (or as the seed) for it,
/// owner-only, and removed when the child's handle goes. Whatever the run writes /// owner-only, and removed when the child's handle goes. Whatever the run writes

View file

@ -2026,57 +2026,6 @@ fn a_brief_the_run_claims_is_in_the_task_once_and_not_again_under_also_open() {
assert!(start.contains("Do the claimed thing.") && !start.contains("Also open for you"), "{start}"); assert!(start.contains("Do the claimed thing.") && !start.contains("Also open for you"), "{start}");
} }
/// The Persona's boundary: the bubblewrap wrapper `ClaudeSpawner` runs when it has a sandbox.
#[cfg(unix)]
mod sandbox {
use std::os::unix::fs::PermissionsExt;
use super::*;
#[test]
fn the_sandbox_arguments_are_pinned() {
let args = sandbox_args(Path::new("/var/lib/mind-x/sandbox"), Path::new("/run/mind-x"));
let expected: Vec<String> = [
"--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp", "--tmpfs", "/run", "--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve", "--ro-bind", "/run/mind-x", "/run/mind-x", "--bind",
"/run/mind-x/claude-config", "/run/mind-x/claude-config", "--tmpfs", "/etc/gamecult", "--tmpfs", "/var/lib", "--bind", "/var/lib/mind-x/sandbox", "/var/lib/mind-x/sandbox", "--unshare-pid", "--die-with-parent", "--new-session", "--chdir", "/var/lib/mind-x/sandbox", "--",
]
.map(String::from)
.to_vec();
assert_eq!(args, expected);
// The credentials are hidden before the sandbox and the scratch are bound back, and the network is not unshared.
let at = |needle: &str| args.iter().position(|arg| arg == needle).unwrap();
assert!(at("/run") < at("/run/mind-x") && at("/var/lib") < at("/var/lib/mind-x/sandbox"));
// The scratch is read-only to her: no plain bind of it, so she cannot plant a link where the organ writes.
assert!(!args.windows(3).any(|w| w[0] == "--bind" && w[1] == "/run/mind-x"), "{args:?}");
assert!(!args.iter().any(|arg| arg == "--unshare-net" || arg == "--unshare-all"));
}
#[test]
fn a_sandboxed_spawner_runs_bwrap_with_its_arguments_then_claude_and_the_child_sees_no_credential() {
let dir = tempfile::tempdir().unwrap();
let (bin, scratch, sandbox) = (dir.path().join("bin"), dir.path().join("scratch"), dir.path().join("sandbox"));
for made in [&bin, &scratch, &sandbox] {
std::fs::create_dir(made).unwrap();
}
let (argv, environment) = (dir.path().join("argv"), dir.path().join("environment"));
let fake = bin.join("bwrap");
std::fs::write(&fake, format!("#!/bin/sh\nprintf '%s\n' \"$@\" > {}\nenv > {}\n", argv.display(), environment.display())).unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut unit: Vec<(std::ffi::OsString, std::ffi::OsString)> = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "UNLISTED_VARIABLE"].iter().map(|name| ((*name).into(), format!("canary-{name}").into())).collect();
unit.push(("PATH".into(), format!("{}:/usr/bin:/bin", bin.display()).into()));
unit.push((SCRATCH_VARIABLE.into(), scratch.clone().into_os_string()));
let spawner = ClaudeSpawner::in_sandbox(unit, "MIND_PERSONA_CONFIG_SEED", Some(sandbox.clone())).unwrap();
let mut child = spawner.spawn(&["--flag".to_string(), "value".to_string()], &token_holding("tok-canary"), None).unwrap();
while !matches!(child.next(StdDuration::from_secs(20)), Read::Exited(_) | Read::Timeout) {}
let recorded: Vec<String> = std::fs::read_to_string(&argv).unwrap().lines().map(String::from).collect();
let mut expected = sandbox_args(&sandbox, &scratch);
expected.extend(["claude", "--flag", "value"].map(String::from));
assert_eq!(recorded, expected, "bwrap, its arguments, then claude and its own");
let seen = std::fs::read_to_string(&environment).unwrap();
assert!(!seen.contains("canary") && !seen.contains("UNLISTED"), "the child's environment is the allow-list: {seen}");
}
}
#[test] #[test]
fn a_user_line_with_images_is_a_text_block_then_one_base64_image_block_each_and_without_them_is_the_bare_text() { fn a_user_line_with_images_is_a_text_block_then_one_base64_image_block_each_and_without_them_is_the_bare_text() {
use super::session::user_line; use super::session::user_line;

View file

@ -9,6 +9,7 @@ mind_body: mod lease_client
mind_body: mod persona mind_body: mod persona
mind_body: mod projection mind_body: mod projection
mind_body: mod queue mind_body: mod queue
mind_body: mod sandbox
mind_body: mod self_run mind_body: mod self_run
mind_body: mod tempo mind_body: mod tempo
mind_body::address: impl Addressee mind_body::address: impl Addressee
@ -177,7 +178,7 @@ mind_body::heartbeat: struct Addressing # [derive (Clone , Debug , Default , Par
mind_body::heartbeat: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[personas: Vec < PersonaId >, operators: Vec < String >, beat_s: u32] mind_body::heartbeat: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[personas: Vec < PersonaId >, operators: Vec < String >, beat_s: u32]
mind_body::heartbeat: struct FileControl pub-fields[] mind_body::heartbeat: struct FileControl pub-fields[]
mind_body::heartbeat: struct FileStore pub-fields[] mind_body::heartbeat: struct FileStore pub-fields[]
mind_body::heartbeat: struct HeartbeatState # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[last_beat_at: DateTime < Utc >, handled_mentions: Vec < String >, last_turn_at: BTreeMap < String , DateTime < Utc > >, owed_starts: BTreeMap < String , u32 >] mind_body::heartbeat: struct HeartbeatState # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[last_beat_at: DateTime < Utc >, handled_mentions: Vec < String >, last_turn_at: BTreeMap < String , DateTime < Utc > >, retired_slot_3: BTreeMap < String , u32 >]
mind_body::heartbeat: struct InstanceTrace # [derive (Clone , Debug , PartialEq , Eq , serde :: Serialize , serde :: Deserialize)] pub-fields[instance: String, vote_beat_s: Option < u32 >, urgency_permille: u16, addressed: bool, busy: bool, released: bool, idle_s: i64, score: String, note: String] mind_body::heartbeat: struct InstanceTrace # [derive (Clone , Debug , PartialEq , Eq , serde :: Serialize , serde :: Deserialize)] pub-fields[instance: String, vote_beat_s: Option < u32 >, urgency_permille: u16, addressed: bool, busy: bool, released: bool, idle_s: i64, score: String, note: String]
mind_body::heartbeat: struct Organs< 'a > pub-fields[seats: & 'a [Seat < 'a >], control: & 'a dyn Control, launcher: & 'a dyn Launcher, clock: & 'a dyn Clock, store: & 'a dyn Store] mind_body::heartbeat: struct Organs< 'a > pub-fields[seats: & 'a [Seat < 'a >], control: & 'a dyn Control, launcher: & 'a dyn Launcher, clock: & 'a dyn Clock, store: & 'a dyn Store]
mind_body::heartbeat: struct PersonaId # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[slug: Slug, public_name: String, handle: String, matrix_id: String, huginn: SocketAddr] mind_body::heartbeat: struct PersonaId # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[slug: Slug, public_name: String, handle: String, matrix_id: String, huginn: SocketAddr]
@ -217,14 +218,14 @@ mind_body::lease_client: struct LeaseRequest # [derive (Clone , Debug , PartialE
mind_body::lease_client: struct SocketLender pub-fields[] mind_body::lease_client: struct SocketLender pub-fields[]
mind_body::lease_client: struct TokenFd pub-fields[] mind_body::lease_client: struct TokenFd pub-fields[]
mind_body::lease_client::socket: impl Lease for Granted mind_body::lease_client::socket: impl Lease for Granted
mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , Drained { turns : usize , acked_through : Option < u64 > , put_refused : usize } , Failed (String) , } mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , Drained { wakes : usize , acked_through : Option < u64 > } , Failed (String) , }
mind_body::persona: const AGENT : & str mind_body::persona: const AGENT : & str
mind_body::persona: const ENV_MINDS : & str mind_body::persona: const ENV_MINDS : & str
mind_body::persona: const ENV_MODEL : & str mind_body::persona: const ENV_MODEL : & str
mind_body::persona: const ENV_OPERATOR : & str mind_body::persona: const ENV_OPERATOR : & str
mind_body::persona: const ENV_REVIEW_ROOM : & str
mind_body::persona: const ENV_ROOMS : & str mind_body::persona: const ENV_ROOMS : & str
mind_body::persona: const ENV_SELF_SENDER : & str mind_body::persona: const ENV_SELF_SENDER : & str
mind_body::persona: const TURNS_PER_START : usize
mind_body::persona: fn carry < C : Chat > (control : & impl ControlSource , swarm : & impl ControlSource , instance : & Slug , build : impl FnOnce () -> Result < Start < C > >) -> Outcome mind_body::persona: fn carry < C : Chat > (control : & impl ControlSource , swarm : & impl ControlSource , instance : & Slug , build : impl FnOnce () -> Result < Start < C > >) -> Outcome
mind_body::persona: fn trace_lines (trace : & dyn TraceView , last : usize) -> Result < Vec < String > > mind_body::persona: fn trace_lines (trace : & dyn TraceView , last : usize) -> Result < Vec < String > >
mind_body::persona: impl Config mind_body::persona: impl Config
@ -243,31 +244,76 @@ mind_body::persona: impl TraceView for TraceSnapshot
mind_body::persona: impl fmt :: Display for Outcome mind_body::persona: impl fmt :: Display for Outcome
mind_body::persona: pub trait Trace : TraceView { fn record (& self , key : & str , record : & Value) -> Result < () > ; } mind_body::persona: pub trait Trace : TraceView { fn record (& self , key : & str , record : & Value) -> Result < () > ; }
mind_body::persona: pub trait TraceView { fn records (& self) -> Result < Vec < Value > > ; } mind_body::persona: pub trait TraceView { fn records (& self) -> Result < Vec < Value > > ; }
mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String] mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String, review_room: Option < String >]
mind_body::persona: struct FileTrace pub-fields[] mind_body::persona: struct FileTrace pub-fields[]
mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >] mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, agent: Box < dyn Steps >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, session: PathBuf, box_socket: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >]
mind_body::persona: struct TraceSnapshot pub-fields[] mind_body::persona: struct TraceSnapshot pub-fields[]
mind_body::persona: struct TurnRecord # [derive (Clone , Debug , PartialEq , DatabaseEntry)] pub-fields[value: Value] mind_body::persona: struct TurnRecord # [derive (Clone , Debug , PartialEq , DatabaseEntry)] pub-fields[value: Value]
mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , Interpreter , } mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , }
mind_body::projection: # [derive (Debug , PartialEq , Eq)] pub enum Put { Committed , Stale , Refused (String) , } mind_body::projection: # [derive (Debug , PartialEq , Eq)] pub enum Put { Committed , Stale , Refused (String) , }
mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value > mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value >
mind_body::projection: impl Affordance
mind_body::projection: impl HuginnPersonaSource mind_body::projection: impl HuginnPersonaSource
mind_body::projection: impl HuginnPersonaSource: fn new (client : HuginnClient) -> Self mind_body::projection: impl HuginnPersonaSource: fn new (client : HuginnClient) -> Self
mind_body::projection: impl PersonaSource for HuginnPersonaSource mind_body::projection: impl PersonaSource for HuginnPersonaSource
mind_body::projection: impl< T : Chat > MouthReader for T mind_body::projection: impl< T : Chat > MouthReader for T
mind_body::projection: mod agent
mind_body::projection: mod harness mind_body::projection: mod harness
mind_body::projection: pub trait MouthReader { fn pending (& self) -> Result < ChatPending > ; } mind_body::projection: pub trait MouthReader { fn pending (& self) -> Result < ChatPending > ; }
mind_body::projection: pub trait PersonaSource { fn persona (& self) -> Result < (Value , String) > ; } mind_body::projection: pub trait PersonaSource { fn persona (& self) -> Result < (Value , String) > ; }
mind_body::projection: pub trait PersonaStore : PersonaSource { fn put (& self , state : & Value , expected_updated_at : Option < & str > , session : & str) -> Result < Put > ; } mind_body::projection: pub trait PersonaStore : PersonaSource { fn put (& self , state : & Value , expected_updated_at : Option < & str > , session : & str) -> Result < Put > ; }
mind_body::projection: pub use domain :: { DomainFacts , DomainSource , HttpForge , MindDomain } ; mind_body::projection: pub use domain :: { DomainFacts , DomainSource , HttpForge , MindDomain } ;
mind_body::projection: pub use narrate :: { Answer , Continued , Failed , KitModel , Model , Reasoning , Spent , Turn , connector_key } ; mind_body::projection: pub use narrate :: { Answer , Failed , KitModel , Model , Spent , StepRequest , Stepped , ToolCall , connector_key } ;
mind_body::projection: pub use read :: { LiveReads , ReadFailure , ReadFixture , ReadRequest , ReadSource } ; mind_body::projection: pub use read :: { LiveReads , ReadFailure , ReadFixture , ReadRequest , ReadSource } ;
mind_body::projection: pub use select :: TurnKind ; mind_body::projection: pub use select :: TurnKind ;
mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ; mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ;
mind_body::projection: struct HuginnPersonaSource pub-fields[] mind_body::projection: struct HuginnPersonaSource pub-fields[]
mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >, domain: Option < & 'a dyn DomainSource >, reads: Option < & 'a dyn ReadSource >] mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >, domain: Option < & 'a dyn DomainSource >, reads: Option < & 'a dyn ReadSource >]
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 >, woken_for: Vec < String >, last_outcome: Option < Value >, last_wake: Option < DateTime < Utc > >, records: Vec < Value >] mind_body::projection: struct Request # [derive (Clone)] pub-fields[instance: String, kind: TurnKind, state: Option < Value >, rooms: Vec < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >, woken_for: Vec < String >, told: Vec < Value >, tools: Vec < String >, last_wake: Option < DateTime < Utc > >, records: Vec < Value >]
mind_body::projection::agent: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize)] # [serde (rename_all = "snake_case")] pub enum Status { Ok , Refused , Error , Unknown , NotSent , Cap , }
mind_body::projection::agent: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cap { ToolCalls , ModelCalls , WakeSpend , DaySpend , }
mind_body::projection::agent: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Ended { EndTurn , Cap (Cap) , Failed (Failed) , }
mind_body::projection::agent: fn instructions (name : & str) -> String
mind_body::projection::agent: fn step (agent : & Agent < '_ > , wake : & Wake < '_ >) -> Result < Turn >
mind_body::projection::agent: impl Cap
mind_body::projection::agent: impl FileSession
mind_body::projection::agent: impl FileSession: fn discard (& self) -> Result < () >
mind_body::projection::agent: impl FileSession: fn load (& self) -> Result < Option < Session > >
mind_body::projection::agent: impl FileSession: fn new (path : impl Into < PathBuf >) -> Self
mind_body::projection::agent: impl FileSession: fn save (& self , session : & Session) -> Result < () >
mind_body::projection::agent: impl Ledger for TraceLedger < '_ >
mind_body::projection::agent: impl Receipt
mind_body::projection::agent: impl Receipt: fn fields (& self) -> & Map < String , Value >
mind_body::projection::agent: impl Receipt: fn json (& self) -> Value
mind_body::projection::agent: impl Receipt: fn new (tool : impl Into < String > , status : Status , fields : Value) -> Self
mind_body::projection::agent: impl Receipt: fn status (& self) -> Status
mind_body::projection::agent: impl Receipt: fn tool (& self) -> & str
mind_body::projection::agent: impl Run < '_ >
mind_body::projection::agent: impl Steps for KitModel
mind_body::projection::agent: impl TraceLedger < 'a >: fn new (trace : & 'a dyn Trace , stem : impl Into < String >) -> Self
mind_body::projection::agent: impl< 'a > TraceLedger < 'a >
mind_body::projection::agent: impl< T : Steps + ? Sized > Steps for std :: rc :: Rc < T >
mind_body::projection::agent: pub trait Executor { fn definitions (& self) -> Vec < ToolDefinition > ; fn run (& self , call : & ToolCall) -> Receipt ; }
mind_body::projection::agent: pub trait Ledger { fn rows (& self) -> Result < Vec < Value > > ; fn append (& self , row : Value) -> Result < u64 > ; }
mind_body::projection::agent: pub trait Steps { fn step (& self , request : StepRequest < '_ >) -> std :: result :: Result < Stepped , Failed > ; }
mind_body::projection::agent: struct Agent< 'a > pub-fields[model: & 'a dyn Steps, session: & 'a FileSession, executors: & 'a [& 'a dyn Executor], ledger: & 'a dyn Ledger, bounds: & 'a AgentTuning, clock: & 'a dyn Fn () -> DateTime < Utc >]
mind_body::projection::agent: struct FileSession pub-fields[]
mind_body::projection::agent: struct Receipt # [derive (Clone , Debug , PartialEq)] pub-fields[]
mind_body::projection::agent: struct Session # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[items: Vec < InputItem >, digest: String, retention: CacheRetention, created_at: DateTime < Utc >, last_call_at: DateTime < Utc >, last_usage: Option < Spent >]
mind_body::projection::agent: struct TraceLedger< 'a > pub-fields[]
mind_body::projection::agent: struct Turn # [derive (Clone , Debug , PartialEq)] pub-fields[ended: Ended, text: String, receipts: Vec < Receipt >, model_calls: usize, tool_calls: usize, usd: f64]
mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, instructions: & 'a str, input: & 'a str, fresh: & 'a str]
mind_body::projection::agent::read: impl Executor for Read < '_ >
mind_body::projection::agent::read: struct Read< 'a > pub-fields[source: Option < & 'a dyn ReadSource >, since: DateTime < Utc >]
mind_body::projection::agent::request_tool: impl Executor for RequestTool
mind_body::projection::agent::request_tool: struct RequestTool pub-fields[]
mind_body::projection::agent::say: impl Executor for Say < '_ >
mind_body::projection::agent::say: impl Mouth < '_ >
mind_body::projection::agent::say: impl Say < '_ >
mind_body::projection::agent::say: struct Say< 'a > pub-fields[]
mind_body::projection::agent::shell: impl Executor for Shell
mind_body::projection::agent::shell: struct Shell pub-fields[socket: PathBuf]
mind_body::projection::commit: impl Commit < '_ >
mind_body::projection::commit: impl Heard
mind_body::projection::domain: impl DomainSource for DomainFacts mind_body::projection::domain: impl DomainSource for DomainFacts
mind_body::projection::domain: impl DomainSource for MindDomain mind_body::projection::domain: impl DomainSource for MindDomain
mind_body::projection::domain: impl ForgeGet for HttpForge mind_body::projection::domain: impl ForgeGet for HttpForge
@ -296,23 +342,22 @@ 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 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 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::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::interpret: impl Drafts
mind_body::projection::interpret: impl GapKind
mind_body::projection::interpret: impl Refusal
mind_body::projection::narrate: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Turn { User (String) , Assistant { text : String , states : Vec < Reasoning > } , }
mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String > mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String >
mind_body::projection::narrate: impl Failed mind_body::projection::narrate: impl Failed
mind_body::projection::narrate: impl KitModel mind_body::projection::narrate: impl KitModel
mind_body::projection::narrate: impl KitModel: fn open (endpoint : SocketAddr , connection_key : String , caller : & str , timeout : Duration) -> Result < Self > mind_body::projection::narrate: impl KitModel: fn open (endpoint : SocketAddr , connection_key : String , caller : & str , timeout : Duration) -> Result < Self >
mind_body::projection::narrate: impl KitModel: fn step (& self , request : StepRequest < '_ >) -> std :: result :: Result < Stepped , Failed >
mind_body::projection::narrate: impl Model for KitModel mind_body::projection::narrate: impl Model for KitModel
mind_body::projection::narrate: impl std :: fmt :: Display for Failed mind_body::projection::narrate: impl std :: fmt :: Display for Failed
mind_body::projection::narrate: pub trait Model { fn ask (& self , request_id : & str , model : & str , prompt : & str , schema : Option < & str >) -> std :: result :: Result < Answer , Failed > ; fn converse (& self , request_id : & str , model : & str , turns : & [Turn]) -> std :: result :: Result < Continued , Failed > { let text : Vec < & str > = turns . iter () . map (| turn | match turn { Turn :: User (text) => text . as_str () , Turn :: Assistant { text , .. } => text . as_str () , }) . collect () ; self . ask (request_id , model , & text . join ("\n\n") , None) . map (| answer | Continued { answer , states : Vec :: new () }) } } mind_body::projection::narrate: impl< T : Model + ? Sized > Model for std :: rc :: Rc < T >
mind_body::projection::narrate: pub trait Model { fn ask (& self , request_id : & str , model : & str , prompt : & str , schema : Option < & str >) -> std :: result :: Result < Answer , Failed > ; }
mind_body::projection::narrate: struct Answer # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[text: String, usage: Option < Spent >] mind_body::projection::narrate: struct Answer # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[text: String, usage: Option < Spent >]
mind_body::projection::narrate: struct Continued # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[answer: Answer, states: Vec < Reasoning >]
mind_body::projection::narrate: struct Failed # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[reason: String, outage: bool, usage: Option < Spent >] mind_body::projection::narrate: struct Failed # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[reason: String, outage: bool, usage: Option < Spent >]
mind_body::projection::narrate: struct KitModel pub-fields[] mind_body::projection::narrate: struct KitModel pub-fields[]
mind_body::projection::narrate: struct Reasoning # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[provider: String, model: String, state: Vec < u8 >] mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >]
mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >] mind_body::projection::narrate: struct StepRequest< 'a > pub-fields[request_id: & 'a str, conversation_id: & 'a str, model: & 'a str, instructions: & 'a str, tools: & 'a [ToolDefinition], input: Vec < InputItem >, retention: Option < CacheRetention >, schema: Option < & 'a str >]
mind_body::projection::narrate: struct Stepped # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[items: Vec < InputItem >, text: String, calls: Vec < ToolCall >, stop: StopReason, usage: Spent]
mind_body::projection::narrate: struct ToolCall # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[call_id: String, name: String, arguments: String]
mind_body::projection::outcome: impl Outcome mind_body::projection::outcome: impl Outcome
mind_body::projection::outcome: impl Part mind_body::projection::outcome: impl Part
mind_body::projection::outcome::form: impl EventPhrase mind_body::projection::outcome::form: impl EventPhrase
@ -327,8 +372,8 @@ mind_body::projection::read: impl LiveReads
mind_body::projection::read: impl LiveReads: fn new (client : HuginnClient , forge : Option < HttpForge >) -> Self mind_body::projection::read: impl LiveReads: fn new (client : HuginnClient , forge : Option < HttpForge >) -> Self
mind_body::projection::read: impl ReadFailure mind_body::projection::read: impl ReadFailure
mind_body::projection::read: impl ReadFixture mind_body::projection::read: impl ReadFixture
mind_body::projection::read: impl ReadRefusal
mind_body::projection::read: impl ReadRequest mind_body::projection::read: impl ReadRequest
mind_body::projection::read: impl ReadRequest: fn from_target (kind : & str , target : & str) -> Result < Self , String >
mind_body::projection::read: impl ReadSource for LiveReads mind_body::projection::read: impl ReadSource for LiveReads
mind_body::projection::read: impl ReadSource for ReadFixture mind_body::projection::read: impl ReadSource for ReadFixture
mind_body::projection::read: pub trait ReadSource { fn read (& self , request : & ReadRequest , since : DateTime < Utc >) -> Result < String , ReadFailure > ; } mind_body::projection::read: pub trait ReadSource { fn read (& self , request : & ReadRequest , since : DateTime < Utc >) -> Result < String , ReadFailure > ; }
@ -347,13 +392,15 @@ mind_body::projection::select: impl Section
mind_body::projection::select: impl std :: fmt :: Display for Who mind_body::projection::select: impl std :: fmt :: Display for Who
mind_body::projection::select: impl< 'a > Inputs < 'a > mind_body::projection::select: impl< 'a > Inputs < 'a >
mind_body::projection::simulate: fn simulate (harness : & Harness , plan_path : & Path) -> Result < String > mind_body::projection::simulate: fn simulate (harness : & Harness , plan_path : & Path) -> Result < String >
mind_body::projection::simulate: impl Actuator for SimRoom < '_ >
mind_body::projection::simulate: impl HeartbeatView for Names < '_ > mind_body::projection::simulate: impl HeartbeatView for Names < '_ >
mind_body::projection::simulate: impl MouthReader for View < '_ > mind_body::projection::simulate: impl MouthReader for View < '_ >
mind_body::projection::simulate: impl ReadSource for CastReads < '_ > mind_body::projection::simulate: impl ReadSource for CastReads < '_ >
mind_body::projection::tuning: const TUNING_FILE : & str mind_body::projection::tuning: const TUNING_FILE : & str
mind_body::projection::tuning: const TUNING_ROOT : & str mind_body::projection::tuning: const TUNING_ROOT : & str
mind_body::projection::tuning: fn load (path : & Path) -> Result < Loaded > mind_body::projection::tuning: fn load (path : & Path) -> Result < Loaded >
mind_body::projection::tuning: impl AgentTuning
mind_body::projection::tuning: impl Default for AgentTuning
mind_body::projection::tuning: impl Default for CacheTtl
mind_body::projection::tuning: impl Default for InterpreterTuning mind_body::projection::tuning: impl Default for InterpreterTuning
mind_body::projection::tuning: impl Default for LensWeights mind_body::projection::tuning: impl Default for LensWeights
mind_body::projection::tuning: impl Default for PersonaTuning mind_body::projection::tuning: impl Default for PersonaTuning
@ -361,16 +408,19 @@ mind_body::projection::tuning: impl Default for PoolCaps
mind_body::projection::tuning: impl Default for ProjectorTuning mind_body::projection::tuning: impl Default for ProjectorTuning
mind_body::projection::tuning: impl Default for SelectTuning mind_body::projection::tuning: impl Default for SelectTuning
mind_body::projection::tuning: impl Default for Tuning mind_body::projection::tuning: impl Default for Tuning
mind_body::projection::tuning: impl Price
mind_body::projection::tuning: impl Tuning mind_body::projection::tuning: impl Tuning
mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, reads_per_wake: usize, read_bytes: usize, wake_read_bytes: usize] mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >]
mind_body::projection::tuning: struct CacheTtl # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[short: u64, long: u64]
mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String]
mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64] mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64]
mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String] mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String]
mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize] mind_body::projection::tuning: struct 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] mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[memories_about_present: usize, other_memories: usize, needs: usize, incubation: usize, stance: usize, value: usize]
mind_body::projection::tuning: struct Price # [derive (Clone , Copy , Debug , PartialEq , Serialize , Deserialize)] pub-fields[input: f64, output: f64, cache_read: f64, cache_write_short: f64, cache_write_long: f64]
mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize] mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize]
mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, notes_bytes: usize, here_bytes: usize, outcome_bytes: usize, domain_bytes: usize, exchange_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, body_bytes: usize, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps] mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, notes_bytes: usize, here_bytes: usize, outcome_bytes: usize, domain_bytes: usize, exchange_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, body_bytes: usize, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps]
mind_body::projection::tuning: struct 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::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, agent: AgentTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >]
mind_body::projection::turn: impl Actuator for Mouth < '_ >
mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held > mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held >
mind_body::queue: impl Held mind_body::queue: impl Held
mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool
@ -382,6 +432,9 @@ mind_body::queue: impl< 'a > HuginnMind < 'a >
mind_body::queue: pub trait MindPort { fn instance (& self) -> & Slug ; fn query (& self , selection : & Selection) -> Result < PipelineSelectionPage > ; fn query_near (& self , _selection : & Selection , _text : & str , _top_k : u32) -> Result < PipelineSelectionPage > { bail ! ("this mind port has no semantic index") } fn stewarded_activity (& self , _repos : & [OrgRepo] , _after : Option < u64 >) -> Result < RepoActivity > { bail ! ("this mind port has no forge to read") } fn roots_touched (& self) -> Result < Vec < RootTouched > > { bail ! ("this mind port has no roots to read") } fn admit (& self , agent : & str , session : & str , documents : Vec < PipelineDocument >) -> Result < PipelineAdmissionOutcome > ; } mind_body::queue: pub trait MindPort { fn instance (& self) -> & Slug ; fn query (& self , selection : & Selection) -> Result < PipelineSelectionPage > ; fn query_near (& self , _selection : & Selection , _text : & str , _top_k : u32) -> Result < PipelineSelectionPage > { bail ! ("this mind port has no semantic index") } fn stewarded_activity (& self , _repos : & [OrgRepo] , _after : Option < u64 >) -> Result < RepoActivity > { bail ! ("this mind port has no forge to read") } fn roots_touched (& self) -> Result < Vec < RootTouched > > { bail ! ("this mind port has no roots to read") } fn admit (& self , agent : & str , session : & str , documents : Vec < PipelineDocument >) -> Result < PipelineAdmissionOutcome > ; }
mind_body::queue: struct Held # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[] mind_body::queue: struct Held # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[]
mind_body::queue: struct HuginnMind< 'a > pub-fields[] mind_body::queue: struct HuginnMind< 'a > pub-fields[]
mind_body::sandbox: const COMMONS_RW : [& str ; 2]
mind_body::sandbox: fn serve_box (mut input : impl Read , mut output : impl Write , paths : & BoxPaths < '_ >) -> std :: io :: Result < () >
mind_body::sandbox: struct BoxPaths< 'a > pub-fields[home: & 'a Path, scratch: & 'a Path, extra_rw: & 'a [& 'a Path]]
mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq , PartialOrd , Ord)] pub enum Stop { Interrupt , Terminate , Kill , } mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq , PartialOrd , Ord)] pub enum Stop { Interrupt , Terminate , Kill , }
mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cause { Own , FlushRequested , Signalled (Stop) , Unstoppable , } mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cause { Own , FlushRequested , Signalled (Stop) , Unstoppable , }
mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Read { Line (String) , Timeout , Eof , Exited (Option < i32 >) , } mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Read { Line (String) , Timeout , Eof , Exited (Option < i32 >) , }
@ -415,7 +468,6 @@ mind_body::self_run: fn start_message (instance : & Slug , run : & PipelineRef ,
mind_body::self_run: fn writes_hour_cache (line : & str) -> Option < bool > mind_body::self_run: fn writes_hour_cache (line : & str) -> Option < bool >
mind_body::self_run: impl Child for ClaudeProcess mind_body::self_run: impl Child for ClaudeProcess
mind_body::self_run: impl ClaudeSpawner mind_body::self_run: impl ClaudeSpawner
mind_body::self_run: impl ClaudeSpawner: fn in_sandbox (unit_environment : impl IntoIterator < Item = (OsString , OsString) > , seed_variable : & str , sandbox : Option < PathBuf >) -> Result < Self >
mind_body::self_run: impl ClaudeSpawner: fn new (unit_environment : impl IntoIterator < Item = (OsString , OsString) >) -> Result < Self > mind_body::self_run: impl ClaudeSpawner: fn new (unit_environment : impl IntoIterator < Item = (OsString , OsString) >) -> Result < Self >
mind_body::self_run: impl Drop for FreshConfig mind_body::self_run: impl Drop for FreshConfig
mind_body::self_run: impl FreshConfig mind_body::self_run: impl FreshConfig