andref-rif #
Custom Discord persona runtime for Orion: one Rust process, one Gateway session, and independent Tokio actors for Nova (funny/gen-z), Quinn (nerdy), and Mochi (anime). They share DeepSeek Flash transport and accounting, while each owns its attention, engagement, initiative, pending turns and scoped Markdown memories. There is no component selecting a speaker for all personas.
The Orion configuration is enabled for reactive replies and low-frequency proactive turns.
Nova, Quinn and Mochi can reply to new messages and maintain scoped persona notes.
Addressing a persona by display name raises its response probability. Each persona
considers initiating a conversation every four hours: initial chances are 12% for
Nova, 4% for Quinn and 8% for Mochi. Quiet hours, recent activity, unanswered
initiations and the shared budget can suppress these turns.
The binding example uses dummy guild/channel/operator IDs. Persona avatars use
distinct public DiceBear PNG URLs; replace their approved HTTPS URLs as desired.
See VERIFICATION.md for the offline tests, actual CSI storage checks and live
Discord validation record.
Runtime and publication #
A Gateway handler persists configured-channel observations before notifying the
actors. Bounded mailboxes carry wake hints; SQLite event receipts recover missed
fan-out. Actors also poll the durable queue. Decisions are sampled and recorded
once per persona/event. After a confirmed public message, follow-up consideration
stays at 98% for Nova, 95% for Quinn and 97% for Mochi throughout the next ten
minutes in that conversation. Each new confirmed message from that persona
restarts its window. After the window, the follow-up contribution decays
exponentially, with a ten-minute timescale, down to the baseline floor.
engagement_seconds controls both the initial window and subsequent decay
timescale; followup_probability controls its plateau. Direct address and interests
can raise consideration further; explicit endings suppress replies. Consideration
starts inference, rather than guaranteeing publication. The model receives its
current participation state and instructions favoring natural continuation,
including greetings and banter, while preserving fitting silence and send checks.
Discord message type, reply-reference IDs, user/role mentions and the everyone mention flag survive ingestion, partial edits, storage and history retrieval. A same-channel reply to a confirmed persona message raises that persona's direct response probability even without its name or a ping. Attribution uses the sent message ID, since all personas can share one webhook. Context includes a bounded excerpt of the stored target, including when it falls outside recent history. Forwards, foreign-channel/server references, unknown/deleted targets and unconfirmed persona identities do not receive this treatment. No referenced content is fetched from Discord or imported from a different conversation.
Personas independently sample whether to respond, then take turns within each conversation. A FIFO conversation mutex serializes context construction and inference across actors. A pending outbox message keeps the next turn waiting through typing delay, HTTP delivery and rate-limit retries. The next persona builds fresh context only after confirmation stores the preceding public message. Its selected turn advances across confirmed persona publications without another probability roll; incorporated events are receipted so they do not trigger a duplicate turn afterward. Different conversations can proceed concurrently.
An actor keeps observing while its selected turn runs or waits. It defers the
newest eligible event while busy. Intervening human activity, edits or deletions
cancel a waiting stale turn; the latest eligible event can then be considered.
Changes during inference still invalidate stale sends. Waiting is bounded by the
original response TTL, and pause/chain checks still apply before inference and
publication. Silence, failed or cancelled delivery releases the conversation;
uncertain delivery blocks it until operator resolution, including after restart.
Expired queued deliveries are cancelled before another turn proceeds. Changed
initiative opportunities are cancelled rather than speaking over new activity.
No old reply is replayed on restart. Self messages and chains beyond
max_persona_chain are suppressed. Posting caps apply globally, independently
of who decided to speak. This coordination sequences chosen turns; it does not
choose speakers or replace the personas' independent decisions.
Each persona/channel has a persistent initiative timer. A due timer only opens an opportunity: quiet hours (UTC), activity, initiative probability and unanswered attempt backoff gate any inference. Missed timers are skipped after downtime. Scoped notes and the recent conversation supply the intention for an opening. No model is called every timer tick or for every persona on every message.
The seven model tools are read_base_document, list_notes, read_note,
write_note, read_messages, send_message and stay_silent. Typed arguments reject unknown
fields and missing required fields. Trusted context binds identity, conversation,
turn and permissions. Models cannot supply filesystem paths, other persona IDs,
webhook credentials, HTTP destinations, SQL or shell commands. Markdown remains
inert text. Prompt instructions complement these checks; they do not grant rights
or guarantee that generated prose is appropriate.
Only send_message stages public text. Ordinary assistant output and reasoning
are private and discarded after the turn. Every completed inference turn must use
exactly one terminal tool: send_message, or stay_silent with a reason code and a
brief operational explanation. An empty or text-only completion is a protocol
failure, never an implicit silence decision. The runtime gives it one final,
metered correction attempt, requiring a single terminal tool. Exhausting ordinary
tool steps or a rejected terminal action also gets at most that one correction.
Repeated noncompliance fails the turn. Correction retains the same conversation
gate, style reference, generation, original deadline, pause checks and budgets.
Every provider request sets tool_choice: "required" with thinking disabled;
ordinary calls offer all seven tools, while the final correction offers only
send_message and stay_silent. The model retains the choice to reply or stay
silent. Request bounds and budget reservations use the same body as transmission.
Conflicting terminal choices are rejected before any tools in that batch run;
other tools must precede the terminal choice. Silence examples in immutable
Markdown that describe ending without a send mean using stay_silent.
A staged send is delayed, bounded to one
per turn, rechecked for freshness/pause/expiry/rate caps and posted through the
channel's webhook with the approved persona name/avatar and mentions disabled.
The default global send limit is 200 messages per rolling 60 minutes, shared by
all personas and conversations. Delivered, sending and uncertain sends consume
slots; queued, failed and cancelled work does not. /rif action:status reports
the used/reserved and available slots, whether this limit blocks sending, and
the next slot time when blocked. Replies retain their original expiry while
waiting, so hitting the limit can cancel a reply before a slot opens.
SSE is decoded internally; tools run only after complete, valid termination.
Public token-by-token streaming is deliberately unavailable in this release;
partial arguments or reasoning cannot become public messages. A future public
stream requires a separately authorized, metered, text-only generation protocol.
The outbox distinguishes queued, sending, delivered, cancelled, failed and uncertain work. Confirmed REST sends and their normalized persona events commit in one SQLite transaction. Gateway echoes are attributed by confirmed message ID, never by display name. Early managed-webhook echoes are held for reconciliation; unrelated bots/webhooks are ignored. HTTP 429 gets at most five bounded attempts; transport failures, malformed success responses and 5xx responses become uncertain, not blindly retried. This does not promise exactly-once remote delivery.
SQLite turns records selected turns as waiting/running, reply queued, explicit
silence, shadow reply, failed, cancelled or interrupted, with safe reason codes.
turn_steps records provider-call timing, correction flags, assistant byte counts,
tool names and denied-tool counts. Raw assistant output and tool arguments are not
retained. Silence explanations are bounded private diagnostics and do not appear
in operational logs or the status summary. Queuing a public reply and recording
its outcome share one transaction; a rejected send cannot count as successful.
The operator-only ephemeral /rif action:status response shows recent outcomes
for the current conversation and joins each queued choice to its delivery status.
Queued means a reply was chosen; the outbox determines actual delivery. Startup
marks unfinished turn records interrupted instead of inventing a silence decision.
These diagnostics use additive, idempotent tables alongside schema 2. Existing messages, event JSON and version checks are unchanged, so the preceding schema-2 image remains compatible for rollback. Historical turns have no backfilled decision explanations.
Configuration and memory #
Avatar artwork is rendered by DiceBear: Nova uses Fun Emoji by Davis Uche, Quinn uses Bottts by Pablo Stanley, and Mochi uses Adventurer by Lisa Wischofsky. Fun Emoji and Adventurer are licensed CC BY 4.0; Bottts is free for personal and commercial use. The configured seeds/backgrounds select each persona's icon. Avatar requests contain fictional persona names only.
config.example.json is the public, declarative operator policy. The constructor
merges the SOPS Discord bindings into it and mounts the complete JSON as a Secret.
The runtime fails closed on invalid IDs, unknown aliases, invalid limits, overlapping mounts,
missing base documents, missing credentials or malformed webhook bindings.
Discord transport uses Serenity's native TLS backend to avoid its older Rustls
0.22 dependency; DeepSeek and webhook HTTP explicitly use current Rustls.
Endpoint configuration is operator-owned HTTPS; routine inference explicitly
sets non-thinking mode. There are no automatic provider retries or fallback models.
An unsuccessful provider call establishes a persistent 60-second backoff shared
by its model profile. Provider outages leave the Gateway and health server running.
| Path | Ownership and purpose |
|---|---|
/run/secrets/andref-rif/config.json |
Read-only JSON policy plus private Discord bindings, supplied by Secret. |
/etc/andref-rif/personas/<id>/{character,examples}.md |
Immutable base documents, loaded on every turn. |
/data/personas/<id>/<conversation>/{development,memories,journal}/<name>.md |
Evolving scoped documents on the NFS PVC. |
/data/revisions/<id>/<conversation>/<collection>/<name>/ |
Bounded prior versions, inaccessible to model tools. |
/var/lib/persona-runtime/runtime.sqlite |
SQLite on its dedicated iSCSI PVC, including WAL/SHM sidecars. |
/run/secrets/andref-rif/ |
Read-only credential projection; inaccessible to model tools. |
Each Markdown document has a generated provenance comment with subject,
fact/impression and source message IDs, followed by text. read_note returns a
content hash; subsequent writes must pass it as expected_version. New documents
use null. No raw path or directory separator is accepted. Descriptor-relative
cap-std/cap-fs-ext operations refuse symlink components and final symlink files.
Writes serialize, preserve bounded revisions, fsync a same-directory temporary
file and atomically rename it. Document quotas apply across that persona's scopes.
The two volumes do not share a transaction. Document operations are journaled in SQLite before file replacement. Startup scans authoritative NFS documents, hashes them, rebuilds the index and reconciles interrupted operations. Replayed operation IDs do not duplicate committed mutations. Never edit live files behind the runtime: use operator controls or stop the writer and reconcile on startup.
Context starts with operating policy, the task and participation state, then explicit introductions to the character description and correct writing-style examples. Both Markdown files are included verbatim. The example replies define the next message's tone, phrasing, rhythm, length, casing, punctuation and humor; earlier bot replies provide conversation context without replacing that style reference. Example situations are illustrative, not the persona's own memories.
Optional scoped notes and the bounded extractive recap are labeled separately as
untrusted context. A transcript introduction precedes the recent conversation.
Each message has a separate metadata record for its speaker, ID, timestamp,
mentions and resolved reply target; its original content is a verbatim API message.
Recent messages and their metadata stay together and take priority over optional
notes/recaps within the byte budget. An oversized latest message fails the turn
instead of being silently omitted or rewritten. The final instruction explicitly
asks for the same writing style as the example replies and delivery through
send_message, with silence allowed when appropriate. Recaps incur no separate
inference. Other speakers remain user-role attributed transcript; only
the current persona's confirmed speech uses assistant role. Everything retrieved
is limited to the current conversation, even if a persona can access several.
There is no automatic cross-channel memory sharing. Conversation aliases are
permanently bound to their guild/channel IDs in SQLite: changing a destination
requires a new alias or an explicit data migration, preventing old private history
from following an alias into a different channel. Adding a persona requires its
JSON policy and two base documents; no runtime code branch changes. For Orion,
also add its import entries in milky-way/lib/andref-rif-personas.libsonnet.
forget removes the active note, its local revisions and retrieval index on
reconciliation. Transcript events, tool-operation hashes, audit records, Discord's
copy and external backups have separate retention; forget is not a claim to
erase those stores. SQLite transcript/audit records are retained until an operator
performs an explicit retention operation. Backups require their own expiration.
Inference cost #
Defaults reserve a $10/month application budget and $3.30/persona, using integer micro-USD (1 USD = 1,000,000 units). Each request reserves an input bound of one token per serialized UTF-8 byte plus framing margin and the configured maximum output. Reservations include schemas and tool results. Actual reported usage settles against configured peak cache-miss rates; cache discounts are ignored. Unknown usage, interrupted streams, crashes and cancelled in-flight requests keep the conservative charge. Every continuation counts; silence still costs inference. Requests belong to the UTC month in which they were reserved, including calls finishing in a later month. Concurrent reservations cannot spend the same allowance.
Example rates, checked 2026-10-31, are $0.30 input and $1.20 output per million
Flash tokens, represented as 300000 and 1200000 micro-USD per million tokens.
See DeepSeek pricing.
Review rates and pricing_as_of when changing providers/models and periodically
against invoices. Application accounting cannot guarantee a provider invoice after
repricing or an invalid token bound. Set an account-side limit where available.
At exhaustion the runtime keeps receiving observations but stops new billable work;
update limits explicitly or wait for UTC month rollover. Unknown charges need
provider reconciliation, not deletion to restart spending.
Discord and credential setup #
- Create a dedicated Discord application/bot and install it in a dedicated test
guild with
botandapplications.commandsscopes. Grant View Channel and Read Message History in allowed channels. Enable Message Content intent in the Developer Portal and obtain approval if Discord requires it. The runtime uses GUILDS, GUILD_MESSAGES and MESSAGE_CONTENT; it does not request Administrator. - Create an incoming webhook in each destination channel using an operator with
Manage Webhooks. The runtime does not need that permission. Save canonical
https://discord.com/api/v10/webhooks/<id>/<token>URLs. Threads must be listed explicitly with their parent ID; use that parent's webhook. Startup verifies each webhook's guild and parent/channel binding through Discord. - Create a dedicated DeepSeek platform API key and provision a small test balance. All personas initially share this key and a single model. Personality comes from their separate base documents, scoped memories and behavioral policy.
- Fill the real guild, channel/thread and authorized operator IDs in
discordBots.andrefRif.bindingsinside SOPS, as shown below. IDs are strings. The publicmilky-way/environments/stage00/orion-system/andref-rif-config.libsonnetholds behavioral policy only; it must not contain Discord IDs. Keepenabled: falseuntil credentials, image and storage are ready.
discordBots.andrefRif and its modelProviders.deepseek child are names in
this repository's encrypted configuration, not provider resources or preexisting
accounts. andrefRif names this application. Merge the following structure into
the existing decrypted Jsonnet inside the SOPS editor, preserving other apps:
{
discordBots: {
// ...existing bots...
andrefRif: {
bindings: {
guild_id: '<Discord server ID>',
operators: ['<your Discord user ID>'],
conversations: {
lounge: { channel_id: '<Discord channel ID>', parent_channel_id: null },
},
},
token: '<dedicated Discord bot token>',
modelProviders: { deepseek: { token: '<dedicated DeepSeek API key>' } },
webhooks: { lounge: 'https://discord.com/api/v10/webhooks/<id>/<token>' },
},
},
}
Edit the encrypted source from the repository root:
sops edit --input-type binary --output-type binary secrets/k8s-config/k8s-secret-values.jsonnet
Do not paste real values into this README, ConfigMaps, examples, shell arguments,
Git diffs or chat. Do not edit the decrypted sops-nix output. The existing Sodium
home-manager SOPS declaration handles this same encrypted file; refresh that
activation/decryption after editing it. The existing milky-way/secrets.libsonnet
registry supplies the resulting values to Orion's constructor. The constructor
writes andref-rif-credentials, mounted read-only (0440 with pod group 1000):
config.json assembled policy, server/channel IDs and operator user IDs
discord-bot-token Discord Gateway/REST authentication
webhooks.json alias -> secret-bearing webhook URL
deepseek-api-key provider Bearer authentication
The public policy references only token_file, webhooks_file and api_key_file.
The alias lounge must match both the webhook key and personas' conversation lists;
it need not match the channel's Discord name. No Discord IDs enter the ConfigMap,
pod arguments or environment. The ConfigMap contains only base persona documents.
The assembled JSON contains credential file references, not token/key/URL values.
Credential types have no Debug/Serialize implementation; logs intentionally disable
third-party HTTP/Gateway traces. Rotation updates the encrypted source, refreshes
sops-nix, and applies the new Secret and Deployment. Its credential checksum rolls
the Recreate pod, which rereads files. ID/policy changes use the same rollout.
Both PVCs stay unchanged. There is no hot reload and no secret environment variable
or credential embedded in the image.
Development and verification #
From the repository root:
nix develop ./experimental/andref-rif
cd experimental/andref-rif
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo nextest run
python3 deploy/check.py
nix flake check ./experimental/andref-rif checks the package, Clippy, docs, Rust
and TOML formatting, the pinned advisory database, licenses and Nextest. Update
only its advisory input with nix flake update --flake ./experimental/andref-rif advisory-db
before auditing against newly published advisories. nix build ./experimental/andref-rif
builds the standalone executable. Tests use temporary separate document/database
roots and fake credentials, providers, clocks and webhook HTTP services.
To inspect the final model prompt, open the checked
Nova conversation and
Nova after reset goldens. They materialize the
actual HTTP request with runtime placeholders, complete persona documents,
message roles/order and tool definitions. cargo test --test golden_prompt
compares both against the current runtime. See the
fixture guide for setup and explicit regeneration.
For a local run, copy the example policy outside the repository, merge the fields
from deploy/discord-bindings.example.json into its discord object, replace all
three roots with distinct absolute temporary directories, copy personas/ to the
chosen base root and set secret-file references to private files outside all
three roots. The database/document directories must already exist. Then:
cargo run -- --config /absolute/private/config.json --check
cargo run -- --config /absolute/private/config.json
--check validates policy, base documents and credential files without opening
Discord or making provider calls. It does not test remote credential validity.
--version reports binary/schema identity. shadow: true records decisions and
meters any inference, but suppresses sends and model/operator memory mutations.
/rif inspect remains read-only. No dry-run mode makes inference free.
Guild-scoped /rif commands require the configured operator ID, current configured
guild/channel and View Channel + Read Message History permissions on every call.
Responses are ephemeral with mentions disabled, except the public reset marker.
Command visibility defaults to
Manage Guild; configure Discord's command permissions for your operator role if
needed, without granting the bot Administrator.
| Action | Additional string options |
|---|---|
status, usage |
None; reports rolling send-limit usage/availability and next slot when blocked, micro-USD, uncertain usage, pricing dates and delivery IDs. |
reset |
None; posts Resetting conversation and starts a new transcript context for all personas in this channel. |
pause, resume |
persona ID; omit for all. Global and individual pauses compose. |
inspect |
persona, name, optional collection (default memories). |
remember |
Same plus content; scoped to the command's conversation. |
forget |
Same identifiers; removes active note and its local revisions. |
resolve |
delivery; optional message_id of an early managed-webhook echo. |
Run /rif action:reset to post Resetting conversation publicly and exclude
messages through that marker from every persona's future transcript, summary,
reply-target excerpts and history-tool reads in this channel. The cutoff persists
across restarts, uses Discord message IDs and also excludes late events and edits
of older messages. It invalidates pending turns and cancels queued replies. A send
already submitted to Discord may still arrive; its old context stays excluded.
This is a transcript reset: persona files and saved Markdown notes remain active.
Discord messages, retained SQLite transcript and audit/usage records are preserved.
Pause persists and cancels queued publication. It cannot retract an HTTP request
already submitted to Discord. Memory edits invalidate pending context. Inspect
Discord before resolving an uncertain send: a matching stored echo can confirm
attribution; omitting message_id cancels local work without resending. If the
Gateway missed the message too, leave the delivery uncertain while investigating
or cancel it after inspection. A restart never silently replays an uncertain send.
Orion rollout and recovery #
The reusable milky-way/lib/andref-rif.libsonnet constructor emits a singleton
Recreate Deployment, one hash-named immutable ConfigMap, a credential Secret and
two dedicated PVCs. It has probes but no Service/Ingress, non-root UID/GID 1000,
read-only root filesystem, dropped capabilities, RuntimeDefault seccomp, disabled
service-account automount, bounded memory/temp storage and the Orion toleration.
/ready requires initialized storage/config and a usable Gateway session; /live
tracks local runtime progress. Provider availability does not control pod restarts.
Build and publish from the repository root through the existing whale workflow:
nix build ./flake-profiles/whale#packages.x86_64-linux.andref-rif-image
nix run ./flake-profiles/whale#andref-rif-push
The push app writes the actual published manifest digest to
exports/whale/digests/andref-rif.txt. Never create a placeholder production pin.
images.libsonnet reads that pin lazily; disabled Orion wiring and fixture rendering
work before publication. After source changes, refresh only the whale input with
nix flake update --flake ./flake-profiles/whale andref-rif.
Before enabling, verify both storage classes with the real CSI driver. The database
PVC must enforce ReadWriteOncePod on my-custom-zfs-generic-iscsi; all SQLite
sidecars use its mount. The NFS PVC must be writable by UID/GID 1000. Provision its
ownership server-side or through an approved storage setup; do not assume fsGroup
fixes root-squashed NFS. The application fails when required mounts cannot be used
and never substitutes an ephemeral database or puts SQLite on the document PVC.
Start with a dedicated test guild, a small budget, shadow mode and initiative probabilities set to zero. Then enable one persona for explicit tests, all three reactively, and finally low-frequency initiative. Check actual voice quality, message attribution, quiet endings, cancellation, usage and restart persistence. Only then enable Orion policy. Render/review using the repository wrapper, without saving real Secret payloads in logs or fixtures:
nix develop ./flake-profiles/milky-way-devenv --impure -c bash -c \
'cd milky-way && tk diff environments/stage00/orion-system'
Apply only reviewed andref-rif resources; avoid unrelated environment changes.
Verify pod readiness, logs and PVC bindings, and test an immutable-base update
without losing evolved notes. Keep older ConfigMaps until rollback is no longer
needed; delete obsolete versions deliberately.
For backups, pause all personas, scale the Deployment to zero and wait for the
writer to exit. Snapshot/copy both volumes as one named recovery set. Preserve
SQLite WAL/SHM with a stopped consistent directory, or use SQLite's supported
backup mechanism; never copy only a live .sqlite file. Record image digest,
schema version, policy and credential references (not plaintext values).
Restore into fresh PVCs with the writer stopped, restore both volumes, mount them
at their original paths, and start with shadow: true plus persisted global pause.
Startup reindexes NFS and marks interrupted sends/usage uncertain. Review pending
and uncertain deliveries before resuming; old queued work expires normally. Test
restore in a dedicated guild before replacing production storage. Roll back only
to images compatible with schema version 2, or restore the matching recovery set
for an incompatible migration. Never reset memories or replace volumes implicitly.
The reply-metadata release migrates schema 1 to 2 transactionally, adding a metadata
table without replacing messages, events, budgets or memories. Older event JSON
loads with empty metadata; previously discarded Discord metadata is not backfilled.
Take a stopped-writer recovery snapshot of both volumes before upgrading. An old
schema-1 image cannot read schema 2 and must be paired with the pre-upgrade recovery
set if rolling back. Public speech still requires send_message; reply recognition
does not force a model response or publish ordinary assistant output.
Protocol sources: DeepSeek tools, thinking mode, Discord webhooks, Gateway intents.