Gossip Engine gives NPCs a memory and lets stories spread between them. It runs on FalkorDB. Your game calls
five functions for memory. The engine keeps one graph for each save, with what each character saw, heard and
believes. It tells you how each character treats the player now, and why.
Quickstart
You need Docker, uv and Node 20 or later. Run these commands from the root of the repository:
docker compose up -d falkordb # FalkorDB on :6392, browser UI on :3012
cp server/.env.example server/.env # optional: add GEMINI_API_KEY
npm install
npm run server # engine on http://localhost:8787
npm run dev # this site + the game on http://localhost:5173
Run the five calls on the live engineChecking the engine…
// The output shows here. The engine deletes the save after the run.
Concepts
Save
One player's world. Each save is a separate FalkorDB graph (save_<saveId>). The server finds
the graph from the save id, so one save cannot read or write another save.
World
The characters, their relationships, what each action means, and which beliefs change which behavior. You
load it with defineWorld. The world is data in the save, so each save can run a different world.
Event ground truth
What really happened (recordEvent). The engine stores it one time. A retelling never changes it.
Memory episodic
One character's version of an event. The kind is direct (it happened to them),
witness (they saw it) or heard (someone told them). A heard memory records who told
it, when, how sure the listener is (confidence) and how far the story moved from the truth
(distortion). It also links to the memory of the teller. These links make a chain back to the
source.
Belief semantic
What a character thinks about the player now, for example “Doesn't pay their debts”, with a strength from 0
to 1. Beliefs that disagree stay side by side. The engine does not delete one belief to keep another.
Rule procedural
A threshold that changes behavior. When the score of a character on a dimension crosses the threshold, an
effect turns on, for example price_multiplier ×2 or refuse_trade. When the score
goes back, the effect turns off.
The gossip loop
advanceTime(hours) runs min(maxRoundsPerNight, hours ÷ hoursPerRound) rounds. In each round:
Each pair of villagers who know each other meets with the probability strength × contact. The
random number comes from a generator seeded with (world seed, night, round, pair). Thus the
luck of one pair never depends on another pair.
With the probability talkativeness, each side shares one memory that the other side does not
have. It picks the memory with the highest action salience × confidence. It shares only if the
confidence is shareMinConfidence or more.
The gossip trait of the teller changes the story: the severity, the distortion, or the
claim itself (“didn't pay” → “stole a sword”). The LLM writes the line in the voice of the teller.
The confidence of the listener is
strength × credulity(valence) × topicBias × (0.5 + 0.5 × teller's confidence), to a maximum of
1. The credulity is 1 when the teller is family.
Beliefs change and the engine checks the rules again. The engine streams the handoff and returns it.
Each decision uses the state from the start of the round. A villager who learns a story in round k can
pass it on in round k + 1 at the earliest. Thus one night of three rounds moves a rumor three hops at
most.
Beliefs, rules and mood
The strength of a belief adds up the evidence with a noisy-OR formula (each piece of evidence raises the strength, up to 1): 1 − Π(1 − severity × confidence).
The score on a dimension, for example honesty, is Σ belief.strength × action.dims[dim], kept between −1 and 1.
A rule fires when score op threshold is true. Each belief that pushes the score gets a TRIGGERS edge.
Trust is Σ npc.values[dim] × score[dim]. Values let groups disagree. For example, a crew that values street cred trusts a robber more.
The mood is distrust if a negative rule is on or trust is −0.3 or less. The mood is affinity if a positive rule is on or trust is 0.3 or more. Otherwise, the mood is neutral.
The same story on each run
The world seed sets who meets whom, so the same choices give the same story on each run. The engine looks for
text in this order: the planted cache in the repository (server/data/llm_cache.json), the live
cache, Gemini, and then a template in the voice of the character, made from the stored memory. Each cache key
includes the world, the teller, the listener and the claim. Free-text dialogue (intent: "free")
always goes to the live model. If the model times out, you get a template line with fallback: true.
The engine keeps all the data that it stored before.
Adds the world to the graph of the save. It also accepts a full WorldDefinition, or no arguments
for the Thornbury world that comes with the engine. If you run it again, it updates the definition and keeps
the memories. To delete the memories, set reset: true.
Stores the event as ground truth. The target gets a direct memory, and each witness gets a
witness memory. Then the engine updates their beliefs and rules. Your game decides who is a
witness. Thornbury uses each villager within six tiles. If there is no witness and no target, nobody has a
story to tell.
Runs the gossip loop and moves the clock forward. The result lists each handoff in order. The engine also
streams each handoff to onGossip subscribers when it commits the handoff. Thus a night animation
shows only what really happened.
{
day: 2, hour: 8, night: 1, rounds: 3,
rumorEvents: [{
round: 2, tellerName: "Pip", listenerName: "Elena",
claim: "stole_sword", groundTruth: "refused_to_pay", storyChanged: true,
versionText: "Miss Elena! The stranger nicked a sword clean off Garrick's anvil. I swear on my boots!",
confidence: 0.53, tellerNote: "Pip twisted the story for fun.",
behaviourChanges: [{ ruleId: "elena_refuse", effect: "refuse_trade", active: true }]
}, …],
discoveries: ["ev1_refused_to_pay"], journalUnread: 1
}
Gives a reply that uses only the memories, beliefs and active rules of that NPC. For a dialogue choice that
you wrote, pass an intent ("greet", "ask_why", …). The engine caches
these lines, so they are the same on each run. For free text, use intent: "free". Free text
goes to the live model.
{
text: "Twenty gold for you, love, up front. Tom says you stiffed his cousin Garrick.",
sourceLabel: "Heard from Tom · last night", sourceNpcId: "tom", sourceEventId: "ev1_refused_to_pay",
rumorDriven: true, distorted: false, fallback: false, textSource: "planted",
attitude: Attitude, discovered: true
}
getAttitude(npcId)
Returns the gameplay modifiers for one NPC, ready to apply, and the one memory that best explains them.
{
mood: "distrust", trust: -0.75, hostility: 0.75, priceMultiplier: 2, refuseTrade: false,
knowsPlayer: true, scores: { honesty: -0.75 },
activeRules: [{ id: "martha_price", effect: "price_multiplier", value: 2, label: "Charges double for a room", tone: "negative" }],
reason: { claimLabel: "Refused to pay Garrick", kind: "heard", sourceNpcName: "Tom",
sourceLabel: "Heard from Tom · last night", versionText: "Watch that newcomer, Martha…" }
}
Read models
Method
What it gives you
state()
The clock, the player state and the attitude of each NPC: all that a game needs when it loads
getAttitudes()
All attitudes by NPC id, for mood markers
journal()
The rumor cards that the player found: tone, reach, versions, distortion and unread state
rumor(eventId)
Data for the Rumor Map: the version of each holder, each hop with the text before and after, the NPCs that the story did not reach, and the social graph
markRumorRead(eventId)
Removes the unread dot from a card
socialGraph()
NPCs and relationship edges
inspectNpc(npcId)
The episodic, semantic and procedural memory of one NPC, with the Cypher query for each
stats()
The graph id, and the node and edge counts for each label. These show that saves stay separate.
replayNight(overrides)
Runs the last night again in a sandbox copy, with changed bonds, traits or seed, and compares the result with what really happened
savePlayer(state) / loadPlayer()
The save data of your game, stored on the Player node
onGossip(listener)
A WebSocket stream of night_start, rumor and night_end. It returns a function that unsubscribes.
track(event, data)
Simple event tracking for the demo, kept for each save
Errors
If a call fails, it throws GossipEngineError with the HTTP status and the message from the server:
400
The input is not valid: an unknown action, an unknown NPC or a bad save id
404
The save, NPC or event does not exist
409
The save has no world yet (call defineWorld), there is no night to replay, or you tried to overwrite a template that comes with the engine
422
The world failed validation, for example because a relationship names an NPC that does not exist. The message lists each problem.
Lies, trust and timelines
The five calls above give NPCs a memory. The calls below give the town a social life. Villagers judge each
other, remember whose word they trust, form groups and forget. The player can use these rules: plant a
lie, listen in on gossip, clear their name, or turn the town against a rival.
plantRumor(teller, listener, claim)
Whispers a made-up story. Before the engine writes to the graph, it checks the text against the
safety policy of the world. Then the model finds what the claim is and who it is about.
Without the model, a simple local parser does this. NPCs repeat only the restatement that the engine writes,
never the raw text. The engine creates a Rumor node with
(Player)-[:ORIGINATED {hidden: true}]->(Rumor). After that, the lie spreads like any other
story. A lie about an NPC becomes a belief about that NPC, not about the player.
const res = await gossip.plantRumor("player", "pip", "Garrick waters down his steel");
// accepted
{ accepted: true, rumorId: "lie2", subjectId: "garrick", label: "Garrick waters down his steel",
confidence: 0.54, believed: true,
reaction: "Garrick? Really? Swear on my boots, I always said his blades bend too easy!" }
// refused: nothing was written
{ accepted: false, reason: "unknown_name", reaction: "Musk? Never heard of them. Nobody round here has." }
The reasons for a refusal are profanity, banned_topic, rating,
unknown_name (real people never enter the world), personal_data,
about_listener, no_subject, no_claim and too_long.
getReputation(npcId) shows what the lie costs its target:
{ customers: 4, population: 7, boycotting: [...] }.
traceRumor(rumorId, { npcId? }) and trust
Each morning, some villagers trace lies. These villagers have the skeptic trait or
investigates: true. They follow the chain of each made-up story that they know back to its
origin. When they reach the origin, they expose the lie:
ORIGINATED.hidden becomes false.
A new event, “Caught spreading a lie”, starts to spread.
The village trusts each villager who passed the lie on less. The engine multiplies each
(NPC)-[:TRUSTS {score}]->(NPC) edge that points to them by exposureTrustFactor (0.6).
With less trust, a listener is less likely to listen to them, and believes them less. Thus their stories
spread more slowly. A villager who hears about the exposure retracts the lie. The memory stays, but it no
longer counts as evidence.
overhear runs daytime gossip, with the same retelling rules as the night. If one NPC knows a
story that the other does not know, they tell it now. If the player is near enough to hear, the player learns
the story too. The result has a source tag for the speech bubble, for example “Nell saw it firsthand”.
getDiary gives one diary entry for each villager for each day. The engine writes the entry from
the memories of that day, and stores it as (NPC)-[:WROTE]->(Diary {day, text}).
getFactions gives the groups in the town. Each night, the engine finds them with community
detection (FalkorDB algo.WCC), which finds the groups of nodes that connect to each other. It
uses only strong bonds in which both sides still trust each other and neither side avoids the other. It writes
the result as (NPC)-[:IN]->(Faction). Thus a lie that lowers trust in someone can split the
town.
If you set forgetRate, villagers forget. A belief that nobody retold for half a day loses that
share of its strength each night. A retelling makes it strong again.
forkSave copies the graph of the save (GRAPH.COPY) into a separate timeline. For
example, you can put a timeline in which the player paid next to one in which the player did not pay.
simulate runs the next nights many times, each time with a different seed, on copies that the
engine deletes after the run. The model is off for these runs. It streams its progress. The odds have
these fields:
Field
Meaning
effectPct
How often each behavior rule fires for each character: { ruleId, label, npcId, name, pct }
turnedAgainst
Who turns against the player
reach
How far each story reaches
topInfluencers
Who passes stories on most
exposedPct
How often someone exposes a lie
scaleTest sends test villages of 8 to 500 NPCs through the same engine. On a laptop, one night
for 500 NPCs takes less than one second and gives about 150 handoffs.
algorithms returns the factions, PageRank over who heard from whom (the most influential
gossips), and the shortest paths to the villager who thinks least of you (the fastest way to clear your
name). The Studio (studio.html) has all of these under Advanced: Worlds, World
Studio, Simulator, Saves and Settings.
Godot, Unity, Unreal
Each call is plain REST and WebSocket, so any game engine can use it. For Godot 4, copy
sdk/godot/addons/gossip_engine into your project. Add one GossipWorld node, and one
GossipNPC node for each character. Then call
await $Martha/GossipNPC.talk("One room, please."). Read price_multiplier, and
connect to signals such as attitude_changed and said. Components for Unity (C#) and Unreal (C++) on the
same API are coming soon.
Agents and the MCP server
The engine serves its graph tools over MCP at /mcp (Streamable HTTP, stateless, JSON responses).
Two agents come with the engine, and both are clients of that server. Sheriff Hale works in the game, and the
Balance Copilot works in the Studio. You can also connect your own agent.
Each agent lists its tools over MCP and lets Gemini choose the next call. The engine streams every call and
its result, so the player or the designer sees each step. The facts in an answer come from tool results. The
model writes only the reasoning and the words.
close_case is refused unless the chain of custody leads to the person that the agent accuses.
try_tuning changes a throwaway fork of the save. It never changes the save itself.
interview_npc takes the facts from the villager's memory in the graph. Gemini only puts them in the villager's voice.
Connect your agent
Add the server to Claude Code, then ask a question about a town:
claude mcp add --transport http gossip-engine https://your-host/mcp
# then: "Who in Thornbury is most likely to turn on the player? Show the path."
For Cursor or another MCP client, use the URL directly:
Each tool takes a save_id. Call list_saves first to find one.
The 16 tools
Tool
What it gives the agent
list_saves
The saves on the server (one FalkorDB graph each), newest first
list_stories
Each story in the town, true or made up. Who made up a lie stays hidden until someone exposes it.
story_holders
Who knows a story, how many hops each one is from the source, and their own version of it
who_told
One hop back along the chain of custody: who told this villager, when, and in what words
trace_rumor
The whole chain of custody of a made-up story, in one multi-hop Cypher query
who_witnessed
Who saw an event, or who heard a rumor first
credibility
How far the town trusts each villager (the average TRUSTS score), and who was caught passing on a lie
shortest_path
The fewest acquaintances between two villagers (shortestPath over KNOWS)
influence
PageRank over who heard from whom: the biggest gossips
get_factions
Community detection (algo.WCC) over strong bonds in which both sides still trust each other
player_attitudes
How each villager treats the player now, and the memory behind it, lowest trust first
interview_npc
A villager's answer to a question, from their memory, in their voice (a Gemini call)
close_case
Fines whoever made up a rumor and posts a notice in the square. The notice spreads overnight, and listeners drop the lie.
world_stats
For each villager: talkativeness, credulity, bonds, reach (Σ strength × contact) and betweenness
simulate_odds
The next nights, run many times with different seeds on throwaway copies. It returns { runs, nights, effects, turnedAgainst, liesExposedPct, topTellers, elapsedMs }: how often each behavior rule fires, who turns against the player, how often someone exposes a lie, and who passes stories on most.
try_tuning
A balance change, tested on a fork, with the odds measured again
runAgent
for await (const step of gossip.runAgent("sheriff", { rumorId: "lie2" })) {
// start · note · tool_call · tool_result · report · error
render(step);
}
gossip.runAgent("copilot", { question: "Michael comes after Franklin in almost every run. Bring it under 40%." });
Event
Meaning
start
The agent connected to the MCP server. It lists the tools that it can use and the model.
note
One sentence from the agent that says why it makes the next call
tool_call · tool_result
The tool that the agent chose, its arguments, the result and the time it took
report
The final answer, the total time, and the Cypher behind each tool that it used
Over REST, the same agents run with POST /saves/{id}/agents/sheriff or /agents/copilot,
with a body of { question?, rumorId? }. The response is an NDJSON stream with one event on each line.
World definition
A world is one JSON document. Thornbury (server/data/thornbury.json) and the open-world example
Los Santos (server/data/examples/los_santos.json) use the same engine with different worlds.
The chance that they share something when they meet someone (0 to 1)
npcs[].credulity / credulityPositive
How much they believe bad and good hearsay
npcs[].topicBias
A multiplier on credulity for stories with these action tags
npcs[].values
The weight of each dimension for trust. Negative weights make groups disagree.
npcs[].family
NPC ids whose word they never doubt. When they retell a wrong done to these NPCs, they make it bigger.
relationships[]
A bond in both directions: strength (how much they trust what the other says) and contact (how often they meet)
actions{}.dims
How the action moves each belief dimension (−1 to 1)
actions{}.twist
What a twister retells it as (another action id)
rules[].effect
getAttitude understands price_multiplier, refuse_trade, hostility and help. The engine passes any other effect (wanted_level, mission_unlock…) through in activeRules, for your game to use.
rules[].tone
"positive" or "negative", for the mood. By default, help and discounts are positive.
Trust and forgetting
Field
Default
Meaning
world.credibilityDim
"honesty"
The belief dimension that decides whose word counts, and what a lie costs
world.defaultTrust
1.0
The starting TRUSTS score between villagers who know each other
world.exposureTrustFactor
0.6
The share of trust that remains in a villager who passed on a lie
world.boycottAt
-0.15
The opinion at which a villager stops dealing with another villager (a shop loses customers)
world.forgetRate
0
The share of a belief lost each night that nobody retells it (Thornbury: 0.06)
npcs[].investigates
skeptics
Traces made-up stories back to their source each morning
npcs[].pos
none
The position on the World Studio canvas (layout only)
Content safety
safety: { rating: "E" | "T" | "M", bannedTopics: [], blockedWords: [], profanityFilter: true }.
The engine checks each whisper that a player types. First, it checks the whisper locally: profanity and your
word list, banned topics, the age rating, links and numbers, and each proper noun that is not a person or a
place in the world. Then the model checks it with the same policy. A refusal comes back in the voice of the
character, and the engine writes nothing. NPCs repeat only the restatement that the engine writes, and the
restatement passes the same checks.
Gossip traits
Trait
What the engine does
Thornbury
exaggerate
When they retell a wrong done to them: severity ×1.25, and more distortion
Garrick
family_loyal
When they retell a wrong done to their family: severity ×1.2, and more distortion
Tom
twister
Replaces the claim with the twist of the action. Distortion +0.5.
Pip
skeptic
Passes stories on in a weaker form: severity ×0.6, and less drift
A label only. Their behavior comes from the numbers: talkativeness, credulity, topic bias, and their relationships (or no relationships)
Nell, Martha, Elena, Old Wren
REST API
The SDK is a thin layer over these endpoints. Any game engine can call them, and a Godot addon is available. Each endpoint takes JSON and returns JSON.
Factions, PageRank and the paths to clear your name, and each story with its believers
POST
/saves/{id}/fork · /simulate · /reset
forkSave, the odds of each outcome (NDJSON), and a reset to day one
GET
/saves/{id}/export · /budget
The full graph as JSON, and the model spend for today
POST
/sim/scale
{ sizes }: scale test (NDJSON)
GET · POST · PUT · DELETE
/worlds · /worlds/{id} · /worlds/{id}/saves
The world library: templates (read-only) and Studio worlds. You can start a save from a world.
POST
/saves/{id}/agents/{agent}
{ question?, rumorId? }: run sheriff or copilot (NDJSON)
POST
/mcp
The MCP server (Streamable HTTP, JSON-RPC)
GET
/settings
The model for each job, and the budget. The response tells you if a secret is set, but never shows it.
Graph schema and Cypher
(NPC)-[:KNOWS {strength, contact}]->(NPC)
(Player)-[:PERFORMED]->(Event)<-[:WITNESSED]-(NPC)
(NPC)-[:REMEMBERS]->(Memory)-[:ABOUT]->(Event)
(Memory)-[:HEARD_FROM {night, round}]->(NPC) (Memory)-[:DERIVED_FROM]->(Memory)
(NPC)-[:BELIEVES]->(Belief)-[:ABOUT]->(Player) (Belief)-[:SUPPORTED_BY {weight}]->(Memory)
(NPC)-[:HAS_RULE]->(Rule)<-[:TRIGGERS]-(Belief)
(Player)-[:MET]->(NPC) (Player)-[:DISCOVERED {unread}]->(Event)
(Player or NPC)-[:ORIGINATED {hidden}]->(Rumor {claim, is_true, origin})-[:CONCERNS]->(NPC)
(NPC)-[:REMEMBERS]->(Memory)-[:ABOUT]->(Rumor) a made-up story travels like a true one
(NPC)-[:TRUSTS {score}]->(NPC) credibility, docked when caught passing on a lie
(NPC)-[:BELIEVES]->(Belief)-[:ABOUT]->(NPC) what villagers think of each other
(NPC)-[:IN]->(Faction {name}) refreshed nightly from (NPC)-[:ALLY]->(NPC)
(NPC)-[:WROTE]->(Diary {day, text})
To try these queries, open the FalkorDB browser at http://localhost:3012 and select a save_… graph.
The chain back to the source, for the version of one villager
MATCH path = (m:Memory {npc_id: 'martha'})-[:DERIVED_FROM*0..]->(origin:Memory)
WHERE NOT (origin)-[:DERIVED_FROM]->()
RETURN [x IN nodes(path) | x.npc_id + ': ' + x.version_text]
Where did the story change?
MATCH (listener:NPC)-[:REMEMBERS]->(m:Memory {story_changed: true})-[:HEARD_FROM]->(teller:NPC)
RETURN teller.name, listener.name, m.ground_truth, m.claim, m.version_text
Expose a liar
MATCH (n:NPC {name: $npc})-[:REMEMBERS]->(m:Memory)-[:ABOUT]->(r:Rumor), (origin)-[:ORIGINATED]->(r)
RETURN r.claim, r.is_true, origin.name
Lower the trust in each villager who passed the lie on (one time for each teller)
MATCH (r:Rumor {id: $rumor, is_true: false})<-[:ABOUT]-(:Memory)-[:HEARD_FROM]->(teller:NPC)
WITH DISTINCT teller
MATCH (listener:NPC)-[t:TRUSTS]->(teller)
SET t.score = t.score * 0.6
Factions, influence, and how to clear your name
CALL algo.WCC({nodeLabels: ['NPC'], relationshipTypes: ['ALLY']}) YIELD node, componentId
CALL algo.pageRank('NPC', 'HEARD') YIELD node, score
MATCH (s:NPC), (t:NPC {id: $target}) WHERE s <> t
WITH s, shortestPath((s)-[:KNOWS*1..6]-(t)) AS p RETURN s.id, [n IN nodes(p) | n.id]
Who has never heard of the player?
MATCH (n:NPC) WHERE NOT (n)-[:REMEMBERS]->(:Memory)
RETURN n.name
Configuration
Variable
Default
GEMINI_API_KEY
(empty)
Live retellings and free-text dialogue
GEMINI_MODEL
gemini-3.8-flash
GOSSIP_LLM
gemini
off uses only the caches and templates
GOSSIP_LLM_TIMEOUT
8
Seconds before the engine uses a template line
FALKORDB_HOST / FALKORDB_PORT
localhost / 6392
GEMINI_MODEL_<JOB>
GEMINI_MODEL
The model for each job: RECALL, RETELL, TALK, WHISPER, EXPOSE
GOSSIP_LIVE_FIRST
0
1 makes every line a fresh Gemini call. The caches are then only the fallback when the model fails or times out.
GEMINI_MODEL_AGENT
GEMINI_MODEL
The model that drives Sheriff Hale and the Balance Copilot
GOSSIP_DAILY_BUDGET
400
Live model calls for each save each day. After that, the engine uses cached lines and templates. 0 means no limit.
VITE_GOSSIP_URL
http://localhost:8787
Where the game and this site find the engine
To record your own showcase run (the run that the landing page replays), run
uv run python scripts/export_showcase.py from server/.