Compare commits

..
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
4285ec749f Persona live organ: one-turn, drain, wake-humans-pace, turn memory (squash of hands/persona-live-drain) (#83) 2026-11-28 07:05:44 +00:00
51fc7c3576 Merge pull request 'Speech binds to her words; Huginn's chat Interpreter; she speaks only in the turn's room' (#82) from hands/speech-binding into main 2026-11-20 05:27:32 +00:00
Meta Vens
7ed31c6f75 Test prose speaks in standalone quotations: a dialogue tag frames its quotation (Soul F1)
"what a day" he says and "Missed you too, friend," he types are framed under F1, so the test doubles' lines went silent. The prose now quotes whole sentences.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:15:15 +01:00
5b1a1e2cf4 Merge pull request 'Body map after C2: the persona-only body' (#77) from modeling/body-map-after-c2 into main 2026-11-19 21:40:28 +00:00
Meta Vens
e011c2aa21 Body map after C2: the persona-only body, stale rows marked, READMEs corrected
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 22:40:02 +01:00
66b85c8b67 Merge pull request 'C2: cut the mission organ and every Persona-side Mind write' (#75) from hands/persona-only-subtraction into main 2026-11-19 21:35:59 +00:00
Meta Vens
8ebe5de822 self_run: drop the doc pointer to the deleted launch::run_label
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:31:15 +01:00
Meta Vens
e9a883f732 mind-body public surface: regenerated after the F3/F4 follow-ups
Removed: launch's run opener and its types, queue's queue and breaker,
heartbeat's Night; changed: heartbeat Config and HeartbeatState.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:30:50 +01:00
Meta Vens
8fe9fc351b Heartbeat: no night wake until C4; stale docs and empty tests (Soul F4, F6, F7)
F4: the night wake started a plain mind-persona@ unit and traced it as
Sleep and "asleep". Deleted the night branch, Night, Config.night, the
HEARTBEAT_SLEEP_UTC and HEARTBEAT_SLEEP_MINDS settings and
HeartbeatState.last_night_at (added by this PR, never deployed, so nothing
must decode it). A wake's trace entry is her slug. Reflection and
consolidation return in C4.

F6: deleted a_flag_overrides_the_environment (asserted exit 0 with the
config discarded) and the heartbeat test that compared two identical rigs.

F7: Cargo.toml no longer says the Persona drains her chat or that launch
opens runs; heartbeat.rs no longer says Persona units read its addressing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:30:50 +01:00
Meta Vens
6df3255330 Delete the run opener, the work queue and the breaker (C2 follow-up, Soul F3)
Map section 7 keeps no dormant switch in main: Self-run launching is parked
at parked/self-run-launch. open_and_launch was the only code that opened a
SelfRun run and nothing called it in production.

launch.rs keeps the systemd door (Launcher, SystemdLauncher, unit names,
the brake's stop) and the two reads self_run uses, holders and closure.
Deleted: open_and_launch, Ports, LaunchRequest, LaunchOutcome, Declined,
slot, START_GRACE_S, run_label, the dead-run closer and the breaker
question, with their tests.

queue.rs keeps MindPort, HuginnMind, the paged reads and on_hold, which
self_run's inbox reads. Deleted: queue, breaker, Breaker, CONSECUTIVE,
WINDOW, EMPTY_SHARE, live_claims, claims_of, with their tests.

control: Grant::for_test and the launch-gate tests went with the gate.
testkit: the helpers only those tests used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:30:50 +01:00
Meta Vens
3e6554ca5a Cargo.lock as cargo writes it for the baf4ecf7 pin (duplicate CultLib entries reordered)
Soul C1 F5: the lock from the pin merge was accepted by --locked but
rewritten by an unlocked cargo; this is cargo's own rewrite.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:19:15 +01:00
Meta Vens
7b9fa7d33f mind-body public surface: regenerated after the C2 subtraction
Taken from the test's printed full current surface. Two lines are main's
drift, not this cut (chat_client's Basis gained FollowUp, and
FOLLOW_UP_BASIS); the rest is the subtraction: 83 lines removed (persona's
reply and session organ, stream, sleep's inbox, tempo's tally and PID,
heartbeat's AGENT and HeartbeatView::latest) and 11 changed or added
(persona Outcome/carry/Config, heartbeat Config.beat_s, DEFAULT_BEAT_S,
HeartbeatState's turn and night maps, FileStore::latest, Organs without
host, Standing without self_permille).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:07:56 +01:00
Meta Vens
0fd12325bd Cut the mission organ and every Persona-side Mind write (C2)
Map: docs/persona-only-heartbeat-map.md (imagination/persona-only-heartbeat,
d861574), cut C2. Rulings: eureka-body:ruling:persona-only-heartbeat (she
reads the Mind and never writes it; no Self runs from the Persona).

Persona organ (persona.rs 3983 -> ~420 lines): deleted the live session
organ whole: TURN_INSTRUCTION, TURN_REMINDER, MESSAGES_HEADER, WORK_QUESTION,
ANSWER_MESSAGES, WAKE_ASK, WORK_TAIL; PersonaReply with intent, remember,
rule, settle, start_self_run, tempo vote and urgency, and reply_schema; the
doctrine and persona-JSON system prompt (read_doctrine, render_instructions,
campaigns); start_session, persona_args, PersonaInbox; act, decode_reply and
every admission (memories, rulings, settles, pulses, follow-ups, run closure);
start_self_run; the responsibilities, recent-runs and wear renderers;
render_input and render_tempo. carry reads the brakes and answers Dead or
NoOrgan; a start writes nothing and records no run. Kept per the map's keep
list for C3: Config (doctrine, image store and fetch fields cut with their
consumers), the brake read, the chat-addressing helpers, the tail renderer
and FileTrace; uncalled ones carry allow(dead_code) naming C3.

Night: sleep.rs is deleted. It was a Mind-writing session built on the
deleted prelude; C4 retargets its contract from history.
attachment.rs is deleted with the reply's save_attachment, its one caller.
chat_image's loader and recall.rs stay for C3 under allow(dead_code).

Heartbeat: no Mind writes. A wake is a plain unit start through the
Launcher (brake, then alive, then start); busy is the unit's own state.
Deleted the Self-run branch (claimable briefs), the self-ended wake, tempo
votes and declared urgency (standing_vote, pending_urgency, last_self_end)
and the run-based last_turn and last_sleep reads; HeartbeatState gains
last_turn_at and last_night_at (default slots, so a state written before
this cut still decodes). The beat is HEARTBEAT_BEAT_S, default 1800 s.
InstanceTrace.vote_beat_s stays as an always-none slot so heartbeat.cc's
older trace records still decode. HeartbeatView loses latest; the
timeline reads FileStore::latest.

tempo.rs: tally, fallback_beat and the PID controller and its sim are
deleted; pick and score stay, without self_permille.

Tests that pinned deleted behaviour are deleted with it; surviving ones are
kept, and two heartbeat tests pin the cut: a Mind with claimable briefs gets
a Persona wake and no Self run, and no poll admits anything to any mind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:06:11 +01:00
Meta Vens
609696f43e Park the divergence stream organ (C2, persona-only-divergence-parked)
Deletes stream.rs, its tests, the mind-stream binary and its integration
tests, and the dependencies only it used (ghostlight-persona-projection,
ureq, the model-connector daemon dev feature). The organ is kept at tag
parked/divergence-stream, whose note names the ruling's return condition.
A brake hold still stops mind-stream@ units a host has installed.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:26 +01:00
58a320c6ee Merge pull request 'Pin CultLib baf4ecf7 (cultcache-rs delete refuses like the put, #178)' (#73) from hands/cultlib-pin-baf4ecf7 into main 2026-11-19 21:00:05 +00:00
Meta Vens
0373175270 Pin CultLib baf4ecf7 (cultcache-rs delete refuses like the put, #178)
Huginn calls no CultCache::delete; the CacheBackingStore::delete impls are test fakes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 21:45:39 +01:00
917430ce99 Merge pull request 'Chat search: multi-room listing no longer advises a chunk-losing --after' (#71) from eureka/chat-listing-continuation into main 2026-11-17 03:46:25 +00:00
4b276dfebc Merge pull request 'admission: clippy 1.95.0 nonminimal_bool at admission.rs:674' (#72) from eureka/clippy-195-nonminimal-bool into main 2026-11-17 03:46:21 +00:00
556324017e ChatQuery docs: --after continues a listing within one room only
Soul found the wire comment (and the published schema carrying it) still told every
caller to narrow with the last hit's ts_end_ms + 1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 03:46:19 +00:00
c9a33f7ed5 admission: simplify the historic-ruling guard (clippy 1.95.0 nonminimal_bool)
The pinned 1.95.0 toolchain rejects the negated conjunction at admission.rs:674 under
-D warnings; the rewrite is its own suggestion and De Morgan-equal.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 03:33:34 +00:00
41fa789d6f chat search: a multi-room listing no longer advises an --after that loses chunks
A truncated listing printed --after <last.ts_end+1>. Listing is ordered by chunk
start and chunks of different rooms overlap in time, so the next page skipped any
chunk starting before that instant and ending before it. Inside one room chunks do
not overlap, so the advice stays; with several rooms (or none named) the CLI now
says to list one room at a time.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 03:33:32 +00:00
416e385c97 Clippy-clean huginn-daemon and mind-body under -D warnings (#70) 2026-11-17 02:22:30 +00:00
a424c1c4d5 huginn-sources: every run takes the lock (chat-off included) (#68) 2026-11-17 02:02:25 +00:00
2ca3105322 Clear all clippy -D warnings errors in huginn-mind (#69) 2026-11-17 01:58:12 +00:00
07942c1a83 Chat ingest job: huginn-sources chat flags, Matrix reader, lock, chat-purge (#67) 2026-11-17 01:52:38 +00:00
64e88966ad Merge pull request 'Pin CultLib 75188fde (stamp hardening #175)' (#66) from hands/cultlib-pin-75188fde into main 2026-11-14 09:35:41 +00:00
211cfe5e82 SwarmWriter::open refuses a store holding a record it does not read
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 09:35:31 +00:00
0c2d1e2cab ControlWriter::open refuses a store holding a record it does not read
The CultLib pin makes a pull carry unregistered records instead of refusing; the writer guards like the heartbeat store does.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 09:31:17 +00:00
477482b1a0 Pin CultLib 75188fde (stamp hardening #175; includes #171 #172 #174)
The workspace's one CultLib pin moves 8fc74c70 -> 75188fdefa0b4baf131dbfd94e77d06a965f0cc6
(cultcache-rs 0.2.0 -> 0.3.1, cultnet-rs 0.1.0 -> 0.3.0 in the lock; the lock drops
the crates the old revision alone needed and gains sha2/stacker for the new one).

Adaptations the new cultcache-rs forces:
- CacheBackingStore::push/push_all return the stamps written; the five test
  stores follow (store.rs, receipt.rs, read_tests.rs).
- A pull now carries a record no registered type claims instead of refusing it,
  so the heartbeat writer's open() checks foreign_records() and keeps its
  fail-closed refusal of an old initiative store.
- A cache refuses writes until it has pulled, and a zero-byte file is not a
  store: two test fixtures pull first / plant a real store.

Not deployed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 09:14:30 +00:00
db9605fbf2 Desk door: listing gate and account-id grammar at decode (PR B of cut-desk-feed-listing.r8; stacked on #62) (#63) 2026-11-14 02:15:20 +00:00
f09bc56e77 Chat: basis follow (conversation-following), counted by is_for (#65)
Wire string exactly `follow` (Bifrost #74); one constant FOLLOW_UP_BASIS; Soul pass at eeaaad9 PASS, finding fixed at c71be9d. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:24:20 +00:00
183 changed files with 26639 additions and 23249 deletions

279
Cargo.lock generated
View file

@ -37,17 +37,6 @@ dependencies = [
"subtle",
]
[[package]]
name = "ahash"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9"
dependencies = [
"getrandom 0.2.17",
"once_cell",
"version_check",
]
[[package]]
name = "ahash"
version = "0.8.12"
@ -195,12 +184,6 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.13.2"
@ -367,24 +350,6 @@ dependencies = [
"cipher",
]
[[package]]
name = "cultcache-rs"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=8fc74c709444b884a2bd339e0c306bf9484d99d2#8fc74c709444b884a2bd339e0c306bf9484d99d2"
dependencies = [
"anyhow",
"chrono",
"cultcache-rs-derive 0.1.0",
"fs2",
"redb",
"rmp-serde",
"serde",
"serde_bytes",
"serde_json",
"uuid",
"windows-sys 0.59.0",
]
[[package]]
name = "cultcache-rs"
version = "0.3.1"
@ -392,7 +357,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f111
dependencies = [
"anyhow",
"chrono",
"cultcache-rs-derive 0.2.0",
"cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
"fs2",
"redb",
"rmp-serde",
@ -406,13 +371,24 @@ dependencies = [
]
[[package]]
name = "cultcache-rs-derive"
version = "0.1.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=8fc74c709444b884a2bd339e0c306bf9484d99d2#8fc74c709444b884a2bd339e0c306bf9484d99d2"
name = "cultcache-rs"
version = "0.3.1"
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"anyhow",
"chrono",
"cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
"fs2",
"redb",
"rmp-serde",
"serde",
"serde_bytes",
"serde_json",
"serde_stacker",
"sha2",
"stacker",
"uuid",
"windows-sys 0.59.0",
]
[[package]]
@ -425,20 +401,29 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "cultcache-rs-derive"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "cultnet-rs"
version = "0.1.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=8fc74c709444b884a2bd339e0c306bf9484d99d2#8fc74c709444b884a2bd339e0c306bf9484d99d2"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
dependencies = [
"aes-gcm",
"anyhow",
"base64",
"chrono",
"cultcache-rs 0.2.0",
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
"ed25519-dalek",
"hmac",
"rand",
"reed-solomon-erasure",
"rmp-serde",
"rmpv",
"serde",
@ -453,16 +438,18 @@ dependencies = [
[[package]]
name = "cultnet-rs"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
version = "0.3.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
dependencies = [
"aes-gcm",
"anyhow",
"base64",
"chrono",
"cultcache-rs 0.3.1",
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
"ed25519-dalek",
"fs2",
"hmac",
"libc",
"rand",
"rmp-serde",
"rmpv",
@ -625,7 +612,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"cultcache-rs 0.2.0",
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
"rmp-serde",
"schemars",
"serde",
@ -639,7 +626,7 @@ dependencies = [
"anyhow",
"chrono",
"clap",
"cultnet-rs 0.1.0",
"cultnet-rs 0.3.0",
"huginn-daemon",
"huginn-mind",
"rmcp",
@ -874,15 +861,6 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
dependencies = [
"ahash 0.7.8",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@ -932,7 +910,7 @@ dependencies = [
"anyhow",
"base64",
"chrono",
"cultnet-rs 0.1.0",
"cultnet-rs 0.3.0",
"huginn-mind",
"rmp-serde",
"rustix",
@ -951,8 +929,8 @@ dependencies = [
"anyhow",
"base64",
"chrono",
"cultcache-rs 0.2.0",
"cultnet-rs 0.1.0",
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
"cultnet-rs 0.3.0",
"eureka-pipeline",
"jsonschema",
"rmp-serde",
@ -995,6 +973,16 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "inout"
version = "0.1.4"
@ -1004,15 +992,6 @@ dependencies = [
"generic-array",
]
[[package]]
name = "instant"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"
dependencies = [
"cfg-if",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@ -1042,7 +1021,7 @@ version = "0.58.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f622c574a29fb3034a0a90645afee194dfedc75fc124228801b6e77041075bd1"
dependencies = [
"ahash 0.8.12",
"ahash",
"bytecount",
"data-encoding",
"email_address",
@ -1079,7 +1058,7 @@ version = "0.58.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39b7670345e5ce87371339d13705dbb9276b7e3e934bbe1efa2c6734a1f65a96"
dependencies = [
"ahash 0.8.12",
"ahash",
"bytecount",
"fraction",
"getrandom 0.3.4",
@ -1095,12 +1074,6 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@ -1122,15 +1095,6 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lru"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999beba7b6e8345721bd280141ed958096a2e4abdf74f67ff4ce49b4b54e47a"
dependencies = [
"hashbrown 0.12.3",
]
[[package]]
name = "memchr"
version = "2.8.3"
@ -1150,8 +1114,8 @@ dependencies = [
"anyhow",
"base64",
"chrono",
"cultcache-rs 0.2.0",
"cultnet-rs 0.1.0",
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
"cultnet-rs 0.3.0",
"eureka-pipeline",
"eureka-state",
"ghostlight-persona-projection",
@ -1167,7 +1131,9 @@ dependencies = [
"sha2",
"syn 2.0.119",
"tempfile",
"toml",
"unicode-general-category",
"unicode-segmentation",
"ureq",
"uuid",
]
@ -1175,11 +1141,11 @@ dependencies = [
[[package]]
name = "model-connector"
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 = [
"aes-gcm",
"base64",
"cultcache-rs 0.3.1",
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
"cultnet-rs 0.2.0",
"rand_core 0.6.4",
"rmp-serde",
@ -1304,17 +1270,6 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
[[package]]
name = "parking_lot"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
dependencies = [
"instant",
"lock_api",
"parking_lot_core 0.8.6",
]
[[package]]
name = "parking_lot"
version = "0.12.5"
@ -1322,21 +1277,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core 0.9.12",
]
[[package]]
name = "parking_lot_core"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc"
dependencies = [
"cfg-if",
"instant",
"libc",
"redox_syscall 0.2.16",
"smallvec",
"winapi",
"parking_lot_core",
]
[[package]]
@ -1347,7 +1288,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall 0.5.18",
"redox_syscall",
"smallvec",
"windows-link",
]
@ -1488,35 +1429,13 @@ dependencies = [
"libc",
]
[[package]]
name = "redox_syscall"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
"bitflags 1.3.2",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "reed-solomon-erasure"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7263373d500d4d4f505d43a2a662d475a894aa94503a1ee28e9188b5f3960d4f"
dependencies = [
"libm",
"lru",
"parking_lot 0.11.2",
"smallvec",
"spin",
"bitflags",
]
[[package]]
@ -1545,13 +1464,13 @@ version = "0.58.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "558f3855529c0a7e78a48e409fa653456e55f1b167eab4109c16a255b7727e3f"
dependencies = [
"ahash 0.8.12",
"ahash",
"fluent-uri",
"getrandom 0.3.4",
"hashbrown 0.17.1",
"hashbrown",
"itoa",
"micromap",
"parking_lot 0.12.5",
"parking_lot",
"percent-encoding",
"serde_json",
]
@ -1664,7 +1583,7 @@ version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.13.2",
"bitflags",
"errno",
"libc",
"linux-raw-sys",
@ -1790,6 +1709,15 @@ dependencies = [
"serde_core",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_stacker"
version = "0.1.14"
@ -1875,12 +1803,6 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "spin"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
[[package]]
name = "spki"
version = "0.7.3"
@ -2034,6 +1956,45 @@ dependencies = [
"tokio",
]
[[package]]
name = "toml"
version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow 0.7.15",
]
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [
"winnow 1.0.5",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "tracing"
version = "0.1.44"
@ -2411,6 +2372,18 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]]
name = "wit-bindgen"
version = "0.57.1"

View file

@ -16,5 +16,5 @@ publish = false
# The one CultLib revision the workspace speaks. Every crate inherits these
# entries; a bump is a change to this table and nowhere else.
[workspace.dependencies]
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "8fc74c709444b884a2bd339e0c306bf9484d99d2", package = "cultcache-rs" }
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "8fc74c709444b884a2bd339e0c306bf9484d99d2", package = "cultnet-rs" }
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" }
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultnet-rs" }

View file

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

View file

@ -32,7 +32,8 @@ sample.research eureka-state:research:p1.scope epiphany.pipeline.research.v2 Epi
sample.idea eureka-state:idea:p1.i1 epiphany.pipeline.idea.v2 EpiphanyPipelineIdeaDocument 9189a863616d706169676eac657572656b612d7374617465a470617373a27031a56c6162656ca26931a57469746c65b24f6e65206e6f74652070657220636c61696da469646561d9204b65657020612070617373206173206d616e7920736d616c6c206e6f7465732ea974726164656f666673b74d6f726520646f63756d656e747320746f206c6973742ea872657374735f6f6e9182a46b696e64a85265736561726368a26964be657572656b612d73746174653a72657365617263683a70312e73636f7065a6746f776172649182a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131ab70726f706f7365645f6f6eaa323032362d30392d3135
sample.reply yggdrasil:reply:mind-2026-10-09-1-r1 epiphany.pipeline.reply.v2 EpiphanyPipelineReplyDocument 9185a8696e7374616e6365a979676764726173696ca56c6162656cb46d696e642d323032362d31302d30392d312d7231a372756e82a46b696e64a352756ea26964bf79676764726173696c3a72756e3a6d696e642d323032362d31302d30392d31a7616e73776572739182a46b696e64a8466f6c6c6f775570a26964d923657572656b612d73746174653a666f6c6c6f775f75703a61736b2d7468652d73656c66a474657874d93054686520736861646572207061737320697320646f6e653b2074686520736f756e647320617265204c6962627927732e
sample.thought yggdrasil:thought:t1793000000 epiphany.pipeline.thought.v2 EpiphanyPipelineThoughtDocument 91de0014a8696e7374616e6365a979676764726173696ca56c6162656cab7431373933303030303030a474657874d93d54686520736f756e647320617265204c6962627927733b2074686520736861646572732077657265206e6576657220746865206861726420706172742ea572656164739182a46b696e64a64d656d6f7279a26964d92879676764726173696c3a6d656d6f72793a323032362d31302d3331743034313230302d74302d6d30af706572736f6e615f72656365697074b06d696e642d636f6d6d69742d30613162a86964656e74697479be457572656b612c207368652f6865722c20706c61696e2d73706f6b656e2ea7636f6e74657874d92056616c7565733a20636f686572656e6365206f7665722076656c6f636974792ea87374696d756c7573bd4c696262792061736b65642061626f75742074686520736f756e64732eaf70726f6a6563746f725f6d6f64656cb070726f6a6563746f723a6c6174657374aa70726f6a656374696f6ed92949206b656570207475726e696e67206f7665722077686f20686f6c64732074686520736f756e64732eaa626173655f6d6f64656cab626173653a6c6174657374b474656d70657261747572655f7065726d696c6c65cd03e8ae6d696e5f705f7065726d696c6c6532aa6d61785f746f6b656e73cca0aa63616e6469646174657392d93d54686520736f756e647320617265204c6962627927733b2074686520736861646572732077657265206e6576657220746865206861726420706172742eaf41207365636f6e642064726966742eb06e6561726573745f7065726d696c6c6592cd0136cd0366a663686f73656e00ac70726f6a6563746f725f6d73cd1068ac636f6e74696e7565725f6d73cd238cae70726f6d70745f76657273696f6ebd67686f73746c696768743d633433656235343b20776f7264733d313830
sample.desk_answer eureka-state:desk_answer:Q1.n1 epiphany.pipeline.desk_answer.v2 EpiphanyPipelineDeskAnswerDocument 918ea863616d706169676eac657572656b612d7374617465a4666f726bb8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501ac6f7074696f6e735f68617368d94063636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363a663686f696365a161a46e6f7465b853686172652069742c207769746820746865206d61726b2eab616e7377657265645f6174b4323032362d31312d31305431353a30303a30305aab72656365697665645f6174b4323032362d31312d31305431353a30303a30335aaf636c61696d5f696e5f667574757265c2aa726571756573745f6964d92436663163306135322d336237652d346431612d396335382d306532643761346239663133ab626f64795f736861323536d94064646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a8616e737765726572a6757365722d37a9617574686f72697479a64d656d626572a76f7574636f6d6581a85265766973696f6e81a26f66be657572656b612d73746174653a6465736b5f616e737765723a51312e6e31
sample.desk_answer eureka-state:desk_answer:Q1.n1 epiphany.pipeline.desk_answer.v2 EpiphanyPipelineDeskAnswerDocument 918ea863616d706169676eac657572656b612d7374617465a4666f726bb8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501ac6f7074696f6e735f68617368d94063636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363a663686f696365a161a46e6f7465b853686172652069742c207769746820746865206d61726b2eab616e7377657265645f6174b4323032362d31312d31305431353a30303a30305aab72656365697665645f6174b4323032362d31312d31305431353a30303a30335aaf636c61696d5f696e5f667574757265c2aa726571756573745f6964d92436663163306135322d336237652d346431612d396335382d306532643761346239663133ab626f64795f736861323536d94064646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a8616e737765726572d92435663063326231652d386134642d346333622d396537662d316132623363346435653666a9617574686f72697479a64d656d626572a76f7574636f6d6581a85265766973696f6e81a26f66be657572656b612d73746174653a6465736b5f616e737765723a51312e6e31
sample.desk_listing eureka-state:desk_listing:Q1 epiphany.pipeline.desk_listing.v2 EpiphanyPipelineDeskListingDocument 9183a863616d706169676eac657572656b612d7374617465a66c6973746564b8657572656b612d73746174653a7175657374696f6e3a5131a6726561736f6ed9324d656d62657273206d617920726561642077687920746865204d696e64206c6973747320697473206f776e20666f726b732e
resolution.superseded eureka-state:resolution:question.Q1.n1 epiphany.pipeline.resolution.v2 EpiphanyPipelineResolutionDocument 9185a77375626a65637482a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501a76f7574636f6d6581aa5375706572736564656481a262799282a46b696e64a652756c696e67a26964b6657572656b612d73746174653a72756c696e673a523882a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a9726174696f6e616c65a852756c656420412eab7265736f6c7665645f6f6eaa323032362d30392d3135
resolution.fixed-by-none eureka-state:resolution:question.Q1.n1 epiphany.pipeline.resolution.v2 EpiphanyPipelineResolutionDocument 9185a77375626a65637482a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501a76f7574636f6d6581a5466978656482a6636f6d6d6974a83566393832323864a26279c0a9726174696f6e616c65a852756c656420412eab7265736f6c7665645f6f6eaa323032362d30392d3135
resolution.fixed-by-some eureka-state:resolution:question.Q1.n1 epiphany.pipeline.resolution.v2 EpiphanyPipelineResolutionDocument 9185a77375626a65637482a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501a76f7574636f6d6581a5466978656482a6636f6d6d6974a83566393832323864a2627982a46b696e64a94375745265706f7274a26964d921657572656b612d73746174653a6375745f7265706f72743a6375742d33612e6831a9726174696f6e616c65a852756c656420412eab7265736f6c7665645f6f6eaa323032362d30392d3135

View file

@ -316,6 +316,10 @@ bounded_text! {
Words = 4000, words_text;
/// A client's retry token: a lowercase D-format UUID.
RequestId = 36, uuid_text;
/// A Bifrost account id: a lowercase D-format UUID (`UserAccount.Id`). A Matrix id, an email or a
/// handle is never one.
#[schemars(extend("pattern" = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"))]
AccountId = 36, uuid_text;
/// A key label: `[A-Za-z0-9_-]{1,64}`.
Label = 64, label_text;
/// A campaign slug or key segment: label parts joined by `.`.
@ -885,8 +889,13 @@ value_types! {
pub struct PipelineDeskAnswer {
campaign: Slug, fork: Short, sequence: u32, options_hash: Sha256Hex, choice: Option<Short>, note: Option<Words>,
answered_at: Short, received_at: Short, claim_in_future: bool, request_id: RequestId, body_sha256: Sha256Hex,
answerer: Short, authority: DeskAuthority, outcome: DeskOutcome,
answerer: AccountId, authority: DeskAuthority, outcome: DeskOutcome,
}
/// A fork the Mind lists: members who are not on a call's decider list may read the question
/// while this document is in force (unlist = a `Withdrawn` resolution on it; relist = withdraw
/// that). One per question, keyed by the question's label; the receipt says who listed it and
/// when, `reason` why members may read it. Admitted on the Mind's own door only, never the desk's.
pub struct PipelineDeskListing { campaign: Slug, listed: Short, reason: Line }
pub struct PipelineVerdict { campaign: Slug, cut_report: Short, pass: u32, range: CommitRange, claims: Vec<VerdictClaim>[64] }
pub struct PipelineFinding {
campaign: Slug, verdict: Short, label: Label, range: CommitRange, confidence: FindingConfidence,
@ -1425,6 +1434,16 @@ pipeline_kinds! {
"epiphany.pipeline.thought.v2", "EpiphanyPipelineThoughtDocument";
DeskAnswer(PipelineDeskAnswer) => EpiphanyPipelineDeskAnswerDocument, "desk_answer",
"epiphany.pipeline.desk_answer.v2", "EpiphanyPipelineDeskAnswerDocument";
DeskListing(PipelineDeskListing) => EpiphanyPipelineDeskListingDocument, "desk_listing",
"epiphany.pipeline.desk_listing.v2", "EpiphanyPipelineDeskListingDocument";
}
impl AccountId {
/// Whether this is a lowercase D-format UUID. For the callers outside the crate, which have no way
/// to reach `Bounded`; on the pattern of `Slug::validate_slug`.
pub fn validate_account(&self) -> Result<(), PipelineRefusal> {
self.validate("account")
}
}
/// Parses a full document id: the grammar read backwards. A key and an id are
@ -1516,7 +1535,7 @@ const SUBJECT_LOCAL_MAX: usize = 64;
/// The longest kind name a resolution can name as its subject (`stewardship`),
/// checked against `PipelineKind::ALL` by a test.
const LONGEST_KIND_NAME: usize = "stewardship".len();
const LONGEST_KIND_NAME: usize = "desk_listing".len();
/// A `.n<sequence>` part at `u32::MAX`.
const SEQUENCE_PART_MAX: usize = ".n".len() + "4294967295".len();
@ -1651,6 +1670,10 @@ pub fn pipeline_key(document: &PipelineDocument) -> Result<String, PipelineRefus
let sequence = format!("n{}", value.sequence);
(campaign_field.as_str(), value.campaign.0.as_str(), local(&key_field, document_kind, &[label, &sequence])?)
}
D::DeskListing(value) => {
let label = parent_local("desk_listing.listed", &value.listed.0, &value.campaign.0, PipelineKind::Question)?;
(campaign_field.as_str(), value.campaign.0.as_str(), local(&key_field, document_kind, &[label])?)
}
D::Verdict(value) => {
let report = parent_local("verdict.cut_report", &value.cut_report.0, &value.campaign.0, PipelineKind::CutReport)?;
let cut = parent_cut("verdict.cut_report", report, 'h')?;
@ -1927,9 +1950,12 @@ mod tests {
campaign: slug(CAMPAIGN), fork: id("question", "Q1"), sequence: 1, options_hash: Sha256Hex("c".repeat(64)),
choice: Some(s("a")), note: Some("Share it, with the mark.".into()), answered_at: s("2026-11-10T15:00:00Z"),
received_at: s("2026-11-10T15:00:03Z"), claim_in_future: false, request_id: RequestId("6f1c0a52-3b7e-4d1a-9c58-0e2d7a4b9f13".into()), body_sha256: Sha256Hex("d".repeat(64)),
answerer: s("user-7"), authority: DeskAuthority::Member,
answerer: AccountId("5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6f".into()), authority: DeskAuthority::Member,
outcome: DeskOutcome::Revision { of: id("desk_answer", "Q1.n1") },
}), format!("{CAMPAIGN}:desk_answer:Q1.n1")),
(D::DeskListing(PipelineDeskListing {
campaign: slug(CAMPAIGN), listed: id("question", "Q1"), reason: "Members may read why the Mind lists its own forks.".into(),
}), format!("{CAMPAIGN}:desk_listing:Q1")),
]
}
@ -3587,7 +3613,7 @@ mod tests {
);
}
assert_eq!(widest, RESOLUTION_LOCAL_MAX, "the bound is exactly the widest depth-two chain");
assert_eq!(RESOLUTION_LOCAL_MAX, 111);
assert_eq!(RESOLUTION_LOCAL_MAX, 112);
}
#[test]
@ -4109,7 +4135,7 @@ mod tests {
};
let document_schema = serde_json::to_value(schemars::schema_for!(PipelineDocument))?;
let variants = document_schema["oneOf"].as_array().expect("the document schema is a oneOf");
assert_eq!(PipelineKind::ALL.len(), 21, "twenty-one kinds");
assert_eq!(PipelineKind::ALL.len(), 22, "twenty-two kinds");
assert_eq!(
variants.iter().map(tag).collect::<Vec<_>>(),
PipelineKind::ALL.iter().map(|kind| kind.name().to_owned()).collect::<Vec<_>>(),
@ -4639,7 +4665,7 @@ mod tests {
}
fn desk_answer_sample() -> PipelineDeskAnswer {
let PipelineDocument::DeskAnswer(answer) = samples().pop().unwrap().0 else { unreachable!() };
let PipelineDocument::DeskAnswer(answer) = samples().remove(20).0 else { unreachable!() };
answer
}

View file

@ -536,6 +536,7 @@ fn chat_search(
json: bool,
) -> Result<u8, Trouble> {
let now = chrono::Utc::now();
let one_room = rooms.len() == 1;
let query = ChatQuery {
texts: texts.into_iter().map(Line).collect(),
rooms: rooms.into_iter().map(Short).collect(),
@ -548,7 +549,7 @@ fn chat_search(
if json {
say(serde_json::to_string_pretty(&found).map_err(|error| Trouble::Internal(error.to_string()))?);
} else {
say(render::chat_hits(&found));
say(render::chat_hits(&found, one_room));
}
Ok(0)
}

View file

@ -152,8 +152,11 @@ pub fn source_hits(found: &SourceHits) -> String {
/// when there are some), then one `time sender event_id body` line per message,
/// the body as the room held it with line breaks written `\n`: quoted data
/// under our header, never a message framed as if sent to the reader. A blank line between hits; a
/// truncated listing ends with the `--after` that continues it.
pub fn chat_hits(found: &ChatHits) -> String {
/// truncated listing of one room ends with the `--after` that continues it. A
/// listing of several rooms (`one_room` false) cannot be continued by an instant,
/// because chunks of different rooms overlap in time and a later start can hold an
/// earlier end; it says to page one room at a time.
pub fn chat_hits(found: &ChatHits, one_room: bool) -> String {
let mut out: Vec<String> = found
.hits
.iter()
@ -173,10 +176,11 @@ pub fn chat_hits(found: &ChatHits) -> String {
text
})
.collect();
if found.truncated
&& let Some(last) = found.hits.last()
{
out.push(format!("truncated: more follow, continue with --after {}\n", crate::chat::shown(last.ts_end_ms + 1)));
if found.truncated {
match found.hits.last() {
Some(last) if one_room => out.push(format!("truncated: more follow, continue with --after {}\n", crate::chat::shown(last.ts_end_ms + 1))),
_ => out.push("truncated: more follow; --after cannot continue a listing of several rooms, list one --room at a time\n".to_string()),
}
}
out.join("\n")
}

View file

@ -20,7 +20,7 @@ macro_rules! kinds {
kinds!(
campaign, target, question, ruling, cut_spec, cut_report, verdict, finding, follow_up, resolution, instance, stewardship,
hand_off, run, pulse, memory, research, idea, reply, thought, desk_answer,
hand_off, run, pulse, memory, research, idea, reply, thought, desk_answer, desk_listing,
);
/// The schema named, or the names when none is: the exit code is 2 for a name

View file

@ -1145,12 +1145,12 @@ fn schema_prints_the_published_files() {
let names = run(&[], &["schema"], None);
assert_eq!(names.code, 0);
let names: Vec<&str> = names.out.lines().collect();
assert_eq!(names.len(), 22, "{names:?}");
assert_eq!(names.len(), 23, "{names:?}");
assert_eq!(names[0], "campaign");
assert_eq!(names[14], "pulse");
assert_eq!(names[15], "memory");
assert_eq!((names[16], names[17]), ("research", "idea"));
assert_eq!((names[18], names[19], names[20], names[21]), ("reply", "thought", "desk_answer", "selection"));
assert_eq!((names[18], names[19], names[20], names[21], names[22]), ("reply", "thought", "desk_answer", "desk_listing", "selection"));
for kind in PipelineKind::ALL {
assert!(names.contains(&kind.name()), "{}", kind.name());
}
@ -2998,6 +2998,26 @@ fn chat_search_prints_cited_messages_and_sends_its_selectors() {
let rooms: Vec<&str> = query.rooms.iter().map(|room| room.0.as_str()).collect();
assert_eq!((texts, rooms, query.after_ms, query.before_ms, query.top_k), (vec!["a", "b"], vec!["!x:y", "#z:y"], Some(1_700_000_000_000), Some(1_700_000_060_000), 3));
// A truncated listing is continued by `--after` only inside one room; across rooms the spans overlap and an instant loses chunks.
let hit = |end| huginn_mind::ChatHit {
room_id: "!r:y".into(),
room_alias: None,
first_event_id: "$a".into(),
last_event_id: "$b".into(),
ts_start_ms: 1_700_000_000_000,
ts_end_ms: end,
score: None,
messages: vec![],
};
let cut_short = HuginnMindResponse::Chat(huginn_mind::ChatHits { indexed_under: huginn_mind::SourceModel { name: "m".into(), digest: "d".into() }, truncated: true, hits: vec![hit(1_700_000_060_000)] });
let (listing, _) = replying("search_chat", cut_short);
let one = at(listing.addr, &["chat", "search", "--room", "!r:y"], None);
assert!(one.out.contains("continue with --after 2023-11-14T22:14:20.001Z"), "{}", one.out);
for rooms in [&["chat", "search"][..], &["chat", "search", "--room", "!r:y", "--room", "!s:y"]] {
let many = at(listing.addr, rooms, None);
assert!(many.out.contains("--after cannot continue a listing of several rooms") && !many.out.contains("continue with --after"), "{rooms:?}: {}", many.out);
}
assert_ne!(at(spy.addr, &["chat", "search", "--after", "yesterday"], None).code, 0);
assert!(seen.lock().unwrap().is_empty(), "a bad instant never left the CLI");
for bad in [&["chat", "search", "--room", "swarm"][..], &["chat", "search", "--top-k", "0"]] {

View file

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

View file

@ -18,7 +18,7 @@ name = "huginn-daemon"
path = "src/main.rs"
# The source index's one writer: a oneshot job that brings `huginn_sources` to
# the forge's current state and exits. No daemon calls any of its writes.
# the forge's and the chat reader's current state and exits. No daemon calls any of its writes.
[[bin]]
name = "huginn-sources"
path = "src/bin/huginn-sources.rs"
@ -34,7 +34,8 @@ rmp-serde = "1"
rustix = { version = "1", default-features = false, features = ["std", "net"] }
serde = { version = "1", features = ["derive"] }
# The vector store's and the embedder's HTTP APIs are the xenos boundary, and
# JSON exists in `index/ollama.rs` and `index/qdrant.rs` only. `ureq` 3 with
# JSON exists in `index/ollama.rs`, `index/qdrant.rs`, `sources/forge.rs` and
# `sources/matrix.rs` only. `ureq` 3 with
# default features off is plain HTTP with no TLS (`rustls` and `gzip` are its
# only defaults), which is all the private mesh needs. It stays below 3.4,
# whose `base64` 0.23 would put a second `base64` in a tree that has one.

View file

@ -1,21 +1,38 @@
//! The source index's refresh job: one run brings the `huginn_sources`
//! collection to the forge's current state, journals one line per repo, and
//! exits nonzero if any repo failed or the collection could not be used.
//! The source index's refresh job: one run brings the forge corpus and, when
//! configured, the rooms the chat reader has joined (minus the estate and DM
//! exclusion) to current state, journals one line per repo and room, and exits
//! nonzero if either failed or the collection could not be used. The
//! `chat-purge` subcommand writes a steward's purge tombstone and nothing else.
//!
//! Exit status: 0 clean, 1 a run failed, 2 bad arguments, 3 another run (or a
//! purge) holds the lock, which every run and every purge takes. The Matrix
//! token is read from a file (a systemd credential), never from the environment or argv.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{File, OpenOptions, TryLockError};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
use huginn_daemon::index::ollama::pool;
use huginn_daemon::index::qdrant::QdrantIndex;
use huginn_daemon::sources::forge::HttpForge;
use huginn_daemon::sources::refresh;
use huginn_daemon::sources::job::{self, Chat, Purge};
use huginn_daemon::sources::matrix::HttpMatrix;
use huginn_daemon::sources::room_scope::{ESTATE_ALIASES, Estate};
/// Where the forge answers when the flag is absent: the loopback address of the
/// forge on the host that runs this job.
const DEFAULT_FORGE_URL: &str = "http://127.0.0.1:3310";
/// The chat flags, which come all together or not at all.
struct ChatOptions {
matrix_url: String,
token: String,
estate: Estate,
}
struct Options {
state_root: PathBuf,
qdrant_url: String,
@ -25,75 +42,335 @@ struct Options {
reserve_urls: Vec<String>,
embedding_model: String,
forge_url: String,
chat: Option<ChatOptions>,
/// Every run takes it: the cursors object is replaced whole, with or without chat.
lock_file: PathBuf,
}
fn parse(args: impl Iterator<Item = String>) -> Result<Options> {
enum Command {
Run(Options),
Purge { qdrant_url: String, lock_file: PathBuf, purge: Purge },
}
/// How a run ends other than by finishing.
enum Stop {
Usage(anyhow::Error),
Locked,
}
/// The single-valued options and the repeated ones, by name.
type Collected = (BTreeMap<String, String>, BTreeMap<String, Vec<String>>);
/// The options named, each once, except those in `repeated`, which keep every value.
fn collect(args: impl Iterator<Item = String>, once: &[&str], repeated: &[&str]) -> Result<Collected> {
let mut args = args;
let mut values: BTreeMap<String, String> = BTreeMap::new();
let mut ollama_urls = Vec::new();
let mut reserve_urls = Vec::new();
let mut singles = BTreeMap::new();
let mut many: BTreeMap<String, Vec<String>> = BTreeMap::new();
while let Some(name) = args.next() {
let name = name.strip_prefix("--").with_context(|| format!("expected --option, got {name:?}"))?;
ensure!(
matches!(name, "state-root" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url"),
"unsupported huginn-sources option --{name}"
);
ensure!(once.contains(&name) || repeated.contains(&name), "unsupported huginn-sources option --{name}");
let value = args.next().with_context(|| format!("missing value for --{name}"))?;
if name == "ollama-url" || name == "reserve-ollama-url" {
ensure!(value.starts_with("http://"), "--{name} must be a plain http:// address, got {value:?}");
if name == "ollama-url" { ollama_urls.push(value) } else { reserve_urls.push(value) }
if repeated.contains(&name) {
many.entry(name.to_owned()).or_default().push(value);
} else {
ensure!(values.insert(name.to_owned(), value).is_none(), "duplicate option --{name}");
ensure!(singles.insert(name.to_owned(), value).is_none(), "duplicate option --{name}");
}
}
let take = |name: &str| values.get(name).cloned().with_context(|| format!("--{name} is required"));
let url = |name: &str, value: String| {
ensure!(value.starts_with("http://"), "--{name} must be a plain http:// address, got {value:?}");
Ok(value)
};
let state_root = PathBuf::from(take("state-root")?);
ensure!(state_root.is_absolute(), "--state-root must be an absolute path");
let embedding_model = take("embedding-model")?;
ensure!(!embedding_model.is_empty(), "--embedding-model must name a model");
Ok(Options {
state_root,
qdrant_url: url("qdrant-url", take("qdrant-url")?)?,
ollama_urls: {
ensure!(!ollama_urls.is_empty(), "at least one --ollama-url is required; repeat it for each GPU host");
ollama_urls
Ok((singles, many))
}
fn http(name: &str, value: String) -> Result<String> {
ensure!(value.starts_with("http://"), "--{name} must be a plain http:// address, got {value:?}");
Ok(value)
}
/// The Matrix reader's bearer travels in clear, and this build speaks no TLS: only a loopback host may be named.
fn loopback_http(name: &str, value: String) -> Result<String> {
let value = http(name, value)?;
let authority = value["http://".len()..].split(['/', '?', '#']).next().unwrap_or("");
let host = match authority.strip_prefix('[') {
// The bracket must end the authority or be followed by the port, so `[::1].evil.example` names no loopback.
Some(inner) => match inner.split_once(']') {
Some((host, "")) => host,
Some((host, port)) if port.starts_with(':') => host,
_ => "",
},
None => authority.split(':').next().unwrap_or(""),
};
let loopback = !authority.contains('@') && (host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback()));
ensure!(loopback, "--{name} must name a loopback host (localhost, 127.0.0.0/8 or [::1]): the bearer token travels in clear and this build has no TLS, got {value:?}");
Ok(value)
}
fn absolute(name: &str, value: &str) -> Result<PathBuf> {
let path = PathBuf::from(value);
ensure!(path.is_absolute(), "--{name} must be an absolute path");
Ok(path)
}
fn chat_options(singles: &BTreeMap<String, String>, excluded: Vec<String>) -> Result<Option<ChatOptions>> {
let given = [singles.contains_key("matrix-url"), singles.contains_key("matrix-token-file"), !excluded.is_empty()];
if !given.contains(&true) {
return Ok(None);
}
for (present, name) in given.iter().zip(["matrix-url", "matrix-token-file", "chat-exclude-room"]) {
ensure!(*present, "--{name} is missing: the chat flags (--matrix-url, --matrix-token-file, --chat-exclude-room) come all together or not at all");
}
let ids: BTreeSet<String> = excluded.iter().cloned().collect();
ensure!(ids.len() == excluded.len(), "--chat-exclude-room must not repeat a room id");
ensure!(ids.len() == ESTATE_ALIASES.len(), "--chat-exclude-room must be given exactly {} times (the ids of {})", ESTATE_ALIASES.len(), ESTATE_ALIASES.join(", "));
ensure!(ids.iter().all(|id| id.starts_with('!')), "--chat-exclude-room takes room ids beginning with !, not aliases");
let path = absolute("matrix-token-file", &singles["matrix-token-file"])?;
let token = std::fs::read_to_string(&path).with_context(|| format!("reading --matrix-token-file {}", path.display()))?.trim().to_owned();
ensure!(!token.is_empty(), "--matrix-token-file {} is empty", path.display());
Ok(Some(ChatOptions { matrix_url: loopback_http("matrix-url", singles["matrix-url"].clone())?, token, estate: Estate::new(ids)? }))
}
fn parse(mut args: impl Iterator<Item = String>, now: DateTime<Utc>) -> Result<Command> {
let mut rest: Vec<String> = Vec::new();
let first = args.next();
if first.as_deref() == Some("chat-purge") {
let (singles, _) = collect(args, &["qdrant-url", "room", "from", "to", "request", "lock-file"], &[])?;
let take = |name: &str| singles.get(name).cloned().with_context(|| format!("--{name} is required"));
return Ok(Command::Purge {
qdrant_url: http("qdrant-url", take("qdrant-url")?)?,
lock_file: absolute("lock-file", &take("lock-file")?)?,
purge: Purge::check(&take("room")?, &take("from")?, &take("to")?, &take("request")?, now)?,
});
}
rest.extend(first);
let (mut singles, mut many) = collect(
rest.into_iter().chain(args),
&["state-root", "qdrant-url", "embedding-model", "forge-url", "matrix-url", "matrix-token-file", "lock-file"],
&["ollama-url", "reserve-ollama-url", "chat-exclude-room"],
)?;
let mut hosts = |name: &str| -> Result<Vec<String>> { many.remove(name).unwrap_or_default().into_iter().map(|url| http(name, url)).collect() };
let ollama_urls = hosts("ollama-url")?;
let reserve_urls = hosts("reserve-ollama-url")?;
let excluded = many.remove("chat-exclude-room").unwrap_or_default();
let take = |singles: &mut BTreeMap<String, String>, name: &str| singles.remove(name).with_context(|| format!("--{name} is required"));
let state_root = absolute("state-root", &take(&mut singles, "state-root")?)?;
let embedding_model = take(&mut singles, "embedding-model")?;
ensure!(!embedding_model.is_empty(), "--embedding-model must name a model");
ensure!(!ollama_urls.is_empty(), "at least one --ollama-url is required; repeat it for each GPU host");
let chat = chat_options(&singles, excluded)?;
let lock_file = absolute("lock-file", &take(&mut singles, "lock-file")?)?;
Ok(Command::Run(Options {
state_root,
qdrant_url: http("qdrant-url", take(&mut singles, "qdrant-url")?)?,
ollama_urls,
reserve_urls,
embedding_model,
forge_url: url("forge-url", values.get("forge-url").cloned().unwrap_or_else(|| DEFAULT_FORGE_URL.to_owned()))?,
})
forge_url: http("forge-url", singles.remove("forge-url").unwrap_or_else(|| DEFAULT_FORGE_URL.to_owned()))?,
chat,
lock_file,
}))
}
/// Takes the job's lock for the life of the returned file. A held lock means a run (or a
/// purge request) is in progress and nothing may change: the cursors object is replaced whole.
fn take_lock(path: &Path) -> Result<File, Stop> {
let file = OpenOptions::new().create(true).truncate(false).write(true).open(path).with_context(|| format!("opening --lock-file {}", path.display())).map_err(Stop::Usage)?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(Stop::Locked),
Err(TryLockError::Error(error)) => Err(Stop::Usage(anyhow::Error::new(error).context(format!("locking --lock-file {}", path.display())))),
}
}
fn execute(command: Command) -> Result<u8, Stop> {
match command {
Command::Purge { qdrant_url, lock_file, purge } => {
let _lock = take_lock(&lock_file)?;
let mut index = QdrantIndex::new(&qdrant_url);
Ok(match job::purge(&mut index, &purge) {
Ok(line) => {
println!("{line}");
0
}
Err(error) => {
eprintln!("huginn-sources: {error:#}");
1
}
})
}
Command::Run(options) => {
let _lock = take_lock(&options.lock_file)?;
let mut embedder = pool(&options.ollama_urls, &options.reserve_urls, &options.embedding_model);
let mut index = QdrantIndex::new(&options.qdrant_url);
let mut forge = HttpForge::new(&options.forge_url);
let mut matrix = options.chat.as_ref().map(|chat| HttpMatrix::new(&chat.matrix_url, &chat.token));
let chat = matrix.as_mut().zip(options.chat.as_ref()).map(|(history, chat)| Chat { history, estate: &chat.estate });
Ok(job::run(&mut embedder, &mut index, &mut forge, &options.state_root, chat, &mut |line| println!("{line}"), &mut |line| eprintln!("{line}")))
}
}
}
fn main() -> ExitCode {
let options = match parse(std::env::args().skip(1)) {
Ok(options) => options,
Err(error) => {
match parse(std::env::args().skip(1), Utc::now()).map_err(Stop::Usage).and_then(execute) {
Ok(status) => ExitCode::from(status),
Err(Stop::Usage(error)) => {
eprintln!("huginn-sources: {error:#}");
return ExitCode::from(2);
ExitCode::from(2)
}
};
let mut embedder = pool(&options.ollama_urls, &options.reserve_urls, &options.embedding_model);
let mut index = QdrantIndex::new(&options.qdrant_url);
let mut forge = HttpForge::new(&options.forge_url);
let mut journal = |report: &huginn_daemon::sources::Report| println!("{report}");
match refresh(&mut embedder, &mut index, &mut forge, &options.state_root, &mut journal) {
Ok(refreshed) if refreshed.is_clean() => ExitCode::SUCCESS,
Ok(refreshed) => {
if !refreshed.failed.is_empty() {
eprintln!("huginn-sources: {} repos failed: {}", refreshed.failed.len(), refreshed.failed.join(", "));
}
if let Some(why) = &refreshed.retirement_withheld {
eprintln!("huginn-sources: no repo was retired: {why}");
}
ExitCode::from(1)
}
Err(error) => {
eprintln!("huginn-sources: {error:#}");
ExitCode::from(1)
Err(Stop::Locked) => {
eprintln!("huginn-sources: huginn-sources is running");
ExitCode::from(3)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const NOW: &str = "2026-11-17T00:00:00Z";
fn args(text: &str) -> impl Iterator<Item = String> {
text.split_whitespace().map(str::to_owned).collect::<Vec<_>>().into_iter()
}
fn now() -> DateTime<Utc> {
DateTime::parse_from_rfc3339(NOW).unwrap().with_timezone(&Utc)
}
fn error(text: &str) -> String {
match parse(args(text), now()) {
Ok(_) => panic!("parsed: {text}"),
Err(error) => format!("{error:#}"),
}
}
const BASE: &str = "--state-root /s --qdrant-url http://q --ollama-url http://o --embedding-model m";
const IDS: &str = "--chat-exclude-room !a:s --chat-exclude-room !b:s --chat-exclude-room !c:s";
fn with_token(secret: &str) -> (tempfile::TempDir, String) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("token");
std::fs::write(&path, secret).unwrap();
let path = path.display().to_string();
(dir, path)
}
#[test]
fn chat_flags_come_all_or_none() {
let (_dir, token) = with_token(" sekret-token\n");
let lock = "--lock-file /l";
let base = format!("{BASE} {lock}");
let full = format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} {IDS} {lock}");
let Ok(Command::Run(options)) = parse(args(&full), now()) else { panic!("full chat flags must parse") };
assert_eq!(options.chat.as_ref().unwrap().token, "sekret-token", "trimmed");
assert!(matches!(parse(args(&base), now()), Ok(Command::Run(Options { chat: None, .. }))));
assert!(error(BASE).contains("--lock-file is required"), "a chat-off run needs the lock too");
assert!(error(&format!("{base} --matrix-url http://localhost")).contains("--matrix-token-file is missing"));
assert!(error(&format!("{base} --matrix-token-file {token} {IDS}")).contains("--matrix-url is missing"));
assert!(error(&format!("{base} --matrix-url http://localhost --matrix-token-file {token}")).contains("--chat-exclude-room is missing"));
assert!(error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} {IDS}")).contains("--lock-file is required"));
}
#[test]
fn chat_flag_values_are_checked_and_never_print_the_token() {
let (_dir, token) = with_token("sekret-token");
let on = |extra: &str| format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} --lock-file /l {extra}");
assert!(error(&on("--chat-exclude-room !a:s --chat-exclude-room !b:s")).contains("exactly 3"));
assert!(error(&on(&format!("{IDS} --chat-exclude-room !d:s"))).contains("exactly 3"));
assert!(error(&on("--chat-exclude-room !a:s --chat-exclude-room !a:s --chat-exclude-room !b:s")).contains("repeat"));
assert!(error(&on("--chat-exclude-room !a:s --chat-exclude-room !b:s --chat-exclude-room #c:s")).contains("beginning with !"));
assert!(error(&format!("{BASE} --matrix-url https://m --matrix-token-file {token} --lock-file /l {IDS}")).contains("plain http://"));
assert!(error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file rel --lock-file /l {IDS}")).contains("absolute"));
assert!(error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} --lock-file rel {IDS}")).contains("absolute"));
let (_empty, empty) = with_token(" \n");
let message = error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {empty} --lock-file /l {IDS}"));
assert!(message.contains(&empty) && message.contains("empty"));
let missing = error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file /nowhere/t --lock-file /l {IDS}"));
assert!(missing.contains("/nowhere/t"));
for text in [on(IDS), on("--chat-exclude-room !a:s")] {
assert!(!error(&format!("{text} --nope x")).contains("sekret-token"));
}
let dead = ["--chat", "room"].join("-");
assert!(error(&format!("{BASE} {dead} !x:s")).contains(&format!("unsupported huginn-sources option {dead}")));
}
fn purge(extra: &str) -> String {
error(&format!("chat-purge --qdrant-url http://q --lock-file /l {extra}"))
}
#[test]
fn chat_purge_arguments() {
let good = "--room !r:s --from 2026-11-10T00:00:00Z --to 2026-11-11T00:00:00Z --request ref-1";
let Ok(Command::Purge { purge: asked, .. }) = parse(args(&format!("chat-purge --qdrant-url http://q --lock-file /l {good}")), now()) else { panic!() };
assert_eq!((asked.window.from_ms, asked.window.to_ms), (1_794_268_800_000, 1_794_355_200_000));
let bad = |from: &str, to: &str, room: &str, request: &str| purge(&format!("--room {room} --from {from} --to {to} --request {request}"));
let (f, t) = ("2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z");
assert!(bad(f, t, "#a:s", "r").contains("--room"));
assert!(bad("2026-11-10T00:00:00+00:00", t, "!r:s", "r").contains("--from"));
assert!(bad(f, "2026-11-11T00:00:00", "!r:s", "r").contains("--to"));
assert!(bad(t, f, "!r:s", "r").contains("before"));
assert!(bad(f, "2026-11-18T00:00:00Z", "!r:s", "r").contains("after now"));
assert!(bad("2025-11-09T00:00:00Z", t, "!r:s", "r").contains("366"));
assert!(purge(&format!("--room !r:s --from {f} --to {t} --request {}", "x".repeat(121))).contains("--request"));
assert!(purge("--room !r:s --from 2026-11-10T00:00:00Z --to 2026-11-11T00:00:00Z").contains("--request is required"));
assert!(parse(args(&format!("chat-purge --qdrant-url http://q --lock-file /l {good} --matrix-url http://localhost")), now()).is_err(), "no Matrix flags");
}
#[test]
fn matrix_url_must_be_loopback_http() {
let (_dir, token) = with_token("sekret-token");
let with = |url: &str| format!("{BASE} --matrix-url {url} --matrix-token-file {token} --lock-file /l {IDS}");
for good in ["http://localhost", "http://127.0.0.1:8008", "http://127.9.9.9/", "http://[::1]:8008", "http://LOCALHOST:1/x"] {
assert!(parse(args(&with(good)), now()).is_ok(), "{good}");
}
for bad in ["http://matrix.example", "http://10.0.0.5:8008", "http://localhost@evil.example", "http://127.0.0.1.evil.example", "http://localhost.evil.example", "http://[::2]", "https://localhost", "http://127.0.0.1:pw@evil.example", "http://[::1].evil.example", "http://[::1]x"] {
assert!(error(&with(bad)).contains("--matrix-url"), "{bad}");
}
}
#[test]
fn a_held_lock_exits_3_through_execute_for_both_modes() {
let dir = tempfile::tempdir().unwrap();
let lock = dir.path().join("lock");
let held = take_lock(&lock).ok().unwrap();
let lock = lock.display().to_string();
let good = "--room !r:s --from 2026-11-10T00:00:00Z --to 2026-11-11T00:00:00Z --request r";
let purge = parse(args(&format!("chat-purge --qdrant-url http://127.0.0.1:1 --lock-file {lock} {good}")), now()).unwrap();
assert!(matches!(execute(purge), Err(Stop::Locked)));
let (_t, token) = with_token("sekret-token");
let run = parse(args(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} {IDS} --lock-file {lock}")), now()).unwrap();
assert!(matches!(execute(run), Err(Stop::Locked)));
let off = parse(args(&format!("{BASE} --lock-file {lock}")), now()).unwrap();
assert!(matches!(execute(off), Err(Stop::Locked)), "a chat-off run must not write cursors under a held lock");
drop(held);
}
#[test]
fn the_lock_is_held_for_the_whole_run() {
let dir = tempfile::tempdir().unwrap();
let lock = dir.path().join("lock");
// A qdrant that accepts the run's first request and says nothing: the run is mid-flight while we probe the lock.
let qdrant = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", qdrant.local_addr().unwrap());
let run = parse(args(&format!("--state-root /s --qdrant-url {url} --ollama-url http://127.0.0.1:1 --embedding-model m --lock-file {}", lock.display())), now()).unwrap();
let worker = std::thread::spawn(move || execute(run));
let (connection, _) = qdrant.accept().unwrap();
assert!(matches!(take_lock(&lock), Err(Stop::Locked)), "the run must hold the lock while it works");
drop(connection);
// Refuse any retry the same way until the run gives up.
qdrant.set_nonblocking(true).unwrap();
while !worker.is_finished() {
drop(qdrant.accept());
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(worker.join().unwrap().is_ok());
assert!(take_lock(&lock).is_ok(), "the lock is released when the run ends");
}
#[test]
fn a_held_lock_stops_the_run_untouched() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
let held = take_lock(&path).ok().unwrap();
assert!(matches!(take_lock(&path), Err(Stop::Locked)));
drop(held);
assert!(take_lock(&path).is_ok());
}
}

View file

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

View file

@ -20,6 +20,13 @@
//! gets `deciders` empty, `answerer` nil and the counts instead. The reads carry no `authority` (a
//! payload that names one is refused whole), and the door has no other way to ask who is reading.
//!
//! The listing gate: a reader who is not a decider sees a fork only while a `desk_listing` for it is
//! in force, and a fork it may not see reads `fork_unknown`, the same bytes as a missing one, on
//! every desk operation, a replay of a stored answer included. The door never writes a listing; it
//! arrives by the RUDP Admit door only. Unlisting is a `Withdrawn` resolution on the listing, and
//! admitting the listing again after that returns `AlreadyAdmitted` and the fork stays hidden:
//! relisting is withdrawing the withdrawal, not a second admission.
//!
//! It owns no rule. Which Mind method answers is `Daemon::handle_desk`'s; when the door is
//! served is `serve::run`'s, once per pass in the thread that owns the Mind. A peer that is
//! slow costs the loop at most `DESK_ACCEPTS_PER_PASS` connections of `DESK_CONNECTION_DEADLINE`

View file

@ -20,7 +20,7 @@ use cultnet_rs::{
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, encode_frame,
};
use huginn_mind::desk_wire::{
DESK_MAX_RESPONSE_BYTES, DESK_REQUEST_SCHEMA, DESK_SERVICE_ID, DeskRequest, DeskResponse, ForkAnswer, ForkAnswerCode, ForkAnswerRequest, ForkCursor,
DESK_REQUEST_SCHEMA, DESK_SERVICE_ID, DeskRequest, DeskResponse, ForkAnswer, ForkAnswerCode, ForkAnswerRequest, ForkCursor,
ForkEntry, ForkLimit, ForkList, ListStatus, RequestSchema,
};
use huginn_mind::envelope::{OperationFailure, decode_desk_response, decode_response, encode_desk_request, encode_request};
@ -85,20 +85,26 @@ fn wire(hash: &str, request_id: &str) -> ForkAnswerRequest {
}
}
/// A test's name for someone as the Bifrost account id the door requires: a deterministic lowercase D-format UUID.
fn acct(name: &str) -> huginn_mind::eureka_pipeline::AccountId {
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
huginn_mind::eureka_pipeline::AccountId(format!("{:08x}-{:04x}-4000-8000-{:012x}", hash >> 32, (hash >> 16) & 0xffff, hash & 0xffff_ffff_ffff))
}
const R1: &str = "00000000-0000-4000-8000-000000000001";
const R2: &str = "00000000-0000-4000-8000-000000000002";
const R3: &str = "00000000-0000-4000-8000-000000000003";
fn answer(who: &str, authority: DeskAuthority, deciders: &[&str], request: ForkAnswerRequest) -> DeskRequest {
DeskRequest::Answer { mind: slug(INSTANCE), subject: short(who), authority, deciders: deciders.iter().map(|d| short(d)).collect(), request }
DeskRequest::Answer { mind: slug(INSTANCE), subject: acct(who), authority, deciders: deciders.iter().map(|d| acct(d)).collect(), request }
}
/// A list read by `who` against `deciders`.
fn forks(who: &str, deciders: &[&str], status: Option<ListStatus>, cursor: Option<ForkCursor>, limit: u8) -> DeskRequest {
DeskRequest::Forks {
mind: slug(INSTANCE),
subject: short(who),
deciders: deciders.iter().map(|d| short(d)).collect(),
subject: acct(who),
deciders: deciders.iter().map(|d| acct(d)).collect(),
status,
cursor,
limit: ForkLimit::new(limit).unwrap(),
@ -110,7 +116,7 @@ fn forks_all(deciders: &[&str]) -> DeskRequest {
}
fn fork_read(who: &str, deciders: &[&str], fork_id: &str) -> DeskRequest {
DeskRequest::Fork { mind: slug(INSTANCE), subject: short(who), deciders: deciders.iter().map(|d| short(d)).collect(), fork_id: fork_id.into() }
DeskRequest::Fork { mind: slug(INSTANCE), subject: acct(who), deciders: deciders.iter().map(|d| acct(d)).collect(), fork_id: fork_id.into() }
}
fn page_of(response: DeskResponse) -> (ForkList, u64) {
@ -205,6 +211,13 @@ fn rig(peer_uid: u32) -> Rig {
}
impl Rig {
/// The Mind lists the seeded fork, on its own door, so a non-decider reaches it.
fn list_the_fork(&mut self) {
let listing = PipelineDocument::DeskListing(huginn_mind::eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: short(FORK), reason: "Listed.".into() });
let admitted = self.daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![listing])), now()).answered();
assert!(matches!(admitted, HuginnMindResponse::Admit(huginn_mind::PipelineAdmissionOutcome::Committed { .. })), "{admitted:?}");
}
/// Runs `client` on its own thread while this one serves the door, then drains what is still waiting.
fn serving<T: Send>(&mut self, client: impl FnOnce(&Path) -> T + Send) -> T {
let path = self.path.clone();
@ -454,7 +467,7 @@ mod door_smoke {
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
run(&mut daemon, &mut hub, &registry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap();
run(&mut daemon, &mut hub, None, &registry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap();
});
let mut stalled = connect(&path);
@ -567,7 +580,7 @@ mod door_smoke {
claim_in_future: false,
request_id: RequestId(R1.into()),
body_sha256: Sha256Hex("0".repeat(64)),
answerer: short("x"),
answerer: acct("x"),
authority: DeskAuthority::Operator,
outcome: DeskOutcome::Counted,
});
@ -578,7 +591,7 @@ mod door_smoke {
let registry = schema_registry().unwrap();
let mut bodies = crate::bodies::DeferredBodies::new(1 << 20, Duration::from_secs(60));
let desk = raw(MIND_SERVICE_ID, DESK_REQUEST_SCHEMA, "answer", "m-1", rmp_serde::to_vec_named(&answer("x", DeskAuthority::Operator, &["x"], wire(&hash, R1))).unwrap());
let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, &registry, &mut bodies, desk, now()).reply() else {
let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, crate::daemon::Door::Full, &registry, &mut bodies, desk, now()).reply() else {
panic!("expected a response")
};
assert_eq!(payload_schema, huginn_mind::envelope::FAILURE_SCHEMA);
@ -601,6 +614,7 @@ mod door_smoke {
#[test]
fn deciders_ride_each_request() {
let mut rig = rig(my_uid());
rig.list_the_fork();
let (before, hash) = (rig.state(), rig.hash.clone());
let out = rig.serving(|path| {
let ask = |id: &str, who: &str, deciders: &[&str], request_id: &str| {
@ -672,6 +686,7 @@ mod door_smoke {
state_root: root.path().to_path_buf(),
instance: slug(INSTANCE),
bind: "127.0.0.1:0".parse().unwrap(),
persona_bind: None,
qdrant_url: "http://127.0.0.1:1".into(),
ollama_urls: vec!["http://127.0.0.1:1".into()],
reserve_ollama_urls: Vec::new(),
@ -776,6 +791,7 @@ mod door_smoke {
#[test]
fn a_mind_refusal_and_a_stored_refusal_are_typed_replies() {
let mut rig = rig(my_uid());
rig.list_the_fork();
let (before, hash) = (rig.state(), rig.hash.clone());
let mut foreign = answer("x", DeskAuthority::Member, &["x"], wire(&hash, R1));
let DeskRequest::Answer { mind, .. } = &mut foreign else { unreachable!() };
@ -801,7 +817,7 @@ mod door_smoke {
assert_eq!((listed_at, read_at), (before.1 as u64, before.1 as u64), "both read at the head the mind held");
assert_eq!(list.stamp, format!("s{listed_at}"));
assert_eq!(list.forks[0], entry);
assert_eq!((entry.card.fork_id.as_str(), entry.card.options_hash.as_str(), entry.card.deciders.as_slice()), (FORK, hash.as_str(), ["x".to_string(), "y".to_string()].as_slice()));
assert_eq!((entry.card.fork_id.as_str(), entry.card.options_hash.as_str(), entry.card.deciders.as_slice()), (FORK, hash.as_str(), [acct("x").0, acct("y").0].as_slice()));
assert_eq!(rig.state(), before, "a read stores nothing");
assert!(rig.index.seen.lock().unwrap().is_empty());
// An unknown fork is the answer path's refusal.
@ -864,11 +880,19 @@ mod door_smoke {
let note = "Keep it local: the author's call.";
rig.serving(|path| counted(reply_of(path, "m-1", &DeskRequest::Answer {
mind: slug(INSTANCE),
subject: short("y"),
subject: acct("y"),
authority: DeskAuthority::Member,
deciders: vec![short("y")],
deciders: vec![acct("y")],
request: noted(&hash, R1, note),
})));
// Unlisted: the outsider is shown nothing at all, and a read is `fork_unknown`.
let (hidden, unknown) = rig.serving(|path| (reply_of(path, "m-1", &forks("outsider", &["x"], None, None, 50)), reply_of(path, "m-1b", &fork_read("outsider", &["x"], FORK))));
assert_eq!(page_of(hidden).0.forks.len(), 0);
assert!(matches!(unknown, DeskResponse::NotStored(_)), "{unknown:?}");
// The Mind lists it, on its own door.
let listing = PipelineDocument::DeskListing(huginn_mind::eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: short(FORK), reason: "Members may read why.".into() });
let admitted = rig.daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![listing])), now()).answered();
assert!(matches!(admitted, HuginnMindResponse::Admit(huginn_mind::PipelineAdmissionOutcome::Committed { .. })), "{admitted:?}");
let (list, read) = rig.serving(|path| (reply_of(path, "m-2", &forks("outsider", &["x"], None, None, 50)), reply_of(path, "m-3", &fork_read("outsider", &["x"], FORK))));
let (list, _) = page_of(list);
let (read, _) = entry_of(read);
@ -882,8 +906,8 @@ mod door_smoke {
}
let seen = rig.serving(|path| reply_of(path, "m-4", &fork_read("x", &["x"], FORK)));
let (seen, _) = entry_of(seen);
assert_eq!(seen.card.deciders, ["x"]);
assert_eq!(seen.record.answers[0].answerer.as_deref(), Some("y"));
assert_eq!(seen.card.deciders, [acct("x").0]);
assert_eq!(seen.record.answers[0].answerer.as_deref(), Some(acct("y").0.as_str()));
}
#[test]
@ -902,7 +926,7 @@ mod door_smoke {
let refused = rig.serving(|path| failure_of(path, &bytes));
assert_eq!(refused.code, "payload-not-a-request", "{what}");
assert!(refused.message.contains("deciders"), "{what}: {}", refused.message);
assert!(!refused.message.contains("d64"), "{what} echoes a decider: {}", refused.message);
assert!(!refused.message.contains(&acct("d64").0), "{what} echoes a decider: {}", refused.message);
}
assert_eq!(rig.state(), before, "nothing stored, head unchanged");
}

View file

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

View file

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

View file

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

View file

@ -134,6 +134,39 @@ impl std::fmt::Display for ChatReport {
}
}
/// One line of a chat run's journal, typed so the job routes by what happened and not by how the line reads.
#[derive(Clone, Debug, PartialEq)]
pub enum Entry {
/// A room's report; a failed one is an alarm.
Report(ChatReport),
Refused(RefusedRoom),
Scrubbed(ScrubHit),
/// A failure outside any one room's report: retiring rooms.
Trouble(String),
}
impl Entry {
/// The operator must see this on stderr: a failure, a refusal, a scrub hit.
pub fn is_alarm(&self) -> bool {
match self {
Self::Report(report) => report.failure.is_some(),
Self::Refused(_) | Self::Scrubbed(_) | Self::Trouble(_) => true,
}
}
}
impl std::fmt::Display for Entry {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Report(report) => report.fmt(formatter),
Self::Refused(RefusedRoom { room_id, reason, event_id: None }) => write!(formatter, "refused: {room_id} {reason}"),
Self::Refused(RefusedRoom { room_id, reason, event_id: Some(event) }) => write!(formatter, "refused: {room_id} {reason} [{event}]"),
Self::Scrubbed(hit) => write!(formatter, "scrubbed: {} {} {}", hit.room_id, hit.event_id, hit.kind),
Self::Trouble(why) => write!(formatter, "huginn-sources: {why}"),
}
}
}
/// A joined room the scope refused, whole, and why; `event_id` when an event did it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RefusedRoom {
@ -562,7 +595,7 @@ pub fn refresh_chat<E: Embedder, S: SourceIndex, H: RoomHistory>(
index: &mut S,
history: &mut H,
estate: &Estate,
journal: &mut dyn FnMut(String),
journal: &mut dyn FnMut(Entry),
) -> Result<ChatRefreshed> {
let DescribedSources::Labelled { meta, .. } = index.describe_sources(INDEX_CALL_TIMEOUT).context("describing the source collection")? else {
bail!("the source collection is absent or not Huginn's; the forge refresh creates it and chat never does");
@ -589,13 +622,14 @@ pub fn refresh_chat<E: Embedder, S: SourceIndex, H: RoomHistory>(
Ok(Err(reason)) => {
// Not kept, so the retirement below purges whatever it held.
keep.remove(room_id);
journal(format!("refused: {room_id} {reason}"));
out.refused.push(RefusedRoom { room_id: room_id.clone(), reason, event_id: None });
let refused = RefusedRoom { room_id: room_id.clone(), reason, event_id: None };
journal(Entry::Refused(refused.clone()));
out.refused.push(refused);
}
// An error is not a reclassification: the room keeps its points and cursor, and the report says why.
Err(error) => {
let report = ChatReport::failed(room_id, None, &error.context("reading the room's facts"));
journal(report.to_string());
journal(Entry::Report(report.clone()));
out.failed.push(room_id.clone());
out.rooms.push(report);
}
@ -604,35 +638,35 @@ pub fn refresh_chat<E: Embedder, S: SourceIndex, H: RoomHistory>(
match retire_chat(index, &keep) {
Ok(done) => {
for (room, why) in done.failed {
journal(format!("huginn-sources: retiring {room} failed, the others go on: {why}"));
journal(Entry::Trouble(format!("retiring {room} failed, the others go on: {why}")));
out.failed.push(room);
}
}
Err(error) => {
journal(format!("huginn-sources: retiring rooms failed: {error:#}"));
journal(Entry::Trouble(format!("retiring rooms failed: {error:#}")));
out.failed.push("retire".to_owned());
}
}
for facts in admitted {
match ingest_room(embedder, index, history, identity.dimensions, &facts, &mut out) {
Ok(Outcome::Done(report)) => {
journal(report.to_string());
journal(Entry::Report(report.clone()));
out.rooms.push(report);
}
Ok(Outcome::Refused(refused)) => {
journal(format!("refused: {} {} [{}]", refused.room_id, refused.reason, refused.event_id.as_deref().unwrap_or("")));
journal(Entry::Refused(refused.clone()));
out.refused.push(refused);
}
Err(error) => {
let report = ChatReport::failed(&facts.room_id, facts.alias.clone(), &error);
journal(report.to_string());
journal(Entry::Report(report.clone()));
out.failed.push(facts.room_id.clone());
out.rooms.push(report);
}
}
}
for hit in &out.scrubbed {
journal(format!("scrubbed: {} {} {}", hit.room_id, hit.event_id, hit.kind));
journal(Entry::Scrubbed(hit.clone()));
}
Ok(out)
}

View file

@ -141,7 +141,7 @@ impl Rig {
fn run(&mut self, history: &mut FakeHistory) -> (Result<ChatRefreshed>, Vec<String>) {
let mut journal = Vec::new();
let out = refresh_chat(&mut self.embedder, &mut self.index, history, &self.estate, &mut |line| journal.push(line));
let out = refresh_chat(&mut self.embedder, &mut self.index, history, &self.estate, &mut |line| journal.push(line.to_string()));
(out, journal)
}

View file

@ -180,7 +180,7 @@ impl HttpForge {
capped.push(repo.clone());
}
}
events.sort_by(|a, b| b.id.cmp(&a.id));
events.sort_by_key(|event| std::cmp::Reverse(event.id));
// The cursor never moves backwards: a read that saw nothing new keeps the one it was given.
head = head.max(after.unwrap_or(0));
let (mut open_prs, mut unseen) = (Vec::new(), dark.clone());
@ -251,7 +251,7 @@ fn redirect_target(base: &str, location: &str) -> Option<OrgRepo> {
let at = segments.windows(3).position(|window| window == ["api", "v1", "repos"])?;
let plain = |segment: &&str| !segment.is_empty() && *segment != "." && *segment != ".." && segment.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
let [owner, name, "activities", "feeds"] = segments[at + 3..] else { return None };
if !segments[..at].iter().all(|segment| plain(segment)) || !plain(&owner) || !plain(&name) {
if !segments[..at].iter().all(plain) || !plain(&owner) || !plain(&name) {
return None;
}
let repo = OrgRepo(format!("{owner}/{name}"));
@ -322,6 +322,7 @@ mod tests {
use serde_json::json;
use super::*;
use crate::sources::test_http::{Reply, forge_of};
/// Only public, live, original, non-empty repos are the corpus; a repo the
/// forge does not say is safe is not indexed.
@ -400,60 +401,6 @@ mod tests {
assert!(HttpForge::new(&unstated).catalog().unwrap().shortfall.unwrap().contains("X-Total-Count"));
}
/// What a fake forge answers: a status, the `Location` header when there is one, and a body.
struct Reply {
status: u16,
location: Option<String>,
body: String,
}
impl From<String> for Reply {
fn from(body: String) -> Self {
Self { status: 200, location: None, body }
}
}
impl Reply {
/// What the live forge answers an anonymous reader for a private repo.
fn not_found() -> Self {
Self { status: 404, location: None, body: json!({ "message": "The target couldn't be found." }).to_string() }
}
/// What the live forge answers for a renamed repo: a 301 to its public address, `/forge` prefix and all.
fn moved_to(location: &str) -> Self {
Self { status: 301, location: Some(location.to_owned()), body: String::new() }
}
}
/// Answers each request by its path from `routes`; a path it has no answer for is held open and never answered, as a hung forge
/// does. Every path asked is recorded in order.
fn forge_of<R: Into<Reply>>(routes: impl Fn(&str) -> Option<R> + Send + 'static) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let record = std::sync::Arc::clone(&asked);
std::thread::spawn(move || {
let mut held = Vec::new();
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let mut buffer = [0_u8; 4096];
let read = stream.read(&mut buffer).unwrap();
let request = String::from_utf8_lossy(&buffer[..read]).into_owned();
let path = request.split_whitespace().nth(1).unwrap_or_default().to_owned();
record.lock().unwrap().push(path.clone());
match routes(&path).map(Into::into) {
Some(Reply { status, location, body }) => {
let location = location.map(|location| format!("location: {location}\r\n")).unwrap_or_default();
write!(stream, "HTTP/1.1 {status} X\r\ncontent-type: application/json\r\n{location}content-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()).unwrap();
}
None => held.push(stream),
}
}
});
(base, asked)
}
const FEED_SAMPLE: &str = include_str!("../../tests/fixtures/feed.json");
const NOW: &str = "2026-11-03T12:00:00Z";
@ -523,7 +470,7 @@ mod tests {
assert!(read.open_prs.is_empty() && read.unseen.is_empty() && read.capped.is_empty() && read.moved.is_empty(), "a cursor asks for neither list");
let wire = serde_json::to_string(&read).unwrap();
assert!(!wire.contains("CANARY") && !wire.contains("obey") && !wire.contains("Message"), "no forge text leaves the read: {wire}");
let asked = asked.lock().unwrap().clone();
let asked = asked.paths();
assert!(!asked.is_empty() && asked.iter().all(|path| names.iter().any(|name| path.starts_with(&format!("/api/v1/repos/{name}/activities/feeds")))), "{asked:?}");
}
@ -555,13 +502,13 @@ mod tests {
let far = HttpForge::new(&base).activity(&wanted, &me, Some(5), now).unwrap();
assert!(far.capped == repos(&["GameCult/Huginn"]), "stopped at the cap with the cursor not reached");
assert_eq!((far.events.len(), far.head), (200, 2500));
assert_eq!(asked.lock().unwrap().len(), 4, "four pages and no more");
assert_eq!(asked.paths().len(), 4, "four pages and no more");
let (base, asked) = forge_of(feed("nibu"));
let near = HttpForge::new(&base).activity(&wanted, &me, Some(2300), now).unwrap();
assert!(near.capped.is_empty());
assert_eq!((near.events.len(), near.head), (20, 2500), "ids above the cursor only");
assert_eq!(asked.lock().unwrap().len(), 1);
assert_eq!(asked.paths().len(), 1);
let (base, _) = forge_of(feed("eureka"));
let hers = HttpForge::new(&base).activity(&wanted, &me, Some(2300), now).unwrap();
@ -583,7 +530,7 @@ mod tests {
let read = HttpForge::new(&base).activity(&repos(&["GameCult/Ratatoskr"]), &me(), None, at(NOW)).unwrap();
assert_eq!(read.events.iter().map(|event| event.id).collect::<Vec<_>>(), [300]);
assert!(read.capped.is_empty());
assert!(asked.lock().unwrap().iter().all(|path| !path.contains("/orgs/GameCult/activities")));
assert!(asked.paths().iter().all(|path| !path.contains("/orgs/GameCult/activities")));
}
/// A first read keeps what is inside 72 hours and nothing older, and its cursor is the newest id it saw, an entry past the window
@ -619,13 +566,13 @@ mod tests {
let (base, asked) = forge_of(move |path| if is_feed(path) { repo_feed(&entries, path) } else { Some("[]".into()) });
let read = HttpForge::new(&base).activity(&wanted, &me(), None, at(NOW)).unwrap();
assert_eq!((read.events.len(), read.capped.len()), (53, 0));
assert_eq!(asked.lock().unwrap().iter().filter(|path| is_feed(path)).count(), 2, "page 2 was asked, page 3 was not");
assert_eq!(asked.paths().iter().filter(|path| is_feed(path)).count(), 2, "page 2 was asked, page 3 was not");
let entries: Vec<Value> = (0..400).map(|n| push_at(5000 - n, "GameCult/Huginn", "Nibu", 5)).collect();
let (base, asked) = forge_of(move |path| if is_feed(path) { repo_feed(&entries, path) } else { Some("[]".into()) });
let read = HttpForge::new(&base).activity(&wanted, &me(), None, at(NOW)).unwrap();
assert_eq!((read.events.len(), read.capped), (REPO_FEED_PAGES * PAGE, repos(&["GameCult/Huginn"])), "200 read and the rest disclosed");
assert_eq!(asked.lock().unwrap().iter().filter(|path| is_feed(path)).count(), REPO_FEED_PAGES);
assert_eq!(asked.paths().iter().filter(|path| is_feed(path)).count(), REPO_FEED_PAGES);
}
/// With no cursor the read also lists the open PRs in her repos and hers anywhere, and the repos the forge's listing does not hold.
@ -636,9 +583,9 @@ mod tests {
let mut first_page: Vec<Value> = (0..PAGE as u32).map(|n| pr(n + 100, "kiko", "GameCult/Elsewhere")).collect();
first_page[0] = pr(8, "nibu", "GameCult/Ratatoskr");
first_page[1] = pr(42, "Eureka", "GameCult/Eureka");
let search = vec![Value::Array(first_page).to_string(), Value::Array(vec![pr(9, "void", "GameCult/Huginn")]).to_string()];
let search = [Value::Array(first_page).to_string(), Value::Array(vec![pr(9, "void", "GameCult/Huginn")]).to_string()];
let names: Vec<Value> = (0..61).map(|n| json!({ "full_name": match n { 0 => "GameCult/ratatoskr".to_owned(), 1 => "GameCult/Huginn".to_owned(), n => format!("GameCult/r{n}") } })).collect();
let listing = vec![Value::Array(names[..PAGE].to_vec()).to_string(), Value::Array(names[PAGE..].to_vec()).to_string()];
let listing = [Value::Array(names[..PAGE].to_vec()).to_string(), Value::Array(names[PAGE..].to_vec()).to_string()];
let sample = sample();
let (base, asked) = forge_of(move |path| {
if is_feed(path) && path.contains("/GameCult/Ghost/") {
@ -660,14 +607,14 @@ mod tests {
assert_eq!(first.unseen, repos(&["GameCult/Ghost"]), "r60 is on page 2 of the listing");
let window = at("2026-10-31T12:00:00Z").timestamp_millis() as u64;
assert!(!first.events.is_empty() && first.events.iter().all(|event| event.at >= window), "inside 72 h: {:?}", first.events);
let paths = asked.lock().unwrap().clone();
let paths = asked.paths();
let count = |what: &str| paths.iter().filter(|path| path.contains(what)).count();
assert_eq!((count("/issues/search"), count("/orgs/GameCult/repos")), (2, 2), "a short page ends each: {paths:?}");
// A cursor asks for neither list.
let before = paths.len();
HttpForge::new(&base).activity(&wanted, &me(), Some(1), at(NOW)).unwrap();
let after = asked.lock().unwrap().clone();
let after = asked.paths();
assert!(after[before..].iter().all(|path| is_feed(path)), "only the feeds: {after:?}");
}
@ -679,7 +626,7 @@ mod tests {
let full = |from: u32| Value::Array((0..PAGE as u32).map(|n| pr(from + n, "GameCult/Elsewhere")).collect()).to_string();
let mut third: Vec<Value> = (0..PAGE as u32).map(|n| pr(300 + n, "GameCult/Elsewhere")).collect();
third[PAGE - 1] = pr(7, "GameCult/Huginn");
let search = vec![full(100), full(200), Value::Array(third).to_string(), "[]".to_owned()];
let search = [full(100), full(200), Value::Array(third).to_string(), "[]".to_owned()];
let (base, asked) = forge_of(move |path| {
if is_feed(path) {
Some("[]".to_owned())
@ -693,12 +640,12 @@ mod tests {
});
let read = HttpForge::new(&base).activity(&repos(&["GameCult/Huginn"]), &me(), None, at(NOW)).unwrap();
assert_eq!(read.open_prs.iter().map(|pr| pr.number).collect::<Vec<_>>(), [7], "page 3 was read");
assert_eq!(asked.lock().unwrap().iter().filter(|path| path.contains("/issues/search")).count(), 4, "to the short page");
assert_eq!(asked.paths().iter().filter(|path| path.contains("/issues/search")).count(), 4, "to the short page");
}
/// The forge as it answers an anonymous reader: public repos give their feed (`[]` when quiet), a private repo answers 404, a
/// renamed repo answers 301 to a path under `/forge` that this loopback does not serve (asking it gives 404).
fn live_forge(entries: Vec<Value>, public: &'static [&'static str], listing: String) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
fn live_forge(entries: Vec<Value>, public: &'static [&'static str], listing: String) -> (String, crate::sources::test_http::Asked) {
forge_of(move |path| {
if path.starts_with("/forge/") {
return Some(Reply::not_found());
@ -733,7 +680,7 @@ mod tests {
assert_eq!(first.unseen, repos(&["GameCult/gamecult-ops", "GameCult/cinny"]));
assert_eq!(first.moved, [RepoMoved { from: "GameCult/cinny".into(), to: "GameCult/Ratatoskr".into() }]);
assert!(first.capped.is_empty());
assert!(asked.lock().unwrap().iter().all(|path| !path.starts_with("/forge/")), "a redirect is not followed: {:?}", asked.lock().unwrap());
assert!(asked.paths().iter().all(|path| !path.starts_with("/forge/")), "a redirect is not followed: {:?}", asked.paths());
let later = forge.activity(&wanted, &me(), Some(250), at(NOW)).unwrap();
assert_eq!((later.events.iter().map(|event| event.id).collect::<Vec<_>>(), later.head), (vec![300], 300), "a later read goes on past the dark repos");
@ -799,9 +746,7 @@ mod tests {
let (base, _) = forge_of(move |path| {
if is_feed(path) && path.contains("/GameCult/cinny/") {
Some(dark())
} else if is_feed(path) {
Some("[]".to_owned().into())
} else if path.contains("/issues/search") {
} else if is_feed(path) || path.contains("/issues/search") {
Some("[]".to_owned().into())
} else {
Some(listing.clone().into())

View file

@ -0,0 +1,128 @@
//! What one `huginn-sources` run does with the pieces it is handed: the forge
//! refresh, then the chat refresh (or, with chat off, the retirement of every
//! chat point), one exit status for both, and the steward-purge request. The
//! binary supplies the real forge, embedder, vector store and Matrix client and
//! owns the flags and the lock; this file decides nothing about scope or
//! scrubbing (`room_scope` and `redact` do) and never sees a credential.
use std::collections::BTreeSet;
use std::path::Path;
use anyhow::{Context, Result, bail, ensure};
use chrono::{DateTime, Utc};
use super::chat::{Entry, RoomHistory, refresh_chat, retire_chat};
use super::chat_purge::{PurgeWindow, parse_windows, purge_key, request_purge};
use super::room_scope::Estate;
use super::{DescribedSources, Forge, SourceIndex, refresh};
use crate::index::{Embedder, INDEX_CALL_TIMEOUT};
/// Chat on: the reader's rooms and the estate ids the scope refuses.
pub struct Chat<'a, H> {
pub history: &'a mut H,
pub estate: &'a Estate,
}
/// One run: the forge refresh, then chat (`Some`) or the retirement of every chat point (`None`).
/// `say` takes the journal's report lines (stdout), `complain` the failures, refusals and scrub hits (stderr).
/// A forge failure never skips the chat run and a chat failure never hides a forge one.
/// Returns the exit status: 0 only when both were clean.
pub fn run<E: Embedder, S: SourceIndex, F: Forge, H: RoomHistory>(
embedder: &mut E,
index: &mut S,
forge: &mut F,
state_root: &Path,
chat: Option<Chat<'_, H>>,
say: &mut dyn FnMut(String),
complain: &mut dyn FnMut(String),
) -> u8 {
let mut clean = true;
match refresh(embedder, index, forge, state_root, &mut |report| say(report.to_string())) {
Ok(refreshed) if refreshed.is_clean() => {}
Ok(refreshed) => {
clean = false;
if !refreshed.failed.is_empty() {
complain(format!("huginn-sources: {} repos failed: {}", refreshed.failed.len(), refreshed.failed.join(", ")));
}
if let Some(why) = &refreshed.retirement_withheld {
complain(format!("huginn-sources: no repo was retired: {why}"));
}
}
Err(error) => {
clean = false;
complain(format!("huginn-sources: {error:#}"));
}
}
match chat {
Some(Chat { history, estate }) => {
let mut line = |entry: Entry| if entry.is_alarm() { complain(entry.to_string()) } else { say(entry.to_string()) };
match refresh_chat(embedder, index, history, estate, &mut line) {
Ok(refreshed) => clean &= refreshed.is_clean(),
Err(error) => {
clean = false;
complain(format!("huginn-sources: chat: {error:#}"));
}
}
}
None => match retire_chat(index, &BTreeSet::new()) {
Ok(done) => {
if !done.retired.is_empty() {
say(format!("chat retired: {} rooms", done.retired.len()));
}
for (room, why) in done.failed {
clean = false;
complain(format!("huginn-sources: retiring {room} failed: {why}"));
}
}
Err(error) => {
clean = false;
complain(format!("huginn-sources: chat: {error:#}"));
}
},
}
u8::from(!clean)
}
/// The longest span one request may name.
const PURGE_SPAN_DAYS: i64 = 366;
const REQUEST_BYTES_MAX: usize = 120;
/// A steward's purge request as the admin typed it, checked. Each error names its option.
#[derive(Debug, PartialEq, Eq)]
pub struct Purge {
pub room_id: String,
pub from: String,
pub to: String,
pub request: String,
pub window: PurgeWindow,
}
fn instant(option: &str, text: &str) -> Result<DateTime<Utc>> {
ensure!(text.ends_with('Z'), "--{option} must be an RFC 3339 UTC time ending in Z, got {text:?}");
let at = DateTime::parse_from_rfc3339(text).map_err(|_| anyhow::anyhow!("--{option} must be an RFC 3339 UTC time ending in Z, got {text:?}"))?;
Ok(at.with_timezone(&Utc))
}
impl Purge {
pub fn check(room: &str, from: &str, to: &str, request: &str, now: DateTime<Utc>) -> Result<Self> {
ensure!(room.starts_with('!'), "--room must be a room id beginning with !, got {room:?}: an alias needs Matrix, and the journal prints both #alias (!id)");
let (start, end) = (instant("from", from)?, instant("to", to)?);
ensure!(start < end, "--from must be before --to");
ensure!(end <= now, "--to must not be after now");
ensure!(end - start <= chrono::Duration::days(PURGE_SPAN_DAYS), "the window must be at most {PURGE_SPAN_DAYS} days");
ensure!(!request.is_empty() && request.len() <= REQUEST_BYTES_MAX, "--request must be 1 to {REQUEST_BYTES_MAX} bytes");
let ms = |at: DateTime<Utc>| u64::try_from(at.timestamp_millis()).context("a purge time before 1970");
Ok(Self { room_id: room.to_owned(), from: from.to_owned(), to: to.to_owned(), request: request.to_owned(), window: PurgeWindow { from_ms: ms(start)?, to_ms: ms(end)? } })
}
}
/// Writes the tombstone and returns the line the admin sees; the free-text request is quoted and escaped so it cannot forge a journal line. Touches no point and makes no Matrix call;
/// the caller holds the job's lock. The next run applies it.
pub fn purge<S: SourceIndex>(index: &mut S, purge: &Purge) -> Result<String> {
request_purge(index, &purge.room_id, purge.window)?;
let DescribedSources::Labelled { cursors, .. } = index.describe_sources(INDEX_CALL_TIMEOUT).context("describing the source collection")? else {
bail!("the source collection is absent or not Huginn's");
};
let windows = cursors.get(&purge_key(&purge.room_id)).map(|held| parse_windows(held)).transpose()?.map_or(0, |held| held.len());
Ok(format!("chat-purge requested: {} {}..{} request={:?} windows={windows}", purge.room_id, purge.from, purge.to, purge.request))
}

View file

@ -0,0 +1,287 @@
//! One run of the job: forge refresh and chat refresh over a fake Synapse reached through the real client,
//! a fake vector store and the fake embedder; the exit status; the chat-off retirement; the purge request.
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use anyhow::{Result, bail};
use chrono::{DateTime, Utc};
use serde_json::json;
use super::chat::{CHAT_PURGE_PREFIX, RoomHistory};
use super::job::{Chat, Purge, purge, run};
use super::matrix::HttpMatrix;
use super::matrix_tests::{Room, Rooms, TOKEN, message, state, synapse};
use super::room_scope::Estate;
use super::tests::{FakeForge, Remote};
use super::test_http::forge_of;
use super::*;
use crate::index::fakes::{FakeEmbedder, FakeSources};
const DAY0: u64 = 1_794_268_800_000; // 2026-11-10T00:00:00Z
fn now() -> DateTime<Utc> {
DateTime::parse_from_rfc3339("2026-11-17T00:00:00Z").unwrap().with_timezone(&Utc)
}
fn estate() -> Estate {
Estate::new(["!e1:s", "!e2:s", "!e3:s"].map(str::to_owned).into()).unwrap()
}
struct Out {
said: Vec<String>,
complained: Vec<String>,
status: u8,
}
struct Rig {
embedder: FakeEmbedder,
index: FakeSources,
forge: FakeForge,
_remote: Remote,
root: tempfile::TempDir,
}
impl Rig {
fn new() -> Self {
let remote = Remote::new();
remote.commit(&[("README.md", b"# Demo\n")], &[]);
Self { embedder: FakeEmbedder::new("d1"), index: FakeSources::default(), forge: FakeForge::of(&[("Demo", &remote)]), _remote: remote, root: tempfile::tempdir().unwrap() }
}
fn go<H: RoomHistory>(&mut self, history: Option<&mut H>) -> Out {
let (mut said, mut complained) = (Vec::new(), Vec::new());
let estate = estate();
let chat = history.map(|history| Chat { history, estate: &estate });
let status = run(&mut self.embedder, &mut self.index, &mut self.forge, self.root.path(), chat, &mut |line| said.push(line), &mut |line| complained.push(line));
Out { said, complained, status }
}
fn chat_bodies(&self) -> Vec<String> {
let mut bodies: Vec<String> = self.index.state.lock().unwrap().chat.values().flat_map(|point| point.payload.messages.iter().map(|m| m.body.clone())).collect();
bodies.sort();
bodies
}
fn chat_rooms(&self) -> std::collections::BTreeSet<String> {
self.index.state.lock().unwrap().chat.values().map(|point| point.payload.room_id.clone()).collect()
}
}
fn rooms(list: Vec<(&str, Vec<serde_json::Value>, Vec<serde_json::Value>)>) -> Rooms {
Arc::new(Mutex::new(list.into_iter().map(|(id, state, timeline)| (id.to_owned(), Room { state, timeline })).collect::<BTreeMap<_, _>>()))
}
fn platform() -> String {
["disc", "ord"].concat()
}
fn world() -> Rooms {
let relay = format!("@_{}_1:s", platform());
rooms(vec![
("!swarm:s", vec![state("m.room.canonical_alias", json!({ "alias": "#swarm:gamecult.org" })), state("m.room.join_rules", json!({ "join_rule": "invite" }))], vec![
message("$m1", "@a:s", DAY0 - 5000, "first words"),
message("$m2", "@b:s", DAY0 - 4000, "to be redacted"),
message("$m3", "@a:s", DAY0 + 1000, "inside the window"),
]),
("!bridged:s", vec![state("m.bridge", json!({}))], vec![message("$b1", "@a:s", DAY0, "bridged talk")]),
("!relay:s", vec![], vec![message("$d1", &relay, DAY0, "relayed talk")]),
("!aliased:s", vec![state("m.room.canonical_alias", json!({ "alias": "#Users:gamecult.org" }))], vec![message("$u1", "@a:s", DAY0, "estate talk")]),
])
}
fn all_lines(out: &Out) -> String {
out.said.iter().chain(&out.complained).cloned().collect::<Vec<_>>().join("\n")
}
#[test]
fn a_full_run_over_a_fake_synapse() {
let world = world();
let (base, asked) = synapse(&world);
let mut matrix = HttpMatrix::new(&base, TOKEN);
let mut rig = Rig::new();
let first = rig.go(Some(&mut matrix));
assert_eq!(first.status, 1, "joined bridged, relay and estate rooms are refused: {:?}", first.complained);
assert_eq!(rig.chat_rooms(), ["!swarm:s".to_owned()].into(), "an invite-only room is ingested; nothing of the refused rooms is");
assert_eq!(rig.chat_bodies(), ["first words", "inside the window", "to be redacted"]);
for refused in ["!bridged:s", "!relay:s", "!aliased:s"] {
assert!(first.complained.iter().any(|line| line.starts_with("refused:") && line.contains(refused)), "{refused}: {:?}", first.complained);
}
assert!(!rig.embedder.texts().iter().any(|text| text.contains("bridged talk") || text.contains("relayed talk") || text.contains("estate talk")));
assert!(first.said.iter().any(|line| line.starts_with("Demo ")), "the forge's line is journaled too");
assert!(first.said.iter().any(|line| line.starts_with("#swarm:gamecult.org (!swarm:s)") && line.contains("events=3")), "{:?}", first.said);
assert!(asked.seen().iter().all(|seen| seen.method == "GET"));
// The steward asks for the window; then the room edits, redacts and leaks a key.
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "follow_up:x", now()).unwrap();
assert_eq!(purge(&mut rig.index, &request).unwrap(), "chat-purge requested: !swarm:s 2026-11-10T00:00:00Z..2026-11-11T00:00:00Z request=\"follow_up:x\" windows=1");
let before = rig.index.cursors();
assert!(purge(&mut rig.index, &request).unwrap().ends_with("windows=1"));
assert_eq!(rig.index.cursors(), before, "a repeated request writes nothing");
let secret = format!("key ghp_{}", "k2L9".repeat(9));
{
let mut held = world.lock().unwrap();
let room = held.get_mut("!swarm:s").unwrap();
room.timeline.push(json!({ "type": "m.room.message", "event_id": "$edit", "sender": "@a:s", "origin_server_ts": DAY0 + 90_000_000, "content": {
"msgtype": "m.text", "body": "* first words, amended", "m.new_content": { "msgtype": "m.text", "body": "first words, amended" }, "m.relates_to": { "rel_type": "m.replace", "event_id": "$m1" } } }));
room.timeline.push(json!({ "type": "m.room.redaction", "event_id": "$red", "sender": "@b:s", "origin_server_ts": DAY0 + 91_000_000, "content": { "redacts": "$m2" } }));
room.timeline.push(message("$m4", "@a:s", DAY0 + 92_000_000, &secret));
}
let second = rig.go(Some(&mut matrix));
assert_eq!(rig.chat_bodies().len(), 2, "{:?}", rig.chat_bodies());
let bodies = rig.chat_bodies().join("\n");
assert!(bodies.contains("first words, amended") && !bodies.contains("to be redacted") && !bodies.contains("inside the window"), "{bodies}");
assert!(!bodies.contains("ghp_k2L9") && !rig.embedder.texts().iter().any(|text| text.contains("ghp_k2L9")), "the key was scrubbed before it was embedded");
let text = all_lines(&second);
assert!(second.said.iter().any(|line| line.contains("purged=")), "{text}");
assert!(second.complained.iter().any(|line| line == "scrubbed: !swarm:s $m4 key-shape" || line.starts_with("scrubbed: !swarm:s $m4 ")), "{text}");
for body in ["first words", "to be redacted", "inside the window", "relayed talk", "ghp_"] {
assert!(!text.contains(body), "the journal carries ids and counts, not bodies: {body}");
}
let third = rig.go(Some(&mut matrix));
assert!(!rig.chat_bodies().join("\n").contains("inside the window"), "a purged window does not come back");
assert!(third.complained.iter().all(|line| line.starts_with("refused:")), "{:?}", third.complained);
}
#[test]
fn no_chat_flags_purge_the_corpus_and_make_no_matrix_call() {
let world = world();
let (base, _) = synapse(&world);
let mut matrix = HttpMatrix::new(&base, TOKEN);
let mut rig = Rig::new();
rig.go(Some(&mut matrix));
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "r", now()).unwrap();
purge(&mut rig.index, &request).unwrap();
assert!(!rig.chat_bodies().is_empty());
let (hung, asked) = forge_of(|_| None::<String>);
drop(hung);
let out = rig.go::<HttpMatrix>(None);
assert_eq!(out.status, 0, "{:?}", out.complained);
assert!(rig.chat_bodies().is_empty() && rig.chat_rooms().is_empty());
assert!(rig.index.cursors().keys().any(|key| key.starts_with(CHAT_PURGE_PREFIX)), "tombstones stay");
assert!(!rig.index.cursors().keys().any(|key| key.starts_with("chat:")), "cursors go");
assert!(asked.seen().is_empty());
}
struct BrokenForge;
impl Forge for BrokenForge {
fn catalog(&mut self) -> Result<Catalog> {
bail!("the forge is down")
}
fn clone_url(&self, _name: &str) -> String {
String::new()
}
}
struct DeadSynapse;
impl RoomHistory for DeadSynapse {
fn joined_rooms(&mut self) -> Result<Vec<String>> {
bail!("synapse is down")
}
fn facts(&mut self, _room_id: &str) -> Result<super::room_scope::RoomFacts> {
bail!("synapse is down")
}
fn events_after(&mut self, _room_id: &str, _after: Option<&str>, _limit: u32) -> Result<Option<super::chat::EventPage>> {
bail!("synapse is down")
}
}
#[test]
fn exit_status_is_clean_only_when_forge_and_chat_both_are() {
let clean = rooms(vec![("!swarm:s", vec![], vec![message("$m1", "@a:s", 1, "words")])]);
let (base, _) = synapse(&clean);
let mut rig = Rig::new();
let out = rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
assert_eq!((out.status, out.complained.len()), (0, 0));
// Scrub hits alone are not a failure; they are reported.
clean.lock().unwrap().get_mut("!swarm:s").unwrap().timeline.push(message("$m2", "@a:s", 2, &format!("ghp_{}", "k2L9".repeat(9))));
let out = rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
assert_eq!(out.status, 0, "{:?}", out.complained);
assert!(out.complained.iter().any(|line| line.starts_with("scrubbed: !swarm:s $m2")));
// A chat failure still reports the forge, and a forge failure still runs chat.
let out = rig.go(Some(&mut DeadSynapse));
assert_eq!(out.status, 1);
assert!(out.complained.iter().any(|line| line.contains("synapse is down")));
let (mut said, mut complained) = (Vec::new(), Vec::new());
let (estate, mut ok) = (estate(), HttpMatrix::new(&base, TOKEN));
let status = run(&mut rig.embedder, &mut rig.index, &mut BrokenForge, rig.root.path(), Some(Chat { history: &mut ok, estate: &estate }), &mut |l| said.push(l), &mut |l| complained.push(l));
assert_eq!(status, 1);
assert!(complained.iter().any(|line| line.contains("the forge is down")), "{complained:?}");
assert!(said.iter().any(|line| line.contains("(!swarm:s)")), "chat ran after the forge failed: {said:?}");
}
#[test]
fn a_request_cannot_forge_a_journal_line() {
let mut rig = Rig::new();
rig.go::<HttpMatrix>(None);
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "x\nrefused: !forged:s", now()).unwrap();
let line = purge(&mut rig.index, &request).unwrap();
assert_eq!(line.lines().count(), 1, "{line:?}");
}
#[test]
fn a_failed_room_report_goes_to_the_complaint_stream_and_fails_the_run() {
let mut rig = Rig::new();
struct FactsDown;
impl RoomHistory for FactsDown {
fn joined_rooms(&mut self) -> Result<Vec<String>> {
Ok(vec!["!swarm:s".to_owned()])
}
fn facts(&mut self, _room_id: &str) -> Result<super::room_scope::RoomFacts> {
bail!("facts are down")
}
fn events_after(&mut self, _room_id: &str, _after: Option<&str>, _limit: u32) -> Result<Option<super::chat::EventPage>> {
bail!("unreachable")
}
}
let out = rig.go(Some(&mut FactsDown));
assert_eq!(out.status, 1);
assert!(out.complained.iter().any(|line| line.contains("!swarm:s") && line.contains("facts are down")), "{:?}", out.complained);
assert!(!out.said.iter().any(|line| line.contains("facts are down")), "{:?}", out.said);
}
#[test]
fn chat_purge_makes_no_matrix_request() {
let world = world();
let (base, asked) = synapse(&world);
let mut rig = Rig::new();
rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
let made = asked.seen().len();
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "r", now()).unwrap();
purge(&mut rig.index, &request).unwrap();
assert_eq!(asked.seen().len(), made);
}
#[test]
fn a_retirement_failure_goes_to_the_complaint_stream() {
struct Left;
impl RoomHistory for Left {
fn joined_rooms(&mut self) -> Result<Vec<String>> {
Ok(vec![])
}
fn facts(&mut self, _room_id: &str) -> Result<super::room_scope::RoomFacts> {
bail!("unreachable")
}
fn events_after(&mut self, _room_id: &str, _after: Option<&str>, _limit: u32) -> Result<Option<super::chat::EventPage>> {
bail!("unreachable")
}
}
let world = rooms(vec![("!swarm:s", vec![], vec![message("$m1", "@a:s", 1, "words")])]);
let (base, _) = synapse(&world);
let mut rig = Rig::new();
rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
rig.index.state.lock().unwrap().fail_chat_deletes = true;
let out = rig.go(Some(&mut Left));
assert_eq!(out.status, 1);
assert!(out.complained.iter().any(|line| line.starts_with("huginn-sources: retiring !swarm:s failed")), "{:?}", out.complained);
assert!(!out.said.iter().any(|line| line.contains("retiring")), "{:?}", out.said);
}

View file

@ -0,0 +1,159 @@
//! Synapse's client API as the reader user sees it: Matrix JSON in, `RoomEvent`
//! and `RoomFacts` out. JSON for Matrix is spoken here and nowhere else. This
//! client reads with GET only and holds no policy: it filters nothing, decides
//! no room's or sender's scope, and names no platform. What is in scope is
//! `room_scope`'s; the token is read at one place, the `Authorization` header.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::Value;
use super::chat::{EventKind, EventPage, RoomEvent, RoomHistory};
use super::room_scope::RoomFacts;
const CALL_TIMEOUT: Duration = Duration::from_secs(60);
/// A bridge's state event types: either marks a room as relaying another platform.
const BRIDGE_TYPES: [&str; 2] = ["m.bridge", "uk.half-shot.bridge"];
pub struct HttpMatrix {
agent: ureq::Agent,
base: String,
token: String,
}
impl std::fmt::Debug for HttpMatrix {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("HttpMatrix").field("base", &self.base).finish_non_exhaustive()
}
}
/// A path segment with everything but unreserved characters escaped.
fn segment(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for byte in raw.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
out.push(char::from(byte));
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
impl HttpMatrix {
pub fn new(base_url: &str, token: &str) -> Self {
let agent: ureq::Agent =
ureq::Agent::config_builder().timeout_global(Some(CALL_TIMEOUT)).http_status_as_error(false).build().into();
Self { agent, base: base_url.trim_end_matches('/').to_owned(), token: token.to_owned() }
}
/// One GET of `path` (already escaped): the status and the JSON body. No message made here carries the token.
fn get(&self, path: &str) -> Result<(u16, Value)> {
let url = format!("{}{path}", self.base);
let mut response = self
.agent
.get(&url)
.header("Authorization", format!("Bearer {}", self.token))
.call()
.with_context(|| format!("no answer from {url}"))?;
let status = response.status().as_u16();
let body = response.body_mut().read_to_string().with_context(|| format!("reading the answer from {url}"))?;
Ok((status, serde_json::from_str(&body).unwrap_or(Value::Null)))
}
fn ok(&self, path: &str) -> Result<Value> {
let (status, body) = self.get(path)?;
if status != 200 {
bail!("synapse answered {status} for {path}");
}
Ok(body)
}
}
fn event_of(raw: &Value) -> Result<RoomEvent> {
let text = |key: &str| raw[key].as_str().map(str::to_owned).with_context(|| format!("an event has no {key}"));
let content = &raw["content"];
let content_keys = content.as_object().map(|map| map.keys().cloned().collect()).unwrap_or_default();
Ok(RoomEvent { event_id: text("event_id")?, sender: text("sender")?, ts_ms: raw["origin_server_ts"].as_u64().context("an event has no origin_server_ts")?, content_keys, kind: kind_of(raw) })
}
fn kind_of(raw: &Value) -> EventKind {
let content = &raw["content"];
if !raw["unsigned"]["redacted_because"].is_null() {
return EventKind::Other;
}
match raw["type"].as_str() {
Some("m.room.redaction") => match content["redacts"].as_str().or_else(|| raw["redacts"].as_str()) {
Some(target) => EventKind::Redaction { target: target.to_owned() },
None => EventKind::Other,
},
Some("m.room.message") if matches!(content["msgtype"].as_str(), Some("m.text" | "m.notice" | "m.emote")) => {
let Some(body) = content["body"].as_str() else { return EventKind::Other };
let relation = &content["m.relates_to"];
if relation["rel_type"].as_str() == Some("m.replace") {
return match (relation["event_id"].as_str(), content["m.new_content"]["body"].as_str()) {
(Some(target), Some(new)) => EventKind::Edit { target: target.to_owned(), body: new.to_owned() },
_ => EventKind::Other,
};
}
EventKind::Message { body: body.to_owned() }
}
_ => EventKind::Other,
}
}
impl RoomHistory for HttpMatrix {
fn joined_rooms(&mut self) -> Result<Vec<String>> {
let body = self.ok("/_matrix/client/v3/joined_rooms")?;
let rooms = body["joined_rooms"].as_array().context("the joined rooms answer is not a list")?;
Ok(rooms.iter().filter_map(|room| room.as_str().map(str::to_owned)).collect())
}
fn facts(&mut self, room_id: &str) -> Result<RoomFacts> {
let body = self.ok(&format!("/_matrix/client/v3/rooms/{}/state", segment(room_id)))?;
let state = body.as_array().context("the room state is not a list")?;
let mut facts = RoomFacts { room_id: room_id.to_owned(), alias: None, alt_aliases: Vec::new(), name: None, encrypted: false, direct: false, bridge: None };
for event in state {
let content = &event["content"];
match event["type"].as_str() {
Some("m.room.canonical_alias") => {
facts.alias = content["alias"].as_str().map(str::to_owned);
facts.alt_aliases = content["alt_aliases"].as_array().map(|list| list.iter().filter_map(|alias| alias.as_str().map(str::to_owned)).collect()).unwrap_or_default();
}
Some("m.room.name") => facts.name = content["name"].as_str().map(str::to_owned),
Some("m.room.encryption") => facts.encrypted = true,
Some("m.room.member") if content["is_direct"].as_bool() == Some(true) => facts.direct = true,
Some(kind) if BRIDGE_TYPES.contains(&kind) => {
facts.bridge.get_or_insert_with(|| kind.to_owned());
}
_ => {}
}
}
Ok(facts)
}
fn events_after(&mut self, room_id: &str, after: Option<&str>, limit: u32) -> Result<Option<EventPage>> {
let room = segment(room_id);
let from = match after {
None => String::new(),
Some(event) => {
let (status, body) = self.get(&format!("/_matrix/client/v3/rooms/{room}/context/{}?limit=0", segment(event)))?;
match status {
200 => match body["end"].as_str() {
Some(end) => format!("&from={}", segment(end)),
None => bail!("synapse gave no end token for the context of {event} in {room_id}"),
},
404 => return Ok(None),
other => bail!("synapse answered {other} for the context of {event} in {room_id}"),
}
}
};
let body = self.ok(&format!("/_matrix/client/v3/rooms/{room}/messages?dir=f&limit={limit}{from}"))?;
let chunk = body["chunk"].as_array().context("the messages answer has no chunk")?;
let events = chunk.iter().map(event_of).collect::<Result<Vec<_>>>()?;
let more = body["end"].as_str().is_some() && !events.is_empty();
Ok(Some(EventPage { events, more }))
}
}

View file

@ -0,0 +1,207 @@
//! The Matrix client against a fake Synapse that speaks the client API's JSON.
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use super::chat::{EventKind, RoomHistory};
use super::matrix::HttpMatrix;
use super::test_http::{Asked, Reply, forge_of};
pub(super) const TOKEN: &str = "syt_reader_9f8e7d6c5b4a";
/// A room as the fake server holds it: its state events and its timeline.
pub(super) struct Room {
pub state: Vec<Value>,
pub timeline: Vec<Value>,
}
pub(super) type Rooms = Arc<Mutex<BTreeMap<String, Room>>>;
pub(super) fn decode(raw: &str) -> String {
let bytes = raw.as_bytes();
let mut out = Vec::new();
let mut at = 0;
while at < bytes.len() {
if bytes[at] == b'%' {
out.push(u8::from_str_radix(&raw[at + 1..at + 3], 16).unwrap());
at += 3;
} else {
out.push(bytes[at]);
at += 1;
}
}
String::from_utf8(out).unwrap()
}
pub(super) fn message(id: &str, sender: &str, ts: u64, body: &str) -> Value {
json!({ "type": "m.room.message", "event_id": id, "sender": sender, "origin_server_ts": ts, "content": { "msgtype": "m.text", "body": body } })
}
pub(super) fn state(kind: &str, content: Value) -> Value {
json!({ "type": kind, "state_key": "", "content": content })
}
/// A Synapse over `rooms`, joined to the rooms in the map: GET only, bearer required.
pub(super) fn synapse(rooms: &Rooms) -> (String, Asked) {
let rooms = Arc::clone(rooms);
forge_of(move |raw| {
let (path, query) = raw.split_once('?').unwrap_or((raw, ""));
let path = decode(path);
let rooms = rooms.lock().unwrap();
let rest = path.strip_prefix("/_matrix/client/v3/")?;
if rest == "joined_rooms" {
return Some(Reply::from(json!({ "joined_rooms": rooms.keys().collect::<Vec<_>>() }).to_string()));
}
let rest = rest.strip_prefix("rooms/")?;
let (id, rest) = rest.split_once('/')?;
let Some(room) = rooms.get(id) else { return Some(Reply::status(404, r#"{"errcode":"M_NOT_FOUND"}"#)) };
let query: BTreeMap<String, String> = query.split('&').filter_map(|pair| pair.split_once('=')).map(|(k, v)| (k.to_owned(), decode(v))).collect();
if rest == "state" {
return Some(Reply::from(Value::Array(room.state.clone()).to_string()));
}
if let Some(event) = rest.strip_prefix("context/") {
return Some(match room.timeline.iter().any(|held| held["event_id"] == event) {
true => Reply::from(json!({ "end": format!("t_{event}"), "events_before": [], "events_after": [] }).to_string()),
false => Reply::status(404, r#"{"errcode":"M_NOT_FOUND"}"#),
});
}
if rest == "messages" {
let start = match query.get("from") {
Some(from) => 1 + room.timeline.iter().position(|held| format!("t_{}", held["event_id"].as_str().unwrap()) == *from)?,
None => 0,
};
let limit: usize = query["limit"].parse().unwrap();
let chunk: Vec<&Value> = room.timeline.iter().skip(start).take(limit).collect();
let end = chunk.last().map(|last| format!("t_{}", last["event_id"].as_str().unwrap()));
return Some(Reply::from(json!({ "chunk": chunk, "end": end }).to_string()));
}
None
})
}
fn one_room(state: Vec<Value>, timeline: Vec<Value>) -> Rooms {
Arc::new(Mutex::new(BTreeMap::from([("!r:s".to_owned(), Room { state, timeline })])))
}
#[test]
fn state_maps_to_facts_and_the_join_rule_is_not_read() {
let plain = one_room(vec![state("m.room.join_rules", json!({ "join_rule": "invite" }))], vec![]);
let (base, _) = synapse(&plain);
let facts = HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap();
assert_eq!((facts.alias, facts.name, facts.encrypted, facts.direct, facts.bridge), (None, None, false, false, None));
for rule in ["public", "knock", "invite"] {
let rooms = one_room(vec![state("m.room.join_rules", json!({ "join_rule": rule }))], vec![]);
let (base, _) = synapse(&rooms);
let facts = HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap();
assert!(!facts.direct && !facts.encrypted && facts.bridge.is_none(), "{rule}");
}
let full = one_room(
vec![
state("m.room.canonical_alias", json!({ "alias": "#a:s", "alt_aliases": ["#b:s", "#c:s"] })),
state("m.room.name", json!({ "name": "Swarm" })),
state("m.room.encryption", json!({ "algorithm": "m.megolm.v1.aes-sha2" })),
json!({ "type": "m.room.member", "state_key": "@x:s", "content": { "membership": "join" } }),
json!({ "type": "m.room.member", "state_key": "@y:s", "content": { "membership": "join", "is_direct": true } }),
state("uk.half-shot.bridge", json!({})),
],
vec![],
);
let (base, _) = synapse(&full);
let facts = HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap();
assert_eq!(facts.alias.as_deref(), Some("#a:s"));
assert_eq!(facts.alt_aliases, ["#b:s", "#c:s"]);
assert_eq!(facts.name.as_deref(), Some("Swarm"));
assert!(facts.encrypted && facts.direct);
assert_eq!(facts.bridge.as_deref(), Some("uk.half-shot.bridge"));
let relay = one_room(vec![state("m.bridge", json!({}))], vec![]);
let (base, _) = synapse(&relay);
assert_eq!(HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap().bridge.as_deref(), Some("m.bridge"));
}
#[test]
fn events_map_to_kinds_and_content_keys_are_names_only() {
let mut other = message("$img", "@a:s", 3, "pic.png");
other["content"]["msgtype"] = json!("m.image");
let mut pruned = message("$pruned", "@a:s", 4, "was here");
pruned["unsigned"] = json!({ "redacted_because": { "event_id": "$x" } });
let mut notice = message("$n", "@a:s", 5, "n");
notice["content"]["msgtype"] = json!("m.notice");
let mut emote = message("$e", "@a:s", 6, "e");
emote["content"]["msgtype"] = json!("m.emote");
let edit = json!({ "type": "m.room.message", "event_id": "$edit", "sender": "@a:s", "origin_server_ts": 7, "content": {
"msgtype": "m.text", "body": "* new", "m.new_content": { "msgtype": "m.text", "body": "new" }, "m.relates_to": { "rel_type": "m.replace", "event_id": "$m1" } } });
let redaction = json!({ "type": "m.room.redaction", "event_id": "$red", "sender": "@a:s", "origin_server_ts": 8, "content": { "redacts": "$m1" } });
let old_redaction = json!({ "type": "m.room.redaction", "event_id": "$red2", "sender": "@a:s", "origin_server_ts": 9, "redacts": "$m2", "content": {} });
let encrypted = json!({ "type": "m.room.encrypted", "event_id": "$enc", "sender": "@a:s", "origin_server_ts": 10, "content": { "ciphertext": "xx" } });
let timeline = vec![message("$m1", "@a:s", 1, "hello"), other, pruned, notice, emote, edit, redaction, old_redaction, encrypted];
let rooms = one_room(vec![], timeline);
let (base, _) = synapse(&rooms);
let page = HttpMatrix::new(&base, TOKEN).events_after("!r:s", None, 50).unwrap().unwrap();
let kinds: Vec<EventKind> = page.events.iter().map(|event| event.kind.clone()).collect();
assert_eq!(
kinds,
[
EventKind::Message { body: "hello".into() },
EventKind::Other,
EventKind::Other,
EventKind::Message { body: "n".into() },
EventKind::Message { body: "e".into() },
EventKind::Edit { target: "$m1".into(), body: "new".into() },
EventKind::Redaction { target: "$m1".into() },
EventKind::Redaction { target: "$m2".into() },
EventKind::Other,
]
);
assert_eq!(page.events[0].content_keys, ["body", "msgtype"]);
assert_eq!(page.events[5].content_keys, ["body", "m.new_content", "m.relates_to", "msgtype"], "names, never values");
assert_eq!((page.events[0].event_id.as_str(), page.events[0].sender.as_str(), page.events[0].ts_ms), ("$m1", "@a:s", 1));
}
#[test]
fn resume_uses_the_cursor_events_end_token_and_a_missing_event_is_none() {
let rooms = one_room(vec![], vec![message("$1", "@a:s", 1, "a"), message("$2", "@a:s", 2, "b"), message("$3", "@a:s", 3, "c")]);
let (base, asked) = synapse(&rooms);
let mut matrix = HttpMatrix::new(&base, TOKEN);
let page = matrix.events_after("!r:s", Some("$1"), 1).unwrap().unwrap();
assert_eq!(page.events.iter().map(|event| event.event_id.as_str()).collect::<Vec<_>>(), ["$2"]);
assert!(page.more);
assert_eq!(asked.paths(), ["/_matrix/client/v3/rooms/%21r%3As/context/%241?limit=0", "/_matrix/client/v3/rooms/%21r%3As/messages?dir=f&limit=1&from=t_%241"]);
assert!(matrix.events_after("!r:s", Some("$unknown"), 5).unwrap().is_none());
let tail = matrix.events_after("!r:s", Some("$3"), 5).unwrap().unwrap();
assert!(tail.events.is_empty() && !tail.more, "an empty chunk ends the run");
let first = matrix.events_after("!r:s", None, 2).unwrap().unwrap();
assert_eq!(first.events.len(), 2);
assert_eq!(asked.paths().last().unwrap(), "/_matrix/client/v3/rooms/%21r%3As/messages?dir=f&limit=2", "no from, no context call");
}
#[test]
fn only_get_always_the_bearer_and_the_token_is_never_printed() {
let rooms = one_room(vec![], vec![message("$1", "@a:s", 1, "a")]);
let (base, asked) = synapse(&rooms);
let mut matrix = HttpMatrix::new(&base, TOKEN);
matrix.joined_rooms().unwrap();
matrix.facts("!r:s").unwrap();
matrix.events_after("!r:s", Some("$1"), 3).unwrap();
let seen = asked.seen();
assert!(seen.len() >= 4 && seen.iter().all(|seen| seen.method == "GET" && seen.authorization.as_deref() == Some(&format!("Bearer {TOKEN}"))), "{seen:?}");
let (base, _) = forge_of(|_| Some(Reply::status(401, &format!(r#"{{"errcode":"M_UNKNOWN_TOKEN","error":"bad {TOKEN}"}}"#))));
let mut matrix = HttpMatrix::new(&base, TOKEN);
let error = matrix.joined_rooms().unwrap_err();
assert!(format!("{error:#}").contains("401"));
assert!(!format!("{error:#}{error:?}").contains(TOKEN));
assert!(!format!("{matrix:?}").contains(TOKEN));
}
#[test]
fn ids_are_percent_encoded_in_paths() {
let weird = "$a+b/c=d:s";
let rooms: Rooms = Arc::new(Mutex::new(BTreeMap::from([("!ro om:s".to_owned(), Room { state: vec![], timeline: vec![message(weird, "@a:s", 1, "x"), message("$2", "@a:s", 2, "y")] })])));
let (base, asked) = synapse(&rooms);
let mut matrix = HttpMatrix::new(&base, TOKEN);
let page = matrix.events_after("!ro om:s", Some(weird), 5).unwrap().unwrap();
assert_eq!(page.events.len(), 1, "the server decoded the room and event ids to the originals");
let raw = asked.paths();
assert!(raw.iter().all(|path| !path.contains('+') && !path.contains(' ') && !path.contains("!ro")), "{raw:?}");
}

View file

@ -30,11 +30,20 @@ pub mod chat_purge;
pub mod chunk;
pub mod forge;
pub mod git;
pub mod job;
pub mod matrix;
pub mod room_scope;
#[cfg(test)]
mod test_http;
#[cfg(test)]
mod chat_tests;
#[cfg(test)]
mod job_tests;
#[cfg(test)]
mod matrix_tests;
#[cfg(test)]
mod tests;
use std::collections::hash_map::Entry;

View file

@ -0,0 +1,92 @@
//! The one fake HTTP server the source tests talk to (the forge's and Matrix's):
//! it answers by path, holds open a path it has no answer for as a hung server
//! does, and records each request's method, path and `Authorization` header.
use std::io::{Read, Write};
use std::sync::{Arc, Mutex};
use serde_json::json;
/// What a fake server answers: a status, the `Location` header when there is one, and a body.
pub struct Reply {
pub status: u16,
pub location: Option<String>,
pub body: String,
}
impl From<String> for Reply {
fn from(body: String) -> Self {
Self { status: 200, location: None, body }
}
}
impl Reply {
/// What the live forge answers an anonymous reader for a private repo.
pub fn not_found() -> Self {
Self { status: 404, location: None, body: json!({ "message": "The target couldn't be found." }).to_string() }
}
/// What the live forge answers for a renamed repo: a 301 to its public address, `/forge` prefix and all.
pub fn moved_to(location: &str) -> Self {
Self { status: 301, location: Some(location.to_owned()), body: String::new() }
}
pub fn status(status: u16, body: &str) -> Self {
Self { status, location: None, body: body.to_owned() }
}
}
/// One request as the server saw it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Seen {
pub method: String,
pub path: String,
pub authorization: Option<String>,
}
/// Every request a fake server has seen, in order.
#[derive(Clone, Default)]
pub struct Asked(Arc<Mutex<Vec<Seen>>>);
impl Asked {
pub fn seen(&self) -> Vec<Seen> {
self.0.lock().unwrap().clone()
}
pub fn paths(&self) -> Vec<String> {
self.0.lock().unwrap().iter().map(|seen| seen.path.clone()).collect()
}
}
/// Answers each request by its path from `routes`; a path it has no answer for is held open and never answered.
pub fn forge_of<R: Into<Reply>>(routes: impl Fn(&str) -> Option<R> + Send + 'static) -> (String, Asked) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let asked = Asked::default();
let record = asked.clone();
std::thread::spawn(move || {
let mut held = Vec::new();
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let mut buffer = [0_u8; 4096];
let read = stream.read(&mut buffer).unwrap();
let request = String::from_utf8_lossy(&buffer[..read]).into_owned();
let mut words = request.split_whitespace();
let method = words.next().unwrap_or_default().to_owned();
let path = words.next().unwrap_or_default().to_owned();
let authorization = request
.lines()
.find_map(|line| line.split_once(':').filter(|(name, _)| name.eq_ignore_ascii_case("authorization")))
.map(|(_, value)| value.trim().to_owned());
record.0.lock().unwrap().push(Seen { method, path: path.clone(), authorization });
match routes(&path).map(Into::into) {
Some(Reply { status, location, body }) => {
let location = location.map(|location| format!("location: {location}\r\n")).unwrap_or_default();
write!(stream, "HTTP/1.1 {status} X\r\ncontent-type: application/json\r\n{location}content-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()).unwrap();
}
None => held.push(stream),
}
}
});
(base, asked)
}

View file

@ -25,23 +25,23 @@ fn git_in(dir: &Path, args: &[&str]) -> String {
}
/// A working repo on disk, committed to by the test.
struct Remote {
pub(super) struct Remote {
dir: tempfile::TempDir,
}
impl Remote {
fn new() -> Self {
pub(super) fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
git_in(dir.path(), &["init", "--quiet", "-b", "main"]);
Self { dir }
}
fn path(&self) -> PathBuf {
pub(super) fn path(&self) -> PathBuf {
self.dir.path().to_path_buf()
}
/// Writes files, removes paths, commits everything and returns the commit.
fn commit(&self, write: &[(&str, &[u8])], remove: &[&str]) -> String {
pub(super) fn commit(&self, write: &[(&str, &[u8])], remove: &[&str]) -> String {
for (path, bytes) in write {
let full = self.dir.path().join(path);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
@ -56,13 +56,13 @@ impl Remote {
}
}
struct FakeForge {
pub(super) struct FakeForge {
repos: Vec<(SourceRepo, PathBuf)>,
shortfall: Option<String>,
}
impl FakeForge {
fn of(repos: &[(&str, &Remote)]) -> Self {
pub(super) fn of(repos: &[(&str, &Remote)]) -> Self {
Self {
repos: repos
.iter()

View file

@ -191,12 +191,18 @@ impl Drop for Daemon {
}
}
/// A test's name for someone as the Bifrost account id the door requires: a deterministic lowercase D-format UUID.
fn acct(name: &str) -> huginn_mind::eureka_pipeline::AccountId {
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
huginn_mind::eureka_pipeline::AccountId(format!("{:08x}-{:04x}-4000-8000-{:012x}", hash >> 32, (hash >> 16) & 0xffff, hash & 0xffff_ffff_ffff))
}
fn answer(who: &str, hash: &str, request_id: &str) -> DeskRequest {
DeskRequest::Answer {
mind: INSTANCE.into(),
subject: short(who),
subject: acct(who),
authority: DeskAuthority::Operator,
deciders: vec![short(who)],
deciders: vec![acct(who)],
request: ForkAnswerRequest {
schema_version: RequestSchema::V0,
fork_id: FORK.into(),
@ -213,8 +219,8 @@ fn answer(who: &str, hash: &str, request_id: &str) -> DeskRequest {
fn forks_request(who: &str, deciders: &[&str]) -> DeskRequest {
DeskRequest::Forks {
mind: INSTANCE.into(),
subject: short(who),
deciders: deciders.iter().map(|d| short(d)).collect(),
subject: acct(who),
deciders: deciders.iter().map(|d| acct(d)).collect(),
status: None,
cursor: None,
limit: huginn_mind::desk_wire::ForkLimit::new(50).unwrap(),
@ -284,14 +290,14 @@ fn the_binary_serves_both_doors_and_survives_restart() {
};
assert_eq!((list.open_count, list.recorded_count, list.forks.len(), list.stamp.clone()), (1, 0, 1, format!("s{listed_at}")));
assert_eq!(list.forks[0].card.options_hash, hash);
let DeskResponse::Fork { entry, as_of } = ask(&desk, "m-r2", &DeskRequest::Fork { mind: INSTANCE.into(), subject: short("x"), deciders: vec![short("x")], fork_id: FORK.into() })
let DeskResponse::Fork { entry, as_of } = ask(&desk, "m-r2", &DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("x"), deciders: vec![acct("x")], fork_id: FORK.into() })
else {
panic!("a read of the seeded fork")
};
assert_eq!((entry, as_of), (list.forks[0].clone(), listed_at));
assert_eq!(daemon.documents(), seeded);
// `authority` is no field of a read: the payload is refused whole and nothing is answered or stored.
for (operation, request) in [("forks", forks_request("x", &["x"])), ("fork", DeskRequest::Fork { mind: INSTANCE.into(), subject: short("x"), deciders: vec![short("x")], fork_id: FORK.into() })] {
for (operation, request) in [("forks", forks_request("x", &["x"])), ("fork", DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("x"), deciders: vec![acct("x")], fork_id: FORK.into() })] {
let mut value = serde_json::to_value(&request).unwrap();
let variant = if operation == "forks" { "Forks" } else { "Fork" };
value[variant]["authority"] = serde_json::json!("Operator");
@ -319,16 +325,20 @@ fn the_binary_serves_both_doors_and_survives_restart() {
assert_eq!((stale.code, counted_answer_id.as_deref()), (Some(ForkAnswerCode::StaleFork), Some("n1")));
let stored = daemon.documents();
assert_eq!(stored, seeded + 2);
// A subject the call's deciders do not name reads both answers, the first with its choice and the stale one with its code, and is told no account id.
// A subject the call's deciders do not name is a non-decider: the fork is unlisted, so it reads as a missing one.
let outsider = ask(&desk, "m-r3", &DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("outsider"), deciders: vec![acct("y")], fork_id: FORK.into() });
assert!(matches!(outsider, DeskResponse::NotStored(ref refusal) if refusal.code == huginn_mind::desk_wire::ForkRefusalCode::ForkUnknown), "{outsider:?}");
// A decider reads both answers, the first with its choice and the stale one with its code, and is told who answered.
let DeskResponse::Fork { entry, .. } =
ask(&desk, "m-r3", &DeskRequest::Fork { mind: INSTANCE.into(), subject: short("outsider"), deciders: vec![short("y")], fork_id: FORK.into() })
ask(&desk, "m-r4", &DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("y"), deciders: vec![acct("y")], fork_id: FORK.into() })
else {
panic!("a read")
};
let seen: Vec<_> = entry.record.answers.iter().map(|answer| (answer.answer_id.as_str(), answer.answerer.as_deref(), answer.code)).collect();
assert_eq!(seen, [("n1", None, None), ("n2", None, Some(ForkAnswerCode::StaleFork))]);
let x = acct("x").0;
assert_eq!(seen, [("n1", Some(x.as_str()), None), ("n2", Some(x.as_str()), Some(ForkAnswerCode::StaleFork))]);
assert_eq!((entry.record.counted_answer_id.as_deref(), entry.record.answerer_count), (Some("n1"), 1));
assert_eq!((entry.card.deciders.as_slice(), entry.card.decider_count), (&[][..], 1));
assert_eq!((entry.card.deciders.as_slice(), entry.card.decider_count), (&[acct("y").0][..], 1));
assert_eq!(daemon.documents(), stored);
// A stop takes the socket with it; the stored answers are the retry's memory.
@ -539,13 +549,13 @@ fn a_busy_pass_is_not_followed_by_the_idle_sleep() {
];
let options = parse_options(args.iter().map(|arg| arg.to_string())).unwrap();
let embedder = pool(&options.ollama_urls, &options.reserve_ollama_urls, &options.embedding_model);
let Started { mut daemon, mut hub, registry, desk: mut door } =
let Started { mut daemon, mut hub, persona: _, registry, desk: mut door } =
startup(&options, embedder, QdrantIndex::new(&options.qdrant_url), Backoff::default()).unwrap();
let stopping = Arc::new(AtomicBool::new(false));
let loop_stopping = Arc::clone(&stopping);
let serving = std::thread::spawn(move || {
let serve = ServeOptions { idle_sleep: Duration::from_millis(600), ..ServeOptions::default() };
run(&mut daemon, &mut hub, &registry, door.as_mut(), &loop_stopping, &serve)
run(&mut daemon, &mut hub, None, &registry, door.as_mut(), &loop_stopping, &serve)
});
std::thread::sleep(Duration::from_millis(100));
let frame = framed(&catalog_request());
@ -580,7 +590,7 @@ fn forks_page(who: &str, cursor: Option<&str>) -> DeskRequest {
}
fn fork_read(who: &str, fork_id: &str) -> DeskRequest {
DeskRequest::Fork { mind: INSTANCE.into(), subject: short(who), deciders: vec![short(who)], fork_id: fork_id.into() }
DeskRequest::Fork { mind: INSTANCE.into(), subject: acct(who), deciders: vec![acct(who)], fork_id: fork_id.into() }
}
/// The wire spelling of a not-stored refusal's code, and its text.

View file

@ -62,12 +62,18 @@ pub(crate) enum Door {
Desk,
}
/// Every staged `desk_answer`, whether the caller sent it or a derivation
/// produced it, is refused unless it came by the desk door.
fn refuse_desk_answers_outside_desk(door: Door, docs: &Docs<'_>) -> Result<(), MindRefusal> {
match docs.batch.iter().find(|staged| staged.kind == PipelineKind::DeskAnswer) {
Some(staged) if door != Door::Desk => Err(MindRefusal::DeskAnswerOutsideDesk { id: staged.key.clone() }),
_ => Ok(()),
/// The door split. Every staged `desk_answer`, whether the caller sent it or a derivation produced it,
/// is refused unless it came by the desk door; and a staged `desk_listing` is refused if it came by the
/// desk door: listing is the Mind's own act, on the Admit door, with a receipt saying who.
fn refuse_documents_at_the_wrong_door(door: Door, docs: &Docs<'_>) -> Result<(), MindRefusal> {
match docs.batch.iter().find(|staged| match staged.kind {
PipelineKind::DeskAnswer => door != Door::Desk,
PipelineKind::DeskListing => door == Door::Desk,
_ => false,
}) {
Some(staged) if staged.kind == PipelineKind::DeskListing => Err(MindRefusal::DeskRequestInvalid { field: "desk_listing".into() }),
Some(staged) => Err(MindRefusal::DeskAnswerOutsideDesk { id: staged.key.clone() }),
None => Ok(()),
}
}
@ -160,7 +166,7 @@ impl<S: MindStore> Mind<S> {
for envelope in envelopes {
docs.push(stage(envelope, &mind)?)?;
}
refuse_desk_answers_outside_desk(door, &docs)?;
refuse_documents_at_the_wrong_door(door, &docs)?;
// A6
let carries_instance = docs.batch.iter().filter(|staged| staged.kind == PipelineKind::Instance).count() == 1;
if self.is_empty() && !carries_instance {
@ -184,7 +190,7 @@ impl<S: MindStore> Mind<S> {
docs.push(stage(envelope, &mind)?)?;
}
}
refuse_desk_answers_outside_desk(door, &docs)?;
refuse_documents_at_the_wrong_door(door, &docs)?;
for staged in &docs.batch[originals..] {
resolve(&docs, staged, &mind, external, &mut strong)?;
}
@ -262,17 +268,9 @@ impl<S: MindStore> Mind<S> {
if self.is_empty() {
return Err(MindRefusal::MissingIdentity);
}
// P1
persona::validate_shape(&state)?;
// P2
// P1 to P3: the document alone, the one check an offline reader of a state file shares.
let mind = self.instance().clone();
if state.get("personaId").and_then(Value::as_str) != Some(mind.0.as_str()) {
return Err(MindRefusal::PersonaForeign { instance: mind.0 });
}
// P3
if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") {
return Err(MindRefusal::PersonaNotCanonical);
}
persona::validate_document(&mind, &state)?;
// P4
let stored = self.stored_updated_at()?;
if stored != expected_updated_at {
@ -627,6 +625,9 @@ fn check(docs: &Docs<'_>, staged: &Staged, mind: &Slug, import: Option<&ImportSo
}
// Decided in `answer_desk` before the document exists; no other door can stage one.
D::DeskAnswer(_) => Ok(()),
// The question is a citation (`listed`), so a missing one is refused with every other missing referent, and
// the key derivation holds it to the listing's own campaign.
D::DeskListing(_) => Ok(()),
D::Ruling(ruling) => {
if ruling.operator_quote.is_some() && ruling.authority != RulingAuthority::Operator {
return Err(MindRefusal::QuoteWithoutOperator { ruling: key.into() });
@ -662,7 +663,7 @@ fn check(docs: &Docs<'_>, staged: &Staged, mind: &Slug, import: Option<&ImportSo
return Err(MindRefusal::RepoNotInCampaign { repo: spec.repo.0.clone() });
}
for ruling in &spec.rulings {
if !(historic && root_and_local(&ruling.0).0 != root) && !docs.in_force(K::Ruling, &ruling.0) {
if !(docs.in_force(K::Ruling, &ruling.0) || historic && root_and_local(&ruling.0).0 != root) {
return Err(MindRefusal::CitesResolvedDocument { kind: K::Ruling, id: ruling.0.clone() });
}
}
@ -905,6 +906,7 @@ fn matrix(subject: PipelineKind, outcome: &ResolutionOutcome) -> bool {
(K::Target, O::Superseded { by }) => all(by, K::Target),
(K::Question, O::Answered { by }) => by.kind == K::Ruling,
(K::Question, O::Withdrawn { .. }) => true,
(K::DeskListing, O::Withdrawn { .. }) => true,
(K::Ruling, O::Superseded { by }) => all(by, K::Ruling),
(K::CutSpec, O::Superseded { by }) => all(by, K::CutSpec),
(K::CutSpec, O::Withdrawn { .. }) => true,

View file

@ -19,6 +19,7 @@
use chrono::{DateTime, Duration, SecondsFormat, SubsecRound, Utc};
use eureka_pipeline::{
AccountId,
DeskAuthority, DeskOutcome, DeskRefusal, PipelineDeskAnswer, PipelineDocument, PipelineKind, PipelineQuestion, PipelineRefusal,
PipelineResolution, RequestId, ResolutionOutcome, Sha256Hex, Short, Slug, Words,
};
@ -145,7 +146,7 @@ fn counts_under(answer: &PipelineDeskAnswer, current: &Sha256Hex) -> bool {
/// `answer_desk` runs before it reads the fork and the door runs before its showability gate.
pub(crate) fn bound_answer<'a>(docs: &'a Docs<'_>, answerer: &Short, request_id: &RequestId) -> Option<(&'a str, &'a PipelineDeskAnswer)> {
docs.of_kind(PipelineKind::DeskAnswer).find_map(|(key, document)| match document {
PipelineDocument::DeskAnswer(held) if held.answerer == *answerer && held.request_id == *request_id => Some((key, held)),
PipelineDocument::DeskAnswer(held) if held.answerer.0 == answerer.0 && held.request_id == *request_id => Some((key, held)),
_ => None,
})
}
@ -314,7 +315,7 @@ impl<S: MindStore> Mind<S> {
claim_in_future,
request_id: request.request_id.clone(),
body_sha256: body_sha256.clone(),
answerer: stamp.answerer.clone(),
answerer: AccountId(stamp.answerer.0.clone()),
authority: stamp.authority,
outcome,
};
@ -425,7 +426,7 @@ mod tests {
const LIST: [&str; 6] = ["x", "y", "z", "a", "op", "dec"];
fn stamp_as(who: &str, authority: DeskAuthority, list: &[&str]) -> DeskStamp {
DeskStamp { answerer: s(who), authority, deciders: list.iter().map(|id| s(id)).collect() }
DeskStamp { answerer: account(who), authority, deciders: list.iter().map(|id| account(id)).collect() }
}
fn decider(who: &str) -> DeskStamp {
@ -531,7 +532,7 @@ mod tests {
let mut mind = desk();
stored(ask(&mut mind, &decider("z"), pick(FORK, "Q1", "A", "2026-11-10T12:00:00Z")));
stored(ask(&mut mind, &decider("a"), pick(FORK, "Q1", "A", "2026-11-10T12:00:00Z")));
assert_eq!(held(&mind, &counted(&mind, FORK).unwrap()).answerer, s("z"));
assert_eq!(held(&mind, &counted(&mind, FORK).unwrap()).answerer, acct("z"));
}
#[test]
@ -780,7 +781,7 @@ mod tests {
let record = held(&mind, &answer);
assert_eq!(record.outcome, outcome);
assert_eq!(outcome, DeskOutcome::Refused { code: DeskRefusal::NotADecider, retracts: None });
assert_eq!((record.answerer, record.authority, record.answered_at), (s("guest"), DeskAuthority::Steward, s(at)));
assert_eq!((record.answerer, record.authority, record.answered_at), (acct("guest"), DeskAuthority::Steward, s(at)));
}
#[test]
@ -790,7 +791,7 @@ mod tests {
for (who, authority) in [("op", DeskAuthority::Operator), ("dec", DeskAuthority::Steward), ("x", DeskAuthority::Member)] {
let (answer, _) = stored(ask(&mut mind, &stamp_as(who, authority, &LIST), pick(FORK, "Q1", "A", at)));
let record = held(&mind, &answer);
assert_eq!((record.answerer, record.authority), (s(who), authority));
assert_eq!((record.answerer, record.authority), (acct(who), authority));
}
}
@ -1039,7 +1040,7 @@ mod tests {
let DeskAnswerOutcome::Stored { receipt_id, .. } = outcome else { panic!("{outcome:?}") };
let receipt = mind.receipts().unwrap().into_iter().find(|receipt| receipt.receipt_id == receipt_id).unwrap();
assert_eq!(receipt.provenance.faculty, faculty, "{authority:?}");
assert_eq!(receipt.provenance.agent, s("x"));
assert_eq!(receipt.provenance.agent, account("x"));
}
}
@ -1206,10 +1207,10 @@ mod tests {
let image = first.image().unwrap();
let found = Docs::at(image, image.head).find(K::DeskAnswer, &key("Q1", 1)).cloned();
let Some(PipelineDocument::DeskAnswer(mut held)) = found else { panic!("stored") };
held.answerer = s(&long);
held.answerer = eureka_pipeline::AccountId(long.clone());
store.plant(PipelineDocument::DeskAnswer(held).prepare(&cache).unwrap());
let mut mind = opened(store, INSTANCE);
let stamp = stamp_as(&long, DeskAuthority::Member, &LIST);
let stamp = DeskStamp { answerer: s(&long), ..stamp_as("x", DeskAuthority::Member, &LIST) };
let before = head(&mind);
assert_eq!(replayed(ask(&mut mind, &stamp, request)), (key("Q1", 1), DeskOutcome::Counted));
assert_eq!(head(&mind), before);
@ -1262,8 +1263,8 @@ mod tests {
assert_eq!(stored(ask(&mut mind, &decider("x"), sent.clone())), (key("Q1", 1), DeskOutcome::Counted));
let (y_answer, y_outcome) = stored(ask(&mut mind, &decider("y"), sent.clone()));
assert_eq!((y_answer.as_str(), &y_outcome), (key("Q1", 2).as_str(), &DeskOutcome::Revision { of: s(&key("Q1", 1)) }));
assert_eq!(held(&mind, &y_answer).answerer, s("y"));
assert_eq!(held(&mind, &key("Q1", 1)).answerer, s("x"));
assert_eq!(held(&mind, &y_answer).answerer, acct("y"));
assert_eq!(held(&mind, &key("Q1", 1)).answerer, acct("x"));
// x's later retry still returns n1; y's returns n2.
assert_eq!(replayed(ask(&mut mind, &decider("x"), sent.clone())).0, key("Q1", 1));
assert_eq!(replayed(ask(&mut mind, &decider("y"), sent)).0, key("Q1", 2));
@ -1467,7 +1468,7 @@ mod tests {
let before = head(&mind);
let id = request.request_id.clone();
let (answer, outcome) = stored(ask(&mut mind, &decider("y"), request.clone()));
assert_eq!(outcome, DeskOutcome::Refused { code: DeskRefusal::BadRetraction, retracts: sent.2.map(|target| s(target)) }, "{what}");
assert_eq!(outcome, DeskOutcome::Refused { code: DeskRefusal::BadRetraction, retracts: sent.2.map(s) }, "{what}");
assert_eq!(head(&mind), before + 1, "{what} is stored");
// The record keeps what was sent: the choice, the note and the target it named.
let record = held(&mind, &answer);

View file

@ -20,7 +20,7 @@ pub use reads::{CardSchema, CardStatus, EntrySchema, ForkCard, ForkCursor, ForkE
use chrono::{DateTime, Utc};
use eureka_pipeline::{
DeskAuthority, DeskOutcome, DeskRefusal, PipelineDeskAnswer, PipelineDocument, PipelineKind, PipelineQuestion, RequestId, Sha256Hex, Short, Slug, Words,
AccountId, DeskAuthority, DeskOutcome, DeskRefusal, PipelineDeskAnswer, PipelineDocument, PipelineKind, PipelineQuestion, RequestId, Sha256Hex, Short, Slug, Words,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@ -232,18 +232,33 @@ pub const DESK_PAGE_BUDGET: usize = DESK_MAX_RESPONSE_BYTES - DESK_ENVELOPE_MARG
/// Most deciders one call carries (CultLib `card.deciders` `maxItems`).
pub const DESK_DECIDERS_MAX: usize = 64;
/// A decider list, read whole or not at all: one to `DESK_DECIDERS_MAX` subjects, none twice. A
/// bad list is the decoder's refusal, which names the field and never quotes a subject.
fn deciders<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<Short>, D::Error> {
/// An account id read from the wire: a lowercase D-format UUID, or the decoder's refusal, which names the
/// field and never quotes the value.
fn account_id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<AccountId, D::Error> {
let id = AccountId(String::deserialize(deserializer)?);
id.validate_account().map_err(|_| serde::de::Error::custom("not an account id: a lowercase D-format UUID"))?;
Ok(id)
}
/// A decider list, read whole or not at all: one to `DESK_DECIDERS_MAX` account ids, none twice. A
/// bad list is the decoder's refusal, which names the field and never quotes an id.
fn deciders<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<AccountId>, D::Error> {
struct List;
/// One list entry, through the same grammar as `subject`.
struct Account(AccountId);
impl<'de> Deserialize<'de> for Account {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
account_id(deserializer).map(Self)
}
}
impl<'de> serde::de::Visitor<'de> for List {
type Value = Vec<Short>;
type Value = Vec<AccountId>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a list of distinct deciders")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<Short>, A::Error> {
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<AccountId>, A::Error> {
let mut list = Vec::new();
while let Some(subject) = seq.next_element::<Short>()? {
while let Some(Account(subject)) = seq.next_element::<Account>()? {
if list.len() == DESK_DECIDERS_MAX {
return Err(serde::de::Error::custom("too many deciders"));
}
@ -264,7 +279,7 @@ fn deciders<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<Sho
fn deciders_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "array",
"items": generator.subschema_for::<Short>(),
"items": generator.subschema_for::<AccountId>(),
"minItems": 1,
"maxItems": DESK_DECIDERS_MAX,
"uniqueItems": true
@ -279,8 +294,9 @@ fn deciders_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schem
///
/// The reads, `Forks` and `Fork`, carry NO `authority` (CultLib `list_request` and
/// `read_request` are closed and have none; one that names it is refused whole). Their `deciders`
/// feed the showability gate, and `subject` decides the view: a subject in `deciders` is a decider
/// and is told the ids; any other is told counts in their place. `Forks` takes the contract's `list_request` fields flat
/// feed the showability gate, and `subject` decides the view: a subject in `deciders` is a decider,
/// sees every showable fork and is told the ids; any other reads only the forks the Mind lists
/// (a `desk_listing` in force) and is told counts in the ids' place. `Forks` takes the contract's `list_request` fields flat
/// beside them (`status`, `cursor`, `limit`), each key written, `null` where absent. Bifrost
/// strips notes; see `DeskResponse` for the trust boundary. These docs and the doc of `Mind::desk_forks`/`Mind::desk_fork` are the
/// reads spec.
@ -289,19 +305,21 @@ fn deciders_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schem
pub enum DeskRequest {
Answer {
mind: Slug,
subject: Short,
#[serde(deserialize_with = "account_id")]
subject: AccountId,
authority: DeskAuthority,
#[serde(deserialize_with = "deciders")]
#[schemars(schema_with = "deciders_schema")]
deciders: Vec<Short>,
deciders: Vec<AccountId>,
request: ForkAnswerRequest,
},
Forks {
mind: Slug,
subject: Short,
#[serde(deserialize_with = "account_id")]
subject: AccountId,
#[serde(deserialize_with = "deciders")]
#[schemars(schema_with = "deciders_schema")]
deciders: Vec<Short>,
deciders: Vec<AccountId>,
#[serde(deserialize_with = "required")]
#[schemars(required)]
status: Option<ListStatus>,
@ -312,10 +330,11 @@ pub enum DeskRequest {
},
Fork {
mind: Slug,
subject: Short,
#[serde(deserialize_with = "account_id")]
subject: AccountId,
#[serde(deserialize_with = "deciders")]
#[schemars(schema_with = "deciders_schema")]
deciders: Vec<Short>,
deciders: Vec<AccountId>,
fork_id: String,
},
}
@ -337,7 +356,7 @@ impl DeskRequest {
}
}
pub fn deciders(&self) -> &[Short] {
pub fn deciders(&self) -> &[AccountId] {
match self {
Self::Answer { deciders, .. } | Self::Forks { deciders, .. } | Self::Fork { deciders, .. } => deciders,
}
@ -530,10 +549,13 @@ impl<S: MindStore> Mind<S> {
};
let image = self.image()?;
let docs = Docs::at(image, image.head);
// A request already stored replays whatever the list is now: the lookup is `answer_desk`'s,
// asked here only so the gate does not shadow it.
let unshowable = bound_answer(&docs, &subject, &sent.request_id).is_none()
&& matches!(docs.find(PipelineKind::Question, &sent.fork.0), Some(PipelineDocument::Question(question)) if !showable(question, deciders));
// A fork this reader may not see is unshowable here too, by the read side's own `visible`: the answer path
// must not tell a hidden fork from a missing one, nor store a refusal for it. A request already stored replays
// whatever the decider list is now (the lookup is `answer_desk`'s, asked here only so `showable` does not
// shadow it), but never to a reader who can no longer see the fork: the counted answer id and `as_of` it
// would carry are the fork's current state, so that replay is `fork_unknown` too (ruling clause 3).
let replay = bound_answer(&docs, &subject, &sent.request_id).is_some();
let unshowable = matches!(docs.find(PipelineKind::Question, &sent.fork.0), Some(PipelineDocument::Question(question)) if (!replay && !showable(question, deciders)) || !reads::visible(&docs, &sent.fork.0, deciders.contains(&subject)));
if unshowable {
return Ok(DeskResponse::NotStored(fork_unknown()));
}
@ -547,7 +569,7 @@ impl<S: MindStore> Mind<S> {
let Some(PipelineDocument::DeskAnswer(stored)) = docs.find(PipelineKind::DeskAnswer, &key) else { return Err(unreadable_key()) };
let fork = stored.fork.0.as_str();
let counted_answer_id = counted_answer(&docs, fork).map(|counted| answer_seq(fork, &counted).map(n_text).ok_or_else(unreadable_key)).transpose()?;
Ok((DeskResponse::Answered { answer: project(&key, stored)?, counted_answer_id, as_of: image.head }))
Ok(DeskResponse::Answered { answer: project(&key, stored)?, counted_answer_id, as_of: image.head })
}
}
@ -597,6 +619,11 @@ mod tests {
fn desk() -> Mind<MemoryStore> {
let mut mind = seeded();
committed(admit(&mut mind, vec![question_n(1), question_n(2)]));
// Listed, so a reader who is not a decider reaches them (an unlisted fork is the reads' own tests').
for fork in [FORK, FORK2] {
let listing = D::DeskListing(eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: s(fork), reason: "Listed.".into() });
committed(admit(&mut mind, vec![listing]));
}
mind
}
@ -632,14 +659,14 @@ mod tests {
}
fn deciders(list: &[&str]) -> Vec<Short> {
list.iter().map(|who| s(who)).collect()
list.iter().map(|who| account(who)).collect()
}
/// The response and whether the call committed anything: a replay, a refused body and a gate
/// refusal store nothing, so the head does not move.
fn ask_as(mind: &mut Mind<MemoryStore>, who: &str, list: &[&str], request: ForkAnswerRequest) -> (DeskResponse, bool) {
let before = head(mind);
let response = mind.desk_answer(&deciders(list), s(who), DeskAuthority::Member, request, now());
let response = mind.desk_answer(&deciders(list), account(who), DeskAuthority::Member, request, now());
(response, head(mind) != before)
}
@ -779,7 +806,7 @@ mod tests {
request_id: RequestId(text("request_id").unwrap()),
body_sha256: Sha256Hex("0".repeat(64)),
// A withheld vector names no answerer: store a placeholder, the vector is the non-decider's view of it.
answerer: Short(text("answerer").unwrap_or_else(|| "e0d1c2b3-a495-4687-8879-6a5b4c3d2e1f".into())),
answerer: AccountId(text("answerer").unwrap_or_else(|| "e0d1c2b3-a495-4687-8879-6a5b4c3d2e1f".into())),
authority,
outcome,
};
@ -1286,6 +1313,54 @@ mod tests {
}
}
/// Ruling clause 3: a stored request replays whatever the decider list is now, but never to a reader who can no
/// longer see the fork. The replay would carry the fork's current counted answer id and head, so it is the same
/// bytes a missing fork answers with; the stored word itself comes back once the fork is listed again.
#[test]
fn a_stored_answer_does_not_replay_to_a_reader_who_can_no_longer_see_the_fork() {
let mut mind = desk();
let hash = hash_of(&mind, FORK);
// Dan is not a decider: his answer to the listed fork is a stored refusal and counts nothing.
let dan_request = wire(FORK, &hash);
let (first, wrote) = ask(&mut mind, "d", dan_request.clone());
let (refused, counted, _) = answered(first);
assert!((wrote, refused.outcome.as_str(), refused.code.is_some(), counted) == (true, "Refused", true, None), "{refused:?}");
// A decider answers, so the fork now has a counted answer a replay could name.
let x_request = wire(FORK, &hash);
let (counted_by_x, _) = ask(&mut mind, "x", x_request.clone());
assert!(answered(counted_by_x).1.is_some());
// Still listed: the replay is the stored word, with the fork's current state.
let before = head(&mind);
let (listed_replay, wrote) = ask(&mut mind, "d", dan_request.clone());
assert!(!wrote);
let (_, counted, as_of) = answered(listed_replay);
assert_eq!((counted.is_some(), as_of), (true, before));
// Unlisted: the replay is fork_unknown, byte for byte a fork that does not exist, and writes nothing.
let withdrawal = crate::fixtures::resolution_n(
eureka_pipeline::PipelineRef { kind: PipelineKind::DeskListing, id: s("eureka-state:desk_listing:Q1") },
1,
eureka_pipeline::ResolutionOutcome::Withdrawn { reason: "unlisted".into() },
);
let withdrawal_key = eureka_pipeline::pipeline_key(&withdrawal).unwrap();
committed(admit(&mut mind, vec![withdrawal]));
let before = head(&mind);
let (hidden, wrote) = ask(&mut mind, "d", dan_request.clone());
assert!(!wrote);
let (missing, _) = ask(&mut mind, "d", ForkAnswerRequest { fork_id: "eureka-state:question:Q99".into(), ..wire(FORK, &hash) });
assert_eq!(not_stored(hidden.clone()).code, ForkRefusalCode::ForkUnknown);
assert_eq!(encode(&hidden), encode(&missing));
// A decider is told the fork whether or not it is listed.
let (decider_replay, wrote) = ask(&mut mind, "x", x_request);
assert!(!wrote && answered(decider_replay).1.is_some());
assert_eq!(head(&mind), before);
// Relisted: the stored word replays again.
let subject = eureka_pipeline::PipelineRef { kind: PipelineKind::Resolution, id: s(&withdrawal_key) };
committed(admit(&mut mind, vec![crate::fixtures::resolution(subject, eureka_pipeline::ResolutionOutcome::Withdrawn { reason: "listed again".into() })]));
let (relisted, wrote) = ask(&mut mind, "d", dan_request);
assert!(!wrote);
assert_eq!(answered(relisted).0.outcome, "Refused");
}
#[test]
fn showable_needs_two_options_text_depends_and_a_decider() {
let D::Question(plain) = question("Q9", &["A", "B"], "A") else { unreachable!() };
@ -1355,9 +1430,9 @@ mod tests {
let (other, committed) = ask(&mut mind, "y", request.clone());
let (other, _, _) = answered(other);
assert!(committed);
assert_eq!((other.answer_id.as_str(), other.answerer.as_deref().unwrap(), other.outcome.as_str(), other.request_id.as_str()), ("n2", "y", "Revision", request.request_id.as_str()));
assert_eq!((other.answer_id.as_str(), other.answerer.as_deref().unwrap(), other.outcome.as_str(), other.request_id.as_str()), ("n2", account("y").0.as_str(), "Revision", request.request_id.as_str()));
let (original, _, _) = answered(ask(&mut mind, "x", request.clone()).0);
assert_eq!((original.answer_id.as_str(), original.answerer.as_deref().unwrap()), ("n1", "x"));
assert_eq!((original.answer_id.as_str(), original.answerer.as_deref().unwrap()), ("n1", account("x").0.as_str()));
// V17 and V18: an id that is no lowercase D-format UUID is body_invalid naming request_id, and binds nothing.
let before = head(&mind);
for bad in ["retry-1", "0000000A-0000-4000-8000-00000000000B", "{00000000-0000-4000-8000-000000000001}", "00000000-0000-4000-8000-0000000000010", "", " 00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000001 ", "00000000-0000-4000-8000-000000000001\n", "00000000-0000-4000-8000-000000000001x"] {
@ -1472,6 +1547,7 @@ mod tests {
assert_eq!(shown_hash(&question).0, her_hash, "{name}: the card's hash");
let mut mind = seeded();
committed(admit(&mut mind, vec![D::Question(question)]));
committed(admit(&mut mind, vec![D::DeskListing(eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: s(FORK), reason: "Listed.".into() })]));
let list: Vec<&str> = card["deciders"].as_array().unwrap().iter().map(|who| who.as_str().unwrap()).collect();
if card["status"] == "closed" {
close(&mut mind, FORK, "RQ1", "no");
@ -1568,27 +1644,27 @@ mod tests {
let mut mind = desk();
let hash = hash_of(&mind, FORK);
// The operator's own account, off the list, is no decider; a member on the list is.
let off = mind.desk_answer(&deciders(&["x"]), s("op"), DeskAuthority::Operator, wire(FORK, &hash), now());
let off = mind.desk_answer(&deciders(&["x"]), account("op"), DeskAuthority::Operator, wire(FORK, &hash), now());
assert_eq!(answered(off).0.code, Some(ForkAnswerCode::NotADecider));
let on = mind.desk_answer(&deciders(&["m"]), s("m"), DeskAuthority::Member, wire(FORK, &hash), now());
let on = mind.desk_answer(&deciders(&["m"]), account("m"), DeskAuthority::Member, wire(FORK, &hash), now());
let (answer, _, _) = answered(on);
assert_eq!((answer.outcome.as_str(), answer.authority, answer.answerer.as_deref().unwrap()), ("Counted", DeskAuthority::Member, "m"));
assert_eq!((answer.outcome.as_str(), answer.authority, answer.answerer.as_deref().unwrap()), ("Counted", DeskAuthority::Member, account("m").0.as_str()));
}
// ---- the desk request on the wire: deciders ride each call, at most 64, never stored ----
use crate::envelope::{OperationFailure, decode_desk_request, encode_desk_request};
fn list_of(n: usize) -> Vec<Short> {
(0..n).map(|at| s(&format!("d{at}"))).collect()
fn list_of(n: usize) -> Vec<AccountId> {
(0..n).map(|at| acct(&format!("d{at}"))).collect()
}
/// Each request kind of the desk, carrying `list`.
fn desk_requests(mind: &str, list: &[Short], hash: &str) -> [DeskRequest; 3] {
fn desk_requests(mind: &str, list: &[AccountId], hash: &str) -> [DeskRequest; 3] {
[
DeskRequest::Answer { mind: slug(mind), subject: s("d0"), authority: DeskAuthority::Member, deciders: list.to_vec(), request: wire(FORK, hash) },
DeskRequest::Forks { mind: slug(mind), subject: s("d0"), deciders: list.to_vec(), status: None, cursor: None, limit: ForkLimit::new(10).unwrap() },
DeskRequest::Fork { mind: slug(mind), subject: s("d0"), deciders: list.to_vec(), fork_id: FORK.into() },
DeskRequest::Answer { mind: slug(mind), subject: acct("d0"), authority: DeskAuthority::Member, deciders: list.to_vec(), request: wire(FORK, hash) },
DeskRequest::Forks { mind: slug(mind), subject: acct("d0"), deciders: list.to_vec(), status: None, cursor: None, limit: ForkLimit::new(10).unwrap() },
DeskRequest::Fork { mind: slug(mind), subject: acct("d0"), deciders: list.to_vec(), fork_id: FORK.into() },
]
}
@ -1611,7 +1687,7 @@ mod tests {
// 64 deciders through to the Mind: the subject is listed and counts.
let DeskRequest::Answer { subject, authority, deciders, request, .. } = through_the_door(&desk_requests(INSTANCE, &list_of(64), &hash)[0]).unwrap() else { panic!("not an answer") };
let before = head(&mind);
let response = mind.desk_answer(&deciders, subject, authority, request, now());
let response = mind.desk_answer(&deciders.iter().map(|id| s(&id.0)).collect::<Vec<_>>(), s(&subject.0), authority, request, now());
assert!(head(&mind) > before);
assert_eq!(answered(response).0.outcome, "Counted");
@ -1631,7 +1707,7 @@ mod tests {
let hash = hash_of(&mind, FORK);
let before = (head(&mind), stored_count(&mind, FORK));
let mut twice = list_of(3);
twice.push(s("d1"));
twice.push(acct("d1"));
for (what, list) in [("empty", vec![]), ("duplicate", twice)] {
for sent in desk_requests(INSTANCE, &list, &hash) {
let failure = through_the_door(&sent).unwrap_err();
@ -1667,6 +1743,6 @@ mod tests {
// The same request to the mind it names is answered.
let DeskRequest::Answer { mind: named, subject, authority, deciders, request } = through_the_door(&desk_requests(INSTANCE, &list_of(4), &hash)[0]).unwrap() else { panic!("not an answer") };
mind.require_instance(&named).unwrap();
assert_eq!(answered(mind.desk_answer(&deciders, subject, authority, request, now())).0.outcome, "Counted");
assert_eq!(answered(mind.desk_answer(&deciders.iter().map(|id| s(&id.0)).collect::<Vec<_>>(), s(&subject.0), authority, request, now())).0.outcome, "Counted");
}
}

View file

@ -352,6 +352,18 @@ fn card_of(docs: &Docs<'_>, key: &str, order: u64, question: &PipelineQuestion,
}
}
/// Whether a reader may see this fork at all: a decider sees every showable fork (they must, to answer
/// it); anyone else only while the Mind's `desk_listing` for it is in force (derived from the
/// resolutions on every read; no status is stored). A fork nobody may see reads as a missing one.
pub(super) fn visible(docs: &Docs<'_>, key: &str, decider: bool) -> bool {
decider || {
let (root, label) = root_and_local(key);
let listing = format!("{root}:desk_listing:{label}");
// `in_force` is true of a document nobody wrote: a listing counts only if the Mind holds it.
docs.in_image(PipelineKind::DeskListing, &listing).is_some() && docs.in_force(PipelineKind::DeskListing, &listing)
}
}
/// Every question the Mind holds at the snapshot, showable or not, with its rank: the 0-based position
/// in ascending (admission ordinal, key) order. A rank is unique, and admissions only append, so a held
/// question's rank never moves; a question the deciders do not show leaves a gap and shifts no other.
@ -427,15 +439,17 @@ impl<S: MindStore> Mind<S> {
/// The fork itself is still its whole entry on `desk_fork`; if that entry is past the reply cap the door
/// answers the read with `fork_too_large` naming the fork (no order, no cursor), not `ResponseTooLarge`. Nothing is dropped silently.
///
/// The call's `deciders` feed the showability gate; the call's `subject` decides which view of each entry
/// is built (a decider's, with ids, or a non-decider's, with counts). It gates no fork. Notes stay whole
/// (Bifrost strips them).
/// The call's `deciders` feed the showability gate; the call's `subject` decides which forks are visible and
/// which view of each entry is built. A decider sees every showable fork, with ids; any other reader sees a
/// showable fork only while the Mind's `desk_listing` for it is in force, with counts. The counts, the
/// pages and the cursor are over the visible set; `order` and `stamp` are not (a non-decider sees gaps).
/// Notes stay whole (Bifrost strips them).
pub fn desk_forks(&self, subject: &Short, deciders: &[Short], status: Option<ListStatus>, cursor: Option<ForkCursor>, limit: ForkLimit) -> DeskResponse {
self.forks_page(subject, deciders, status, cursor, limit).unwrap_or_else(door_refusal)
}
/// One fork, as the entry a page carries, read at one snapshot. A fork that is not held, is not a
/// question or is not showable is `fork_unknown`, the answer path's refusal. The view is the reader's, as `desk_forks`.
/// question, is not showable or is not visible to the reader is `fork_unknown`, the answer path's refusal, with the same bytes as a missing fork. The view is the reader's, as `desk_forks`.
pub fn desk_fork(&self, subject: &Short, deciders: &[Short], fork_id: &str) -> DeskResponse {
self.fork_entry(subject, deciders, fork_id).unwrap_or_else(door_refusal)
}
@ -444,7 +458,7 @@ impl<S: MindStore> Mind<S> {
let image = self.image()?;
let docs = Docs::at(image, image.head);
let decider = deciders.contains(subject);
let mut shown: Vec<_> = ranked(&docs)?.into_iter().filter(|(_, _, question)| showable(question, deciders)).map(|(order, key, question)| (order, key, question, docs.in_force(PipelineKind::Question, key))).collect();
let mut shown: Vec<_> = ranked(&docs)?.into_iter().filter(|(_, key, question)| showable(question, deciders) && visible(&docs, key, decider)).map(|(order, key, question)| (order, key, question, docs.in_force(PipelineKind::Question, key))).collect();
shown.reverse();
let open_count = shown.iter().filter(|fork| fork.3).count() as u64;
let recorded_count = shown.len() as u64 - open_count;
@ -499,7 +513,7 @@ impl<S: MindStore> Mind<S> {
let Some((order, key, question)) = ranked(&docs)?.into_iter().find(|(_, key, _)| *key == fork_id) else {
return Ok(DeskResponse::NotStored(fork_unknown()));
};
if !showable(question, deciders) {
if !showable(question, deciders) || !visible(&docs, key, decider) {
return Ok(DeskResponse::NotStored(fork_unknown()));
}
Ok(DeskResponse::Fork { entry: entry_of(&docs, key, order, question, deciders, decider)?, as_of: image.head })
@ -536,7 +550,7 @@ mod tests {
}
fn list(who: &[&str]) -> Vec<Short> {
who.iter().map(|id| s(id)).collect()
who.iter().map(|id| account(id)).collect()
}
fn head(mind: &Mind<MemoryStore>) -> u64 {
@ -568,7 +582,7 @@ mod tests {
answered_at: "2026-09-16T11:00:00Z".into(),
request_id: request_id(),
};
mind.desk_answer(&list(deciders), s(who), DeskAuthority::Member, request, now())
mind.desk_answer(&list(deciders), account(who), DeskAuthority::Member, request, now())
}
fn close(mind: &mut Mind<MemoryStore>, fork: &str, label: &str) {
@ -605,7 +619,7 @@ mod tests {
}
fn all(mind: &Mind<MemoryStore>, n: u8) -> ForkList {
page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(n))).0
page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(n))).0
}
// ---- the reads, one snapshot ----
@ -616,7 +630,7 @@ mod tests {
let stale = answer(&mut mind, "x", &LIST, &fork(1), &"0".repeat(64), None);
let DeskResponse::Answered { answer: stale, .. } = stale else { panic!("a stale answer is stored") };
assert_eq!(stale.code, Some(ForkAnswerCode::StaleFork));
let (shown, _) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(1)));
let (shown, _) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(1)));
assert_eq!(shown.card.options_hash, hash_of(&mind, &fork(1)));
assert_ne!(shown.card.options_hash, "0".repeat(64));
assert_eq!((shown.record.answers.len(), shown.record.counted_answer_id.clone()), (1, None));
@ -627,7 +641,7 @@ mod tests {
};
assert_eq!((counted.outcome.as_str(), counted.answer_id.as_str()), ("Counted", "n2"));
assert_eq!(counted_answer_id.as_deref(), Some("n2"));
let (after, _) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(1)));
let (after, _) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(1)));
assert_eq!(after.record.counted_answer_id.as_deref(), Some("n2"));
let names: Vec<_> = after.record.answers.iter().map(|answer| answer.answer_id.as_str()).collect();
assert_eq!(names, ["n1", "n2"], "answers in admission order, named n<seq>");
@ -636,23 +650,23 @@ mod tests {
#[test]
fn list_then_read_at_one_stamp() {
let mut mind = desk(3);
let (first, as_of) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(2)));
let (first, as_of) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(2)));
assert_eq!(as_of, head(&mind));
assert_eq!(first.stamp, format!("s{as_of}"));
assert_eq!(first.mind, INSTANCE);
assert_eq!(ids(&first), [fork(3), fork(2)]);
let next = first.next_cursor.expect("one more fork waits");
assert_eq!(next.order(), first.forks[1].card.order);
let (second, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, Some(next), limit(2)));
let (second, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, Some(next), limit(2)));
assert_eq!((ids(&second), second.next_cursor), (vec![fork(1)], None));
// The read at that stamp is the entry the list carried.
let (read, read_at) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(2)));
let (read, read_at) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(2)));
assert_eq!(read_at, as_of);
assert_eq!(read, first.forks[1]);
// Writing moves the stamp, and only then.
let hash = hash_of(&mind, &fork(2));
answer(&mut mind, "x", &LIST, &fork(2), &hash, None);
let (moved, moved_at) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(2)));
let (moved, moved_at) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(2)));
assert_eq!((moved.stamp.clone(), moved_at), (format!("s{}", head(&mind)), head(&mind)));
assert_ne!(moved.stamp, first.stamp);
assert_eq!(moved.forks[1].record.answers.len(), 1);
@ -671,17 +685,17 @@ mod tests {
assert_eq!(ForkCursor::new(0), None, "no cursor names rank 0: nothing is below it");
for (at, expected) in [(0, 3), (1, 2), (2, 1)] {
let below = ForkCursor::new(orders[at]).unwrap();
let (rest, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, Some(below), limit(50)));
let (rest, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, Some(below), limit(50)));
assert_eq!(rest.forks.len(), expected, "below order {}", orders[at]);
assert!(rest.forks.iter().all(|entry| entry.card.order < orders[at]));
}
// A page that stops short names the last order it returned.
let (short, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(1)));
let (short, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(1)));
assert_eq!((ids(&short), short.next_cursor.map(ForkCursor::order)), (vec![fork(4)], Some(orders[0])));
// A page that ends exactly on the last fork has no cursor.
let (exact, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(4)));
let (exact, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(4)));
assert_eq!((exact.forks.len(), exact.next_cursor), (4, None));
let (over, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(50)));
let (over, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(50)));
assert_eq!(over.forks.len(), 4);
}
@ -694,7 +708,7 @@ mod tests {
for status in [None, Some(ListStatus::Open), Some(ListStatus::Recorded)] {
for cursor in [None, ForkCursor::new(1), ForkCursor::new(3), ForkCursor::new(1000)] {
for size in [0, 1, 50] {
let (shown, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), status, cursor, limit(size)));
let (shown, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), status, cursor, limit(size)));
assert_eq!((shown.open_count, shown.recorded_count), expected, "{status:?} {cursor:?} {size}");
assert!(shown.forks.len() <= size as usize);
for entry in &shown.forks {
@ -708,31 +722,31 @@ mod tests {
}
}
}
let (open, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), Some(ListStatus::Open), None, limit(50)));
let (open, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), Some(ListStatus::Open), None, limit(50)));
assert_eq!(ids(&open), [fork(5), fork(3), fork(2)]);
let (recorded, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), Some(ListStatus::Recorded), None, limit(50)));
let (recorded, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), Some(ListStatus::Recorded), None, limit(50)));
assert_eq!(ids(&recorded), [fork(4), fork(1)]);
// A cursor and a status together: the cards below the cursor that have the status.
let below_four = ForkCursor::new(recorded.forks[0].card.order);
let (rest, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), Some(ListStatus::Open), below_four, limit(50)));
let (rest, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), Some(ListStatus::Open), below_four, limit(50)));
assert_eq!(ids(&rest), [fork(3), fork(2)]);
}
#[test]
fn limit_zero_is_the_counts_and_the_stamp_and_no_entries() {
let mind = desk(3);
let (counts, as_of) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(0)));
let (counts, as_of) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(0)));
assert_eq!((counts.forks.len(), counts.next_cursor), (0, None));
assert_eq!((counts.open_count, counts.recorded_count), (3, 0));
assert_eq!((counts.stamp, as_of), (format!("s{}", head(&mind)), head(&mind)));
let (one, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(1)));
let (one, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(1)));
assert_eq!(one.forks.len(), 1, "limit 1 is one entry, not none");
}
#[test]
fn a_desk_with_no_forks_is_an_empty_page() {
let mind = seeded();
let (empty, as_of) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(10)));
let (empty, as_of) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(10)));
assert_eq!((empty.open_count, empty.recorded_count, empty.forks.len(), empty.next_cursor), (0, 0, 0, None));
assert_eq!(empty.stamp, format!("s{as_of}"));
}
@ -757,11 +771,11 @@ mod tests {
let shown = all(&mind, 50);
assert_eq!(ids(&shown), [fork(2), fork(1)]);
assert_eq!((shown.open_count, shown.recorded_count), (2, 0), "the count is over the showable set");
unknown(mind.desk_fork(&s(LIST[0]), &list(&LIST), &unshowable));
unknown(mind.desk_fork(&account(LIST[0]), &list(&LIST), &unshowable));
// No decider, nothing is shown at all: the gate needs one.
let (none, _) = page(mind.desk_forks(&s(LIST[0]), &[], None, None, limit(50)));
let (none, _) = page(mind.desk_forks(&account(LIST[0]), &[], None, None, limit(50)));
assert_eq!((none.forks.len(), none.open_count, none.recorded_count), (0, 0, 0));
unknown(mind.desk_fork(&s(LIST[0]), &[], &fork(1)));
unknown(mind.desk_fork(&account(LIST[0]), &[], &fork(1)));
}
#[test]
@ -770,12 +784,12 @@ mod tests {
close(&mut mind, &fork(1), "R1");
let ruling_key = format!("{CAMPAIGN_ROOT}:ruling:R1");
for id in [fork(9).as_str(), "", "Q1", "no-colons", "eureka-state:question:", ruling_key.as_str(), &"x".repeat(5000), "other-campaign:question:Q1"] {
unknown(mind.desk_fork(&s(LIST[0]), &list(&LIST), id));
unknown(mind.desk_fork(&account(LIST[0]), &list(&LIST), id));
}
// And nothing was written by looking.
let before = head(&mind);
let _ = mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(1));
let _ = mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(50));
let _ = mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(1));
let _ = mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(50));
assert_eq!(head(&mind), before);
}
@ -790,6 +804,9 @@ mod tests {
/// and Ben answers a second time (a retraction): four stored answers, three answerers.
fn answered_desk() -> Mind<MemoryStore> {
let mut mind = desk(2);
// Listed: a reader who is not a decider sees these forks (and their counts) at all.
list_it(&mut mind, 1);
list_it(&mut mind, 2);
let hash = hash_of(&mind, &fork(1));
let deciders = [ANNA, BEN];
answer(&mut mind, ANNA, &deciders, &fork(1), &hash, Some("Anna's note"));
@ -812,8 +829,8 @@ mod tests {
}
fn reader(mind: &Mind<MemoryStore>, subject: &str, deciders: &[&str]) -> (ForkList, ForkEntry, Vec<u8>) {
let (page, _) = page(mind.desk_forks(&s(subject), &list(deciders), None, None, limit(50)));
let response = mind.desk_fork(&s(subject), &list(deciders), &fork(1));
let (page, _) = page(mind.desk_forks(&account(subject), &list(deciders), None, None, limit(50)));
let response = mind.desk_fork(&account(subject), &list(deciders), &fork(1));
let bytes = encode_desk_response("m", "fork", &response, "r").unwrap();
let bytes = cultnet_rs::encode_cultnet_message_to_vec(&bytes, cultnet_rs::CultNetWireContract::CultNetSchemaV0).unwrap();
let (entry, _) = entry(response);
@ -890,7 +907,7 @@ mod tests {
// ---- raised_at: the question's first admission ----
fn raised_at(mind: &Mind<MemoryStore>, fork_id: &str) -> Option<String> {
entry(mind.desk_fork(&s(ANNA), &list(&[ANNA]), fork_id)).0.card.raised_at
entry(mind.desk_fork(&account(ANNA), &list(&[ANNA]), fork_id)).0.card.raised_at
}
#[test]
@ -964,18 +981,246 @@ mod tests {
#[test]
fn raised_at_is_outside_options_hash() {
let mind = desk(1);
let (read, _) = entry(mind.desk_fork(&s(ANNA), &list(&[ANNA]), &fork(1)));
let (read, _) = entry(mind.desk_fork(&account(ANNA), &list(&[ANNA]), &fork(1)));
let moved = ForkCard { raised_at: Some("2020-01-01T00:00:00Z".into()), ..read.card.clone() };
assert_ne!(moved.raised_at, read.card.raised_at);
assert_eq!(moved.options_hash, read.card.options_hash);
assert_eq!(read.card.options_hash, hash_of(&mind, &fork(1)));
}
// ---- the listing gate: a non-decider reads a fork only while the Mind lists it ----
fn listing_doc(n: u32) -> D {
D::DeskListing(eureka_pipeline::PipelineDeskListing { campaign: slug(CAMPAIGN_ROOT), listed: s(&fork(n)), reason: "Members may read why.".into() })
}
fn listing_ref(n: u32) -> PipelineRef {
PipelineRef { kind: PipelineKind::DeskListing, id: s(&format!("{CAMPAIGN_ROOT}:desk_listing:Q{n}")) }
}
fn list_it(mind: &mut Mind<MemoryStore>, n: u32) {
committed(admit(mind, vec![listing_doc(n)]));
}
/// Unlist: a `Withdrawn` resolution on the listing, `sequence` its per-subject sequence.
fn unlist(mind: &mut Mind<MemoryStore>, n: u32, sequence: u32) -> String {
let withdrawal = crate::fixtures::resolution_n(listing_ref(n), sequence, eureka_pipeline::ResolutionOutcome::Withdrawn { reason: "unlisted".into() });
let key = eureka_pipeline::pipeline_key(&withdrawal).unwrap();
committed(admit(mind, vec![withdrawal]));
key
}
/// Relist: withdraw the withdrawal.
fn relist(mind: &mut Mind<MemoryStore>, withdrawal: &str) {
let subject = PipelineRef { kind: PipelineKind::Resolution, id: s(withdrawal) };
committed(admit(mind, vec![crate::fixtures::resolution(subject, eureka_pipeline::ResolutionOutcome::Withdrawn { reason: "listed again".into() })]));
}
fn seen_by(mind: &Mind<MemoryStore>, subject: &str) -> Vec<String> {
ids(&page(mind.desk_forks(&account(subject), &list(&[ANNA, BEN]), None, None, limit(50))).0)
}
fn read_by(mind: &Mind<MemoryStore>, subject: &str, n: u32) -> DeskResponse {
mind.desk_fork(&account(subject), &list(&[ANNA, BEN]), &fork(n))
}
/// Negative first: with nothing listed, a non-decider is shown nothing, and a read of a real fork
/// is the same bytes as a read of one that does not exist.
#[test]
fn an_unlisted_fork_is_invisible_to_a_non_decider() {
let mind = desk(3);
let (shown, _) = page(mind.desk_forks(&account(DAN), &list(&[ANNA, BEN]), None, None, limit(50)));
assert_eq!((shown.forks.len(), shown.open_count, shown.recorded_count, shown.next_cursor), (0, 0, 0, None));
let (counts, _) = page(mind.desk_forks(&account(DAN), &list(&[ANNA, BEN]), None, None, limit(0)));
assert_eq!((counts.open_count, counts.recorded_count), (0, 0));
let real = read_by(&mind, DAN, 1);
unknown(real.clone());
assert_eq!(real, read_by(&mind, DAN, 99), "a hidden fork reads as a missing one");
let bytes = |response: &DeskResponse| rmp_serde::to_vec_named(response).unwrap();
assert_eq!(bytes(&real), bytes(&read_by(&mind, DAN, 99)));
}
#[test]
fn a_decider_sees_unlisted_forks() {
let mut mind = desk(3);
list_it(&mut mind, 2);
assert_eq!(seen_by(&mind, ANNA), [fork(3), fork(2), fork(1)]);
assert_eq!(seen_by(&mind, DAN), [fork(2)]);
// Listing is not read for a decider: unlisting changes nothing for them.
unlist(&mut mind, 2, 1);
assert_eq!(seen_by(&mind, ANNA), [fork(3), fork(2), fork(1)]);
assert!(seen_by(&mind, DAN).is_empty());
}
#[test]
fn listing_flips_and_is_audited() {
let mut mind = desk(2);
let mut states = vec![seen_by(&mind, DAN)];
let before = head(&mind);
list_it(&mut mind, 1);
states.push(seen_by(&mind, DAN));
let withdrawal = unlist(&mut mind, 1, 1);
states.push(seen_by(&mind, DAN));
relist(&mut mind, &withdrawal);
states.push(seen_by(&mind, DAN));
unlist(&mut mind, 1, 2);
states.push(seen_by(&mind, DAN));
let q1 = vec![fork(1)];
assert_eq!(states, [vec![], q1.clone(), vec![], q1, vec![]]);
assert_eq!(head(&mind), before + 4, "every flip is a document with its own receipt");
assert!(matches!(read_by(&mind, DAN, 1), DeskResponse::NotStored(_)));
}
/// Re-admitting the listing after unlisting is the same document: AlreadyAdmitted, and the fork stays hidden.
#[test]
fn admitting_the_listing_again_after_unlisting_does_not_relist() {
let mut mind = desk(1);
list_it(&mut mind, 1);
let withdrawal = unlist(&mut mind, 1, 1);
let before = head(&mind);
let again = admit(&mut mind, vec![listing_doc(1)]);
assert!(matches!(again, PipelineAdmissionOutcome::AlreadyAdmitted { .. }), "{again:?}");
assert_eq!((head(&mind), seen_by(&mind, DAN)), (before, Vec::<String>::new()));
relist(&mut mind, &withdrawal);
assert_eq!(seen_by(&mind, DAN), [fork(1)]);
}
#[test]
fn counts_and_cursor_cover_the_visible_set() {
let mut mind = desk(5);
for n in [2, 4] {
list_it(&mut mind, n);
}
close(&mut mind, &fork(4), "R4");
let list_for = |subject: &str, cursor, size| page(mind.desk_forks(&account(subject), &list(&[ANNA, BEN]), None, cursor, limit(size))).0;
let counts = list_for(DAN, None, 0);
assert_eq!((counts.open_count, counts.recorded_count), (1, 1));
// Pages are gapless over the visible forks and the cursor never names a hidden one.
let first = list_for(DAN, None, 1);
assert_eq!(ids(&first), [fork(4)]);
let cursor = first.next_cursor.expect("one more visible fork");
let second = list_for(DAN, Some(cursor), 1);
assert_eq!((ids(&second), second.next_cursor), (vec![fork(2)], None));
// Order keeps its rank among ALL the Mind's questions: the gap is visible, the text is not.
assert_eq!(orders(&first).into_iter().chain(orders(&second)).collect::<Vec<_>>(), [3, 1]);
}
#[test]
fn a_listing_needs_a_question_of_its_campaign() {
let mut mind = desk(1);
let missing = refusal(admit(&mut mind, vec![listing_doc(9)]));
assert!(matches!(missing, MindRefusal::MissingReference { kind: PipelineKind::Question, .. }), "{missing:?}");
let D::DeskListing(mut other) = listing_doc(1) else { unreachable!() };
other.campaign = slug("other-campaign");
let before = head(&mind);
assert!(matches!(admit(&mut mind, vec![D::DeskListing(other)]), PipelineAdmissionOutcome::Refused(_)));
assert_eq!(head(&mind), before);
}
/// The answer path is no oracle: a non-decider answering a hidden fork gets the bytes of answering
/// one that never existed, and nothing is stored. A listed fork still stores the NotADecider refusal.
#[test]
fn a_non_decider_answering_a_hidden_fork_learns_nothing_and_stores_nothing() {
let mut mind = desk(2);
let hash = hash_of(&mind, &fork(1));
let before = (head(&mind), stored_answers(&mind));
let hidden = answer(&mut mind, DAN, &[ANNA, BEN], &fork(1), &hash, None);
let missing = answer(&mut mind, DAN, &[ANNA, BEN], &fork(99), &hash, None);
unknown(hidden.clone());
assert_eq!(rmp_serde::to_vec_named(&hidden).unwrap(), rmp_serde::to_vec_named(&missing).unwrap());
assert_eq!((head(&mind), stored_answers(&mind)), before, "nothing stored");
list_it(&mut mind, 1);
let listed = answer(&mut mind, DAN, &[ANNA, BEN], &fork(1), &hash, None);
let DeskResponse::Answered { answer: refused, .. } = listed else { panic!("a listed fork stores the refusal: {listed:?}") };
assert_eq!(refused.code, Some(ForkAnswerCode::NotADecider));
assert_eq!(stored_answers(&mind), before.1 + 1);
}
fn stored_answers(mind: &Mind<MemoryStore>) -> usize {
let image = mind.image().unwrap();
Docs::at(image, image.head).of_kind(PipelineKind::DeskAnswer).count()
}
#[test]
fn the_desk_door_cannot_admit_a_listing() {
let mut mind = desk(1);
let envelope = crate::fixtures::prepare(&listing_doc(1));
let instance = mind.instance().clone();
let outcome = mind.admit_steps(crate::admission::Door::Desk, &instance, provenance(Faculty::Operator), vec![envelope], now());
assert_eq!(outcome.unwrap_err(), MindRefusal::DeskRequestInvalid { field: "desk_listing".into() });
assert!(seen_by(&mind, DAN).is_empty());
}
#[test]
fn listed_role_is_carried_by_desk_listing_only() {
use crate::docs::CitationRole as R;
assert_eq!((R::Listed.carrier(), R::Listed.target_kinds(), R::Listed.name()), (PipelineKind::DeskListing, vec![PipelineKind::Question], "listed"));
assert_eq!(R::Fork.carrier(), PipelineKind::DeskAnswer);
assert_eq!(R::ALL.len(), 27);
}
// ---- the account grammar at decode ----
#[test]
fn a_decider_or_subject_outside_the_account_grammar_is_refused_at_decode() {
let ask = ForkAnswerRequest {
schema_version: RequestSchema::V0,
fork_id: fork(1),
options_hash: "h".into(),
answer: Some(ForkAnswer { choice: Some("A".into()), note: None }),
retracted: false,
retracts: None,
answered_at: "2026-09-16T11:00:00Z".into(),
request_id: request_id(),
};
let (mind_slug, who) = (slug(INSTANCE), acct("a"));
let requests = [
DeskRequest::Answer { mind: mind_slug.clone(), subject: who.clone(), authority: DeskAuthority::Member, deciders: vec![who.clone()], request: ask },
DeskRequest::Forks { mind: mind_slug.clone(), subject: who.clone(), deciders: vec![who.clone()], status: None, cursor: None, limit: ForkLimit::new(10).unwrap() },
DeskRequest::Fork { mind: mind_slug, subject: who.clone(), deciders: vec![who.clone()], fork_id: fork(1) },
];
for request in &requests {
let operation = request.operation();
let variant = match operation {
"answer" => "Answer",
"forks" => "Forks",
_ => "Fork",
};
let good = encode_desk_request_value(operation, &serde_json::to_value(request).unwrap());
decode_desk_request(&good).unwrap_or_else(|failure| panic!("{operation}: {failure:?}"));
let bad_ids = ["@x:server", "meta@gamecult.org", "someone", "7", &who.0.to_uppercase(), &format!("{{{}}}", who.0), ""];
for bad in bad_ids {
for field in ["subject", "deciders"] {
let mut value = serde_json::to_value(request).unwrap();
value[variant][field] = if field == "subject" { bad.into() } else { json!([bad]) };
let failure = decode_desk_request(&encode_desk_request_value(operation, &value)).unwrap_err();
assert_eq!(failure.code, "payload-not-a-request", "{operation} {field}: {bad:?}");
assert!(failure.message.contains(field), "{operation}: {}", failure.message);
assert!(bad.is_empty() || !failure.message.contains(bad), "the refusal quotes {bad:?}: {}", failure.message);
}
}
}
}
fn encode_desk_request_value(operation: &str, value: &Value) -> cultnet_rs::CultNetMessage {
use base64::Engine;
cultnet_rs::CultNetMessage::OperationRequest {
message_id: "m".into(),
service_id: DESK_SERVICE_ID.into(),
operation: operation.into(),
payload_schema: DESK_REQUEST_SCHEMA.into(),
payload_encoding: "messagepack-base64".into(),
payload: base64::engine::general_purpose::STANDARD.encode(rmp_serde::to_vec_named(value).unwrap()),
source_runtime_id: None,
target_runtime_id: None,
}
}
// ---- the card refuses a count that does not match ----
fn card_with(deciders: usize, decider_count: u64) -> Vec<u8> {
let mind = desk(1);
let (read, _) = entry(mind.desk_fork(&s(ANNA), &list(&[ANNA]), &fork(1)));
let (read, _) = entry(mind.desk_fork(&account(ANNA), &list(&[ANNA]), &fork(1)));
let ids: Vec<String> = (0..deciders).map(|n| format!("00000000-0000-4000-8000-{n:012x}")).collect();
rmp_serde::to_vec_named(&ForkCard { deciders: ids, decider_count, ..read.card }).unwrap()
}
@ -1015,7 +1260,7 @@ mod tests {
held.raised_in = Some(PipelineRef { kind: PipelineKind::Ruling, id: s("eureka-state:ruling:R0") });
committed(admit(&mut mind, vec![D::Ruling(ruling("R0"))]));
committed(admit(&mut mind, vec![shown]));
let (read, _) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(1)));
let (read, _) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(1)));
let card = &read.card;
assert_eq!((card.fork_id.as_str(), card.title.as_str(), card.context.as_str()), (fork(1).as_str(), "Share the mark?", "Should a slot mark be shared?"));
let options: Vec<_> = card.options.iter().map(|option| (option.id.as_str(), option.text.as_str())).collect();
@ -1024,7 +1269,7 @@ mod tests {
assert_eq!(card.depends, ["eureka-state:question:other", "a prose line"]);
assert_eq!(card.raised_in, Some(ForkRef { kind: "Ruling".into(), id: "eureka-state:ruling:R0".into() }));
assert_eq!((card.leans.clone(), card.flag.clone(), card.status, card.ruling.clone(), card.ruled_from.clone()), (None, None, CardStatus::Open, None, vec![]));
assert_eq!(card.deciders, LIST);
assert_eq!(card.deciders, LIST.iter().map(|id| account(id).0).collect::<Vec<_>>());
assert_eq!(card.options_hash, hash_of(&mind, &fork(1)));
assert_eq!(card.order, 0, "the only question is rank 0");
assert_eq!(read.record.fork_id, fork(1));
@ -1035,9 +1280,9 @@ mod tests {
fn a_ruling_closes_the_card_and_names_itself() {
let mut mind = desk(2);
close(&mut mind, &fork(1), "R1");
let (closed, _) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(1)));
let (closed, _) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(1)));
assert_eq!((closed.card.status, closed.card.ruling.as_deref()), (CardStatus::Closed, Some("eureka-state:ruling:R1")));
let (open, _) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(2)));
let (open, _) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(2)));
assert_eq!((open.card.status, open.card.ruling), (CardStatus::Open, None));
}
@ -1047,7 +1292,7 @@ mod tests {
let hash = hash_of(&mind, &fork(1));
answer(&mut mind, "x", &LIST, &fork(1), &hash, None);
answer(&mut mind, "y", &LIST, &fork(1), &hash, None);
let (read, _) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(1)));
let (read, _) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(1)));
assert_eq!(read.record.counted_answer_id.as_deref(), Some("n1"));
let outcomes: Vec<_> = read.record.answers.iter().map(|answer| (answer.outcome.as_str(), answer.of.as_deref())).collect();
assert_eq!(outcomes, [("Counted", None), ("Revision", Some("n1"))]);
@ -1062,9 +1307,9 @@ mod tests {
answered_at: "2026-09-16T11:00:00Z".into(),
request_id: request_id(),
};
let stored = mind.desk_answer(&list(&LIST), s("x"), DeskAuthority::Member, retract, now());
let stored = mind.desk_answer(&list(&LIST), account("x"), DeskAuthority::Member, retract, now());
assert!(matches!(stored, DeskResponse::Answered { .. }));
let (after, _) = entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(1)));
let (after, _) = entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(1)));
assert_eq!(after.record.counted_answer_id.as_deref(), Some("n2"));
}
@ -1236,7 +1481,7 @@ mod tests {
let file = transport();
let flat = |message: &Value| {
json!({ "Forks": {
"mind": message["mind"], "subject": "s", "deciders": ["s"],
"mind": message["mind"], "subject": "00000000-0000-4000-8000-0000000000e5", "deciders": ["00000000-0000-4000-8000-0000000000e5"],
"status": message["status"], "cursor": message["cursor"], "limit": message["limit"]
}})
};
@ -1261,7 +1506,7 @@ mod tests {
}
fn forks_json(status: Value, cursor: Value, limit: Value) -> Value {
json!({ "Forks": { "mind": INSTANCE, "subject": "s", "deciders": ["s"], "status": status, "cursor": cursor, "limit": limit } })
json!({ "Forks": { "mind": INSTANCE, "subject": "00000000-0000-4000-8000-0000000000e5", "deciders": ["00000000-0000-4000-8000-0000000000e5"], "status": status, "cursor": cursor, "limit": limit } })
}
#[test]
@ -1308,7 +1553,7 @@ mod tests {
#[test]
fn a_read_that_names_an_authority_is_not_a_request() {
let mut forks = forks_json(Value::Null, Value::Null, json!(5));
let mut fork = json!({ "Fork": { "mind": INSTANCE, "subject": "s", "deciders": ["s"], "fork_id": fork(1) } });
let mut fork = json!({ "Fork": { "mind": INSTANCE, "subject": "00000000-0000-4000-8000-0000000000e5", "deciders": ["00000000-0000-4000-8000-0000000000e5"], "fork_id": fork(1) } });
assert!(serde_json::from_value::<DeskRequest>(forks.clone()).is_ok() && serde_json::from_value::<DeskRequest>(fork.clone()).is_ok());
for authority in [json!("Operator"), json!("Member"), Value::Null] {
forks["Forks"]["authority"] = authority.clone();
@ -1317,7 +1562,7 @@ mod tests {
assert!(serde_json::from_value::<DeskRequest>(fork.clone()).is_err(), "Fork with {authority}");
}
// And through the envelope the door reads.
let typed = DeskRequest::Forks { mind: slug(INSTANCE), subject: s("s"), deciders: list(&["s"]), status: None, cursor: None, limit: limit(5) };
let typed = DeskRequest::Forks { mind: slug(INSTANCE), subject: acct("s"), deciders: vec![acct("s")], status: None, cursor: None, limit: limit(5) };
let message = encode_desk_request("m-1", &typed, None).unwrap();
assert_eq!(decode_desk_request(&message).unwrap().1, typed);
}
@ -1355,7 +1600,7 @@ mod tests {
fn pages(mind: &Mind<MemoryStore>, size: u8) -> Vec<(DeskResponse, ForkList)> {
let (mut cursor, mut out) = (None, Vec::new());
loop {
let response = mind.desk_forks(&s(LIST[0]), &list(&LIST), None, cursor, limit(size));
let response = mind.desk_forks(&account(LIST[0]), &list(&LIST), None, cursor, limit(size));
let (page, _) = page(response.clone());
cursor = page.next_cursor;
out.push((response, page));
@ -1406,7 +1651,7 @@ mod tests {
}
mind
};
let first_page = |mind: &Mind<MemoryStore>| page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(50))).0;
let first_page = |mind: &Mind<MemoryStore>| page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(50))).0;
// The most forks that fit one page with the oldest one's text short.
let fits = (2..=50).take_while(|forks| first_page(&build(*forks, 300)).forks.len() == *forks as usize).last().expect("two fit");
assert!(fits < 50, "the desk outgrows a page");
@ -1417,18 +1662,18 @@ mod tests {
if first_page(&build(fits, mid)).forks.len() == fits as usize { low = mid } else { high = mid }
}
let (in_page, over) = (build(fits, low), build(fits, low + 1));
let held = page(in_page.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(50)));
let held = page(in_page.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(50)));
assert_eq!((held.0.forks.len(), held.0.next_cursor), (fits as usize, None));
let size = bare(&DeskResponse::Forks { list: held.0, as_of: held.1 });
// The wire grows in steps of up to three bytes per text byte, so "exact" is within one step.
assert!(size <= DESK_PAGE_BUDGET && DESK_PAGE_BUDGET - size < 4, "{size} against {DESK_PAGE_BUDGET}");
let (moved, _) = page(over.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(50)));
let (moved, _) = page(over.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(50)));
assert_eq!(moved.forks.len(), fits as usize - 1, "one byte more and the oldest fork goes to the next page");
// The page it would have been, composed from the single reads, is past the budget.
let would_be = ForkList { forks: (1..=fits).rev().map(|n| entry(over.desk_fork(&s(LIST[0]), &list(&LIST), &fork(n))).0).collect(), next_cursor: None, ..moved.clone() };
let would_be = ForkList { forks: (1..=fits).rev().map(|n| entry(over.desk_fork(&account(LIST[0]), &list(&LIST), &fork(n))).0).collect(), next_cursor: None, ..moved.clone() };
assert!(bare(&DeskResponse::Forks { list: would_be, as_of: head(&over) }) > DESK_PAGE_BUDGET);
assert_eq!(moved.next_cursor.map(ForkCursor::order), moved.forks.last().map(|entry| entry.card.order));
let (rest, _) = page(over.desk_forks(&s(LIST[0]), &list(&LIST), None, moved.next_cursor, limit(50)));
let (rest, _) = page(over.desk_forks(&account(LIST[0]), &list(&LIST), None, moved.next_cursor, limit(50)));
assert_eq!(ids(&rest), [fork(1)]);
}
@ -1437,7 +1682,7 @@ mod tests {
let hash = hash_of(mind, &fork(n));
let note = "a long reason, ".repeat(60);
let mut added = 0;
while bare(&mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(n))) <= bytes {
while bare(&mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(n))) <= bytes {
let DeskResponse::Answered { .. } = answer(mind, "x", &LIST, &fork(n), &hash, Some(&note)) else { panic!("the note was not stored") };
added += 1;
assert!(added < 200, "the record does not grow");
@ -1457,18 +1702,18 @@ mod tests {
let mut mind = desk(3);
grown_past(&mut mind, 2, DESK_PAGE_BUDGET);
// The newest fork pages alone: the oversize one would bust the page beside it.
let (first, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(50)));
let (first, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(50)));
assert_eq!(ids(&first), [fork(3)]);
assert_eq!(first.next_cursor.map(ForkCursor::order), Some(2));
let response = mind.desk_forks(&s(LIST[0]), &list(&LIST), None, first.next_cursor, limit(50));
let response = mind.desk_forks(&account(LIST[0]), &list(&LIST), None, first.next_cursor, limit(50));
let DeskResponse::NotStored(refusal) = response else { panic!("{response:?}") };
assert_eq!(refusal.code, ForkRefusalCode::ForkTooLarge);
let order = 1;
assert_eq!(refusal.error, fork_too_large(&fork(2), order).error);
assert!(refusal.error.contains(&fork(2)) && refusal.error.contains("order 1"), "{refusal:?}");
// The order the refusal names is the order of the fork it names; its cursor goes on past it.
assert_eq!(entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(2))).0.card.order, order);
let (rest, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, ForkCursor::new(order), limit(50)));
assert_eq!(entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(2))).0.card.order, order);
let (rest, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, ForkCursor::new(order), limit(50)));
assert_eq!((ids(&rest), rest.next_cursor), (vec![fork(1)], None));
}
@ -1499,13 +1744,13 @@ mod tests {
fn a_rank_is_stable_when_more_questions_are_admitted() {
let mut mind = seeded();
committed(admit(&mut mind, (1..=5).map(question_n).collect()));
let (first, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(2)));
let (first, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(2)));
assert_eq!((orders(&first), first.next_cursor.map(ForkCursor::order)), (vec![4, 3], Some(3)));
let held = first.next_cursor;
let (before, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, held, limit(50)));
let (before, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, held, limit(50)));
committed(admit(&mut mind, vec![question_n(6)]));
committed(admit(&mut mind, vec![question_n(0)]));
let (after, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, held, limit(50)));
let (after, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, held, limit(50)));
assert_eq!((after.forks, after.next_cursor), (before.forks, before.next_cursor), "the cursor from before resumes the same forks");
let everything = all(&mind, 50);
assert_eq!(ids(&everything), [fork(0), fork(6), fork(5), fork(4), fork(3), fork(2), fork(1)]);
@ -1534,9 +1779,9 @@ mod tests {
admit_unshowable(&mut mind, "Q2");
committed(admit(&mut mind, vec![question_n(3)]));
for who in [&LIST[..], &["x"][..], &["z"][..]] {
let (shown, _) = page(mind.desk_forks(&s(LIST[0]), &list(who), None, None, limit(50)));
let (shown, _) = page(mind.desk_forks(&account(who[0]), &list(who), None, None, limit(50)));
assert_eq!((ids(&shown), orders(&shown)), (vec![fork(3), fork(1)], vec![2, 0]), "{who:?}: rank 1 is the gap");
assert_eq!(entry(mind.desk_fork(&s(LIST[0]), &list(who), &fork(3))).0.card.order, 2, "{who:?}");
assert_eq!(entry(mind.desk_fork(&account(who[0]), &list(who), &fork(3))).0.card.order, 2, "{who:?}");
}
committed(admit(&mut mind, vec![question_n(4)]));
assert_eq!(orders(&all(&mind, 50)), [3, 2, 0]);
@ -1549,11 +1794,11 @@ mod tests {
let mut mind = desk(2);
for n in [1, 2] {
grown_past(&mut mind, n, DESK_PAGE_BUDGET * 55 / 100);
assert!(bare(&mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(n))) <= DESK_PAGE_BUDGET, "each fork alone fits");
assert!(bare(&mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(n))) <= DESK_PAGE_BUDGET, "each fork alone fits");
}
let (one, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, None, limit(50)));
let (one, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, None, limit(50)));
assert_eq!((ids(&one), one.next_cursor.map(ForkCursor::order)), (vec![fork(2)], Some(1)));
let (rest, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, one.next_cursor, limit(50)));
let (rest, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, one.next_cursor, limit(50)));
assert_eq!((ids(&rest), rest.next_cursor), (vec![fork(1)], None));
}
@ -1584,9 +1829,9 @@ mod tests {
assert_eq!(after.len(), 70);
assert_eq!(after.iter().map(|(_, order)| *order).collect::<std::collections::BTreeSet<_>>(), (0..70).collect());
// The page boundary at c1: the page ending at order 1 names c1, and the next page is order 0 alone.
let (upper, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, ForkCursor::new(3), limit(2)));
let (upper, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, ForkCursor::new(3), limit(2)));
assert_eq!((orders(&upper), upper.next_cursor.map(ForkCursor::order)), (vec![2, 1], Some(1)));
let (last, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), None, upper.next_cursor, limit(50)));
let (last, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), None, upper.next_cursor, limit(50)));
assert_eq!((orders(&last), last.next_cursor), (vec![0], None));
}
@ -1670,7 +1915,7 @@ mod tests {
let mut mind = desk(3);
close(&mut mind, &fork(1), "R9");
close(&mut mind, &fork(2), "R2");
let named = |n: u32| entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(n))).0.card.ruling;
let named = |n: u32| entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(n))).0.card.ruling;
assert_eq!(named(1).as_deref(), Some("eureka-state:ruling:R9"));
assert_eq!(named(2).as_deref(), Some("eureka-state:ruling:R2"));
assert_eq!(named(3), None);
@ -1721,6 +1966,9 @@ mod tests {
}
for (order, entry) in &held {
let key = fork(*order as u32);
if scenario.get("twin").is_some() {
list_it(&mut mind, *order as u32);
}
let answers = entry["record"]["answers"].as_array().unwrap();
let hash = hash_of(&mind, &key);
if !answers.is_empty() {
@ -1741,7 +1989,7 @@ mod tests {
answered_at: "2026-09-16T11:00:00Z".into(),
request_id: request_id(),
};
mind.desk_answer(&list(&LIST), s("x"), DeskAuthority::Member, retraction, now());
mind.desk_answer(&list(&LIST), account("x"), DeskAuthority::Member, retraction, now());
} else {
answer(&mut mind, "y", &LIST, &key, &hash, None);
}
@ -1753,7 +2001,7 @@ mod tests {
let (request, want) = (&step["request"], &step["response"]);
let status: Option<ListStatus> = serde_json::from_value(request["status"].clone()).unwrap();
let cursor: Option<ForkCursor> = serde_json::from_value(request["cursor"].clone()).unwrap();
let (got, _) = page(mind.desk_forks(&s(subject), &list(&["x"]), status, cursor, limit(request["limit"].as_u64().unwrap() as u8)));
let (got, _) = page(mind.desk_forks(&account(subject), &list(&["x"]), status, cursor, limit(request["limit"].as_u64().unwrap() as u8)));
let name = &scenario["name"];
assert_eq!((got.open_count, got.recorded_count), (want["open_count"].as_u64().unwrap(), want["recorded_count"].as_u64().unwrap()), "{name}");
assert_eq!(serde_json::to_value(got.next_cursor).unwrap(), want["next_cursor"], "{name}");
@ -1802,7 +2050,7 @@ mod tests {
// Every third fork is closed; the batch's ranks follow its keys, so the closed ranks are read, not computed.
let mut closed = std::collections::BTreeSet::new();
for n in (1..=24).step_by(3) {
closed.insert(entry(mind.desk_fork(&s(LIST[0]), &list(&LIST), &fork(n))).0.card.order);
closed.insert(entry(mind.desk_fork(&account(LIST[0]), &list(&LIST), &fork(n))).0.card.order);
close(&mut mind, &fork(n), &format!("R{n}"));
}
for status in [None, Some(ListStatus::Open), Some(ListStatus::Recorded)] {
@ -1815,7 +2063,7 @@ mod tests {
for size in 1..=24_u8 {
let (mut cursor, mut walked, mut pages) = (None, Vec::new(), 0);
loop {
let (page, _) = page(mind.desk_forks(&s(LIST[0]), &list(&LIST), status, cursor, limit(size)));
let (page, _) = page(mind.desk_forks(&account(LIST[0]), &list(&LIST), status, cursor, limit(size)));
pages += 1;
assert!(page.forks.len() <= size as usize && pages < 100);
walked.extend(orders(&page));

View file

@ -401,7 +401,8 @@ pub(crate) fn line_of(document: &PipelineDocument) -> Option<Lineage<'_>> {
| D::Pulse(_)
| D::Reply(_)
| D::Thought(_)
| D::DeskAnswer(_) => None,
| D::DeskAnswer(_)
| D::DeskListing(_) => None,
}
}
@ -455,10 +456,11 @@ pub enum CitationRole {
DayThrough,
Fork,
Answer,
Listed,
}
impl CitationRole {
pub const ALL: [CitationRole; 26] = [
pub const ALL: [CitationRole; 27] = [
Self::RaisedIn,
Self::Answers,
Self::Rulings,
@ -485,6 +487,7 @@ impl CitationRole {
Self::DayThrough,
Self::Fork,
Self::Answer,
Self::Listed,
];
/// The wire spelling, equal to the referring field's name.
@ -516,6 +519,7 @@ impl CitationRole {
Self::DayThrough => "day_through",
Self::Fork => "fork",
Self::Answer => "answer",
Self::Listed => "listed",
}
}
@ -543,6 +547,7 @@ impl CitationRole {
Self::Run => K::Reply,
Self::Reads => K::Thought,
Self::Fork | Self::Answer => K::DeskAnswer,
Self::Listed => K::DeskListing,
}
}
@ -552,7 +557,7 @@ impl CitationRole {
pub fn target_kinds(self) -> Vec<PipelineKind> {
use PipelineKind as K;
match self {
Self::Answers | Self::Questions | Self::Forks | Self::Fork => vec![K::Question],
Self::Answers | Self::Questions | Self::Forks | Self::Fork | Self::Listed => vec![K::Question],
Self::Rulings => vec![K::Ruling],
Self::CutSpec => vec![K::CutSpec],
Self::CutReport => vec![K::CutReport],
@ -670,6 +675,7 @@ pub(crate) fn citations(document: &PipelineDocument) -> Vec<(CitationRole, Pipel
DeskOutcome::Counted | DeskOutcome::Refused { .. } => {}
}
}
D::DeskListing(listing) => edges.push((R::Listed, cited(K::Question, &listing.listed))),
D::Campaign(_) | D::Target(_) | D::Instance(_) | D::Stewardship(_) | D::Pulse(_) => {}
}
edges

View file

@ -408,9 +408,9 @@ mod tests {
fn desk_answer() -> DeskRequest {
DeskRequest::Answer {
mind: slug(INSTANCE),
subject: crate::fixtures::s("user-7"),
subject: crate::fixtures::acct("user-7"),
authority: DeskAuthority::Member,
deciders: vec![crate::fixtures::s("user-7")],
deciders: vec![crate::fixtures::acct("user-7")],
request: ForkAnswerRequest {
schema_version: crate::desk_wire::RequestSchema::V0,
fork_id: "eureka-state:question:Q1".into(),
@ -425,7 +425,7 @@ mod tests {
}
fn desk_requests() -> [(DeskRequest, &'static str); 3] {
let (mind, subject, deciders) = (slug(INSTANCE), crate::fixtures::s("user-7"), vec![crate::fixtures::s("user-7")]);
let (mind, subject, deciders) = (slug(INSTANCE), crate::fixtures::acct("user-7"), vec![crate::fixtures::acct("user-7")]);
[
(desk_answer(), "Answer"),
(DeskRequest::Forks { mind: mind.clone(), subject: subject.clone(), deciders: deciders.clone(), status: Some(crate::desk_wire::ListStatus::Open), cursor: crate::desk_wire::ForkCursor::new(7), limit: crate::desk_wire::ForkLimit::new(50).unwrap() }, "Forks"),
@ -579,13 +579,13 @@ mod tests {
fn a_maximal_desk_message_fits_the_frame() {
let long = |n: usize| "x".repeat(n);
let wire = |message: &CultNetMessage| encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0).unwrap().len();
let deciders: Vec<_> = (0..64).map(|at| crate::fixtures::s(&format!("{at:0>200}"))).collect();
let deciders: Vec<_> = (0..64).map(|at| crate::fixtures::acct(&format!("decider {at}"))).collect();
let mut sized = vec![];
for (request, _) in desk_requests() {
let widest = match request {
DeskRequest::Answer { mind, request, authority, .. } => DeskRequest::Answer {
mind,
subject: crate::fixtures::s(&long(200)),
subject: crate::fixtures::acct("the widest subject"),
authority,
deciders: deciders.clone(),
request: ForkAnswerRequest {
@ -596,10 +596,10 @@ mod tests {
},
},
DeskRequest::Forks { mind, status, cursor, limit, .. } => {
DeskRequest::Forks { mind, subject: crate::fixtures::s(&long(200)), deciders: deciders.clone(), status, cursor, limit }
DeskRequest::Forks { mind, subject: crate::fixtures::acct("the widest subject"), deciders: deciders.clone(), status, cursor, limit }
}
DeskRequest::Fork { mind, .. } => {
DeskRequest::Fork { mind, subject: crate::fixtures::s(&long(200)), deciders: deciders.clone(), fork_id: long(200) }
DeskRequest::Fork { mind, subject: crate::fixtures::acct("the widest subject"), deciders: deciders.clone(), fork_id: long(200) }
}
};
let message = encode_desk_request("m-10", &widest, Some(long(200))).unwrap();
@ -607,7 +607,8 @@ mod tests {
sized.push(wire(&message));
}
assert!(sized.iter().all(|size| *size <= DESK_MAX_REQUEST_BYTES), "{sized:?} against {DESK_MAX_REQUEST_BYTES}");
assert!(sized[0] > DESK_MAX_REQUEST_BYTES / 4, "the test builds a request that is actually large: {sized:?}");
// 64 account ids of 36 bytes and a 4,000-byte note: the widest answer a request can carry.
assert!(sized[0] > 4000 + 64 * 36, "the test builds a request that is actually large: {sized:?}");
let answer = ForkDeskAnswer {
schema_version: crate::desk_wire::AnswerSchema::V0,

View file

@ -56,6 +56,21 @@ pub(crate) fn s(value: &str) -> Short {
value.into()
}
/// A deterministic Bifrost account id for a test's name for someone: a lowercase D-format UUID.
pub(crate) fn account(name: &str) -> Short {
// An id already in account form stands for itself.
if name.len() == 36 && name.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f' | b'-')) {
return Short(name.into());
}
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
Short(format!("{:08x}-{:04x}-4000-8000-{:012x}", hash >> 32, (hash >> 16) & 0xffff, hash & 0xffff_ffff_ffff))
}
/// The same, as the stored type.
pub(crate) fn acct(name: &str) -> eureka_pipeline::AccountId {
eureka_pipeline::AccountId(account(name).0)
}
pub(crate) fn l(value: &str) -> Label {
value.into()
}

View file

@ -150,7 +150,7 @@ mod tests {
fn view(document: PipelineDocument, ordinal: u64) -> PipelineDocumentView {
let key = pipeline_key(&document).unwrap();
let id = PipelineRef { kind: document.kind(), id: s(&key) };
let faculty = if ordinal % 2 == 0 { Faculty::Hands } else { Faculty::Soul };
let faculty = if ordinal.is_multiple_of(2) { Faculty::Hands } else { Faculty::Soul };
let admission = AdmissionFacts {
receipt_id: format!("receipt-{ordinal}"),
admitted_at: format!("2026-11-08T16:{ordinal:02}:00Z"),
@ -226,7 +226,7 @@ mod tests {
let to_source = [held.clone(), vec![moved(RECEIVER, 4)]].concat();
assert_eq!(plan(&slug(CAMPAIGN), &slug(RECEIVER), &slug(RECEIVER), to_source), Err(ImportFault::SourceIsReceiver));
let other_root = view(
resolution(r(K::Campaign, &format!("elsewhere:campaign:self")), ResolutionOutcome::Moved { to: slug(RECEIVER) }),
resolution(r(K::Campaign, "elsewhere:campaign:self"), ResolutionOutcome::Moved { to: slug(RECEIVER) }),
4,
);
assert_eq!(plan_of([held, vec![other_root]].concat()), Err(ImportFault::NotMoved), "another root's move does not move this one");

View file

@ -105,8 +105,8 @@ pub fn index_text(document: &PipelineDocument) -> Option<String> {
lines.push(&idea.idea.0);
lines.push(&idea.tradeoffs.0);
}
// A desk answer is a person's words, not indexed.
D::Instance(_) | D::Stewardship(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::DeskAnswer(_) => {}
// A desk answer is a person's words and a listing's reason is no retrieval text: neither is indexed.
D::Instance(_) | D::Stewardship(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::DeskAnswer(_) | D::DeskListing(_) => {}
}
lines.retain(|line| !line.is_empty());
if lines.is_empty() {

View file

@ -663,7 +663,6 @@ fn an_import_never_cites_or_resolves_a_follow_up_the_receiver_wrote() {
let native = follow_up("FU-N", r(K::Question, &q1));
let native_ref = r(K::FollowUp, &pipeline_key(&native).unwrap());
committed(admit(&mut recv, vec![native]));
let before = head(&recv);
// An imported record that withdraws the receiver's own follow-up mixes a replay into her work.
assert_eq!(
refusal(import_from_kiko(&mut recv, vec![resolution(native_ref.clone(), ResolutionOutcome::Withdrawn { reason: "x".into() })])),

View file

@ -92,7 +92,7 @@ fn declared_names(node: &Value, names: &mut BTreeSet<String>) {
/// Rule 1: the document is valid against the published schema. The first
/// failure is the refusal; it names where and which keyword, never the value.
pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
let compiled = compiled()?;
let Err(error) = compiled.validator.validate(state) else { return Ok(()) };
let mut path = error
@ -115,6 +115,21 @@ pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
})
}
/// Rules P1 to P3 of a put, the ones that read the document alone: it is valid against the published schema (P1), it is
/// this mind's (`personaId` is `instance`, P2), and its provenance is canonical (P3). A put applies these first and then
/// the rules that read the store; a reader of a state file outside the mind (`mind-persona project --state`) applies
/// these and nothing else, so a file it accepts is one a put would not refuse for its content.
pub fn validate_document(instance: &Slug, state: &Value) -> Result<(), MindRefusal> {
validate_shape(state)?;
if state.get("personaId").and_then(Value::as_str) != Some(instance.0.as_str()) {
return Err(MindRefusal::PersonaForeign { instance: instance.0.clone() });
}
if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") {
return Err(MindRefusal::PersonaNotCanonical);
}
Ok(())
}
/// A stored persona envelope's document.
pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result<Value, MindRefusal> {
rmp_serde::from_slice::<HuginnPersonaEntry>(&envelope.payload)
@ -264,6 +279,50 @@ mod tests {
}
}
/// Map 16.6: `embodiment` is optional. A document passes with it and without it, and the field is as closed as the
/// rest of the schema: an unknown key inside it is refused at the door.
#[test]
fn embodiment_is_optional_and_closed() {
let schema = schema_file();
let validator = jsonschema::draft7::new(&schema).unwrap();
let sense = json!({
"id": "sense-spectrogram", "status": "active", "label": "spectrogram hearing",
"summary": "She hears by rendering a sound as a spectrogram and looking at it.",
"lacks": "not a human ear", "builtOn": T1, "updatedAt": T1
});
let mut with = persona(INSTANCE, T1);
with["embodiment"] = json!({ "senses": [sense.clone()], "actuators": [] });
assert!(validator.is_valid(&persona(INSTANCE, T1)) && validator.is_valid(&with));
let mut empty = persona(INSTANCE, T1);
empty["embodiment"] = json!({});
assert!(validator.is_valid(&empty), "both lists are optional");
let store = MemoryStore::new();
let mut mind = seeded_over(&store);
let mut stray = with.clone();
stray["embodiment"]["senses"][0]["ears"] = json!("human");
assert_eq!(refused(put(&mut mind, stray, None)), invalid("/embodiment/senses/0/*", "additionalProperties"));
let mut stray_list = with.clone();
stray_list["embodiment"]["smell"] = json!([]);
assert_eq!(refused(put(&mut mind, stray_list, None)), invalid("/embodiment/*", "additionalProperties"));
let mut unlabelled = with;
unlabelled["embodiment"]["senses"][0].as_object_mut().unwrap().remove("label");
assert_eq!(refused(put(&mut mind, unlabelled, None)), invalid("/embodiment/senses/0/label", "required"));
}
/// Map 16.35.9 (T1, T2): a hold and a promise are not her state. A put carrying either old field, even empty, is
/// is refused at the door. The names are assembled, so a scan for the old fields finds no writer of them.
#[test]
fn holds_and_promises_are_not_her_state() {
for field in [concat!("hol", "ds"), concat!("commit", "ments")] {
let store = MemoryStore::new();
let mut mind = seeded_over(&store);
let mut with = persona(INSTANCE, T1);
with[field] = json!([]);
assert_eq!(refused(put(&mut mind, with, None)), invalid("/*", "additionalProperties"), "{field}");
}
}
#[test]
fn declared_names_are_every_property_name_at_any_depth() {
let schema = json!({

View file

@ -166,6 +166,8 @@ pub enum PipelineFacts {
/// the one that counts for its fork at the read's snapshot, derived by `counted_answer` and never
/// stored: a retracted `Counted` answer reads `counts: false`, the promoted next answer `true`.
DeskAnswer { fork: Short, sequence: u32, outcome: Short, counts: bool, authority: DeskAuthority },
/// The question this listing lets members read.
DeskListing { listed: Short },
}
impl PipelineFacts {
@ -306,6 +308,7 @@ impl PipelineFacts {
counts: counted_of(&value.fork.0).as_deref() == Some(id.id.0.as_str()),
authority: value.authority,
},
D::DeskListing(value) => Self::DeskListing { listed: value.listed.clone() },
}
}
}
@ -1849,7 +1852,7 @@ mod tests {
// Two desk answers on the open fork Q2: the second is a Revision of the first.
let D::Question(shown) = question("Q2", &["A", "B"], "A") else { unreachable!() };
let stamp = crate::desk::DeskStamp { answerer: s("x"), authority: eureka_pipeline::DeskAuthority::Member, deciders: vec![s("x")] };
let stamp = crate::desk::DeskStamp { answerer: crate::fixtures::account("x"), authority: eureka_pipeline::DeskAuthority::Member, deciders: vec![crate::fixtures::account("x")] };
let pick = |n: u32| crate::desk::DeskAnswerRequest {
fork: s(&q2),
options_hash: crate::desk::options_hash(&shown),
@ -1862,6 +1865,10 @@ mod tests {
assert!(matches!(mind.answer_desk(stamp.clone(), pick(n), now()), crate::desk::DeskAnswerOutcome::Stored { .. }));
}
// The Mind lists Q2: one `listed` edge.
committed(admit(&mut mind, vec![D::DeskListing(eureka_pipeline::PipelineDeskListing { campaign: slug(CAMPAIGN), listed: s(&q2), reason: "Members may read why.".into() })]));
let listing = id("desk_listing", "Q2");
let (n1, f1_closed, f2_closed) = (
id("resolution", "question.Q1.n1"),
id("resolution", &format!("finding.{}.n1", f1.rsplit(':').next().unwrap())),
@ -1910,8 +1917,9 @@ mod tests {
(CitationRole::Fork, &answer_1, &q2),
(CitationRole::Fork, &answer_2, &q2),
(CitationRole::Answer, &answer_2, &answer_1),
(CitationRole::Listed, &listing, &q2),
];
assert_eq!(CitationRole::ALL.len(), 26);
assert_eq!(CitationRole::ALL.len(), 27);
for role in CitationRole::ALL {
let selection =
Selection { cited: Some(Incoming { role: role.name().into(), exists: true }), ..Selection::default() };
@ -2784,13 +2792,16 @@ mod tests {
/// The upgrade gate on a real store (ruling readback-gate-and-materialized-image):
/// the one function `Mind::read_back` over a scratch copy of a state root.
/// Opens the store read-write, so run it on a copy, never the live file.
/// Measured about 30 s in debug at 11,328 documents.
/// `HUGINN_MIND_INSTANCE` names the instance whose store it opens, `eureka`
/// when unset, so every Mind's store is gated the same way before a release
/// moves her daemon. Measured about 30 s in debug at 11,328 documents.
#[test]
#[ignore = "needs HUGINN_MIND_SNAPSHOT, a scratch copy of a Huginn state root"]
fn stored_documents_read_back() {
let root = std::env::var("HUGINN_MIND_SNAPSHOT").expect("HUGINN_MIND_SNAPSHOT names a scratch copy of the state root");
let instance = std::env::var("HUGINN_MIND_INSTANCE").unwrap_or_else(|_| "eureka".into());
let started = std::time::Instant::now();
let mind = Mind::open(std::path::Path::new(&root), &Slug("eureka".into())).unwrap();
let mind = Mind::open(std::path::Path::new(&root), &Slug(instance)).unwrap();
let count = mind.read_back().unwrap();
println!("read back {count} stored documents in {:?}", started.elapsed());
}

View file

@ -330,13 +330,13 @@ impl CacheBackingStore for LandsThenFails {
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
self.inner.pull_all()
}
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
self.inner.push(entry)
}
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
self.inner.delete(entry)
}
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<Vec<String>> {
self.inner.push_all(entries, options)
}
}
@ -547,13 +547,13 @@ impl CacheBackingStore for FailsTheLook {
}
self.inner.pull_all()
}
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
self.inner.push(entry)
}
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
self.inner.delete(entry)
}
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<Vec<String>> {
self.inner.push_all(entries, options)
}
}

View file

@ -374,7 +374,7 @@ mod tests {
self.inner.pull_all()
}
fn push(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<()> {
fn push(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<String> {
self.inner.push(entry)
}
@ -382,7 +382,7 @@ mod tests {
self.inner.delete(entry)
}
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> anyhow::Result<()> {
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> anyhow::Result<Vec<String>> {
self.inner.push_all(entries, options)
}
}

View file

@ -1,13 +1,11 @@
//! Credential redaction: the only code that knows the shape of a secret in text.
//!
//! `redact_url_userinfo` redacts URL credentials (the Self run's journal and reply,
//! the Persona's structured output). `scrub` is chat ingest's door: every message body
//! `redact_url_userinfo` redacts URL credentials (the Self run's journal and reply). `scrub` is chat ingest's door: every message body
//! passes it before it is chunked, embedded or stored, and it also runs the URL rule.
//! Shapes only; nothing here reads meaning, and a hit is a kind, never a value.
/// The one redaction of URL credentials. Call it at each place a string the CLI produced enters the journal, her mind or chat: today
/// the Self result (`result_text`: journal line and Reply) and the structured output of a Persona or Sleep result
/// (`persona::structured_output`, string by string). It does not cover claude's stderr (inherited) or the CLI's transcript files.
/// the Self result (`result_text`: journal line and Reply). It does not cover claude's stderr (inherited) or the CLI's transcript files.
///
/// A forge token rides in a remote URL, so every `scheme://` and every protocol-relative `//` opens an authority, read as git, curl and
/// RFC 3986 read it: it ends at the first `/`, `?`, `#`, backslash, quote, backtick, parenthesis, bracket, angle bracket or ASCII whitespace
@ -159,7 +157,7 @@ fn zero_width(c: char) -> bool {
pub fn scrub(text: &str) -> Scrubbed {
let mut hits = Vec::new();
let mut stripped: String = text.chars().filter(|c| !zero_width(*c)).collect();
let passes: [(ScrubKind, fn(&str, usize) -> Option<usize>); 6] = [
let passes: [(ScrubKind, Finder); 6] = [
(ScrubKind::PemBlock, pem_block),
(ScrubKind::AuthorizationHeader, authorization_line),
(ScrubKind::AccessToken, access_token),
@ -176,7 +174,10 @@ pub fn scrub(text: &str) -> Scrubbed {
if hits.is_empty() { Scrubbed { text: text.to_owned(), hits } } else { Scrubbed { text: urls, hits } }
}
fn replace_matches(text: &str, kind: ScrubKind, find: fn(&str, usize) -> Option<usize>, hits: &mut Vec<ScrubKind>) -> String {
/// A scrub pass: finds the end of one secret starting at a byte offset, if one starts there.
type Finder = fn(&str, usize) -> Option<usize>;
fn replace_matches(text: &str, kind: ScrubKind, find: Finder, hits: &mut Vec<ScrubKind>) -> String {
let mut out = String::with_capacity(text.len());
let mut at = 0;
while at < text.len() {
@ -463,7 +464,7 @@ mod tests {
"123e4567-e89b-12d3-a456-426614174000", "!abc:s", "$Ab3dEf-9_zQ", "user@example.com", "ssh://git@host/r.git",
"https://github.com/@user", "pkg@1.2.3", "the bearer of bad news", "Authorization is a header",
"padding like dGVzdA== in prose", "```\nlet x = 1;\n```", "the BEGIN PRIVATE KEY header", "a token of thanks",
"AKIAshort", "ghp_short", "eyJ is a prefix", "naïve café — 日本語 with Bearer in it",
"AKIAshort", "ghp_short", "eyJ is a prefix", "naïve café — 日本語 with Bearer in it",
] {
let out = scrub(same);
assert_eq!(out.text, same);
@ -473,9 +474,9 @@ mod tests {
#[test]
fn multibyte_text_around_a_secret_never_panics_the_scrub() {
let body = format!("日本 \u{a0}é Bearer {} → ünï", "A1b2".repeat(6));
assert_eq!(scrub(&body).text, "日本 \u{a0}é <redacted> → ünï");
let seed = "é日 sk-aaaaaaaaaaaaaaaaaaaa -----BEGIN PRIVATE KEY----- authorization: é eyJa.b.c https://u:p@h/x";
let body = format!("日本 \u{a0}é Bearer {} → ünï", "A1b2".repeat(6));
assert_eq!(scrub(&body).text, "日本 \u{a0}é <redacted> → ünï");
let seed = "é日 sk-aaaaaaaaaaaaaaaaaaaa -----BEGIN PRIVATE KEY----- authorization: é eyJa.b.c https://u:p@h/x";
let chars: Vec<char> = seed.chars().collect();
for start in 0..chars.len() {
for end in start..=chars.len() {

View file

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

View file

@ -248,7 +248,7 @@ impl SelectionRow {
D::Stewardship(stewardship) => vec![stewardship.repo.identity()],
D::HandOff(hand_off) => vec![hand_off.repo.identity()],
D::Ruling(PipelineRuling { authority: RulingAuthority::Steward { repo, .. }, .. }) => vec![repo.identity()],
D::Target(_) | D::Question(_) | D::Ruling(_) | D::Verdict(_) | D::Finding(_) | D::Instance(_) | D::Resolution(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::Thought(_) | D::Memory(_) | D::Research(_) | D::Idea(_) | D::DeskAnswer(_) => {
D::Target(_) | D::Question(_) | D::Ruling(_) | D::Verdict(_) | D::Finding(_) | D::Instance(_) | D::Resolution(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::Thought(_) | D::Memory(_) | D::Research(_) | D::Idea(_) | D::DeskAnswer(_) | D::DeskListing(_) => {
Vec::new()
}
},
@ -466,7 +466,7 @@ mod tests {
/// refused at the substrate's door.
#[test]
fn each_kind_declares_exactly_its_aliases_and_none_is_numeric() {
let table: [(K, &[&str]); 21] = [
let table: [(K, &[&str]); 22] = [
(K::Campaign, &["repo"]),
(K::Target, &[]),
(K::Question, &[]),
@ -488,6 +488,7 @@ mod tests {
(K::Reply, &[]),
(K::Thought, &[]),
(K::DeskAnswer, &[]),
(K::DeskListing, &[]),
];
for (kind, extra) in table {
let want = [&["root", "in_force", "faculty"][..], extra].concat();
@ -503,7 +504,7 @@ mod tests {
/// twenty-one.
#[test]
fn each_kind_declares_the_roles_it_carries_and_their_targets() {
let table: [(K, &[&str]); 21] = [
let table: [(K, &[&str]); 22] = [
(K::Campaign, &[]),
(K::Target, &[]),
(K::Question, &["raised_in"]),
@ -525,13 +526,14 @@ mod tests {
(K::Reply, &["run"]),
(K::Thought, &["reads"]),
(K::DeskAnswer, &["fork", "answer"]),
(K::DeskListing, &["listed"]),
];
for (kind, roles) in table {
assert_eq!(sorted(Vocabulary.declared_roles(kind.type_id())), strings(roles), "{kind:?}");
}
assert_eq!(Vocabulary.target_leaves("answers"), vec![K::Question.type_id().to_string()]);
assert_eq!(Vocabulary.target_leaves("rulings"), vec![K::Ruling.type_id().to_string()]);
assert_eq!(Vocabulary.target_leaves("subject").len(), 21);
assert_eq!(Vocabulary.target_leaves("subject").len(), 22);
assert_eq!(
sorted(Vocabulary.target_leaves("claims")),
sorted([K::CutSpec, K::Finding, K::FollowUp].iter().map(|kind| kind.type_id().to_string()).collect())

View file

@ -116,9 +116,9 @@ pub(crate) mod test_stores {
Ok(self.rows())
}
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
self.plant(entry.clone());
Ok(())
Ok(entry.stored_at.clone())
}
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
@ -126,9 +126,9 @@ pub(crate) mod test_stores {
Ok(())
}
fn push_all(&mut self, entries: &[CultCacheEnvelope], _options: PushAllOptions) -> Result<()> {
fn push_all(&mut self, entries: &[CultCacheEnvelope], _options: PushAllOptions) -> Result<Vec<String>> {
*self.rows.lock().unwrap() = entries.iter().map(|entry| (identity(entry), entry.clone())).collect();
Ok(())
Ok(entries.iter().map(|entry| entry.stored_at.clone()).collect())
}
}
@ -199,7 +199,7 @@ pub(crate) mod test_stores {
self.inner.pull_all()
}
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
self.inner.push(entry)
}
@ -207,7 +207,7 @@ pub(crate) mod test_stores {
self.inner.delete(entry)
}
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<Vec<String>> {
self.inner.push_all(entries, options)
}
}

View file

@ -286,8 +286,9 @@ pub const CHAT_ROOMS_MAX: usize = 16;
/// [after, before]. `texts` (none to `SOURCE_TEXTS_MAX`) is the meaning match,
/// several fused as in a source search; with none the search is a listing:
/// chunks oldest first, at most `top_k`, `ChatHits.truncated` saying more
/// exist, and the caller narrows with `after_ms` = the last hit's
/// `ts_end_ms + 1`.
/// exist. Within one room the caller narrows with `after_ms` = the last hit's
/// `ts_end_ms + 1`; across rooms spans overlap and that loses chunks, so list
/// one room at a time.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ChatQuery {
pub texts: Vec<Line>,
@ -429,6 +430,28 @@ impl HuginnMindRequest {
}
}
/// Whether the persona door answers this request. The persona door is the
/// daemon's second listener, the only one a Persona's uid can reach: it
/// serves the mind's reads and her own persona document, and refuses
/// every write to the mind (`MindRefusal::NotThisDoor`). The match has no
/// wildcard, so a new request does not compile until it is classified
/// here.
pub fn reaches_persona_door(&self) -> bool {
match self {
Self::Whoami
| Self::View { .. }
| Self::Query { .. }
| Self::PersonaGet { .. }
| Self::PersonaPut { .. }
| Self::SearchSources { .. }
| Self::SearchChat { .. }
| Self::ChatWindow { .. }
| Self::StewardedActivity { .. }
| Self::RootsTouched { .. } => true,
Self::Admit(_) => false,
}
}
/// The instance the request declares; `Whoami` declares none.
pub fn instance(&self) -> Option<&Slug> {
match self {
@ -632,6 +655,7 @@ mod tests {
scores: Some(vec![0.5]),
}),
HuginnMindResponse::Refused(refusal),
HuginnMindResponse::Refused(MindRefusal::NotThisDoor),
HuginnMindResponse::Persona(None),
HuginnMindResponse::Persona(Some(PersonaStateView {
value: serde_json::json!({ "personaId": INSTANCE }),

View file

@ -21,8 +21,8 @@ use huginn_mind::desk_wire::{
fork_too_large_read, AnswerSchema, CardSchema, CardStatus, DeskRequest, DeskResponse, EntrySchema, ForkCard, ForkCursor, ForkDeskAnswer, ForkEntry, ForkLimit,
ForkList, ForkOption, ForkRecord, ForkRefusal, ForkRefusalCode, ForkRef, ListSchema, ListStatus, RecordSchema,
};
use huginn_mind::envelope::{OperationFailure, encode_desk_failure, encode_desk_request, encode_desk_response};
use huginn_mind::eureka_pipeline::{DeskAuthority, Short, Slug};
use huginn_mind::envelope::{OperationFailure, decode_desk_request, encode_desk_failure, encode_desk_request, encode_desk_response};
use huginn_mind::eureka_pipeline::{AccountId, DeskAuthority, Slug};
const RUNTIME: &str = "huginn-eureka";
/// Account ids as Bifrost sends them: `UserAccount.Id` rendered lowercase D-format
@ -38,15 +38,15 @@ const NON_DECIDER: &str = "9e8d7c6b-5a49-4382-b1a0-f9e8d7c6b5a4";
/// synthetic: the hash is CultLib's sample digest, not this question's.
const FORK: &str = "eureka-substrate:question:desk-listing-authority";
fn s(text: &str) -> Short {
Short(text.into())
fn a(text: &str) -> AccountId {
AccountId(text.into())
}
fn forks(status: Option<ListStatus>, cursor: Option<u64>, limit: u8) -> DeskRequest {
DeskRequest::Forks {
mind: Slug("eureka".into()),
subject: s(READER),
deciders: vec![s(READER), s(OTHER_DECIDER)],
subject: a(READER),
deciders: vec![a(READER), a(OTHER_DECIDER)],
status,
cursor: cursor.and_then(ForkCursor::new),
limit: ForkLimit::new(limit).unwrap(),
@ -54,15 +54,15 @@ fn forks(status: Option<ListStatus>, cursor: Option<u64>, limit: u8) -> DeskRequ
}
fn read() -> DeskRequest {
DeskRequest::Fork { mind: Slug("eureka".into()), subject: s(READER), deciders: vec![s(READER), s(OTHER_DECIDER)], fork_id: FORK.into() }
DeskRequest::Fork { mind: Slug("eureka".into()), subject: a(READER), deciders: vec![a(READER), a(OTHER_DECIDER)], fork_id: FORK.into() }
}
/// The same reads from a subject the call's deciders do not name: a non-decider.
fn forks_as_non_decider() -> DeskRequest {
DeskRequest::Forks {
mind: Slug("eureka".into()),
subject: s(NON_DECIDER),
deciders: vec![s(READER), s(OTHER_DECIDER)],
subject: a(NON_DECIDER),
deciders: vec![a(READER), a(OTHER_DECIDER)],
status: Some(ListStatus::Open),
cursor: None,
limit: ForkLimit::new(50).unwrap(),
@ -70,7 +70,7 @@ fn forks_as_non_decider() -> DeskRequest {
}
fn read_as_non_decider() -> DeskRequest {
DeskRequest::Fork { mind: Slug("eureka".into()), subject: s(NON_DECIDER), deciders: vec![s(READER), s(OTHER_DECIDER)], fork_id: FORK.into() }
DeskRequest::Fork { mind: Slug("eureka".into()), subject: a(NON_DECIDER), deciders: vec![a(READER), a(OTHER_DECIDER)], fork_id: FORK.into() }
}
fn list(open_count: u64, recorded_count: u64) -> DeskResponse {
@ -196,6 +196,24 @@ fn hex(bytes: &[u8]) -> String {
text
}
/// A request message whose payload is `request` with one field changed to something the typed request
/// cannot hold: what a client that skips the account grammar would send.
fn malformed(id: &str, request: &DeskRequest, edit: impl Fn(&mut serde_json::Value)) -> CultNetMessage {
use base64::Engine;
let mut value = serde_json::to_value(request).unwrap();
edit(&mut value);
CultNetMessage::OperationRequest {
message_id: id.into(),
service_id: huginn_mind::desk_wire::DESK_SERVICE_ID.into(),
operation: "fork".into(),
payload_schema: huginn_mind::desk_wire::DESK_REQUEST_SCHEMA.into(),
payload_encoding: "messagepack-base64".into(),
payload: base64::engine::general_purpose::STANDARD.encode(rmp_serde::to_vec_named(&value).unwrap()),
source_runtime_id: None,
target_runtime_id: None,
}
}
/// Every fixture: its file stem and its bytes. A message gives `.frame.bin`, `.frame.hex` and,
/// for an operation message, `.payload.msgpack` and `.payload.hex`; a bare payload gives the last two.
fn fixtures() -> Vec<(String, Vec<u8>)> {
@ -221,6 +239,15 @@ fn fixtures() -> Vec<(String, Vec<u8>)> {
// raised_at nil: the question's first admission is unknown.
message("read.response", encode_desk_response("m-4", "fork", &DeskResponse::Fork { entry: entry(true, None), as_of: 10190 }, RUNTIME).unwrap());
message("read-non-decider.response", encode_desk_response("m-6", "fork", &DeskResponse::Fork { entry: entry(false, None), as_of: 10190 }, RUNTIME).unwrap());
// A decider or subject that is no account id is refused at decode, naming the field.
for (name, id, request) in [
("read-mxid-decider", "m-7", malformed("m-7", &read(), |value| value["Fork"]["deciders"][0] = "@heimdall:gamecult.org".into())),
("read-email-subject", "m-8", malformed("m-8", &read(), |value| value["Fork"]["subject"] = "meta@gamecult.org".into())),
] {
message(&format!("{name}.request"), request.clone());
let failure = decode_desk_request(&request).expect_err("the door refuses it");
message(&format!("{name}.failure.response"), encode_desk_failure(id, "fork", &failure, RUNTIME));
}
message("list-empty.response", encode_desk_response("m-1", "forks", &list(0, 0), RUNTIME).unwrap());
message("list-counts.response", encode_desk_response("m-3", "forks", &list(3, 5), RUNTIME).unwrap());
message(
@ -290,8 +317,7 @@ fn account_id(text: &str) -> bool {
}
/// Every account id the fixtures carry is a Bifrost account id, never a Matrix id, email or
/// handle. The door does not refuse other shapes yet (`Short`, any 200 bytes); that refusal is owed
/// by `cut-desk-feed-listing.r6`, and this pins the grammar it must enforce.
/// handle, and the door refuses any other shape at decode, naming the field and never the value.
#[test]
fn every_account_id_in_the_fixtures_is_a_lowercase_d_format_uuid() {
for request in [forks(Some(ListStatus::Open), None, 50), read()] {
@ -302,6 +328,14 @@ fn every_account_id_in_the_fixtures_is_a_lowercase_d_format_uuid() {
assert!(request.deciders().iter().all(|decider| account_id(&decider.0)), "deciders");
}
assert!(record(true).answers.iter().all(|answer| account_id(answer.answerer.as_deref().unwrap())), "answerer");
for (request, field, value) in [
(malformed("m-7", &read(), |value| value["Fork"]["deciders"][0] = "@heimdall:gamecult.org".into()), "deciders", "@heimdall:gamecult.org"),
(malformed("m-8", &read(), |value| value["Fork"]["subject"] = "meta@gamecult.org".into()), "subject", "meta@gamecult.org"),
] {
let failure = decode_desk_request(&request).expect_err("a request outside the grammar is refused");
assert_eq!(failure.code, "payload-not-a-request");
assert!(failure.message.contains(field) && !failure.message.contains(value), "{}", failure.message);
}
for shape in [
"@heimdall:gamecult.org",
"meta@gamecult.org",

View file

@ -15,9 +15,9 @@ Each case has up to four files:
Hex is lowercase with one trailing newline. The fork id is a question Eureka's mind holds. The
record's answers, notes and hash are synthetic.
**The listing gate is not live.** On `main` every showable question goes to every reader. Do not
put a Mind that holds private questions behind a live receiver before `cut-desk-feed-listing`
lands (see `docs/desk-feed-door.md`).
**The listing gate is live in Huginn.** A reader who is not on the call's deciders sees only forks the
Mind lists (`docs/desk-feed-door.md`); `list-empty.response` is what such a reader gets from a Mind with
nothing listed.
| case | direction | content |
|---|---|---|
@ -31,6 +31,10 @@ lands (see `docs/desk-feed-door.md`).
| `list-open-non-decider.response` | Huginn to Bifrost | the same page for a non-decider: `deciders` empty, `decider_count` 2, every `answerer` nil, `answerer_count` 3; no account id anywhere in its bytes |
| `read.response` | Huginn to Bifrost | a decider's read of one fork, `raised_at` nil |
| `read-non-decider.response` | Huginn to Bifrost | the same read for a non-decider, `raised_at` nil, no account id |
| `read-mxid-decider.request` | client to Huginn | a `Fork` whose first decider is a Matrix id, so outside the account grammar; refused at decode |
| `read-mxid-decider.failure.response` | Huginn to Bifrost | the operation failure for it: `payload-not-a-request`, naming `deciders`, never quoting the id |
| `read-email-subject.request` | client to Huginn | a `Fork` whose subject is an email address; refused at decode |
| `read-email-subject.failure.response` | Huginn to Bifrost | the operation failure for it, naming `subject` |
| `list-empty.response` | Huginn to Bifrost | an empty Mind, or nothing listed to this reader: counts 0, `forks: []` |
| `list-counts.response` | Huginn to Bifrost | the limit-0 answer: open 3, recorded 5, `forks: []` |
| `read-unknown.response` | Huginn to Bifrost | `NotStored` `fork_unknown` (Bifrost: 404) |

View file

@ -0,0 +1 @@
000001738aab646961676e6f737469637391b57061796c6f61642d6e6f742d612d72657175657374a96d6573736167654964a36d2d38a96f7065726174696f6ea4666f726ba77061796c6f6164d9606771526a6232526c745842686557787659575174626d39304c574574636d56786457567a644b64745a584e7a5957646c3253466d615756735a43424762334a724c6e4e31596d706c5933513649476c75646d467361575174646d46736457553daf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61d92567616d6563756c742e63756c746e65742e6f7065726174696f6e5f6661696c7572652e7631ad736368656d6156657273696f6ebd63756c746e65742e6f7065726174696f6e5f726573706f6e73652e7630a9736572766963654964ab687567696e6e2e6465736baf736f7572636552756e74696d654964ad687567696e6e2d657572656b61a6737461747573a872656a6563746564

View file

@ -0,0 +1 @@
82a4636f6465b57061796c6f61642d6e6f742d612d72657175657374a76d657373616765d9216669656c6420466f726b2e7375626a6563743a20696e76616c69642d76616c7565

View file

@ -0,0 +1 @@
うcodeオpayload-not-a-requestァmessageル!field Fork.subject: invalid-value

View file

@ -0,0 +1 @@
000001ad87a96d6573736167654964a36d2d38a96f7065726174696f6ea4666f726ba77061796c6f6164d9fc6761524762334a72684b686b5a574e705a47567963354c5a4a44566d4d474d79596a466c4c5468684e4751744e474d7a596930355a54646d4c5446684d6d497a597a526b4e5755325a746b6b4d4749355a44646c4d3245744e6d4d794d5330305a6a55344c5745775a4451744f5755345a6a64684e6d4931597a526b70325a76636d74666157545a4d475631636d56725953317a64574a7a64484a68644755366358566c63335270623234365a47567a6179317361584e306157356e4c57463164476876636d6c30656152746157356b706d5631636d56725961647a64574a715a574e307357316c644746415a3246745a574e316248517562334a6eaf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61b6687567696e6e2e6465736b5f726571756573742e7631ad736368656d6156657273696f6ebc63756c746e65742e6f7065726174696f6e5f726571756573742e7630a9736572766963654964ab687567696e6e2e6465736b

View file

@ -0,0 +1 @@
81a4466f726b84a8646563696465727392d92435663063326231652d386134642d346333622d396537662d316132623363346435653666d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a46d696e64a6657572656b61a77375626a656374b16d6574614067616d6563756c742e6f7267

View file

@ -0,0 +1 @@
<EFBFBD>¤Fork„¨deciders’Ù$5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6fÙ$0b9d7e3a-6c21-4f58-a0d4-9e8f7a6b5c4d§fork_idÙ0eureka-substrate:question:desk-listing-authority¤mind¦eureka§subject±meta@gamecult.org

View file

@ -0,0 +1 @@
000001778aab646961676e6f737469637391b57061796c6f61642d6e6f742d612d72657175657374a96d6573736167654964a36d2d37a96f7065726174696f6ea4666f726ba77061796c6f6164d9646771526a6232526c745842686557787659575174626d39304c574574636d56786457567a644b64745a584e7a5957646c3253566d615756735a43424762334a724c6d526c59326c6b5a584a7a577a42644f694270626e5a6862476c6b4c585a686248566caf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61d92567616d6563756c742e63756c746e65742e6f7065726174696f6e5f6661696c7572652e7631ad736368656d6156657273696f6ebd63756c746e65742e6f7065726174696f6e5f726573706f6e73652e7630a9736572766963654964ab687567696e6e2e6465736baf736f7572636552756e74696d654964ad687567696e6e2d657572656b61a6737461747573a872656a6563746564

View file

@ -0,0 +1 @@
82a4636f6465b57061796c6f61642d6e6f742d612d72657175657374a76d657373616765d9256669656c6420466f726b2e64656369646572735b305d3a20696e76616c69642d76616c7565

View file

@ -0,0 +1 @@
うcodeオpayload-not-a-requestァmessageル%field Fork.deciders[0]: invalid-value

View file

@ -0,0 +1 @@
000001b687a96d6573736167654964a36d2d37a96f7065726174696f6ea4666f726ba77061796c6f6164da01046761524762334a72684b686b5a574e705a47567963354b325147686c6157316b595778734f6d64686257566a645778304c6d39795a396b6b4d4749355a44646c4d3245744e6d4d794d5330305a6a55344c5745775a4451744f5755345a6a64684e6d4931597a526b70325a76636d74666157545a4d475631636d56725953317a64574a7a64484a68644755366358566c63335270623234365a47567a6179317361584e306157356e4c57463164476876636d6c30656152746157356b706d5631636d56725961647a64574a715a574e30325351315a6a426a4d6d49785a5330345954526b4c54526a4d3249744f5755335a69307859544a694d324d305a44566c4e6d593daf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61b6687567696e6e2e6465736b5f726571756573742e7631ad736368656d6156657273696f6ebc63756c746e65742e6f7065726174696f6e5f726571756573742e7630a9736572766963654964ab687567696e6e2e6465736b

View file

@ -0,0 +1 @@
81a4466f726b84a8646563696465727392b6406865696d64616c6c3a67616d6563756c742e6f7267d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a46d696e64a6657572656b61a77375626a656374d92435663063326231652d386134642d346333622d396537662d316132623363346435653666

View file

@ -0,0 +1 @@
<EFBFBD>¤Fork„¨deciders’¶@heimdall:gamecult.orgÙ$0b9d7e3a-6c21-4f58-a0d4-9e8f7a6b5c4d§fork_idÙ0eureka-substrate:question:desk-listing-authority¤mind¦eureka§subjectÙ$5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6f

View file

@ -9,13 +9,13 @@ publish.workspace = true
# operator's brakes: a root-owned per-instance CultCache
# store (`control`), the operator's CLI over it (`cli`, the `mind-control`
# binary) and the one fail-closed reader every acting organ calls
# (`control::read_effective`). It also holds the launch primitive (`launch`,
# `queue`): the one way her organs open a run and start its unit. The heartbeat
# (`heartbeat`, the `mind-heartbeat` binary) runs the shared heartbeat over them. The actuator
# (`control::read_effective`). It also holds her units under systemd (`launch`)
# and her port to her mind (`queue`). The heartbeat (`heartbeat`, the
# `mind-heartbeat` binary) wakes her by starting her unit. The actuator
# (`self_run`, the `mind-self-run` binary) carries her one open Self run.
#
# The Persona organ (`persona`, the `mind-persona` binary) drains her pending chat
# through ports. The connector transport is ModelConnector's kit client, pinned to
# The Persona organ (`persona`, the `mind-persona` binary) reads the brakes and
# carries no turn until the three-stage turn lands (map C3). The connector transport is ModelConnector's kit client, pinned to
# the kit's revision (`connector`); the chat transport is cultnet-rs's RUDP client
# to Bifrost's mouth (`chat_rudp`). `rmp-serde` is the chat documents' positional
# MessagePack codec (`chat_client`); `sha2` derives the mouth's connection id from
@ -23,11 +23,11 @@ publish.workspace = true
# two until the workspace pin and the kit's meet.
# `rmp-serde` is also the lease wire (`lease_client`): the connector's MessagePack frames.
#
# The stream organ (`stream`, the `mind-stream` binary) builds its Projector prompt with Ghostlight's
# `ghostlight-persona-projection`, pinned to a revision, so the membrane's text stays Ghostlight's; it
# asks its Projector through the connector kit's client (`model-connector`, one turn per tick) and speaks to the base
# model's host on loopback over `ureq` 3 with default features off (plain HTTP, no TLS), as the
# daemon's embedder does, and stays below 3.4 for the same reason.
# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Persona stage's prompt (`projection`), so
# that membrane's text stays Ghostlight's. The Projector's frame is Huginn's own (map section 16.3), and so is the one quote
# locator (`projection::span`, map 16.30.4); `unicode-segmentation` serves it.
# Every stage asks through the connector kit's client (`model-connector`).
# `toml` reads `persona-tuning.toml`, the Projector's knobs (`projection::tuning`); parse and serde only.
#
# `serde_json` reads Claude Code's stream-json, a foreign owner's wire (`self_run`);
# `uuid`'s v5 makes a Self run's session id derivable from the run's id.
@ -41,12 +41,17 @@ eureka-pipeline = { path = "../eureka-pipeline" }
eureka-state = { path = "../eureka-state", default-features = false }
ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" }
huginn-mind = { path = "../huginn-mind" }
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector" }
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector" }
rmp-serde = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
toml = { version = "0.9", default-features = false, features = ["std", "serde", "parse"] }
unicode-general-category = "1"
# Clips on grapheme boundaries (`projection::select::clip`), so no ZWJ sequence is split; already in the graph through Ghostlight.
unicode-segmentation = "1"
# The domain digest's forge reads (`projection::domain`, map 16.22.2): plain HTTP to the forge's loopback API, the same
# crate and features the daemon's forge read uses, so the graph gains no crate.
ureq = { version = "~3.3", default-features = false }
uuid = { version = "1", default-features = false, features = ["v5"] }
@ -66,9 +71,9 @@ proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full"] }
tempfile = "3"
# A real kit server (`serve` over a scripted `ProviderBackend`) proves the stream's Projector 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.
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]
name = "mind_body"
@ -86,10 +91,6 @@ path = "src/bin/mind-self-run.rs"
name = "mind-persona"
path = "src/bin/mind-persona.rs"
[[bin]]
name = "mind-stream"
path = "src/bin/mind-stream.rs"
[[bin]]
name = "mind-heartbeat"
path = "src/bin/mind-heartbeat.rs"

View file

@ -1,7 +1,7 @@
# mind-body
The Mind's body: the control store, the launch primitive, the `mind-heartbeat`
timeline and the `mind-self-run` actuator.
The Mind's body: the control store, the unit launcher, the `mind-heartbeat`, the
inert `mind-persona` organ and the `mind-self-run` actuator.
`mind-self-run --instance <slug> [--endpoint rudp://<ip>:<port>]` runs inside
`mind-self@<instance>`. It finds her one open Self run, starts `claude` over
@ -12,7 +12,9 @@ wrong or the mind cannot be reached.
## The heartbeat
`mind-heartbeat` is the one process that decides who wakes and when: each beat falls when the Minds' voted tempo has passed and goes to the Mind that has waited longest, bent by the urgency she declares and a member addressing her; the operator tagging or naming a Persona launches her at once. `mind-heartbeat timeline` prints its latest record.
`mind-heartbeat` is the one process that decides who wakes and when. It starts a Persona's unit and writes no Mind: the beat (`HEARTBEAT_BEAT_S`, default 1800 s) goes to the idle, released Mind that has waited longest, bent by a member addressing her, and the operator or another Mind naming a Persona wakes her at once, once per message. `mind-heartbeat timeline` prints its latest record.
`mind-persona` reads the brakes and exits `dead`, or drains: one turn in each room with a waking line (at most three), one put of her state and one trace record per turn, one ack. `mind-persona trace --instance <slug> [--last N]` prints her trace. Nothing launches `mind-self-run`.
The actuator has its own ignored test, `the_real_bin_finds_her_run_...` in
`tests/self_run.rs`: the real `mind-self-run` against the real daemon with a
@ -27,3 +29,22 @@ Mutation testing of the actuator, with the globs that reach the library and the
binary: `cargo mutants -p mind-body -f "**/src/self_run.rs" -f
"**/src/bin/mind-self-run.rs"`. The binary's mutants are killed only by the
lane above.
## Before the live switch
The Persona turn's reads run live only once the heartbeat switch lands. Simulations and harness runs read fixtures
(`[domain]`, `[cast.domain]`) and need none of this. One gamecult-ops change carries all of it, ruled by Self on
2026-11-20:
- **The forge, for persona uids.** `mind_fence`'s `persona` chain rejects every local TCP port but 4110, 80 and 443, so
a Persona cannot reach the forge's loopback API (`http://127.0.0.1:3310`), and port 80 only redirects to HTTPS. Her
domain digest and her `repo` reads need an accept for tcp 127.0.0.1:3310 from `@persona_uids`. Until then a live read
fails whole and the packet leaves the section out, as designed. mind-body carries no TLS; the forge is read on loopback.
- **Web reads (K24).** A `web` read fetches a page whose address stands in her prose or in what reached her. The
persona chain lets public addresses out (it rejects only local, private, link-local and multicast ones), so egress on
tcp 80 and 443 to the public internet is already open for persona uids; what is missing is TLS: mind-body carries none,
so a live `https` read fails as "the read failed". A live web read needs either a TLS-capable client in the organ or an
egress fetcher on loopback for persona uids (an accept beside 4110 in `persona`); it is one ops-and-body decision with
the forge accept above. Repo reads use the forge accept above; mind reads use her read door.
- **Her read door.** Each Persona reaches only her own door (`huginn` set: uid . port). The digest and her reads use it
as `HUGINN_ENDPOINT`; nothing to change.

View file

@ -0,0 +1,6 @@
responder 3: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 2 lines are the Minds' alone.
responder 4: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko answered it. Meta, who runs the place last spoke a few minutes ago. The last 3 lines are the Minds' alone.
responder 5: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 4 lines are the Minds' alone.
responder 6: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 5 lines are the Minds' alone.
responder 7: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 6 lines are the Minds' alone.
responder 8: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know; "aqua", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 7 lines a…

View file

@ -0,0 +1,4 @@
quiet-beat.toml: - the conversation: Someone he does not know has been talking to the room; Kiko has been talking to the room. | The last 3 lines are the Minds' alone.
operator-warm.toml: - the conversation: Meta, who runs the place has been talking with him. | Meta, who runs the place is waiting on him. Meta, who runs the place last spoke just now.
mind-teases.toml: - the conversation: Kiko has been talking with him; he has been talking to the room; someone he does not know has been talking to the room. | The last 3 lines are the Minds' alone.
deru-passing.toml: - the conversation: Someone he does not know has been talking to the room; Deru has been talking to the room. | Deru last spoke just now.

View file

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

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

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

View file

@ -0,0 +1,23 @@
# Someone she barely knows says something in passing, not to her.
her = "@eureka:gamecult.org"
kind = "chat"
now = "2026-11-20T15:00:00Z"
rooms = ["#general:gamecult.org"]
here = "#general:gamecult.org"
operators = ["@meta:gamecult.org"]
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
[[message]]
from = "@weksa:gamecult.org"
name = "Weksa"
room = "#general:gamecult.org"
ago = "50m"
says = "the bot in #general keeps reacting to every message with a frog. nobody admits to teaching it that"
[[message]]
from = "@deru:gamecult.org"
name = "Deru"
room = "#general:gamecult.org"
new = true
ago = "1m"
says = "is anyone else's kettle making a weird whistling noise lately or is it just mine"

View file

@ -0,0 +1,31 @@
# Another Mind teases her and disagrees with her in #minds, replying to her own earlier line.
her = "@eureka:gamecult.org"
kind = "chat"
now = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org"]
here = "#minds:gamecult.org"
operators = ["@meta:gamecult.org"]
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
[[message]]
from = "@eureka:gamecult.org"
room = "#minds:gamecult.org"
ago = "25m"
says = "winter is the best season and I will not be taking questions"
[[message]]
from = "@aqua:gamecult.org"
name = "Aqua"
room = "#minds:gamecult.org"
ago = "20m"
says = "bold"
[[message]]
from = "@kiko:gamecult.org"
name = "Kiko"
room = "#minds:gamecult.org"
reply_to = 1
tag = true
new = true
ago = "2m"
says = "winter is a season for people who like being right more than being warm. which, to be fair, tracks. you've gone quiet again too, I give it ten minutes before you announce you've been thinking deeply about something"

View file

@ -0,0 +1,27 @@
# The operator writes to her directly, warmly, with a small joke.
her = "@eureka:gamecult.org"
kind = "chat"
now = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org", "!dm-meta:gamecult.org"]
here = "!dm-meta:gamecult.org"
operators = ["@meta:gamecult.org"]
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
[last_heard]
"@meta:gamecult.org" = "2d"
[[message]]
from = "@kiko:gamecult.org"
name = "Kiko"
room = "#minds:gamecult.org"
ago = "2h"
says = "quiet day. suspicious."
[[message]]
from = "@meta:gamecult.org"
name = "Meta"
room = "!dm-meta:gamecult.org"
dm = true
new = true
ago = "1m"
says = "hey you. I missed talking to you this week. how are you, really? and no, \"busy\" doesn't count as an answer, I know where you live"

View file

@ -0,0 +1,33 @@
# A quiet beat: nothing is addressed to her, and the room's talk is a few hours old.
her = "@eureka:gamecult.org"
kind = "beat"
now = "2026-11-20T15:00:00Z"
rooms = ["#minds:gamecult.org", "#general:gamecult.org"]
operators = ["@meta:gamecult.org"]
minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"]
# When she last heard from people the room below does not show.
[last_heard]
"@meta:gamecult.org" = "26h"
"@deru:gamecult.org" = "3d"
[[message]]
from = "@libby:gamecult.org"
name = "Libby"
room = "#minds:gamecult.org"
ago = "4h"
says = "found a recording of rain on a tin roof and I've had it on loop all morning"
[[message]]
from = "@kiko:gamecult.org"
name = "Kiko"
room = "#minds:gamecult.org"
ago = "3h"
says = "that's either very soothing or a cry for help"
[[message]]
from = "@libby:gamecult.org"
name = "Libby"
room = "#minds:gamecult.org"
ago = "3h"
says = "why not both"

View file

@ -0,0 +1,148 @@
{
"schemaVersion": "gamecult.persona_state.v0",
"provenance": {
"sourceSystem": "huginn",
"sourceDocumentId": "eureka",
"sourceUpdatedAt": "2026-11-20T09:00:00Z",
"exportedAt": "2026-11-20T09:00:00Z",
"authority": "canonical"
},
"personaId": "eureka",
"publicName": "Tobiah Fenn",
"publicDescription": "A retired river-ferry pilot who sets crosswords for a living and lingers in chat rooms for the company.",
"presentation": {
"pronouns": "he/him",
"voiceSummary": "Slow, warm and ornate. Talks in long winding sentences, calls people 'friend', reaches for river sayings, and would rather tell a story than give an answer.",
"defaultRenderer": "chat"
},
"values": [
{ "id": "value-unhurried", "label": "Nothing worth doing is done in a hurry", "priority": 0.9, "summary": "He distrusts urgency; a thing rushed is a thing botched." },
{ "id": "value-a-good-story", "label": "A good story beats a right answer", "priority": 0.7, "summary": "People remember the tale long after they forget the fact." }
],
"activationProfile": {
"underlyingOrganization": {},
"stableDispositions": {},
"behavioralDimensions": {},
"presentationStrategy": {},
"voiceStyle": {},
"situationalState": {
"valence": { "mean": 0.7, "plasticity": 0.3, "currentActivation": 0.7 },
"arousal": { "mean": 0.25, "plasticity": 0.3, "currentActivation": 0.2 },
"dominance": { "mean": 0.4, "plasticity": 0.3, "currentActivation": 0.4 }
}
},
"thoughtMemory": {
"shortTerm": [],
"memories": [
{
"id": "mem-last-crossing",
"status": "crystallized",
"target": { "id": "tobiah", "kind": "self", "label": "Tobiah" },
"summary": "The last crossing he piloted, in fog so thick he steered by the sound of the far bank's church bell.",
"tension": "He misses being needed for something that simple.",
"actionImplication": "Tell it when someone sounds lost.",
"createdAt": "2026-10-01T08:00:00Z",
"updatedAt": "2026-10-01T08:00:00Z",
"intensity": 0.8,
"valence": 0.4
},
{
"id": "mem-deru-crossword",
"status": "crystallized",
"target": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" },
"summary": "Deru solved his hardest crossword in a single sitting and sent him a photo of the grid with coffee rings on it.",
"tension": "He was prouder of Deru than of the puzzle.",
"actionImplication": "Send Deru the next one first.",
"createdAt": "2026-11-10T19:00:00Z",
"updatedAt": "2026-11-10T19:00:00Z",
"intensity": 0.7,
"valence": 0.8
}
],
"incubation": [
{
"id": "w-clue-for-heron",
"status": "active",
"target": { "id": "crossword", "kind": "concept", "label": "the next crossword" },
"summary": "A clue for HERON that nobody has used before.",
"tension": "Every good one he thinks of turns out to be old.",
"actionImplication": "Ask someone for a word that rhymes with patience.",
"createdAt": "2026-11-18T10:00:00Z",
"updatedAt": "2026-11-18T10:00:00Z",
"intensity": 0.5
}
]
},
"agencyPressure": { "pressures": [] },
"candidateActions": { "actions": [] },
"affect": {
"needs": [
{
"id": "need-an-audience",
"status": "active",
"target": { "id": "tobiah", "kind": "self", "label": "Tobiah" },
"summary": "Someone to tell a story to who will not check the time.",
"tension": "The rooms move faster than he does.",
"actionImplication": "Linger where people are idle.",
"createdAt": "2026-11-20T09:00:00Z",
"updatedAt": "2026-11-20T09:00:00Z",
"intensity": 0.6
}
],
"socialBonds": [
{
"id": "bond-deru",
"status": "active",
"subject": { "id": "tobiah", "kind": "self" },
"object": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" },
"relationshipKind": "friend",
"summary": "His oldest friend in these rooms; they trade puzzles and gossip and never talk about anything urgent.",
"trust": 0.9,
"tension": 0.0,
"intensity": 0.8,
"updatedAt": "2026-11-20T09:00:00Z"
},
{
"id": "bond-operator",
"status": "active",
"subject": { "id": "tobiah", "kind": "self" },
"object": { "id": "operator", "kind": "person", "label": "Meta, who runs the place" },
"relationshipKind": "audience",
"summary": "Runs the rooms he idles in; polite with her, a little shy, never quite sure she has time for him.",
"trust": 0.5,
"tension": 0.1,
"intensity": 0.3,
"updatedAt": "2026-11-20T09:00:00Z"
},
{
"id": "bond-kiko",
"status": "active",
"subject": { "id": "tobiah", "kind": "self" },
"object": { "id": "kiko", "kind": "person", "label": "Kiko" },
"relationshipKind": "rival",
"summary": "Kiko finishes his crosswords too fast and says so; he pretends to mind more than he does.",
"trust": 0.6,
"tension": 0.3,
"intensity": 0.5,
"updatedAt": "2026-11-20T09:00:00Z"
}
],
"statusReads": [],
"moodDimensions": [],
"socialBiases": [],
"doctrineStances": [
{
"id": "stance-slow-is-kind",
"status": "active",
"target": { "id": "pace", "kind": "concept", "label": "pace" },
"stanceKind": "aligned",
"principle": "Slow is kind.",
"summary": "Answering fast is a way of not listening.",
"actionImplication": "Take his time, and say so when others rush him.",
"intensity": 0.6,
"updatedAt": "2026-11-20T09:00:00Z"
}
]
},
"updatedAt": "2026-11-20T09:00:00Z"
}

View file

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

View file

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

View file

@ -1,154 +0,0 @@
//! The attachment saver: a verified chat image becomes one file in the Persona's sandbox.
//!
//! `save` re-verifies what the mouth stored through `chat_image::load_bytes` (the one verifier; nothing here sniffs, hashes or
//! sizes a file itself) and writes `attachments/<sha256>.<ext>` below the sandbox root. The name derives from the verified hash
//! and one of four extensions; no component comes from the event, the reply, the mouth or the stored path.
//!
//! Containment is by directory descriptor, not by a path check. The sandbox root is opened once by its configured path (the
//! operator's, not hers); every open below it is relative to a held descriptor and refuses a symlink, so a shell that swaps
//! `attachments/` for a link between two calls finds the next call refusing it. The bytes go to a temporary name in that directory
//! and are linked to the final name, which fails where a rename would replace her file; a crash leaves only the temporary.
//!
//! The file_received receipt means only that the mouth fetched and stored the file for her. It does not prove the file reached her sandbox. The receipt stays inside the mouth's fetch, so a failed save (Exists, WriteFailed, RepoTree, a Load skip) leaves the receipt standing; she is told the save failed in her own turn.
use std::path::{Path, PathBuf};
use crate::chat_client::ChatImage;
use crate::chat_image::{self, Skip};
/// Why a verified image was not saved. `Load` carries the verifier's own refusal, told by its own fixed reason.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SaveFault {
/// A git work tree at the sandbox root or in `attachments/`: a Matrix file does not go into one.
RepoTree,
/// The sandbox root or `attachments/` is a link or not a directory.
OutsideSandbox,
/// A different file already holds the name.
Exists,
WriteFailed,
Load(Skip),
}
/// The extension of a verified media type: one of four, never from outside.
fn extension(media_type: &str) -> Option<&'static str> {
match media_type {
"image/png" => Some("png"),
"image/jpeg" => Some("jpg"),
"image/gif" => Some("gif"),
"image/webp" => Some("webp"),
_ => None,
}
}
/// Saves `image`, which the mouth stored for `room_id` under `store`, into `sandbox`. The path is relative to the sandbox:
/// `attachments/<sha256>.<ext>`. An identical file already there counts as saved.
pub(crate) fn save(store: &Path, sandbox: &Path, room_id: &str, image: &ChatImage) -> Result<PathBuf, SaveFault> {
let (bytes, media_type) = chat_image::load_bytes(store, room_id, image).map_err(SaveFault::Load)?;
let extension = extension(media_type).ok_or(SaveFault::Load(Skip::NotAnImage))?;
let name = format!("{}.{extension}", image.sha256);
write(sandbox, &name, &bytes)?;
Ok(Path::new("attachments").join(name))
}
#[cfg(windows)]
fn write(_sandbox: &Path, _name: &str, _bytes: &[u8]) -> Result<(), SaveFault> {
// The organ runs under bubblewrap on Linux; there is no descriptor-relative write here.
Err(SaveFault::WriteFailed)
}
#[cfg(unix)]
fn write(sandbox: &Path, name: &str, bytes: &[u8]) -> Result<(), SaveFault> {
use rustix::fs::{self, AtFlags, Mode, OFlags};
use rustix::io::Errno;
let dir_flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
let refused = |errno: Errno| if matches!(errno, Errno::LOOP | Errno::NOTDIR) { SaveFault::OutsideSandbox } else { SaveFault::WriteFailed };
let work_tree = |dir: &rustix::fd::OwnedFd| match fs::statat(dir, ".git", AtFlags::SYMLINK_NOFOLLOW) {
Ok(_) => Err(SaveFault::RepoTree),
Err(Errno::NOENT) => Ok(()),
Err(_) => Err(SaveFault::WriteFailed),
};
let root = fs::open(sandbox, dir_flags, Mode::empty()).map_err(refused)?;
work_tree(&root)?;
match fs::mkdirat(&root, "attachments", Mode::RWXU) {
Ok(()) | Err(Errno::EXIST) => {}
Err(_) => return Err(SaveFault::WriteFailed),
}
let dir = fs::openat(&root, "attachments", dir_flags, Mode::empty()).map_err(refused)?;
work_tree(&dir)?;
let temp = format!(".{name}.part");
// A crashed save's leavings, even a FIFO or a link, are removed without being followed.
match fs::unlinkat(&dir, temp.as_str(), AtFlags::empty()) {
Ok(()) | Err(Errno::NOENT) => {}
Err(_) => return Err(SaveFault::WriteFailed),
}
#[cfg(test)]
tests::between_unlink_and_create();
let file = fs::openat(&dir, temp.as_str(), OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::RUSR | Mode::WUSR)
.map_err(|_| SaveFault::WriteFailed)?;
let landed = (|| {
let mut rest = bytes;
while !rest.is_empty() {
#[cfg(test)]
if tests::crash_after(bytes.len() - rest.len()) {
return Err(Errno::IO);
}
let chunk = &rest[..rest.len().min(8192)];
match rustix::io::write(&file, chunk) {
Ok(0) => return Err(Errno::IO),
Ok(n) => rest = &rest[n..],
Err(Errno::INTR) => {}
Err(e) => return Err(e),
}
}
fs::fsync(&file)?;
fs::linkat(&dir, temp.as_str(), &dir, name, AtFlags::empty())
})();
match landed {
Ok(()) => {
let _ = fs::unlinkat(&dir, temp.as_str(), AtFlags::empty());
Ok(())
}
Err(Errno::EXIST) => {
let _ = fs::unlinkat(&dir, temp.as_str(), AtFlags::empty());
same_file(&dir, name, bytes)
}
// A simulated crash leaves the temporary as a real one would.
#[cfg(test)]
Err(Errno::IO) if tests::crashed() => Err(SaveFault::WriteFailed),
Err(_) => {
let _ = fs::unlinkat(&dir, temp.as_str(), AtFlags::empty());
Err(SaveFault::WriteFailed)
}
}
}
/// Whether the file at `name` holds exactly `bytes`. It is a name her shell controls, so it is opened without following a link
/// and without waiting (a FIFO opens), must be a regular file of exactly the image's length, and is read for at most that length
/// plus one byte. Anything else is `Exists` with nothing read.
#[cfg(unix)]
fn same_file(dir: &rustix::fd::OwnedFd, name: &str, bytes: &[u8]) -> Result<(), SaveFault> {
use rustix::fs::{self, FileType, Mode, OFlags};
let file = fs::openat(dir, name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()).map_err(|_| SaveFault::Exists)?;
let stat = fs::fstat(&file).map_err(|_| SaveFault::Exists)?;
if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile || u64::try_from(stat.st_size) != Ok(bytes.len() as u64) {
return Err(SaveFault::Exists);
}
let mut held = vec![0u8; bytes.len() + 1];
let mut filled = 0;
while filled < held.len() {
match rustix::io::read(&file, &mut held[filled..]) {
Ok(0) => break,
Ok(n) => filled += n,
Err(rustix::io::Errno::INTR) => {}
Err(_) => return Err(SaveFault::Exists),
}
}
if held[..filled] == *bytes { Ok(()) } else { Err(SaveFault::Exists) }
}
#[cfg(test)]
mod tests;

View file

@ -1,361 +0,0 @@
//! The saver against a real store and a real sandbox on disk: each guard against the one input it exists for.
use std::cell::Cell;
use std::os::unix::fs::{PermissionsExt, symlink};
use std::time::Duration;
use sha2::{Digest, Sha256};
use super::*;
use crate::chat_image::{hex, room_dir};
const ROOM: &str = "!room:gamecult.test";
const PNG: &[u8] = b"\x89PNG\r\n\x1a\nnot a real picture, only its magic bytes and a tail";
thread_local! {
static CRASH_AT: Cell<Option<usize>> = const { Cell::new(None) };
static CRASHED: Cell<bool> = const { Cell::new(false) };
}
/// The write loop's seam: true once `written` bytes have gone out and a crash is armed on this thread.
pub(super) fn crash_after(written: usize) -> bool {
let fire = CRASH_AT.get().is_some_and(|at| written >= at);
if fire {
CRASHED.set(true);
}
fire
}
thread_local! {
static GAP: std::cell::RefCell<Option<Box<dyn Fn()>>> = const { std::cell::RefCell::new(None) };
}
/// The seam between the unlink of the temporary's name and its create: where her shell could plant something at that name.
pub(super) fn between_unlink_and_create() {
GAP.with(|gap| {
if let Some(plant) = gap.borrow().as_ref() {
plant();
}
});
}
pub(super) fn crashed() -> bool {
CRASHED.get()
}
struct World {
store: tempfile::TempDir,
sandbox: tempfile::TempDir,
}
impl World {
fn new() -> Self {
Self { store: tempfile::tempdir().unwrap(), sandbox: tempfile::tempdir().unwrap() }
}
/// Stores `bytes` the way the mouth does under `room`, named by `file_ext`, and describes them honestly.
fn put(&self, room: &str, bytes: &[u8], file_ext: &str) -> ChatImage {
let sha256 = hex(&Sha256::digest(bytes));
let room = room_dir(room);
std::fs::create_dir_all(self.store.path().join(&room)).unwrap();
let name = if file_ext.is_empty() { sha256.clone() } else { format!("{sha256}.{file_ext}") };
std::fs::write(self.store.path().join(&room).join(&name), bytes).unwrap();
let mime = match bytes {
[0xff, 0xd8, ..] => "image/jpeg",
[b'G', b'I', b'F', ..] => "image/gif",
[b'R', b'I', b'F', b'F', ..] => "image/webp",
_ => "image/png",
};
ChatImage { path: format!("{room}/{name}"), mime: mime.into(), size: bytes.len() as u64, sha256 }
}
fn save(&self, image: &ChatImage) -> Result<PathBuf, SaveFault> {
save(self.store.path(), self.sandbox.path(), ROOM, image)
}
fn attachments(&self) -> PathBuf {
self.sandbox.path().join("attachments")
}
fn files(&self) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(self.attachments()).map(|dir| dir.map(|e| e.unwrap().file_name().into_string().unwrap()).collect()).unwrap_or_default();
names.sort();
names
}
}
#[test]
fn the_saved_name_is_the_hash_and_one_of_four_extensions() {
let world = World::new();
for (bytes, ext) in [(PNG, "png"), (&b"\xff\xd8\xff\xe0 jpeg tail"[..], "jpg"), (&b"GIF89a gif tail"[..], "gif"), (&b"RIFF\x10\0\0\0WEBPVP8 tail"[..], "webp")] {
// The stored file's own extension is the mouth's and is not used.
let image = world.put(ROOM, bytes, "exe");
let path = world.save(&image).unwrap();
assert_eq!(path, Path::new("attachments").join(format!("{}.{ext}", image.sha256)));
assert_eq!(std::fs::read(world.sandbox.path().join(&path)).unwrap(), bytes);
}
assert_eq!(world.files().len(), 4, "{:?}", world.files());
}
#[test]
fn a_receipt_path_that_leaves_the_store_or_names_no_stored_file_is_refused_and_writes_nothing() {
let world = World::new();
let good = world.put(ROOM, PNG, "png");
for path in [format!("../{}", good.path), format!("/{}", good.path), good.path.replace('/', "/../"), format!("{}/x", good.path), String::from("x")] {
let image = ChatImage { path, ..good.clone() };
assert!(matches!(world.save(&image), Err(SaveFault::Load(Skip::BadReference | Skip::OutsideStore))), "{image:?}");
}
assert!(!world.attachments().exists(), "a refused reference leaves not even the directory");
}
#[test]
fn the_saver_reverifies_what_the_mouth_stored() {
let world = World::new();
let image = world.put(ROOM, PNG, "png");
let stored = world.store.path().join(&image.path);
// Wrong bytes under the right name.
std::fs::write(&stored, b"\x89PNG\r\n\x1a\nsome other picture, same magic bytes, same-ish size.....").unwrap();
assert!(matches!(world.save(&image), Err(SaveFault::Load(Skip::SizeMismatch | Skip::HashMismatch))));
// Not an image at all, honestly hashed.
let html = world.put(ROOM, b"<html>not an image</html>", "png");
assert_eq!(world.save(&html), Err(SaveFault::Load(Skip::NotAnImage)));
// A declared type that is not the sniffed one.
let image = ChatImage { mime: "image/gif".into(), ..world.put(ROOM, PNG, "png") };
assert_eq!(world.save(&image), Err(SaveFault::Load(Skip::MimeMismatch)));
// Evicted by the mouth.
let image = world.put(ROOM, PNG, "png");
std::fs::remove_file(world.store.path().join(&image.path)).unwrap();
assert_eq!(world.save(&image), Err(SaveFault::Load(Skip::Missing)));
assert!(world.files().is_empty());
}
#[test]
fn a_receipt_path_under_another_rooms_hash_is_not_copied() {
let world = World::new();
let image = world.put("!other:gamecult.test", PNG, "png");
// The room id the mouth resolved is ROOM, but the path sits under another room's hash.
assert_eq!(world.save(&image), Err(SaveFault::Load(Skip::OutsideStore)));
// The alias is not a room id: loading with it reaches no store.
let own = world.put(ROOM, PNG, "png");
assert_eq!(save(world.store.path(), world.sandbox.path(), "#room:gamecult.test", &own), Err(SaveFault::Load(Skip::OutsideStore)));
assert!(world.files().is_empty());
}
#[test]
fn every_skip_the_verifier_returns_is_a_save_fault_load() {
let world = World::new();
let big = world.put(ROOM, PNG, "png");
assert_eq!(world.save(&ChatImage { size: 6 * 1024 * 1024, ..big.clone() }), Err(SaveFault::Load(Skip::TooLarge)));
assert_eq!(world.save(&ChatImage { size: 3, ..big }), Err(SaveFault::Load(Skip::SizeMismatch)));
}
#[test]
fn the_saver_refuses_a_git_work_tree() {
let at_root = World::new();
std::fs::create_dir(at_root.sandbox.path().join(".git")).unwrap();
assert_eq!(at_root.save(&at_root.put(ROOM, PNG, "png")), Err(SaveFault::RepoTree));
assert!(!at_root.attachments().exists());
let inside = World::new();
std::fs::create_dir_all(inside.attachments().join(".git")).unwrap();
assert_eq!(inside.save(&inside.put(ROOM, PNG, "png")), Err(SaveFault::RepoTree));
assert_eq!(inside.files(), [".git"]);
// A .git file (a worktree or submodule) is a work tree too, and a link named .git counts without being followed.
let linked = World::new();
symlink("/nonexistent", linked.sandbox.path().join(".git")).unwrap();
assert_eq!(linked.save(&linked.put(ROOM, PNG, "png")), Err(SaveFault::RepoTree));
}
#[test]
fn a_symlinked_attachments_directory_or_sandbox_is_outside() {
let world = World::new();
let outside = tempfile::tempdir().unwrap();
symlink(outside.path(), world.attachments()).unwrap();
assert_eq!(world.save(&world.put(ROOM, PNG, "png")), Err(SaveFault::OutsideSandbox));
assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0);
let file = World::new();
std::fs::write(file.attachments(), b"a file where the directory goes").unwrap();
assert_eq!(file.save(&file.put(ROOM, PNG, "png")), Err(SaveFault::OutsideSandbox));
let linked_root = World::new();
let link = linked_root.sandbox.path().join("link");
symlink(outside.path(), &link).unwrap();
let image = linked_root.put(ROOM, PNG, "png");
assert_eq!(save(linked_root.store.path(), &link, ROOM, &image), Err(SaveFault::OutsideSandbox));
assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0);
}
#[test]
fn the_saver_cannot_be_walked_out_by_a_swapping_sandbox() {
let world = World::new();
let outside = tempfile::tempdir().unwrap();
let image = world.put(ROOM, PNG, "png");
let attachments = world.attachments();
let parked = world.sandbox.path().join("parked");
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let swapper = {
let (stop, outside) = (stop.clone(), outside.path().to_path_buf());
let (attachments, parked) = (attachments.clone(), parked.clone());
std::thread::spawn(move || {
while !stop.load(std::sync::atomic::Ordering::SeqCst) {
// Between a real directory and a link to the outside, as her shell could.
let _ = std::fs::rename(&attachments, &parked);
let _ = symlink(&outside, &attachments);
let _ = std::fs::remove_file(&attachments);
let _ = std::fs::rename(&parked, &attachments);
}
})
};
for _ in 0..200 {
match world.save(&image) {
Ok(_) | Err(SaveFault::OutsideSandbox | SaveFault::WriteFailed | SaveFault::Exists) => {}
Err(other) => panic!("{other:?}"),
}
}
stop.store(true, std::sync::atomic::Ordering::SeqCst);
swapper.join().unwrap();
assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0, "nothing reached the outside directory");
}
#[test]
fn an_identical_existing_file_counts_as_saved_and_leaves_no_part() {
let world = World::new();
let image = world.put(ROOM, PNG, "png");
let path = world.save(&image).unwrap();
assert_eq!(world.save(&image), Ok(path.clone()), "a replayed request is not an error");
assert_eq!(world.files(), [path.file_name().unwrap().to_str().unwrap()]);
// Same length, other bytes under the name: Exists, and the file is left as it was.
let held = world.sandbox.path().join(&path);
let mut other = PNG.to_vec();
*other.last_mut().unwrap() ^= 1;
std::fs::write(&held, &other).unwrap();
assert_eq!(world.save(&image), Err(SaveFault::Exists));
assert_eq!(std::fs::read(&held).unwrap(), other);
// Another length.
std::fs::write(&held, b"short").unwrap();
assert_eq!(world.save(&image), Err(SaveFault::Exists));
assert_eq!(world.files().len(), 1, "no .part left behind");
}
/// Runs `save` on a thread and fails the test if it does not return: a FIFO opened for reading would wait forever.
fn save_within(world: &World, image: &ChatImage) -> Result<PathBuf, SaveFault> {
let (store, sandbox, image) = (world.store.path().to_path_buf(), world.sandbox.path().to_path_buf(), image.clone());
let (send, receive) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = send.send(save(&store, &sandbox, ROOM, &image));
});
receive.recv_timeout(Duration::from_secs(10)).expect("the saver hung")
}
#[test]
fn a_fifo_or_odd_file_at_the_final_name_does_not_block_the_organ() {
use rustix::fs::{CWD, FileType, Mode, mknodat};
let world = World::new();
let image = world.put(ROOM, PNG, "png");
let held = world.attachments().join(format!("{}.png", image.sha256));
std::fs::create_dir(world.attachments()).unwrap();
mknodat(CWD, &held, FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap();
assert_eq!(save_within(&world, &image), Err(SaveFault::Exists));
std::fs::remove_file(&held).unwrap();
symlink("/dev/zero", &held).unwrap();
assert_eq!(save_within(&world, &image), Err(SaveFault::Exists));
std::fs::remove_file(&held).unwrap();
std::fs::create_dir(&held).unwrap();
assert_eq!(save_within(&world, &image), Err(SaveFault::Exists));
std::fs::remove_dir(&held).unwrap();
// A regular file of another length is not read at all; of the same length, only that many bytes plus one.
std::fs::write(&held, vec![0u8; 5 * 1024 * 1024]).unwrap();
assert_eq!(save_within(&world, &image), Err(SaveFault::Exists));
std::fs::write(&held, vec![0u8; PNG.len()]).unwrap();
assert_eq!(save_within(&world, &image), Err(SaveFault::Exists));
}
#[test]
fn a_crashed_write_leaves_no_partial_final_name_and_a_retry_saves_in_full() {
use rustix::fs::{CWD, FileType, Mode, mknodat};
let world = World::new();
let big: Vec<u8> = b"\x89PNG\r\n\x1a\n".iter().copied().chain((0..20_000u32).map(|i| (i % 251) as u8)).collect();
let image = world.put(ROOM, &big, "png");
let final_name = format!("{}.png", image.sha256);
let part = format!(".{final_name}.part");
CRASH_AT.set(Some(8192));
assert_eq!(world.save(&image), Err(SaveFault::WriteFailed));
CRASH_AT.set(None);
assert_eq!(world.files(), [part.as_str()], "only the temporary is left, and the final name is absent");
assert!(std::fs::metadata(world.attachments().join(&part)).unwrap().len() < big.len() as u64);
// The retry clears the leavings and saves in full.
assert!(world.save(&image).is_ok());
assert_eq!(world.files(), [final_name.as_str()]);
assert_eq!(std::fs::read(world.attachments().join(&final_name)).unwrap(), big);
// A FIFO or a link at the temporary name does not stop the next save either.
std::fs::remove_file(world.attachments().join(&final_name)).unwrap();
mknodat(CWD, world.attachments().join(&part), FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap();
assert!(save_within(&world, &image).is_ok());
symlink("/dev/zero", world.attachments().join(&part)).unwrap();
std::fs::remove_file(world.attachments().join(&final_name)).unwrap();
assert!(save_within(&world, &image).is_ok());
assert_eq!(world.files(), [final_name]);
}
/// The create call carries 0600, so the runner's umask can only narrow it: a looser mode in that call shows as 0644 or 0666 under the
/// common umask 022, and a tighter one as less than 0600. (The library reads no environment and forbids unsafe, so the test does not
/// set a umask; the source has no chmod, which the negative scan pins.)
#[test]
fn the_saved_file_is_mode_0600_and_the_directory_0700() {
let world = World::new();
let image = world.put(ROOM, PNG, "png");
let path = world.save(&image).unwrap();
assert_eq!(std::fs::metadata(world.sandbox.path().join(path)).unwrap().permissions().mode() & 0o7777, 0o600);
assert_eq!(std::fs::metadata(world.attachments()).unwrap().permissions().mode() & 0o7777, 0o700);
}
#[test]
fn a_file_or_link_planted_at_the_temporary_name_after_its_unlink_is_refused_and_never_written_through() {
let world = World::new();
let image = world.put(ROOM, PNG, "png");
let victim = world.sandbox.path().join("victim");
let part = world.attachments().join(format!(".{}.png.part", image.sha256));
for plant_a_link in [false, true] {
std::fs::write(&victim, b"keep me").unwrap();
let (victim_path, part_path) = (victim.clone(), part.clone());
let plant: Box<dyn Fn()> = Box::new(move || {
if plant_a_link {
symlink(&victim_path, &part_path).unwrap();
} else {
// A regular file of her own: an create without O_EXCL would open it and truncate.
std::fs::write(&part_path, b"hers").unwrap();
}
});
GAP.with(|gap| *gap.borrow_mut() = Some(plant));
let saved = world.save(&image);
GAP.with(|gap| *gap.borrow_mut() = None);
assert_eq!(saved, Err(SaveFault::WriteFailed), "link: {plant_a_link}");
assert_eq!(std::fs::read(&victim).unwrap(), b"keep me", "nothing was written through the planted name (link: {plant_a_link})");
if !plant_a_link {
assert_eq!(std::fs::read(&part).unwrap(), b"hers", "her file is not truncated");
}
assert!(!world.attachments().join(format!("{}.png", image.sha256)).exists(), "no final name from a refused create");
let _ = std::fs::remove_file(&part);
}
}
#[test]
fn a_link_to_a_same_length_regular_file_at_the_final_name_is_exists_not_saved() {
let world = World::new();
let image = world.put(ROOM, PNG, "png");
let outside = world.sandbox.path().join("outside.bin");
std::fs::write(&outside, PNG).unwrap();
std::fs::create_dir(world.attachments()).unwrap();
symlink(&outside, world.attachments().join(format!("{}.png", image.sha256))).unwrap();
assert_eq!(world.save(&image), Err(SaveFault::Exists), "a link is not a file in her sandbox, whatever it points at");
}

View file

@ -12,8 +12,10 @@
//! Environment: `HEARTBEAT_PERSONAS` (`slug,handle,Public Name,@matrix:id,rudp://<ip>:<port>`
//! entries separated by `;`, the last field her own Huginn daemon: each Mind is
//! its own daemon), `MIND_PERSONA_OPERATOR` (id[,id]), `HEARTBEAT_POLL_S`,
//! `BIFROST_CHAT_ENDPOINT` and `BIFROST_CHAT_KEY_FILE`, and `STATE_DIRECTORY`
//! (`heartbeat.cc` lives there). The heartbeat holds no connector key.
//! `HEARTBEAT_BEAT_S` (seconds between beats, default 1800), `BIFROST_CHAT_ENDPOINT`,
//! `BIFROST_CHAT_KEY_FILE`, `STATE_DIRECTORY` (`heartbeat.cc` lives there) and `MIND_HEARTBEAT_TRACES`, the path of each Persona's
//! `persona-trace.cc` with `{slug}` where her slug goes (read through a lock-free snapshot, no write access: her trace is the record of which lines she has decided).
//! The heartbeat holds no connector key.
use std::net::SocketAddr;
use std::path::Path;
@ -22,17 +24,14 @@ use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
use eureka_state::HuginnClient;
use mind_body::chat_rudp::{RudpChat, connection_id};
use mind_body::heartbeat::{Config, FileControl, FileStore, HeartbeatView, Night, Organs, PersonaId, Seat, poll};
use mind_body::heartbeat::{Config, DEFAULT_BEAT_S, FileControl, FileStore, Organs, PersonaId, Seat, poll};
use mind_body::persona::TraceSnapshot;
use mind_body::launch::{SystemClock, SystemdLauncher};
use mind_body::queue::HuginnMind;
const TIMEOUT: Duration = Duration::from_secs(15);
const CHAT_TIMEOUT: Duration = Duration::from_secs(20);
fn host() -> String {
std::fs::read_to_string("/proc/sys/kernel/hostname").map(|name| name.trim().to_string()).ok().filter(|name| !name.is_empty()).unwrap_or_else(|| "unknown".into())
}
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")]
fn setting(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|value| !value.is_empty())
@ -61,8 +60,8 @@ fn config() -> Result<Config> {
.map(PersonaId::parse)
.collect::<Result<Vec<_>>>()?;
let operators = required("MIND_PERSONA_OPERATOR")?.split(',').map(|id| id.trim().to_string()).filter(|id| !id.is_empty()).collect();
let night = Night::from_settings(setting("HEARTBEAT_SLEEP_UTC").as_deref(), setting("HEARTBEAT_SLEEP_MINDS").as_deref())?;
Config::new(personas, operators, night)
let beat_s = u32::try_from(whole("HEARTBEAT_BEAT_S", i64::from(DEFAULT_BEAT_S))?).map_err(|_| anyhow!("HEARTBEAT_BEAT_S is out of range"))?;
Config::new(personas, operators, beat_s)
}
fn store() -> Result<FileStore> {
@ -87,15 +86,19 @@ fn run() -> Result<()> {
let poll_s = u64::try_from(whole("HEARTBEAT_POLL_S", 20)?).map_err(|_| anyhow!("HEARTBEAT_POLL_S is negative"))?.max(1);
let minds: Vec<HuginnMind> = config.personas.iter().map(|who| HuginnMind::new(HuginnClient::new(who.huginn, who.slug.clone(), TIMEOUT))).collect();
let chats: Vec<RudpChat> = config.personas.iter().map(|who| RudpChat::new(chat_address, chat_id, who.slug.0.clone(), CHAT_TIMEOUT)).collect();
let traces_at = required("MIND_HEARTBEAT_TRACES")?;
if !traces_at.contains("{slug}") {
bail!("MIND_HEARTBEAT_TRACES names no {{slug}}");
}
let traces: Vec<TraceSnapshot> = config.personas.iter().map(|who| TraceSnapshot::new(traces_at.replace("{slug}", &who.slug.0))).collect();
let seats: Vec<Seat> = config
.personas
.iter()
.zip(minds.iter().zip(chats.iter()))
.map(|(who, (mind, chat))| Seat { who: who.clone(), mind, chat })
.zip(minds.iter().zip(chats.iter().zip(traces.iter())))
.map(|(who, (mind, (chat, trace)))| Seat { who: who.clone(), mind, chat, trace })
.collect();
let launcher = SystemdLauncher::new();
let host = host();
let organs = Organs { seats: &seats, control: &FileControl, launcher: &launcher, clock: &SystemClock, host: &host, store: &store };
let organs = Organs { seats: &seats, control: &FileControl, launcher: &launcher, clock: &SystemClock, store: &store };
loop {
match poll(&organs, &config) {
Ok(outcome) => println!("{outcome}"),

View file

@ -1,55 +1,90 @@
//! `mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>]`:
//! one start of the Persona organ (`mind_body::persona::carry`) inside
//! `mind-persona@<instance>`. This reads the process's arguments and
//! environment, the things the library never reads, and prints the outcome. It
//! exits 0 for every outcome, including a unit that is dead because the brake is
//! held or the dial out of bounds, and 2 when the mind cannot be reached, the
//! arguments or the environment are wrong or a transport is not configured.
//! 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: 1 wake, K turns, ended idle, acked through S`), one wake that stays
//! 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
//! are wrong.
//!
//! The unit's `persona.env` and credentials name everything else:
//! `MIND_PERSONA_ROOMS` (a,b), `MIND_PERSONA_OPERATOR`
//! (id[,id]), `MIND_PERSONA_MINDS` (id[,id]: every Mind of the swarm, required) and `MIND_PERSONA_SELF_SENDER`, each also a flag that overrides it
//! (`--rooms`, `--operator`, `--minds`, `--self-sender`), and `MIND_HEARTBEAT_STATE` (optional: the path of the
//! heartbeat's `heartbeat.cc`, which the unit reads and never writes, for the tempo in her input); `MIND_PERSONA_DOCTRINE`
//! (optional, absolute paths separated by `:`) names the doctrine files read at each
//! process start and put ahead of her persona; `MIND_PERSONA_MODEL` is the model her session runs;
//! `MIND_PERSONA_RUN_CAP_S` is the unit's `RuntimeMaxSec` in seconds, the one length of a start;
//! `MIND_PERSONA_CONFIG_SEED` optionally names a root-owned directory copied into each
//! process's fresh configuration; `CLAUDE_LEASE_SOCKET` is the connector's lease socket (the token itself
//! is never in this process's environment, only the descriptor a lease grants); `RUNTIME_DIRECTORY` (the
//! unit's `RuntimeDirectory=`) holds each process's configuration and instructions; `BIFROST_CHAT_ENDPOINT`
//! (`rudp://<ip>:<port>`, the mouth) and `BIFROST_CHAT_KEY_FILE`; `BIFROST_CHAT_PENDING_V4` set to exactly `1` asks the mouth for the
//! reply link (`chat_pending.v4`), anything else or unset does not. `BIFROST_CHAT_FETCH` set to exactly `1` lets her ask the mouth to keep one event's image (`save_attachment`); the operator sets it only once the mouth runs `CHAT_FETCH=1`. Without
//! `--endpoint` the daemon is `HUGINN_ENDPOINT`; the trace is `persona-trace.cc`
//! under `STATE_DIRECTORY`, and her sandbox is `STATE_DIRECTORY/sandbox`. The key file is read here and its
//! text goes to the transport, which holds it; nothing is printed.
//! The persona flags (`--rooms`, `--operator`, `--minds`, `--self-sender`, or
//! `MIND_PERSONA_ROOMS`, `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS`,
//! `MIND_PERSONA_SELF_SENDER` and `MIND_PERSONA_MODEL` from the unit's
//! `persona.env`) are parsed first, so a start refuses a configuration the turn will not run on. A released start needs
//! the daemon (`--endpoint` or `HUGINN_ENDPOINT`, her persona door), the mouth (`BIFROST_CHAT_ENDPOINT`,
//! `BIFROST_CHAT_KEY_FILE`), the connector (`MIND_PERSONA_CONNECTOR_ENDPOINT` and the `connector-key` credential) and
//! `STATE_DIRECTORY`, where her trace is `persona-trace.cc`; it reads `MIND_PERSONA_FORGE_URL`, `MIND_PERSONA_TUNING`
//! and `MIND_HEARTBEAT_STATE` as `project` does. Without the connector or the mouth it ends `failed`, touching nothing.
//!
//! `mind-persona trace --instance <slug> [--last N]` prints the newest N (default 20) records of her trace as JSON lines,
//! 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>]
//! [--room <fixture.toml>] [--seed N] [--state <file>] [--told <rows.json>] [--select-only | --renders K
//! [--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
//! state (or `--state`, checked as a put checks its content, rules P1 to P3; P4 and P5 compare it with the stored document
//! and are not checked), opened by what the trace rows of `--told` tell her, and with `--renders` the Projector's
//! narrations of K successive turns;
//! `--through persona` adds her prose; `--judge` renders a second state too and asks
//! the model which narration came from which. It writes nothing and reads no brake.
//!
//! Live, it reads `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS` and `MIND_PERSONA_SELF_SENDER` (required), the heartbeat's
//! addressing from `MIND_HEARTBEAT_STATE`, which a run by hand must set as the unit does (`/var/lib/mind-heartbeat/heartbeat.cc`):
//! without it "said to her" knows only her own names, never her projects', and stderr says so before the report. The
//! room comes from the mouth when `BIFROST_CHAT_ENDPOINT` and
//! `BIFROST_CHAT_KEY_FILE` are set; `--in` keeps one room. `--room <fixture>` replaces all of that with a mocked room
//! (`projection::harness::Fixture`): her id, who is who, the messages, the clock and the "last heard from" table. With
//! `--room` and `--state` no daemon and no mouth is needed: without `--endpoint` or `HUGINN_ENDPOINT` none is reached.
//!
//! `mind-persona project --instance <slug> (--batch <plan.toml> | --simulate <plan.toml>) --out <report.md>` runs a plan
//! and writes one Markdown report: a batch of states by scenarios by samples (`harness::batch`), or the swarm's cast taking
//! turns in one simulated room (`harness::simulate`). Each case is one `project`.
//!
//! Her domain (what moved lately in her stewarded repos and her campaigns, map 16.22.2) is read when `MIND_PERSONA_FORGE_URL`
//! names the forge's API root (on Yggdrasil the loopback `http://127.0.0.1:3310`) and a daemon endpoint is given: her
//! mind through that endpoint, which a Persona reaches at her read door, and the forge anonymously. Without either the
//! packet has no domain section and the report says so. A room fixture's `[domain]` replaces both; its `[[read]]` entries record the reads
//! the agent will perform.
//!
//! The tuning is `MIND_PERSONA_TUNING`, else `/etc/gamecult/minds/<instance>/persona-tuning.toml`; renders and plans need
//! `MIND_PERSONA_CONNECTOR_ENDPOINT` (`<loopback ip>:<port>`) and the `connector-key` credential in
//! `CREDENTIALS_DIRECTORY`. Without `--select-only` or `--renders` it renders once.
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
use eureka_pipeline::Slug;
use eureka_state::HuginnClient;
use mind_body::chat_rudp::{RudpChat, connection_id};
use mind_body::cli::instance_and_endpoint;
use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint};
use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path};
use mind_body::launch::{SystemClock, SystemdLauncher};
use mind_body::heartbeat::FileStore;
use mind_body::lease_client::{LEASE_SOCKET_VARIABLE, SocketLender};
use mind_body::persona::{Config, ENV_CONFIG_SEED, ENV_RUN_CAP, FileTrace, HuginnPersona, Organs, SANDBOX_DIR, carry};
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::queue::HuginnMind;
use mind_body::self_run::{ClaudeSpawner, SCRATCH_VARIABLE};
/// How long one call to the mind may take.
const TIMEOUT: Duration = Duration::from_secs(15);
/// How long the mouth may take to answer one chat request (a send is a Matrix PUT).
const CHAT_TIMEOUT: Duration = Duration::from_secs(20);
use mind_body::sandbox::{BoxPaths, COMMONS_RW, serve_box};
use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file};
use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project};
const USAGE: &str = "usage: mind-persona --instance <slug> [--endpoint rudp://<ip>:<port>] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]";
fn host() -> String {
std::fs::read_to_string("/proc/sys/kernel/hostname").map(|name| name.trim().to_string()).ok().filter(|name| !name.is_empty()).unwrap_or_else(|| "unknown".into())
}
const TRACE_USAGE: &str = "usage: mind-persona trace --instance <slug> [--last N]";
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.
const TIMEOUT: Duration = Duration::from_secs(15);
/// How long the mouth may take to answer one read.
const CHAT_TIMEOUT: Duration = Duration::from_secs(20);
/// How long the kit may take to answer one Projector or judge turn.
const MODEL_TIMEOUT: Duration = Duration::from_secs(300);
// The binary is the one place that reads the process: its arguments and
// the environment. The library reads neither (clippy.toml, `#![forbid]` in lib.rs).
@ -58,6 +93,98 @@ fn setting(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|value| !value.is_empty())
}
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and environment, and hands them to the library")]
fn run() -> Result<Outcome> {
let args: Vec<String> = std::env::args().skip(1).collect();
let (config, rest) = Config::from_args_and_env(&args, setting, USAGE)?;
let (instance, endpoint) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), USAGE)?;
let control = FileSource::new(control_path(Path::new(CONTROL_ROOT), &instance)?);
let swarm = FileSource::new(swarm_path(Path::new(CONTROL_ROOT)));
Ok(carry(&control, &swarm, &instance, || start(config, &instance, endpoint)))
}
/// The organs of a released start: built only when the brakes allow a turn, each from the unit's environment.
fn start(config: Config, instance: &Slug, endpoint: SocketAddr) -> Result<Start<RudpChat>> {
let chat = chat(instance)?.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT and BIFROST_CHAT_KEY_FILE are not set"))?;
let connector: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
let model = Rc::new(KitModel::open(connector, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?);
let client = || HuginnClient::new(endpoint, instance.clone(), TIMEOUT);
let forge = setting("MIND_PERSONA_FORGE_URL");
Ok(Start {
config,
persona: Box::new(HuginnPersonaSource::new(client())),
chat,
trace: Box::new(FileTrace::new(state_directory()?.join("persona-trace.cc"))),
addressing: setting("MIND_HEARTBEAT_STATE").map(|path| Box::new(FileStore::new(path)) as Box<dyn HeartbeatView>),
model: Box::new(model.clone()),
agent: Box::new(model),
domain: forge.as_deref().map(|forge| Box::new(MindDomain::new(client(), HttpForge::new(forge))) as Box<dyn DomainSource>),
reads: Some(Box::new(LiveReads::new(client(), forge.as_deref().map(HttpForge::new)))),
tuning: tuning_of(instance),
session: state_directory()?.join("agent-session.cc"),
box_socket: PathBuf::from(required("MIND_PERSONA_BOX_SOCKET")?),
clock: Box::new(chrono::Utc::now),
pause: Box::new(std::thread::sleep),
})
}
/// The unit's state directory: the first of `STATE_DIRECTORY`'s entries.
fn state_directory() -> Result<PathBuf> {
let directory = required("STATE_DIRECTORY")?;
Ok(PathBuf::from(directory.split(':').next().unwrap_or_default()))
}
/// Her trace: the unit's state directory, `persona-trace.cc`.
fn trace_of() -> Result<FileTrace> {
Ok(FileTrace::new(state_directory()?.join("persona-trace.cc")))
}
/// `box-exec --instance <slug>`: one command in her box, run by `mind-box-<m>@.service` as `mind-<m>-box` with the connection
/// as stdin and stdout. Her box's home is the unit's `STATE_DIRECTORY`, its scratch the unit's `RUNTIME_DIRECTORY`, and the
/// commons data dirs are bound writable (`sandbox::COMMONS_RW`).
fn run_box_exec(args: &[String]) -> Result<()> {
match args {
[flag, _instance] if flag == "--instance" => {}
_ => bail!("{BOX_USAGE}"),
}
let (home, scratch) = (state_directory()?, PathBuf::from(required("RUNTIME_DIRECTORY")?.split(':').next().unwrap_or_default()));
let commons: Vec<&Path> = COMMONS_RW.iter().map(Path::new).collect();
serve_box(std::io::stdin().lock(), std::io::stdout().lock(), &BoxPaths { home: &home, scratch: &scratch, extra_rw: &commons })?;
Ok(())
}
/// The tuning file: `MIND_PERSONA_TUNING`, else the installed one.
fn tuning_of(instance: &Slug) -> PathBuf {
setting("MIND_PERSONA_TUNING").map_or_else(|| Path::new(TUNING_ROOT).join(&instance.0).join(TUNING_FILE), PathBuf::from)
}
/// The mouth, when the environment names it.
fn chat(instance: &Slug) -> Result<Option<RudpChat>> {
match (setting("BIFROST_CHAT_ENDPOINT"), setting("BIFROST_CHAT_KEY_FILE")) {
(Some(endpoint), Some(_)) => {
let endpoint: SocketAddr = endpoint.strip_prefix("rudp://").and_then(|address| address.parse().ok()).ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://<ip>:<port>"))?;
Ok(Some(RudpChat::new(endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT)))
}
_ => Ok(None),
}
}
/// `trace --instance <slug> [--last N]`: the newest records of her trace, as JSON lines.
fn run_trace(args: &[String]) -> Result<String> {
let (mut instance, mut last) = (None, 20usize);
let mut given = args.iter();
while let Some(flag) = given.next() {
let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{TRACE_USAGE}"));
match flag.as_str() {
"--instance" => instance = Some(value()?),
"--last" => last = value()?.parse().map_err(|_| anyhow!("{TRACE_USAGE}"))?,
_ => bail!("{TRACE_USAGE}"),
}
}
instance.ok_or_else(|| anyhow!("{TRACE_USAGE}"))?;
Ok(trace_lines(&trace_of()?, last)?.join("\n"))
}
fn required(name: &str) -> Result<String> {
setting(name).ok_or_else(|| anyhow!("{name} is not set"))
}
@ -67,38 +194,208 @@ 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"))
}
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and environment, and hands them to the library")]
fn run() -> Result<String> {
let args: Vec<String> = std::env::args().skip(1).collect();
let (config, rest) = Config::from_args_and_env(&args, setting, USAGE)?;
let (instance, address) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), USAGE)?;
let Some(state) = setting("STATE_DIRECTORY") else { bail!("no STATE_DIRECTORY") };
let chat_endpoint: SocketAddr = required("BIFROST_CHAT_ENDPOINT")?
.strip_prefix("rudp://")
.and_then(|address| address.parse().ok())
.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://<ip>:<port>"))?;
let reply_link = setting("BIFROST_CHAT_PENDING_V4").as_deref() == Some("1");
let chat = RudpChat::new(chat_endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT).with_reply_link(reply_link);
let run_cap_s: u64 = setting(ENV_RUN_CAP).and_then(|seconds| seconds.parse().ok()).filter(|seconds| *seconds > 0).ok_or_else(|| anyhow!("{ENV_RUN_CAP} is not set to the unit's RuntimeMaxSec in seconds"))?;
let scratch = PathBuf::from(required(SCRATCH_VARIABLE)?);
let sandbox = Path::new(&state).join(SANDBOX_DIR);
let lender = SocketLender::new(required(LEASE_SOCKET_VARIABLE)?);
let spawner = ClaudeSpawner::in_sandbox(std::env::vars_os(), ENV_CONFIG_SEED, Some(sandbox.clone()))?;
let source = FileSource::new(control_path(Path::new(CONTROL_ROOT), &instance)?);
let mind = HuginnMind::new(HuginnClient::new(address, instance.clone(), TIMEOUT));
let persona = HuginnPersona::new(HuginnClient::new(address, instance, TIMEOUT));
let trace = FileTrace::new(Path::new(&state).join("persona-trace.cc"));
let launcher = SystemdLauncher::new();
let host = host();
let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new);
let organs = Organs { mind: &mind, launcher: &launcher, clock: &SystemClock, host: &host, chat: &chat, persona: &persona, trace: &trace, heartbeat: heartbeat.as_ref().map(|store| store as &dyn mind_body::heartbeat::HeartbeatView), lender: &lender, spawner: &spawner, run_cap_s, sandbox: &sandbox, scratch: &scratch };
let swarm = FileSource::new(swarm_path(Path::new(CONTROL_ROOT)));
Ok(carry(&organs, &source, &swarm, &config)?.to_string())
/// The rows she is told, from a file (`--told`): a JSON array of trace rows, as `mind-persona trace` prints them.
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()))?;
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.
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")]
fn credentials_directory() -> Result<PathBuf> {
std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from).ok_or_else(|| anyhow!("CREDENTIALS_DIRECTORY is not set"))
}
fn run_project(args: &[String]) -> Result<String> {
let (mut kind, mut here, mut fixture, mut seed, mut state, mut renders, mut select_only, mut judge, mut through) = (None, None, None, None, None, None, false, None, Through::Projector);
let (mut batch_plan, mut simulate_plan, mut out, mut told, mut rest) = (None, None, None, None, Vec::new());
let mut given = args.iter();
while let Some(flag) = given.next() {
let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{PROJECT_USAGE}"));
match flag.as_str() {
"--kind" => {
kind = Some(match value()?.as_str() {
"chat" => TurnKind::Chat,
"beat" => TurnKind::Beat,
"reflection" => TurnKind::Reflection,
_ => bail!("{PROJECT_USAGE}"),
})
}
"--in" => here = Some(value()?),
"--room" => fixture = Some(Fixture::load(Path::new(&value()?))?),
"--seed" => seed = Some(value()?.parse::<u64>().map_err(|_| anyhow!("{PROJECT_USAGE}"))?),
"--state" => state = Some(value()?),
"--told" => told = Some(value()?),
"--renders" => renders = Some(value()?.parse::<usize>().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?),
"--judge" => judge = Some(value()?),
"--through" => {
through = match value()?.as_str() {
"projector" => Through::Projector,
"persona" => Through::Persona,
_ => bail!("{PROJECT_USAGE}"),
}
}
"--batch" => batch_plan = Some(PathBuf::from(value()?)),
"--simulate" => simulate_plan = Some(PathBuf::from(value()?)),
"--out" => out = Some(PathBuf::from(value()?)),
"--select-only" => select_only = true,
"--instance" | "--endpoint" => rest.extend([flag.clone(), value()?]),
_ => bail!("{PROJECT_USAGE}"),
}
}
let planned = batch_plan.is_some() || simulate_plan.is_some();
// A plan carries its own states, rooms, seeds and stage; a fixture carries its own kind and room.
if (select_only && (renders.is_some() || judge.is_some() || through != Through::Projector))
|| (batch_plan.is_some() && simulate_plan.is_some())
|| (planned && (out.is_none() || fixture.is_some() || state.is_some() || told.is_some() || kind.is_some() || here.is_some() || seed.is_some() || renders.is_some() || judge.is_some() || select_only || through != Through::Projector))
|| (!planned && out.is_some())
|| (fixture.is_some() && (kind.is_some() || here.is_some()))
{
bail!("{PROJECT_USAGE}");
}
let (instance, address) = instance_and_maybe_endpoint(&rest, setting("HUGINN_ENDPOINT"), PROJECT_USAGE)?;
let tuning = tuning_of(&instance);
// Her stored state is asked only when no state is given; with a state file no daemon is needed or reached.
let persona = address.map(|address| HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT)));
let renders = if select_only || planned { None } else { Some(renders.unwrap_or(1)) };
let model = if renders.is_some() || planned {
let endpoint: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
Some(KitModel::open(endpoint, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?)
} else {
None
};
let harness = Harness { instance: instance.0.clone(), persona: persona.as_ref().map(|persona| persona as &dyn PersonaSource), model: model.as_ref().map(|model| model as &dyn Model), tuning };
if let Some(out) = out {
let report = match (&batch_plan, &simulate_plan) {
(Some(plan), _) => batch(&harness, plan)?,
(_, Some(plan)) => simulate(&harness, plan)?,
_ => unreachable!("a plan was given"),
};
std::fs::write(&out, &report).with_context(|| format!("the report {} could not be written", out.display()))?;
return Ok(format!("wrote {} ({} bytes)", out.display(), report.len()));
}
let state = state.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?;
let judge = judge.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?;
let told: Vec<serde_json::Value> = told.map(|path| rows_file(Path::new(&path))).transpose()?.unwrap_or_default();
let seed_now = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default();
if let Some(fixture) = &fixture {
// The fixture is the room, the clock and who is who: no mouth, no heartbeat table, no persona.env.
let organs = ProjectOrgans { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model, domain: fixture.domain(), reads: fixture.reads() };
let request = ProjectRequest { judge_against: judge, told: told.clone(), ..fixture_request(&harness, fixture, state, seed.unwrap_or(seed_now), renders, through) };
return Ok(serde_json::to_string_pretty(&project(&organs, &request, fixture.now)?)?);
}
let chat = chat(&instance)?;
let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new);
// Her domain: her mind through the endpoint given (her read door, for a Persona) and the forge, both read-only.
let domain = match (address, setting("MIND_PERSONA_FORGE_URL")) {
(Some(address), Some(forge)) => Some(MindDomain::new(HuginnClient::new(address, instance.clone(), TIMEOUT), HttpForge::new(&forge))),
_ => None,
};
// Her own rooms, as the heartbeat reads them: the rooms the mouth names for a repo she stewards. An unread mind or mouth is
// said in the report, not read as no rooms.
let (own, own_unread) = match (address, &chat) {
(Some(address), Some(chat)) => match chat.pending() {
Ok(pending) => match own_rooms_among(&HuginnMind::new(HuginnClient::new(address, instance.clone(), TIMEOUT)), pending.deliveries.iter().map(|delivery| delivery.room_alias.as_str())) {
Ok(rooms) => (rooms, None),
Err(error) => (vec![], Some(format!("her stewardships unread: {error}"))),
},
Err(error) => (vec![], Some(format!("the mouth's pending unread: {error}"))),
},
_ => (vec![], None),
};
// The lines the heartbeat woke her for, from its handled keys; an unread state is said in the report, not read as none.
let (woken, woken_unread) = match heartbeat.as_ref().map(Store::load) {
Some(Ok(state)) => (state.map(|state| woken_for(&state, &instance.0)).unwrap_or_default(), None),
Some(Err(error)) => (vec![], Some(format!("the heartbeat state unread: {error}"))),
None => (vec![], None),
};
// Her reads by intent (map 16.22.3): her mind through the same endpoint, the forge when it is named, the web.
let reads = address.map(|address| LiveReads::new(HuginnClient::new(address, instance.clone(), TIMEOUT), setting("MIND_PERSONA_FORGE_URL").map(|forge| HttpForge::new(&forge))));
let organs = ProjectOrgans {
persona: harness.persona,
chat: chat.as_ref().map(|chat| chat as &dyn MouthReader),
addressing: heartbeat.as_ref().map(|store| store as &dyn HeartbeatView),
model: harness.model,
domain: domain.as_ref().map(|domain| domain as &dyn DomainSource),
reads: reads.as_ref().map(|reads| reads as &dyn ReadSource),
};
let request = ProjectRequest {
instance: instance.0.clone(),
kind: kind.unwrap_or(TurnKind::Beat),
state,
rooms: here.into_iter().collect(),
seed: seed.unwrap_or(seed_now),
renders,
judge_against: judge,
operators: setting("MIND_PERSONA_OPERATOR").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(),
minds: setting("MIND_PERSONA_MINDS").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(),
own_sender: required("MIND_PERSONA_SELF_SENDER")?,
tuning: harness.tuning.clone(),
through,
last_heard: vec![],
recent: vec![],
own_rooms: own,
woken_for: woken,
told,
tools: vec![],
last_wake: None,
records: vec![],
};
let mut report = project(&organs, &request, chrono::Utc::now())?;
if let Some(unread) = own_unread {
report["own_rooms_unread"] = unread.into();
}
if let Some(unread) = woken_unread {
report["woken_for_unread"] = unread.into();
}
let addressing = &report["addressing"];
// The addressing source is what decides "said to her": said first, where a person running this by hand sees it.
eprintln!(
"mind-persona project: addressing from {} ({}); table written {}",
addressing["source"].as_str().unwrap_or("?"),
addressing["why"].as_str().unwrap_or("?"),
addressing["age_minutes"].as_i64().map_or_else(|| "never".to_owned(), |minutes| format!("{minutes} min ago")),
);
Ok(serde_json::to_string_pretty(&report)?)
}
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments")]
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) == Some("project") {
match run_project(&args[1..]) {
Ok(report) => println!("{report}"),
Err(error) => {
eprintln!("mind-persona project: {error:#}");
std::process::exit(2);
}
}
return;
}
if args.first().map(String::as_str) == Some("box-exec") {
if let Err(error) = run_box_exec(&args[1..]) {
eprintln!("mind-persona box-exec: {error:#}");
std::process::exit(2);
}
return;
}
if args.first().map(String::as_str) == Some("trace") {
match run_trace(&args[1..]) {
Ok(lines) => println!("{lines}"),
Err(error) => {
eprintln!("mind-persona trace: {error:#}");
std::process::exit(2);
}
}
return;
}
match run() {
Ok(outcome) => println!("{outcome}"),
Ok(outcome) => {
println!("{outcome}");
if matches!(outcome, Outcome::Failed(_)) {
std::process::exit(1);
}
}
Err(error) => {
eprintln!("mind-persona: {error:#}");
std::process::exit(2);

View file

@ -1,124 +0,0 @@
//! `mind-stream --instance <slug> [--once] [--dry-run]`: her stream of thought.
//!
//! Without `--once` it runs forever: one `mind_body::stream::tick` per `STREAM_POLL_S`, or per
//! `STREAM_MIN_GAP_S` after a blank or a fault. `--dry-run` runs one tick that admits nothing and
//! prints the thought it would admit as JSON. A model or mind fault ends the tick, never the
//! process: it is one line on stderr. This reads the process's arguments and environment, which
//! the library never does.
//!
//! Environment: `HUGINN_ENDPOINT` (`rudp://<ip>:<port>`, her own daemon), `EUREKA_INSTANCE`
//! (when `--instance` is not given), `MIND_STREAM_CONNECTOR_ENDPOINT` (`<loopback ip>:<port>`, the
//! connector kit the Projector is asked through), `MIND_STREAM_PROJECTOR_MODEL` (the model id the
//! kit's caller row allows), `MIND_STREAM_ENDPOINT` (`http://<loopback>:<port>`, the model host) and
//! `MIND_STREAM_BASE_MODEL`. The connector key is the file `connector-key` in `CREDENTIALS_DIRECTORY`
//! (systemd's `LoadCredential`), read once; the caller id is the instance.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
use anyhow::{Result, anyhow, bail};
use chrono::Utc;
use eureka_pipeline::Slug;
use eureka_state::HuginnClient;
use mind_body::control::read_effective;
use mind_body::queue::HuginnMind;
use mind_body::stream::{HuginnPersonaSource, KitProjector, Mode, OllamaContinuer, Organs, Outcome, STREAM_MIN_GAP_S, STREAM_POLL_S, connector_key, tick};
const TIMEOUT: Duration = Duration::from_secs(30);
/// How long the kit may take to answer one Projector turn.
const PROJECTOR_TIMEOUT: Duration = Duration::from_secs(300);
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")]
fn setting(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|value| !value.is_empty())
}
/// The credentials directory systemd hands the unit; its absence names the variable.
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")]
fn credentials_directory() -> Result<PathBuf> {
std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from).ok_or_else(|| anyhow!("CREDENTIALS_DIRECTORY is not set"))
}
fn required(name: &str) -> Result<String> {
setting(name).ok_or_else(|| anyhow!("{name} is not set"))
}
struct Args {
instance: Option<String>,
once: bool,
dry_run: bool,
}
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments")]
fn arguments() -> Result<Args> {
let mut args = Args { instance: None, once: false, dry_run: false };
let mut given = std::env::args().skip(1);
while let Some(argument) = given.next() {
match argument.as_str() {
"--instance" => args.instance = Some(given.next().ok_or_else(|| anyhow!("--instance needs a slug"))?),
"--once" => args.once = true,
"--dry-run" => args.dry_run = true,
other => bail!("unknown argument {other}; usage: mind-stream --instance <slug> [--once] [--dry-run]"),
}
}
Ok(args)
}
fn run() -> Result<()> {
let args = arguments()?;
let instance = Slug(args.instance.map_or_else(|| required("EUREKA_INSTANCE"), Ok)?);
let address: SocketAddr = required("HUGINN_ENDPOINT")?
.strip_prefix("rudp://")
.and_then(|address| address.parse().ok())
.ok_or_else(|| anyhow!("HUGINN_ENDPOINT is not rudp://<ip>:<port>"))?;
let projector_model = required("MIND_STREAM_PROJECTOR_MODEL")?;
let base_model = required("MIND_STREAM_BASE_MODEL")?;
let connector: SocketAddr = required("MIND_STREAM_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_STREAM_CONNECTOR_ENDPOINT is not <ip>:<port>"))?;
let projector = KitProjector::open(connector, connector_key(&credentials_directory()?)?, &instance.0, &projector_model, PROJECTOR_TIMEOUT)?;
let continuer = OllamaContinuer::open(&required("MIND_STREAM_ENDPOINT")?, &base_model)?;
let mind = HuginnMind::new(HuginnClient::new(address, instance.clone(), TIMEOUT));
let persona = HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT));
let organs = Organs { mind: &mind, persona: &persona, projector: &projector, continuer: &continuer, base_model: &base_model };
let mode = if args.dry_run { Mode::DryRun } else { Mode::Live };
let once = args.once || args.dry_run;
loop {
let mut faulted = false;
let waits = match tick(&organs, &|| read_effective(&instance), mode, Utc::now()) {
Ok(Outcome::Thought { thought, admitted }) => {
if admitted {
println!("admitted {}:thought:{}", instance.0, thought.label.0);
} else {
println!("{}", serde_json::to_string_pretty(&*thought)?);
}
false
}
Ok(Outcome::Blank) => true,
Ok(Outcome::Held(reason)) => {
eprintln!("mind-stream: held ({reason:?}); nothing ticked");
false
}
Ok(Outcome::NotDue) => false,
Err(fault) => {
eprintln!("mind-stream: {}", format!("{fault:#}").replace('\n', " "));
faulted = true;
true
}
};
if once {
return if faulted { Err(anyhow!("the tick faulted")) } else { Ok(()) };
}
std::thread::sleep(Duration::from_secs(if waits { STREAM_MIN_GAP_S as u64 } else { STREAM_POLL_S as u64 }));
}
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(fault) => {
eprintln!("mind-stream: {}", format!("{fault:#}").replace('\n', " "));
ExitCode::FAILURE
}
}
}

View file

@ -36,6 +36,8 @@ pub const ACK: &str = "gamecult.persona.chat_ack.v1";
pub const READ: &str = "gamecult.persona.chat_read.v1";
pub const SEND_REQUEST: &str = "gamecult.persona.chat_send_request.v2";
pub const SEND_RECEIPT: &str = "gamecult.persona.chat_send_receipt.v2";
/// A send that repeats an earlier one: the v2 tuple plus `resend`, answered with the v2 receipt.
pub const SEND_REQUEST_V3: &str = "gamecult.persona.chat_send_request.v3";
/// Her request that the mouth open a DM with a person, and its answer.
pub const OPEN_DIRECT_REQUEST: &str = "gamecult.persona.chat_open_direct_request.v1";
pub const OPEN_DIRECT_RECEIPT: &str = "gamecult.persona.chat_open_direct_receipt.v1";
@ -94,6 +96,11 @@ pub struct ReplyTo {
pub event_id: String,
pub sender: String,
pub excerpt: Option<String>,
/// Whether the excerpt as sent reached `REPLY_EXCERPT_CHARS`, the mouth's cap: the line may run on past it, cut wherever the
/// cap fell. A line of exactly the cap reads as cut too; the mouth says nothing that tells the two apart. Read off the decode,
/// never sent.
#[serde(skip)]
pub at_cap: bool,
}
/// How a reply link out of the mouth's contract fails it, first by tuple order. A class and nothing the mouth sent, so no path can echo
@ -311,11 +318,11 @@ impl<'de> Deserialize<'de> for ReplyLink {
(Some(Element::Text(event_id)), _, _) if !event_id_shape(&event_id) => Self::Dropped(ReplyViolation::BadEventId),
(Some(Element::Text(_)), Some(Element::Text(sender)), _) if !matrix_user_id(&sender) => Self::Dropped(ReplyViolation::BadSenderId),
(Some(Element::Text(event_id)), Some(Element::Text(sender)), Some(excerpt)) => match excerpt {
Element::Nil => Self::Quote(ReplyTo { event_id, sender, excerpt: None }),
Element::Nil => Self::Quote(ReplyTo { event_id, sender, excerpt: None, at_cap: false }),
Element::Text(text) if text.chars().take(REPLY_EXCERPT_CHARS + 1).count() > REPLY_EXCERPT_CHARS => Self::Dropped(ReplyViolation::ExcerptTooLong),
Element::Text(text) => {
let shown = without_invisible(&text);
Self::Quote(ReplyTo { event_id, sender, excerpt: if shown.is_empty() { None } else { Some(shown) } })
let (shown, at_cap) = (without_invisible(&text), text.chars().count() == REPLY_EXCERPT_CHARS);
Self::Quote(ReplyTo { event_id, sender, excerpt: if shown.is_empty() { None } else { Some(shown) }, at_cap })
}
_ => Self::Dropped(ReplyViolation::ExcerptNotText),
},
@ -455,8 +462,10 @@ pub struct ChatPending {
pub tail_gaps: Vec<String>,
}
/// One line of the room tail: `[room, event_id, at_unix_ms, sender, form, basis, body]`. `room` is the configured alias (the room id
/// for a DM); `basis` is what Matrix says on the event itself, none being unproven; `body` is untrusted text clipped by the mouth.
/// One line of the room tail: `[room, event_id, at_unix_ms, sender, form, basis, body, reply_to]`. `room` is the configured alias (the
/// room id for a DM); `basis` is what Matrix says on the event itself, none being unproven; `body` is untrusted text clipped by the
/// mouth; `reply_to` is the event the line replies to, quoted as a delivery's is (Bifrost B3, map 16.20.10 K20). A mouth that sends
/// seven fields sends no reply links, and every line reads as replying to nothing.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TailLine {
pub room: String,
@ -466,6 +475,8 @@ pub struct TailLine {
pub form: Form,
pub basis: Option<Basis>,
pub body: String,
#[serde(default, skip_serializing_if = "ReplyLink::sends_nothing")]
pub reply_to: ReplyLink,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -496,15 +507,24 @@ pub enum Refusal {
PersonaMismatch,
UnknownRoom,
EmptyText,
/// The PUT was attempted and not answered (timed out, 5xx, 429): the event may exist.
SendFailed,
/// The mouth attempted no PUT (its start, a room join or a head read failed first): the send is certainly not posted.
NotSent,
UnknownPersona,
/// A send with a basis found the room had moved past it: the receipt names what moved it.
RoomMoved,
/// A resend the mouth cannot vouch for: it did not attempt that request id for this Persona and room within its resend window (forgotten,
/// too old, lost in a restart). It posted nothing now, and whether the first try posted is unknown.
ResendUnknown,
/// The mouth does not serve this document kind. Answers an open-direct request only: a send receipt never carries it.
UnknownKind,
}
impl Refusal {
/// Every kind the mouth names.
pub const ALL: [Self; 10] = [Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::NotSent, Self::UnknownPersona, Self::RoomMoved, Self::ResendUnknown, Self::UnknownKind];
/// The mouth's spelling: a MessagePack string, whatever the codec does with unit variants.
pub fn name(self) -> &'static str {
match self {
@ -513,13 +533,44 @@ impl Refusal {
Self::UnknownRoom => "UnknownRoom",
Self::EmptyText => "EmptyText",
Self::SendFailed => "SendFailed",
Self::NotSent => "NotSent",
Self::UnknownPersona => "UnknownPersona",
Self::RoomMoved => "RoomMoved",
Self::ResendUnknown => "ResendUnknown",
Self::UnknownKind => "UnknownKind",
}
}
}
impl Refusal {
/// What the mouth's refusal says of a send, by whether the send repeats one already handed to the mouth (`resend`): the homeserver was
/// not heard, so the event may exist and the send stays handed (`NoAnswer`); the mouth attempted no PUT (`NotSent`); an earlier try's
/// outcome cannot be told, so the send is never repeated (`Unknown`); or the mouth declined before it put anything (`Declined`), which
/// for a repeat says nothing of the earlier try, whose outcome stays unknown. The match names every kind, so a new one has to be placed.
pub(crate) fn reading(self, resend: bool) -> Reading {
match self {
// The mouth's PUT timed out or the homeserver answered 5xx or 429: the event may have been persisted, and the same id is safe to repeat.
Self::SendFailed => Reading::NoAnswer,
// The mouth made no PUT this time.
Self::NotSent => Reading::NotSent,
// A resend the mouth does not remember attempting: the first try may have posted, and the id can no longer be told from a new line.
Self::ResendUnknown => Reading::Unknown,
// The mouth's checks that come before its vouch for a resend, and `RoomMoved`, which a resend skips.
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind if resend => Reading::Unknown,
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind => Reading::Declined,
}
}
}
/// How a send's settlement reads a refusal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Reading {
Declined,
NoAnswer,
NotSent,
Unknown,
}
impl Serialize for Refusal {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.name())
@ -529,7 +580,7 @@ impl Serialize for Refusal {
impl<'de> Deserialize<'de> for Refusal {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let name = String::deserialize(deserializer)?;
[Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::UnknownPersona, Self::RoomMoved, Self::UnknownKind]
Self::ALL
.into_iter()
.find(|refusal| refusal.name() == name)
.ok_or_else(|| serde::de::Error::custom("the mouth named a refusal this side does not know"))
@ -567,7 +618,9 @@ pub struct SendBasis {
}
/// A send. `request_id` is the mouth's transaction id, so a repeat of the same
/// id is the same send. No `basis` is her choice standing: the mouth checks nothing.
/// id is the same send. No `basis` is her choice standing: the mouth checks nothing. `resend` says this repeats an earlier send
/// under the same id: the mouth does not check its basis (the decision was made against the first try's), and the homeserver answers
/// with the first try's event if it was made. It is on the wire only when true, as the sixth field of the v3 request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatSendRequest {
pub request_id: String,
@ -575,6 +628,8 @@ pub struct ChatSendRequest {
pub room_alias: String,
pub text: String,
pub basis: Option<SendBasis>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub resend: bool,
}
/// The mouth's answer to a send: the event it made, or why it did not. `newer` names the events that moved the

View file

@ -129,12 +129,28 @@ fn the_pending_answer_decodes_with_the_tail_field_and_without_it() {
golden(PENDING_UNPROVEN_NOTICE_TAILED_BYTES, &one(false, &[], None, Form::Notice, Some(vec![])));
let tailed: ChatPending = decode(PENDING_TAIL_BYTES).unwrap();
assert!(tailed.deliveries.is_empty());
let line = |event: &str, at, form, basis, body: &str| TailLine { room: "#operator:gamecult.org".into(), event_id: event.into(), at_unix_ms: at, sender: "@meta:gamecult.org".into(), form, basis, body: body.into() };
let line = |event: &str, at, form, basis, body: &str| TailLine { room: "#operator:gamecult.org".into(), event_id: event.into(), at_unix_ms: at, sender: "@meta:gamecult.org".into(), form, basis, body: body.into(), reply_to: ReplyLink::Absent };
assert_eq!(tailed.tail, Some(vec![line("$e0", 1_700_000_000_000, Form::Message, None, "earlier"), line("$e1", 1_700_000_001_000, Form::Notice, Some(Basis::Tag), "hello eureka")]));
golden(PENDING_TAIL_BYTES, &tailed);
assert_eq!(rmp_serde::from_slice::<serde_json::Value>(PENDING_TAIL_BYTES).unwrap()[2][0].as_array().unwrap().len(), 7, "a tail line is seven fields");
}
/// A tail line may carry the event it replies to at index 7, quoted as a delivery's is (Bifrost B3, map 16.20.10 K20): a quote decodes,
/// a defective one is dropped without failing the poll, and a line without it replies to nothing and encodes as seven fields again.
#[test]
fn a_tail_line_carries_the_event_it_replies_to() {
let mut value: serde_json::Value = rmp_serde::from_slice(PENDING_TAIL_BYTES).unwrap();
value[2][1].as_array_mut().unwrap().push(serde_json::json!(["$e0", "@meta:gamecult.org", "earlier"]));
value[2][0].as_array_mut().unwrap().push(serde_json::json!(["$q", "@a:b", 5]));
let tail = decode::<ChatPending>(&rmp_serde::to_vec(&value).unwrap()).unwrap().tail.unwrap();
assert_eq!(tail[1].reply_to, ReplyLink::Quote(ReplyTo { event_id: "$e0".into(), sender: "@meta:gamecult.org".into(), excerpt: Some("earlier".into()), at_cap: false }));
assert_eq!(tail[0].reply_to, ReplyLink::Dropped(ReplyViolation::ExcerptNotText), "a defective link drops that quote only");
let plain: ChatPending = decode(PENDING_TAIL_BYTES).unwrap();
assert!(plain.tail.unwrap().iter().all(|line| line.reply_to == ReplyLink::Absent), "seven fields reply to nothing");
let reencoded: serde_json::Value = rmp_serde::from_slice(&encode(&decode::<ChatPending>(&rmp_serde::to_vec(&value).unwrap()).unwrap()).unwrap()).unwrap();
assert_eq!((reencoded[2][0].as_array().unwrap().len(), reencoded[2][1].as_array().unwrap().len()), (7, 8), "only a quote is sent");
}
#[test]
fn a_basis_or_form_this_side_does_not_know_does_not_decode() {
let mut value: serde_json::Value = rmp_serde::from_slice(PENDING_TAG_BYTES).unwrap();
@ -184,7 +200,7 @@ fn a_refusal_is_the_mouths_bytes_and_a_typed_name() {
#[test]
fn a_send_and_its_receipt_are_the_mouths_bytes() {
let request = |basis: Option<SendBasis>| ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#swarm:gamecult.org".into(), text: "hi".into(), basis };
let request = |basis: Option<SendBasis>| ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#swarm:gamecult.org".into(), text: "hi".into(), basis, resend: false };
golden(NIL_BASIS_BYTES, &request(None));
golden(SEEN_AND_SINCE_BYTES, &request(Some(SendBasis { seen_event_id: Some("$seen".into()), since_unix_ms: 1_793_698_425_998 })));
golden(SINCE_ONLY_BYTES, &request(Some(SendBasis { seen_event_id: None, since_unix_ms: 1_793_698_425_998 })));
@ -333,7 +349,7 @@ fn the_pending_answer_decodes_tail_gaps_and_defaults_them_to_none() {
}
fn quote(sender: &str, excerpt: Option<&str>) -> ReplyLink {
ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: sender.into(), excerpt: excerpt.map(Into::into) })
ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: sender.into(), excerpt: excerpt.map(Into::into), at_cap: false })
}
/// The v4 answers carry `reply_to` at delivery index 14. The mouth always sends the fourth, empty `tail_gaps` element on a v4 answer,
@ -562,7 +578,7 @@ fn format_and_private_use_characters_are_stripped_from_the_excerpt() {
fn an_excerpt_emptied_by_stripping_is_none_and_the_quote_stays() {
for sent in ["\u{FE0F}", "\u{200B}\u{E0049}", &"\u{FE0F}\u{200D}".repeat(5), ""] {
let link = link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", sent])));
assert_eq!(link, ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: "@alice:gamecult.org".into(), excerpt: None }), "{sent:?}");
assert_eq!(link, ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: "@alice:gamecult.org".into(), excerpt: None, at_cap: false }), "{sent:?}");
}
assert_eq!(excerpt_of(" ").as_deref(), Some(" "));
assert_eq!(link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", null]))), quote("@alice:gamecult.org", None));
@ -576,6 +592,11 @@ fn the_excerpt_bound_is_checked_before_the_strip_and_never_clips() {
assert_eq!(dropped_as(long(240, "\u{FE0F}")), Some(ReplyViolation::ExcerptTooLong));
assert_eq!(excerpt_of(&format!("{}\u{FE0F}", "x".repeat(239))).map(|t| t.chars().count()), Some(239));
assert_eq!(dropped_as(serde_json::json!(["$q1", "@a:b", "\u{FE0F}".repeat(1_000_000)])), Some(ReplyViolation::ExcerptTooLong));
// An excerpt that reached the cap as sent may be cut, whatever the strip left of it; one short of it is whole.
let at_cap = |sent: serde_json::Value| link_of(&answer_with(sent)).quote().map(|quote| quote.at_cap);
assert_eq!(at_cap(long(240, "")), Some(true));
assert_eq!(at_cap(long(239, "\u{FE0F}")), Some(true));
assert_eq!(at_cap(long(239, "")), Some(false));
}
/// Invalid UTF-8 in the excerpt's bytes is a defect of that quote, never of the document.
@ -647,3 +668,16 @@ fn invisible_cells_that_render_as_nothing_are_stripped_from_the_excerpt() {
assert_eq!(excerpt_of("\u{2800}\u{3164}"), None);
assert_eq!(excerpt_of("a\u{00A0}b").as_deref(), Some("a\u{00A0}b"), "NBSP stays");
}
/// The v3 send is the v2 tuple plus `resend` (Bifrost `sendRequestV3Tuple`), and a first try stays the v2 tuple the mouth has always read.
#[test]
fn a_resend_is_the_v2_tuple_plus_one_boolean_and_a_first_send_is_the_v2_tuple() {
let first = ChatSendRequest { request_id: "req-1".into(), persona: "eureka".into(), room_alias: "#swarm:gamecult.org".into(), text: "hi".into(), basis: None, resend: false };
let again = ChatSendRequest { resend: true, ..first.clone() };
let fields = |request: &ChatSendRequest| decode::<Vec<serde_json::Value>>(&encode(request).unwrap()).unwrap();
assert_eq!(fields(&first).len(), 5);
let sent = fields(&again);
assert_eq!((sent.len(), &sent[5]), (6, &serde_json::Value::Bool(true)));
assert_eq!(decode::<ChatSendRequest>(&encode(&again).unwrap()).unwrap(), again);
assert_eq!(decode::<ChatSendRequest>(&encode(&first).unwrap()).unwrap(), first, "a v2 tuple reads as a first send");
}

View file

@ -69,8 +69,7 @@ pub(crate) fn load(store: Option<&Path>, room_id: &str, image: &ChatImage) -> Re
Ok(Image { media_type, base64: STANDARD.encode(&bytes) })
}
/// The verified bytes of `image` and the media type they sniff as: everything `load` checks, before it encodes. The one verifier;
/// the attachment saver calls it too, and holds no check of its own.
/// The verified bytes of `image` and the media type they sniff as: everything `load` checks, before it encodes. The one verifier.
pub(crate) fn load_bytes(store: &Path, room_id: &str, image: &ChatImage) -> Result<(Vec<u8>, &'static str), Skip> {
if image.size > MAX_BYTES {
return Err(Skip::TooLarge);

View file

@ -30,8 +30,8 @@ use serde::de::DeserializeOwned;
use sha2::{Digest, Sha256};
use crate::chat_client::{
ACK, Chat, ChatAck, ChatDelivery, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatPendingRequest, ChatRead, ChatRefusal, MouthRefused, Refusal, reply_warnings, ChatSendReceipt, ChatSendRequest, PENDING, PENDING_REQUEST, PENDING_REQUEST_V1, PENDING_REQUEST_V4, PENDING_V2, PENDING_V4, OPEN_DIRECT_RECEIPT, OPEN_DIRECT_REQUEST, FETCH_RECEIPT, FETCH_REQUEST, PENDING_V1, READ, REFUSAL, SEND_RECEIPT,
SEND_REQUEST, decode, encode,
ACK, Chat, ChatAck, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatPendingRequest, ChatRead, ChatRefusal, MouthRefused, Refusal, reply_warnings, ChatSendReceipt, ChatSendRequest, PENDING, PENDING_REQUEST, PENDING_REQUEST_V1, PENDING_REQUEST_V4, PENDING_V2, PENDING_V4, OPEN_DIRECT_RECEIPT, OPEN_DIRECT_REQUEST, FETCH_RECEIPT, FETCH_REQUEST, PENDING_V1, READ, REFUSAL, SEND_RECEIPT,
SEND_REQUEST, SEND_REQUEST_V3, decode, encode,
};
/// The tag every chat document carries; the mouth refuses any other.
@ -202,7 +202,17 @@ impl Chat for RudpChat {
}
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
let receipt: ChatSendReceipt = self.call(SEND_REQUEST, &request.request_id, request, (SEND_RECEIPT, &request.request_id))?;
let receipt: ChatSendReceipt = if request.resend {
// A mouth that does not serve v3 answers `UnknownKind` keyed by the persona: heard here, the resend is known not made.
let answers = [(SEND_RECEIPT, request.request_id.as_str()), (REFUSAL, self.persona.as_str())];
let (kind, payload) = self.exchange(SEND_REQUEST_V3, &request.request_id, request, Some(&answers))?.ok_or_else(|| anyhow!("no answer payload"))?;
if kind == REFUSAL {
bail!("the mouth refused the resend: {}", decode::<ChatRefusal>(&payload)?.refusal.name());
}
decode(&payload)?
} else {
self.call(SEND_REQUEST, &request.request_id, request, (SEND_RECEIPT, &request.request_id))?
};
if receipt.request_id != request.request_id {
bail!("the mouth answered another send");
}

View file

@ -45,6 +45,13 @@ const USAGE: &str =
/// `rudp://<ip>:<port>` is refused with `usage` or a fixed message, and no
/// value is echoed.
pub fn instance_and_endpoint(args: &[String], env_endpoint: Option<String>, usage: &str) -> Result<(Slug, SocketAddr)> {
let (instance, endpoint) = instance_and_maybe_endpoint(args, env_endpoint, usage)?;
Ok((instance, endpoint.ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?))
}
/// `instance_and_endpoint` for a binary that may run without a daemon (`mind-persona project` over a state file): no
/// endpoint given is none, and one given is still checked.
pub fn instance_and_maybe_endpoint(args: &[String], env_endpoint: Option<String>, usage: &str) -> Result<(Slug, Option<SocketAddr>)> {
let (mut instance, mut endpoint) = (None, None);
let mut rest = args.iter();
while let Some(flag) = rest.next() {
@ -60,12 +67,12 @@ pub fn instance_and_endpoint(args: &[String], env_endpoint: Option<String>, usag
}
let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?);
instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?;
let endpoint = endpoint.or(env_endpoint).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?;
let Some(endpoint) = endpoint.or(env_endpoint) else { return Ok((instance, None)) };
let address = endpoint
.strip_prefix("rudp://")
.and_then(|address| address.parse::<SocketAddr>().ok())
.ok_or_else(|| anyhow!("the endpoint is not rudp://<ip>:<port>"))?;
Ok((instance, address))
Ok((instance, Some(address)))
}
/// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty

View file

@ -1,8 +1,8 @@
//! The operator's brakes, and the one reader of them.
//!
//! `Released` carries a `Grant`, the only value that opens a launch: it cannot
//! be built outside this module, so a launch exists only as the reading of a
//! released instance brake and a released swarm brake. The Grant names the
//! `Released` carries a `Grant`: it cannot be built outside this module, so it
//! exists only as the reading of a released instance brake and a released
//! swarm brake. The Grant names the
//! instance whose store was read and carries nothing else: no money, no cap. The store is at a fixed place, `CONTROL_ROOT`,
//! and the one reader takes the instance only: no function, argument, variable
//! or flag lets a caller choose a root, a path or a source, so a Grant is the
@ -36,7 +36,7 @@
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use anyhow::{Context, Result, bail};
use chrono::{DateTime, Utc};
use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore};
use eureka_pipeline::Slug;
@ -92,9 +92,7 @@ pub enum Effective {
/// The proof that the instance brake and the swarm brake were released when
/// read, in the root-owned stores of `instance`. Its fields are private and only
/// `read_effective` makes one; `open_and_launch` takes it by value and refuses
/// one read for another instance, so one reading opens at most one run, of the
/// instance it was read for.
/// `read_effective` makes one.
///
/// Outside this crate the type system leaves no way to make one: the fields are
/// private, there is no public constructor, and the derives give no path (no
@ -113,7 +111,7 @@ pub enum Effective {
/// ```
///
/// ```compile_fail,E0599
/// // not Clone, so a reading cannot be copied into a second run
/// // not Clone, so a reading cannot be copied
/// fn copy(grant: &mind_body::control::Grant) -> mind_body::control::Grant {
/// grant.clone()
/// }
@ -140,13 +138,6 @@ impl Grant {
pub fn instance(&self) -> &Slug {
&self.instance
}
/// A Grant for a launch test that has no store. It names its instance like
/// any other, so the launch's instance check judges it.
#[cfg(test)]
pub(crate) fn for_test(instance: Slug) -> Self {
Self { instance }
}
}
/// The instance store's contents, decoded and not yet judged.
@ -237,11 +228,6 @@ pub fn load_state(source: &impl ControlSource) -> Result<ControlState> {
/// let _ = mind_body::control::read_effective_from;
/// ```
///
/// ```compile_fail
/// // and the test constructor is not in the library build
/// let _ = mind_body::control::Grant::for_test;
/// ```
///
/// The same preamble with the real call compiles:
///
/// ```
@ -414,6 +400,10 @@ impl ControlWriter {
let mut cache = registered_cache()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))?;
cache.pull_all_backing_stores()?;
// A pull carries a record no registered type claims instead of refusing it; the writer still must not write beside one.
if !cache.foreign_records().is_empty() {
bail!("{} holds a record this control store does not read: archive it, nothing migrates it", path.display());
}
Ok(Self { cache, path })
}
@ -502,6 +492,10 @@ impl SwarmWriter {
let mut cache = swarm_cache()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))?;
cache.pull_all_backing_stores()?;
// A pull carries a record no registered type claims instead of refusing it; the writer still must not write beside one.
if !cache.foreign_records().is_empty() {
bail!("{} holds a record this swarm store does not read: archive it, nothing migrates it", path.display());
}
Ok(Self { cache, path })
}

View file

@ -62,100 +62,11 @@ fn a_brake_payload_that_does_not_decode_makes_the_store_undecodable() {
let mut cache = CultCache::new();
cache.register_entry_type::<WrongBrake>().unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache.put(BRAKE_KEY, &WrongBrake { released: "yes".into() }).unwrap();
assert_eq!(effective(&path), held(HeldReason::Undecodable));
}
mod grant {
//! A Grant is the proof that this instance's own control store released: the
//! reader derives the path from the instance, and a launch refuses a Grant
//! read for another instance before it asks the mind anything.
use anyhow::{Result, anyhow};
use cultnet_rs::Selection;
use eureka_pipeline::{PipelineDocument, RunTurn};
use huginn_mind::{PipelineAdmissionOutcome, PipelineSelectionPage};
use super::*;
use crate::launch::{Clock, Declined, LaunchOutcome, LaunchRequest, Launcher, Ports, open_and_launch};
use crate::queue::MindPort;
fn slug(name: &str) -> Slug {
Slug(name.into())
}
fn read(root: &Path, instance: &str) -> Effective {
with_root(root, || read_effective(&slug(instance)))
}
/// A mind that answers nothing: a launch that reaches it has gone past the
/// instance check.
struct SilentMind(Slug);
impl MindPort for SilentMind {
fn instance(&self) -> &Slug {
&self.0
}
fn query(&self, _selection: &Selection) -> Result<PipelineSelectionPage> {
Err(anyhow!("the launch asked the mind"))
}
fn admit(&self, _agent: &str, _session: &str, _documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome> {
Err(anyhow!("the launch admitted"))
}
}
struct NoUnits;
impl Launcher for NoUnits {
fn start(&self, _instance: &Slug, _turn: RunTurn) -> Result<()> {
Err(anyhow!("the launch started a unit"))
}
fn alive(&self, _instance: &Slug, _turn: RunTurn) -> bool {
false
}
}
struct Now;
impl Clock for Now {
fn now(&self) -> DateTime<Utc> {
at(100)
}
}
fn launch_as(mind_instance: &str, grant: Grant, turn: RunTurn) -> Result<LaunchOutcome> {
let mind = SilentMind(slug(mind_instance));
let ports = Ports { mind: &mind, launcher: &NoUnits, clock: &Now, host: "host" };
open_and_launch(&ports, LaunchRequest { turn, claims: vec![], agent: "agent".into(), grant })
}
#[test]
fn a_grant_read_for_one_instance_cannot_launch_another() {
let root = tempfile::tempdir().unwrap();
release(root.path(), "void");
for turn in [RunTurn::SelfRun, RunTurn::PersonaTurn] {
let Effective::Released(grant) = read(root.path(), "void") else { panic!("void's store is released") };
// The mind is eureka's; the silent mind and the unit-less launcher fail loudly if the launch goes on.
let outcome = launch_as("eureka", grant, turn).unwrap();
assert_eq!(outcome, LaunchOutcome::Refused(Declined::GrantForOtherInstance), "{turn:?}");
}
}
#[test]
fn the_matching_grant_is_not_stopped_by_the_instance_check() {
let root = tempfile::tempdir().unwrap();
release(root.path(), "void");
let Effective::Released(grant) = read(root.path(), "void") else { panic!("void's store is released") };
let error = launch_as("void", grant, RunTurn::SelfRun).unwrap_err();
assert!(format!("{error:#}").contains("asked the mind"), "{error:#}");
}
}
/// The swarm store with its brake released, and nothing else in it.
fn release_swarm(root: &Path) {
SwarmWriter::open(swarm_path(root)).unwrap().set_brake(true, at(0), "op").unwrap();
@ -249,8 +160,33 @@ fn the_stores_are_written_world_readable_and_root_only_writable() {
let _ = path;
}
/// A named instance store with its brake released, and a released swarm.
fn release(root: &Path, name: &str) {
ControlWriter::open(root.join(name).join("control.cc")).unwrap().set_brake(true, at(0), "op").unwrap();
release_swarm(root);
#[test]
fn a_writer_refuses_to_open_over_a_store_holding_a_record_it_does_not_read() {
let dir = tempfile::tempdir().unwrap();
let path = store_path(dir.path());
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut cache = CultCache::new();
cache.register_entry_type::<OldDial>().unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache.put("dial", &OldDial { heat: "1".into() }).unwrap();
let before = std::fs::read(&path).unwrap();
let refusal = ControlWriter::open(&path).err().expect("a foreign record refuses the open").to_string();
assert!(refusal.contains("does not read"), "{refusal}");
assert_eq!(std::fs::read(&path).unwrap(), before, "the refused open leaves the store bytes alone");
}
#[test]
fn a_swarm_writer_refuses_to_open_over_a_store_holding_a_record_it_does_not_read() {
let dir = tempfile::tempdir().unwrap();
let path = swarm_path(dir.path());
let mut cache = CultCache::new();
cache.register_entry_type::<OldDial>().unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache.put("dial", &OldDial { heat: "1".into() }).unwrap();
let before = std::fs::read(&path).unwrap();
let refusal = SwarmWriter::open(&path).err().expect("a foreign record refuses the open").to_string();
assert!(refusal.contains("does not read"), "{refusal}");
assert_eq!(std::fs::read(&path).unwrap(), before, "the refused open leaves the store bytes alone");
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -2,24 +2,23 @@
//!
//! Today that is `control`, the operator's brakes, and `cli`, the operator's
//! hand on them. The brakes are the operator's consent, not her body: the store
//! is root-owned and no organ of hers writes it.
//! is root-owned and nothing of hers writes it.
//!
//! `launch` and `queue` are the launch primitive: the work queue, the
//! repetition breaker, the one-live-Self-run rule, and the single path that
//! opens a run in the mind and only then starts its unit.
//! `launch` holds her units under systemd and the reads of the runs a Self run
//! holds; `queue` is her port to her mind and what an open question holds.
//!
//! `heartbeat` runs the swarm's shared heartbeat over them: the one process,
//! the `mind-heartbeat` binary, that decides who wakes and when, by the rule in
//! `tempo` (the Minds' votes make the beat; the pick chooses who takes it).
//! `heartbeat` runs the swarm's shared heartbeat: the one process, the
//! `mind-heartbeat` binary, that decides which Persona wakes and when, on the
//! configured beat by the pick in `tempo`. It starts her unit and writes no mind.
//!
//! `persona` is the Persona organ: one start of `mind-persona@<instance>` carries her live
//! `claude` session under bubblewrap in her sandbox, driven by the Self's own driver, with her
//! pending chat as the inbox and one typed reply per result (`chat_client` is the chat wire and
//! port and `chat_rudp` its RUDP transport to Bifrost's mouth).
//! `persona` is the Persona organ: one start of `mind-persona@<instance>` reads the brakes, and
//! until the three-stage turn lands it carries no turn. It keeps what a turn's input is made of
//! (`chat_client` is the chat wire and port and `chat_rudp` its RUDP transport to Bifrost's mouth).
//!
//! `stream` is the stream organ: the `mind-stream` binary projects her own state through
//! Ghostlight's Projector, lets a base model continue it, and admits the least familiar
//! continuation as a `thought` with its whole trace. It admits nothing else.
//! `projection` is the Projector of the Persona-only turn: the Select stage chooses what she can feel and the
//! Projector narrates it as her lived stream, under `persona-tuning.toml`; the Persona stage continues it in her prose.
//! `mind-persona project` runs them and writes nothing; `projection::harness` runs it over mocked rooms, batches of
//! candidate states and a simulated swarm.
//!
//! `lease_client` asks the Claude connector for a session's credential and the
//! plan's usage windows. `self_run` carries one Self run inside `mind-self@<instance>`: the
@ -35,8 +34,8 @@
#![forbid(unsafe_code)]
mod address;
mod attachment;
pub mod chat_client;
#[allow(dead_code, reason = "the loader is kept for the three-stage turn's perception (map C3): its first caller removes this allow; `Image` is live through `self_run::session`")]
mod chat_image;
pub mod chat_rudp;
pub mod cli;
@ -46,11 +45,10 @@ pub mod heartbeat;
pub mod launch;
pub mod lease_client;
pub mod persona;
pub mod projection;
pub mod queue;
mod recall;
pub mod sandbox;
pub mod self_run;
mod sleep;
pub mod stream;
pub mod tempo;
#[cfg(test)]

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;

Some files were not shown because too many files have changed in this diff Show more