Natural Nudges
Natural Nudges lets personas speak without being triggered. The code lives in
src/modules/natural-nudges/: SQL in db/repositories.ts, the runtime in runtime/, and the
/config and /nudge-studio pages in discord/. This page covers both modes: idle nudges, which start
something in a quiet channel, and Active Nudges, which join a live conversation. User-facing behavior is
on the feature page. The panel shows these as Idle
Nudges and Active Nudges, and labels the ping_user, revive_topic, start_topic, and play_scene
categories Ping User, Revive Topic, Start Topic, and Play Scene.
Flow and ownership
Section titled “Flow and ownership”Every idle nudge passes three phases. Only Phase A runs inside the scheduled work cycle, so model calls never delay reminders.
| Phase | Owner | Work |
|---|---|---|
| A, decide | NaturalNudgeProcessor (runtime/processor.ts), the coordinator step after reminder and random-trigger dispatch | Plain code, no model call: due time, waking hours, lull, persona and category raffles, then a weighted shortlist within that category with allowed channels. A server whose scheduled-work lane is running is skipped |
| B, plan | planIdleNudge (runtime/planner.ts) | One structured-output call to the planner model (resolvePlannerModel): nudge and channel within the drawn category, opener direction, agenda, or proceed: false |
| C, speak | runIdleNudgeAttempt (runtime/runner.ts) | Fresh re-checks, then a normal tomoriChat turn on the channel’s latest message, run like reminders |
Phase A runs every 60 seconds on the coordinator’s reconcile tick, because no due-time column
exists to wake on. Natural Nudges is on by default. listEnabledIdleNudgeServers returns only
server IDs, Discord IDs, and timezone offsets for guild servers with idle nudges enabled, including
servers with no config row. The cached readNaturalNudgeGate snapshot supplies Phase A’s settings
and heat eligibility. Both modes require a direct chat trigger within the last 14 days, stored as
server_natural_nudge_runtime_state.last_direct_chat_at. The scheduler filters dormant servers in
SQL using an index on that timestamp. Both modes also require measured heat of at least 1,
effective heat of at least 1, and a non-empty configured or automatic channel set. Heat adjustments change the pace
of an eligible server; they cannot supply the measured activity needed to leave dormancy. Idle
nudges turned off or an attempt in flight also skip evaluation. A server that is not due skips
history, runtime, and meter reads until its due time or 15 minutes later, whichever comes first;
a server with no due time waits 15 minutes, while pending verdicts keep their existing cadence.
Migration 121_natural_nudge_dormancy preserves existing eligible guild servers once: it seeds a
missing activity timestamp from the latest channel turn within 14 days only when measured and
effective heat reach 1 and an eligible channel set exists. Historical channel turns can include
passive autochat and reminders, so this is a rollout proxy rather than proof of direct chat. The
original activity time is kept, and an existing timestamp is never overwritten. Unused, low-heat,
and channel-less servers remain dormant. New installations require their first direct chat.
planChatTurns records a direct mention, persona trigger word, or reply after trigger and access
admission, before credential resolution. Passive autochat, commands, reminders, random triggers,
persona jobs, impersonation, and nudges do not renew the timestamp. runtime/configCache.ts caches
dormant activity until a successful direct-chat write replaces it and invalidates inactive or loading
readNaturalNudgeGate snapshots. Low heat, missing channels, and both modes switched off also cache
an inactive result until direct chat or a successful settings change invalidates it. Ordinary
channel chatter and scheduler ticks then need no repeated per-server settings, history, or metric
reads. Eligible snapshots expire after five minutes, and cached timestamps still close the window
at the 14-day boundary. A direct turn carries isDirectChat through empty-response retries; after
its usage stats persist, post-turn effects invalidate inactive or loading snapshots again so buffered
activity cannot leave a newly eligible server stuck in the inactive cache.
Both runners re-check dormancy before delivery; chat planning also drops queued nudge scene turns
after the window closes. Nudge generation suppresses public error notices, and its tool progress
cards post only in the thought log, so a nudge never shows a working card in the channel.
Repository reads retry retired database connections through withTransientDbRetry. Exhausted metric
reads fail the evaluation instead of supplying empty activity data that could be cached for later
cycles. Reads inside a caller’s transaction stay with that transaction and do not retry independently.
flowchart TD tick["reconcile tick"] --> proc["NaturalNudgeProcessor.processDueIdleNudges"] proc -->|"pending opener?"| opener["resolve its verdict, stop"] proc -->|"failure or unanswered stop?"| stop["stop"] proc --> heat["heat → idle nudges per day → due time, level's daily cap, waking hours"] heat --> lull["lull: effective channels quiet for 1-3 hours (gateway lastMessageId)"] lull --> replied["drop channels whose last idle opener has no human reply since;<br/>awaiting_reply abort and backoff when none remain"] replied --> model["planner model: llm_id, else chat model;<br/>no_model abort and backoff unless it resolves"] model --> persona["persona raffle → persona scope filter →<br/>channel sample → channel/tool eligibility"] persona --> cat["category raffle → target lottery when required →<br/>full prerequisites → weighted nudge shortlist<br/>(Play Scene: one shared partner draw and compatible channels)"] cat --> detached["detached: planIdleNudge → recheckBeforeSend →<br/>tomoriChat({ naturalNudge, sceneTurn? })"] detached --> rows["fire row + one agenda row per speaker"]State: fire history and derived meters
Section titled “State: fire history and derived meters”Nothing decays on a job. Every meter is an elapsed-time read over the fire log
(natural_nudge_fires): persona, category, and idle nudge rest; the level’s daily cap; the pending
opener; and the unanswered streak. History reads retain both the latest idle fires and the latest
invitations, so intervening scenes cannot hide the three-invitation unanswered stop. Heat and waking
hours come from stat_counters:
- Heat is the server’s
message_sentper day, each day halved every three days (computeHeatinruntime/meters.ts);computeEffectiveHeatadds the server’s savedheat_offsetand clamps the result to 0-50 for both modes. The adjustment affects both modes without changing statistics; the shared eligibility snapshot supplies heat to both modes, while the idle meter cache holds waking hours and last engagement. Measured heat and stored activity stay uncapped, so activity above the scheduling ceiling still decays from its full value. - Waking hours come from 30 days of
active_hour, with a fixed local night below 50 turns.
Each delivered idle fire stores its planner topic for 30 days. Pruning then deletes the fire, except
each channel’s latest idle fire, which the reply gate needs and which keeps no topic or target; Active Nudge
fires leave it null. The planner sees the lead persona’s five latest idle topics in this server as
escaped data and must avoid repeating a subject, declining if every fitting nudge would repeat one.
That rule is advisory, so planIdleNudge also declines a plan whose topic matches one of those
entries once case, spacing, and punctuation are ignored (planner_repeated_topic). The schema asks
the planner to copy an entry’s wording when the subject matches, which keeps that check reliable.
Human /reward turns contribute three times as much heat as an ordinary turn; /punish contributes
once. Their message_sent rows use reward or punish as the metric key and still count as one
message in statistics. getServerDailyHeatCounts applies the reward weight before time decay.
Persona-to-persona Playful Interaction reactions skip message_sent, active_hour, channel_turn,
and short-term memory writes, so generated exchanges cannot sustain nudges or establish human
relationships. Their conditioning records and usage statistics still record.
Nudge turns must never feed either input. naturalNudge on the chat input makes
postTurnEffects skip message_sent and active_hour, and the empty-response retry carries the
marker. It also skips the short-term memory write: a nudge answers nobody, and storing it would give
whoever spoke last a short-term memory, which the Ping User gate counts as a relationship. Without that, each nudge would raise its own heat and drag waking hours toward its fire
times. Token and model stats still record.
Channels and model
Section titled “Channels and model”- Effective channels (
resolveEffectiveChannelIdsinruntime/channels.ts): a non-emptychannel_disc_idsis used exactly. An empty list means automatic: the distinctchannel_turnkeys of the last 14 days, minus Channel Rulesrp_channel_ids.channel_turnis recorded besideactive_hourwith the channel ID (a thread’s parent), and turns that borrow a trigger skip it, so only human-triggered turns make a channel eligible. 14 days is heat’s horizon; with stat tracking off, the automatic set stays empty along with heat. Idle planning excludes channels where the bot lacks send permission, and channels whose last idle opener has no human reply after it (loadLatestIdleOpenerswithhasHumanReplyAfter). The pending verdict covers only the server’s newest opener for 12 hours, so this per-channel check is what stops a nudge from landing on an ignored one.hasHumanReplyAfter, which also decides that verdict, reads the page right after the opener and, when that page is full, the newest page too, because Discord’safternever reaches past a long run of bot messages. Webhook messages count as replies only when they resolve to a member through message-proxy attribution. The processor remembers a found reply per channel and opener, so a reopened channel is not re-read on every lull. Fire-time admission still enforces send permission, the channel whitelist, and persona access. - Channel purpose: Phase B receives each offered channel’s name, description (Discord topic), and recent messages. The planner must fit the opener and agenda to the channel’s purpose, even when recent messages drift off topic, and decline if no offered nudge and channel fit. The planner sees budgeted persona attributes and escaped transcripts that favor the newest messages, with clips preferring sentence boundaries; the speaking turn keeps the full persona.
- Nudge shortlist: Phase A raffles one category using category weights and rest among categories
with a nudge that passes channel and tool checks. It excludes the last idle category when another
category with positive weight passes those checks. Only then does it load target context when a
candidate in that category needs it, check full eligibility, and sample up to six distinct nudges
using nudge rest and target-repeat penalties. Before sampling, it excludes that category’s most
recent nudge in the loaded history when another fully eligible option remains, so the planner
cannot choose it again. Both checks read the three-day server-wide history plus the latest idle
fires; Active Nudges do not reset them. A sole eligible category or nudge can repeat.
If no option remains eligible, the attempt stops without drawing another category.
Phase B chooses the final nudge and channel within that
category together in one call. Each option carries its allowed channels and the shared cast for
a Scene attempt. The response schema limits
nudgeto the offered IDs, and acceptance checks the channel pairing and selected scene’s script. Only the selected option supplies tools, target behavior, fire records, and agendas to Phase C. Planner failures and declines include the drawn category but have no selected nudge in telemetry. - Planner model (
resolvePlannerModelinruntime/model.ts):llm_idwhen pinned, else the server’s chat model (tomoriState.llm, never a persona override). Either must passresolveServerStructuredModel; a failed pin does not fall back. Without a usable model the server stays idle and the plugin page says why. Telemetry records the model that planned and its credential provider.
Phase A also keeps a few values in memory, by the “what breaks on restart?” test: the in-flight
lock (runtime/inFlight.ts, one nudge per server across both modes), the rolled lull, the
retry-after-abort time, a five-minute eligibility snapshot, and a 15-minute cache of waking hours and
last engagement. A restart discards these caches and re-rolls the lull and retry time; persisted
activity still controls dormancy.
Constraints
Section titled “Constraints”- Explicit persona mentions can continue an ordinary nudge. After a completed non-scene turn,
postTurnEffects.tsmatches@-prefixed trigger words in delivered dialogue and queues the named personas in mention order throughqueuePersonaJobsAtFront, up to the server’s match limit. A persona already queued in the same nudge chain is excluded before that limit applies. These jobs retainnaturalNudge, system quota routing, and the borrowed anchor, so they cannot add human engagement, renew dormancy, or write short-term memory. They receive reply guidance without the opener’s private goal or tool grants. The opener starts a fresh cascade budget ofmin(cascade_limit, NUDGE_MENTION_CASCADE_LIMIT)mention replies. The limit is independent of scene length because a scene is scripted up front, while a mention chain is open-ended. Gateway echoes cannot reset it. A member’s message cancels queued nudge replies and prevents the current turn from adding more. Admission rejection or a turn that finishes without delivery discards the remaining queued nudge turns; a pending empty-response retry decides whether the chain can continue. - Abort on any doubt; never queue. An abort posts nothing and writes no fire row. A nudge
that meets a busy channel is dropped in
admissionQueue.tsrather than queued behind the turn. After an abort the idle nudge stays due and waits a fresh lull, so it cannot retry every cycle. The exceptions are a Play Scene’s later turns and explicit persona replies, which the running nudge queues itself. - Re-check right before sending.
recheckBeforeSendreads settings, category weights, caps, the persona, the persona channel whitelist, and Ping User target eligibility fresh. It also re-resolves the planned idle nudge from fresh server and persona rows and re-admits its tools, hanging conversation, eligible partners, and target memories or activity when required. It aborts asidle_nudge_unavailable,idle_nudge_changed,tools_unavailable, orprerequisites_unavailablewhen the entry or a required condition changed during planning. The lull admits planning. Generation reads the current conversation, while the channel processing lock and admission gate still prevent overlapping turns. - Caps follow the frequency level.
IDLE_NUDGE_DAILY_CAPSandACTIVE_NUDGE_DAILY_CAPSinruntime/tuning.tsmap each level to its daily ceiling, so the panel estimate, the idle nudge re-check, and the Active Nudge check read one source.IDLE_NUDGE_DAILY_PLANNER_CAPSseparately limits planner requests per server, counting every provider call including format retries, declines, failures, and plans aborted before delivery, with no refunds; it resets at the server’s local midnight and is forgotten on restart. Phase A skips fire-history reads while it is spent. The server’scategory_weightsset relative idle category tickets, with zero excluding a category in stored or imported settings./config>Plugins>Natural Nudgesedits these weights andheat_offsetfor members withManage Server. The weight modal accepts four positive whole numbers totaling 100 and saves them together. Heat buttons use atomic database updates. Both writes invalidate the shared nudge eligibility snapshot after success. - Failure cooldown. Planner failures after their one format retry, and generation errors, count
toward
server_natural_nudge_runtime_state.consecutive_failures; three pause both modes for three hours fromstopped_at. Both modes admit the next eligible attempt after expiry throughruntime/failureStop.ts, keeping the streak so another failure renews the full cooldown. A delivered nudge clears both fields, and a normal turn succeeding afterstopped_atclears them early when either mode next evaluates. Aborts never count. Cooldowns survive restarts, while waking hours, activity, ignored invitations, and daily request limits still gate retries. - Server keys only. The planner, checker, and interest generation resolve through
resolveNudgeModel(runtime/model.ts), which wrapsresolveServerStructuredModel(src/utils/provider/serverStructuredOutput.ts) and never uses a personal key. The turn planner routes the nudge turn’s text credentials to the server too. Servers inuser_byok_modeand DM workspaces never run idle nudges. - Each model bills its own slot. A pinned planner bills
nudge-plannerand a pinned or recommended text checker billsnudge-checker; the chat model, when no planner is pinned, billstext. Pinning or clearing a model claims or releases its slot, so a provider option that owns the slot pays and reports usage through the call’s usage context (see Provider options). Checker Decision models come fromloadDecisionModelsForScope, the same listcallDecisionsForProvideraccepts. A pinned Decision checker usesnudge-checker; a selected or default Decision checker usesdecision. The picker keeps the selected provider alias when it shares a catalog with BYOK, so pinning claims that option’snudge-checkerslot and selecting BYOK releases it. Subscription ownership is stored inserver_model_configs.subscription_capabilitiesasnudge_planner,nudge_checker, ordecision; having a sponsor alone does not select that payer. Imports preserve an unchanged pin’s payer and infer a changed pin’s Subscription payer only when no OpenRouter BYOK key makes the destination ambiguous. Removing a provider clears its pins while preserving pins owned by the other payer. Every actual call, including a format retry, binds the resolved usage context. A refusal from the paying option is an abort with reasondenied, logged as a warning; on the checker it also pauses the server’s checks like an HTTP 429. - The borrowed trigger lends no identity. Phase C passes the channel’s newest message to
tomoriChatas its trigger, but its author is a bystander.borrowsTriggerMessage(shared with reminders and random triggers) means the server text key only (a reminder bills its creator’s personal key instead), and no blacklist, role-whitelist, spotlight, or user-block gate from that author (only the persona channel whitelist applies). A guild turn uses the guild locale and the server’s Deliberate Tool Mode, ignoring that author’s language and personal override. Their name still fills{user}, except in a Ping User nudge (below). Every borrowed turn skips the reunion note and presence write, and nudge turns also skip the “continue your last message” directive. Deliberate Tool Mode admits the idle nudge’s tools fromnaturalNudge.toolNames, because no human message carries their trigger words. - The anchor uses current history. The runner borrows the newest surviving message, including messages posted during planning. The placeholder is sent only when the history read succeeds and comes back empty, and it is deleted again before the turn starts, so the turn borrows a message object whose blank line is already gone from the channel.
- Private channels plan alone. The shared
getChannelPrivacyReasoncheck includes restricted Discord audiences, private threads, unresolved audiences, and the manual private channel list. A private channel is offered to the planner by itself, so its history never shapes a nudge in another channel. STM sharing does not relax planner isolation. - Agendas belong to one persona.
natural_nudge_agendasrows key by(message_disc_id, persona_id). Context rebuild and the prompt snapshot render an agenda above its opener only for that persona, and only the newest one in the visible history (loadLatestPersonaAgendainruntime/agendas.ts), so older goals never stack. The agenda expires when a newer opener with an agenda for that persona enters the same history, or when the opener leaves the context window. A new idle opener’s own turn (naturalNudge.opensIdleNudgewith scene turn 0) skips stored agendas, because its goal arrives in the opener context while its agenda row is written only after delivery. An opener that cannot be anchored records no agenda row, so the previous goal stays in that case. - Opener anchoring. The fire row and agenda anchor to
GenerationTurnResult.firstDeliveredMessageId, carried from the stream state. When a tool delivered the opener, the runner looks for the first bot or managed-webhook message after the anchor instead.
Ping User targets
Section titled “Ping User targets”drawPingUserTarget (runtime/targets.ts) runs once per attempt after the category raffle and before
the shortlist draw, because three prerequisites read the drawn target. It is skipped when no
channel-eligible nudge in that category needs a target. Custom and persona-authored nudges can
require a target in any category. One query,
listPingUserCandidates, applies every hard exclusion in SQL and is read fresh rather than through
userCache, so the before-send re-check (onlyUserId) sees an opt-out made a moment earlier.
| Stage | Rule |
|---|---|
| Interaction gate | Own message_sent with this persona’s lineage in the server within 14 days. A memory alone never qualifies: memories can come from talk around Tomori rather than to her, and they carry no server, so a pointer persona would otherwise reach people it only knows from another server |
| Hard exclusions | natural_nudge_opt_out, PrivacyLevel.FULL, personalization_blacklist, an active persona_user_blocks row for this persona; bots, external bridge IDs, members who left, and members who can view none of the persona’s quiet channels are dropped when drawn |
| Relationship gate | A memory with this lineage (or lineage 0) touched in the last 30 days, or a live short-term memory with it in this server (candidates’ short-term memory is warmed from the database in one query first, because the cache starts empty after a restart). Memories count only when the persona has personal_memories_enabled |
| Lottery | Tickets from capped counts of the member’s turns with this lineage in this server and short-term memory channels, current activity, and penalties for a ping inside the idle nudge rest window (pingUserTickets); never below 1. Memories only gate eligibility and feed the planner, because they carry no server |
The lottery decides who; shortlist sampling then reduces repeats. When an eligible option needs a
target, loadTargetIdleNudgeFires reads this persona’s idle nudges on that
member over the last 14 days (PING_USER_REPEAT_REST_MS), and idleNudgeTickets multiplies each one’s
server-wide rest by its rest on that pair. Repeats admitted by the shortlist keep reduced weight,
so a member with only one eligible idle nudge can still get it. The window is keyed on persona_id,
so a re-created persona starts fresh.
Prompt exposure follows a normal turn’s privacy rules: the planner sees the target’s recent memories
only at PrivacyLevel.MINIMAL with personal_memories_enabled, and their activity only at minimal
privacy with the GuildPresences intent. recent_memory and presence_activity pass only when that
exposure exists, so an idle nudge never plans around data the planner cannot see.
When target context is exposed, every channel offered in that call must be visible to the target,
including channels for untargeted alternatives, because that context can shape any chosen plan.
The before-send re-check confirms target eligibility and view permission again even when an
untargeted alternative wins, because the plan may use the exposed target context.
Selecting an untargeted nudge clears the target before generation and recording.
Member-written text (the target’s name, activity, and memories) appears only inside the
<target> block, escaped so it cannot close the block; briefs and the opener instruction refer to the
target rather than quoting their name, so a crafted nickname or activity cannot become an instruction.
The Phase C turn carries naturalNudge.targetUserDiscId, which changes these things and nothing else:
- Naming.
resolveNamingSubject(turnPlanner.ts) fills{user}and the triggerer name from the target’s row, live name, and per-persona naming. Credentials, quotas, and stats stay with the borrowed trigger’s author. - Short-term memory and tools. The opener reads the target’s short-term memory
(
shortTermMemoryUserId), and tool calls act for the target (toolLoop.ts), so a reminder or memory the opener creates defaults to them rather than to a bystander. - Mentions. The target’s handles join the forced mentions, and
mentionableUserIdsmakes the stream sendallowedMentionswith only that user and noparse, so the opener cannot ping roles,@everyone, or another member. Thereplyaction ofmanage_messagehonors the same list. After delivery,ensureDiscordUserMentionposts a bare mention if the opener omitted it, through the persona’s webhook for an alter (sendAlterPersonaMention). - Records.
target_user_idis written on the fire row (the lottery penalty reads it) and on the agenda rows, so erasing the user deletes both through the foreign key.
Play Scene
Section titled “Play Scene”A Play Scene idle nudge reuses the /generate scene machinery: the runner passes a sceneTurn, and
turnPlanner.ts queues the remaining turns at the front of the channel queue under turn 0’s lock
(queueScenePersonaJobsAtFront).
- Partners.
drawScenePartners(runtime/partners.ts) draws one partner, and a second atPLAY_SCENE_SECOND_PARTNER_CHANCE, by the lead’s own ticket formula (talkativeness times rested share) among personas whose channel whitelist shares a channel with every speaker so far. The cast is drawn once for the attempt, and its profiles appear once in the planner prompt. Every offered scene nudge uses that cast; each option’s allowed channels narrow to the shared set, and options with no compatible channel are removed.two_personaspasses when such a partner exists. Every Play Scene idle nudge needs one, even a custom one that omitstwo_personas. - Script. The planner returns
script(speaker numbers, lead first, no speaker twice in a row, everyone at least once). Its length comes from a per-attempt draw: 2-4 turns, or 5-8 atPLAY_SCENE_LONG_CHANCE. Every scene turn carries a brevity instruction, so a long scene is an exchange of one-line reactions and the opener stays a short hook while the substance lives in the agendas. It also returns onepartner_agendasentry per partner.sceneScriptIssueschecks every one of these rules, the lengths included, because Anthropic’s output grammar rejectsminItemsabove 1; a violation gets the one format retry. Other categories omit these fields from the planner response schema and receive no scene partner profiles. - Private goals per speaker.
SceneTurnMetadata.turnContextItemsreplaces turn 0’s injected context for each queued turn, so a partner’s first turn carries only its own agenda and never the lead’s. The fire row and every speaker’s agenda row anchor to turn 0’s opener, written when turn 0 settles. - Queued turns stay nudge turns. The queued jobs carry
naturalNudgeandborrowsTriggerMessage, so they skip stats and the short-term memory write and keep the borrowed author’s gates off. - Members interrupt. Any real member message, before any admission gate can drop it, calls
interruptNudgeScene(channelQueue.ts), which discards the queued turns that carry bothsceneTurnandnaturalNudgewith thescene_interruptedreason./generate sceneturns carry no nudge marker and keep running. The opener and its agendas stay. - The next speaker catches the member.
interruptNudgeScenereturns the first dropped turn’s persona, or the scene persona speaking now when nothing was queued, asnudgeSceneCatcherPersonaId. A message that triggers on its own (a name, a mention, a reply) keeps normal persona selection; any other message is queued anyway and answered by the catcher, subject to the member’s own whitelist, spotlight, and access gates. It is a normal member turn. - The scene’s own lines start nothing. While a nudge turn holds the channel lock, while nudge turns
wait in its queue, and for five seconds after the last one releases, admission ignores persona
gateway messages there (
nudge_output). Ordinary nudges route explicit mentions after generation; scripted scenes keep their planned sequence. Ignoring gateway echoes prevents duplicate replies and replies that lose the nudge marker. - A failed turn ends the scene. The channel queue only advances when a lock is released, so
tomoriChatitself drops the remaining turns whenever a nudge scene turn (the opener included) is rejected at admission or delivers nothing. An empty reply that is being retried does not count, because the retry decides for itself. A scene never plays without its opener or with a speaker missing, and its turns never wait in the queue for an unrelated turn to release them. - Targets are not pinged. Scheming draws a target like a Ping User nudge, so naming, short-term memory, tools, and the mention allow-list follow it, but the opener is not forced to ping them.
- Re-check.
recheckBeforeSendalso confirms each partner still exists and is allowed in the chosen channel.
Active Nudges
Section titled “Active Nudges”An Active Nudge has no planner. A message counter decides when to look, one matcher call decides whether
the conversation matches a persona’s interest, and the winner gets a plain turn. The messageCreate
handler starts the counter check in the background, so its settings read does not delay chat.
flowchart TD msg["messageCreate (activeNudge.ts)"] --> obs["observeActiveNudgeMessage"] obs -->|"persona message"| reset["counter starts over;<br/>an open check's watch notes it"] obs -->|"human message in effective channel<br/>(thread counts toward parent)"| roll["count reaches roll (activeNudgeTripRange) →<br/>claim server → detached check"] roll --> check["runActiveNudgeCheck"] check --> phaseA["Phase A, fresh reads: settings, stop,<br/>daily cap, 1 per channel per hour, matcher"] phaseA --> opts["options: interests of personas with<br/>talkativeness above 0 allowed in channel"] opts --> match["matchActiveNudge over last 5 messages →<br/>interest or none"] match --> win["winner: owner of that interest who did not<br/>speak in window; 10% detour"] win --> wait["wait 15-45 s → recheckBeforeSend,<br/>one re-match when 5 posted"] wait --> chat["tomoriChat({ naturalNudge, borrowsTriggerMessage }) →<br/>fire row (mode active)"]- Counter in memory.
ActiveNudgeCounterkeeps one count per listed channel, shared with its threads, so a conversation that moves into a thread keeps its count. The check reads and speaks in the channel or thread whose message tripped it, and the hourly cap covers a parent and its threads together (a fire row stores the thread;listedChannelOfmaps it back through the channel cache). The trip range starts at 15-40 human messages at heat 15, scales by 15 over heat (held to ½-4), then by the frequency level, and nothing counts below heat 1. Any check that does not fire rests the channel before a new roll: 10 minutes, doubling with each empty check in a row up to 3 hours, and a fire resets it. A restart only resets the counts. - Check budget.
ActiveNudgeCheckBudgetcaps checker calls per server per server-day (10, 20, 40, or 60 by level, including format retries and re-matches), because the fire cap never stops checks that find nothing. A text-model checker that answers HTTP 429 pauses the whole server for 3 hours, since the quota belongs to its key; the Decision path reports no status, so it cannot trigger the pause. The budget is in memory, so a restart forgets the day’s count. - Gate cache. The counter reads settings, effective channels, and heat through a 5-minute cache instead of the database, because it runs on every guild message. Everything after the trip reads fresh.
- Checker choice (
resolveMatcherBackend). The Active Nudge Checker is separate from the idle nudge planner because it runs far more often on a much smaller task. An admin can pin a text model (checker_llm_id) or a Decision model (checker_decision_model_id), at most one, and a pinned checker that cannot answer does not fall back. Unpinned, the recommended checker is resolved from the server’s current keys on every check, so adding or removing a provider needs no write: the Decision model selected in/config > Models, then Google’s defaultgemini-decision-1on a Google key, then the catalog’s default OpenRouter Decision model, then the planner model. - Matcher, one boundary, two backends (
runtime/matcher.ts). A Decision model gets onechoicequestion and must listchoiceinsupported_primitives. A text model gets a structured enum of the option IDs at temperature 0, with one format retry. Both use the wording the false-fire evaluation measured, up to 25 interests plusnone(some Decision models reject more than 26 options; personas whose new labels would overflow sit the check out), and argmax. A refused, blocked, or unparseable answer reads asnone, and so does a choice that is not its own most likely option. A transport failure is recorded but never counts toward the failure cooldown, so a broken matcher cannot pause idle nudges. - Member text stays data. The evidence is
Name: textlines read through the same privacy filter as planner transcripts. A text-model checker sees it inside an escaped<<< >>>block; the Decision API receives it as its separate evidence field. - Winner rule. Owners who spoke in the evidence window are excluded before options are built. Shared labels become one option with every remaining owner, under the first owner’s description. With no remaining interests, a busy channel, or a persona reply observed during the initial reads, no matcher request is sent.
- Detours. 10% of the time another persona allowed in the channel, with talkativeness above 0, a
message_sentin the last 60 days, and no message in the window, takes the turn. Its tickets are talkativeness times rested share times an underdog boost of 1-4 from its share of the top persona’s 30-day count. The fire row recordsdetour. - Send permission. Phase A and the re-check skip a channel where the bot cannot send, so a read-only listed channel never costs a matcher call.
- Re-check. After the delay,
recheckBeforeSendrepeats the Phase A reads and the speaker’s persona checks, then aborts when a persona spoke in the channel or the channel is locked. When five members posted, it runs the matcher once more on the newest five messages with the same options; the reply speaks only if the same interest wins again and the speaker is not in that window, otherwise it aborts aswindow_gone. - Plain turn. The turn carries
naturalNudgewith no tools andborrowsTriggerMessage, and no brief, agenda, or injected context, so it skips the same stats and memory writes as an idle nudge. Active Nudges have no pending or unanswered rules; generation failures count toward the shared cooldown. - Telemetry. One
natural_nudge_activerow per check: outcome, phase, reason, heat, matcher kind, model, and credential provider, option count, the Decision margin overnone, detour, matcher tokens, and whether a second call ran with its own tokens.
Idle Nudges as data
Section titled “Idle Nudges as data”Built-in idle nudges (BUILTIN_IDLE_NUDGES in runtime/idleNudges.ts), server custom idle nudges, and
persona-authored idle nudges share one shape: category, planner brief, agenda hint, prerequisites, and
recommended tools. Prerequisites come from a
fixed registry: hanging_conversation, the three target facts (relationship_user, recent_memory,
presence_activity), two_personas, and tool:<name>, where tool availability is what the persona’s
turn would be offered on that channel’s text model. Each category implies one prerequisite (CATEGORY_IMPLIED_PREREQUISITES): Ping
User needs a drawn target, Revive Topic a hanging conversation, and Play Scene a partner, even for a
custom idle nudge that omits it, and /nudge-studio neither offers nor stores that prerequisite. Any
idle nudge listing one of the three target facts needs a target too; outside a scene, such an idle
nudge pings its target. An unknown prerequisite makes an idle nudge ineligible rather than silently
dropping the check.
An idle nudge can be limited to chosen personas (server_natural_nudge_persona_scopes, keyed by the idle
nudge key; no row means every persona). After the persona raffle, Phase A drops every runnable idle nudge
whose scope excludes the drawn persona, before the target draw. Scope binds only the lead: a Play Scene
partner may be any persona. The scope is an allow-list, so a persona created later stays out until
checked. The Studio’s Toggle Availability modal writes the on/off switch and the scope together
(saveIdleNudgeAvailability): checking every live persona deletes the row, and checking none turns the
idle nudge off and deletes it too. Persona IDs are stored as JSONB rather than
foreign-keyed rows: a cascade would empty a scope whose personas were all deleted, and an empty scope
reads as open to everyone. Readers filter out deleted IDs instead. Deleting or importing custom idle
nudges drops their scopes (import assigns new IDs), the workspace export omits scopes because persona IDs
do not port, and a server reset clears them.
A persona-authored idle nudge has an owner instead of a scope. Its runtime key is
persona:<personaId>:<localId> (personaAuthoredIdleNudgeKey), where <personaId> is the local
persona instance and <localId> is unique only inside that persona’s list, so two servers can hold
the same local ID. listPersonaRunnableIdleNudges builds the Phase A pool for the drawn persona: enabled
built-ins, scope-allowed server customs, then that persona’s locally enabled entries. Owner entries
never pass through isInPersonaScope and never read server_natural_nudge_persona_scopes, so a
missing scope row cannot widen them. Like scope, ownership binds only the Play Scene lead; any other
nudging persona may partner. The entries then meet the same prerequisites, raffles, rest windows, and
caps as every other idle nudge, which is why authoring more of them never raises how often a persona
speaks. Fire rows store the key, and telemetry masks it to persona so authored IDs never become
metric dimensions.
/nudge-studio (discord/studio*.ts) marks an enabled idle nudge as blocked through
findIdleNudgeBlocker, which judges only facts that hold for days: whether a nudging persona in scope
exists, whether one of them holds every tool the idle nudge needs, and whether a Play Scene has a second
nudging persona. Hanging conversations, targets, and presence change between draws, so they never mark
one blocked.
Pointer personas
Section titled “Pointer personas”persona_natural_nudge_configs holds a persona’s talkativeness, interests, authored idle nudges
(authored_idle_nudges), and local availability (disabled_idle_nudge_ids). A missing row reads as the
live preset defaults (persona_presets.natural_nudge_*, including natural_nudge_idle_nudges) for an
unforked pointer and as the column defaults otherwise. materializeIfPointer copies the preset values
into a row, and re-pointing a persona at a preset deletes the row so it reads the preset again.
The authored list has three states on a pointer’s row: NULL reads the live preset list, an array is
the persona’s own list, and an empty array means it deliberately owns none. Content and availability
are separate columns. The first content write (addPersonaIdleNudge, updatePersonaIdleNudge,
removePersonaIdleNudge) snapshots the whole effective list into the row, so later preset edits stop
reaching that persona; per-entry overlays would let a preset edit change half an entry.
setPersonaIdleNudgeAvailability writes only the disabled IDs, so a toggle never snapshots.
restorePersonaIdleNudgeList sets the list back to NULL and prunes disabled IDs that no longer
exist in the preset, leaving interests and talkativeness alone. A full resync still deletes the row.
Persona removal checklists and preset-list restore confirmations retain content fingerprints. The repository checks those fingerprints under the persona write lock, so a stale confirmation cannot discard content edited after the dialog opened.
Cards carry the effective list as natural_nudge_idle_nudges but never availability or server custom
nudges. Import validates the list before any write, restores it through replacePersonaIdleNudges
(which clears local availability, so imports start enabled), and re-links to the official pointer only
when the card’s list is absent or equals the preset’s. Seeding therefore gives every language row of a lineage the
same list, or a card exported from one language would not match another’s preset. The workspace
export carries server custom nudges only, because persona-owned content belongs to the persona.
Source pointers
Section titled “Source pointers”src/modules/natural-nudges/runtime/processor.ts: Phase A.src/modules/natural-nudges/runtime/runner.ts: Phases B and C, re-checks, fire recording.src/modules/natural-nudges/runtime/meters.ts: heat, due time, waking hours, raffles.src/modules/natural-nudges/runtime/targets.ts: Ping User gates, lottery, and re-check.src/modules/natural-nudges/runtime/partners.ts: Play Scene partner draw.src/modules/natural-nudges/runtime/activeNudges.ts: Active Nudge counter, check, re-check, and turn.src/modules/natural-nudges/runtime/matcher.ts: the Active Nudge matcher and its two backends.src/modules/natural-nudges/runtime/tuning.ts: every pacing and selection constant (heat, lull, waking hours, rest windows, stops, retention, Ping User windows and points, scene length and partner count, idle nudge category weights and daily caps, Active Nudge trip range, daily cap, window, delay, and detours). Schema and Discord limits stay with their owners.src/modules/natural-nudges/db/repositories.ts: every Natural Nudges query.src/modules/natural-nudges/db/types.ts: schemas and limits shared by storage, cards, seeding, and the runtime, including the authored idle nudge shape and the prerequisite and tool registries.src/modules/natural-nudges/runtime/idleNudges.ts: built-ins, owner normalization, and the selection pool.src/modules/natural-nudges/discord/panel.ts: the personaNudgespage, including itsIdle Nudgessection.src/modules/natural-nudges/discord/studioPanel.ts: the/nudge-studiopanel and its modal builders.src/modules/natural-nudges/discord/studioRoutes.ts:/nudge-studiorouting, authorization, and checklist writes.- Related: Database Schema, Prompt Snapshot, Persona Presets.