@dsh-agentic-roleplay/state 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["pad","present","list","name","isObject","MAX_TEXT","isObject","resolve","DAY","toItem","RANGES","checked","SESSION_ID","fromRow"],"sources":["../../dsh-roleplay-model/src/character.ts","../../dsh-roleplay-model/src/intent.ts","../../dsh-roleplay-model/src/item.ts","../../dsh-roleplay-model/src/location.ts","../../dsh-roleplay-model/src/session.ts","../../dsh-roleplay-model/src/memory.ts","../../dsh-roleplay-model/src/relationship.ts","../../dsh-roleplay-model/src/knowledge.ts","../../dsh-roleplay-model/src/faction.ts","../../dsh-roleplay-model/src/clock.ts","../../dsh-roleplay-model/src/agenda.ts","../../dsh-roleplay-model/src/variable.ts","../../dsh-roleplay-model/src/trigger.ts","../../dsh-roleplay-model/src/visual.ts","../../dsh-roleplay-model/src/lore.ts","../../dsh-roleplay-model/src/plot.ts","../src/clock.ts","../src/driver/node-sqlite.ts","../src/errors.ts","../src/sqlite/support.ts","../src/records/edit-types.ts","../src/sqlite/agenda-repositories.ts","../src/records/time.ts","../src/records/agenda-edit.ts","../src/records/items.ts","../src/records/movement.ts","../src/records/template.ts","../src/sqlite/variable-repository.ts","../src/records/variables.ts","../src/records/trigger-rules.ts","../src/records/wire.ts","../src/records/edit.ts","../src/records/triggers.ts","../src/records/deferred.ts","../src/memory/recall.ts","../src/records/read.ts","../src/sqlite/event-repository.ts","../src/sqlite/memory-repository.ts","../src/sqlite/narrative-repositories.ts","../src/sqlite/recall-index.ts","../src/sqlite/trigger-repository.ts","../src/sqlite/clock-repository.ts","../src/sqlite/item-repository.ts","../src/sqlite/relationship-repository.ts","../src/sqlite/location-repository.ts","../src/sqlite/vector-extension.ts","../src/sqlite/character-repository.ts","../src/sqlite/intent-repository.ts","../src/sqlite/metadata-repository.ts","../src/sqlite/schema.ts","../src/sqlite/migrate.ts","../src/sqlite/state-repository.ts","../src/sqlite/visual-identity-repository.ts","../src/sqlite/knowledge-repository.ts","../src/sqlite/faction-repositories.ts","../src/sqlite/lore-repository.ts","../src/store.ts","../src/sessions.ts","../src/records/lint.ts","../src/records/agenda.ts","../src/tools/index.ts","../src/plugin.ts","../src/tools/character.ts"],"sourcesContent":["import type { RoutineDefinition } from './agenda.ts'\nimport type { VariableValue } from './variable.ts'\nimport type { RelationshipDefinition } from './relationship.ts'\nimport type { CharacterStart } from './state.ts'\nimport type { VisualIdentityInput } from './visual.ts'\nimport type { KnowledgeDefinition } from './knowledge.ts'\n\nexport const CHARACTER_ROLES = ['playable', 'npc'] as const\nexport const CHARACTER_TIERS = ['principal', 'supporting', 'background'] as const\nexport const CHARACTER_KINDS = ['person', 'group'] as const\n\n/** Whether the player may choose the character; a world can offer several. */\nexport type CharacterRole = typeof CHARACTER_ROLES[number]\n\n/**\n * How much simulation a character gets: principals act on their own,\n * supporting characters act when the scene involves them, background\n * characters only react as the world changes.\n */\nexport type CharacterTier = typeof CHARACTER_TIERS[number]\n\n/** A single person, or a crowd or organisation treated as one participant. */\nexport type CharacterKind = typeof CHARACTER_KINDS[number]\n\nexport interface CharacterSpeech {\n style: string\n examples: string[]\n}\n\n/** A character as authored in a world. */\nexport interface CharacterDefinition {\n /** Provisional, unique within the world; only for links inside the exported files. */\n id: string\n name: string\n /** Nicknames and other names the character answers to. */\n aliases: string[]\n age?: string\n gender?: string\n /** May differ from the gender, for example \"she/her\". */\n pronouns?: string\n kind: CharacterKind\n tier: CharacterTier\n role: CharacterRole\n /** One or two sentences, for lists and previews. */\n summary: string\n personality: string\n background: string\n appearance: string\n /** Stable visual facts; current expression, clothing, activity and surroundings do not belong here. */\n visualIdentity?: VisualIdentityInput\n speech: CharacterSpeech\n /** Provider voice id used for spoken utterances. */\n voice?: string\n start: CharacterStart\n /** How this character stands towards others of the world, by their ids. */\n relationships?: RelationshipDefinition[]\n /** Places, things and ways this character knows exist when the story starts. */\n knowledge?: KnowledgeDefinition\n /** The recurring day of the character: what it is doing and where, by the clock. */\n routine?: RoutineDefinition[]\n /** What it starts with of what the world tracks (a value for each of the variables named), by variable key. */\n variables?: Record<string, VariableValue>\n}\n","export const INTENT_TYPES = ['need', 'obligation', 'quest', 'agenda', 'aspiration', 'relationship', 'habit', 'reaction'] as const\nexport const INTENT_STATUSES = ['active', 'paused', 'completed', 'failed', 'abandoned'] as const\nexport const INTENT_HORIZONS = ['immediate', 'short', 'day', 'long', 'open_ended'] as const\n\nexport type IntentType = typeof INTENT_TYPES[number]\nexport type IntentStatus = typeof INTENT_STATUSES[number]\nexport type IntentHorizon = typeof INTENT_HORIZONS[number]\n\n/** A driving thread behind what a character does. */\nexport interface Intent {\n type: IntentType\n name: string\n description: string\n status: IntentStatus\n horizon: IntentHorizon\n /** 0 to 1. */\n priority: number\n /** 0 to 1. */\n urgency: number\n plan: string[]\n openThreads: string[]\n constraints: string[]\n /** ISO 8601 date-time. */\n deadline?: string\n}\n","import type { CharacterId } from './session.ts'\nimport type { LocationId } from './location.ts'\nimport type { VisualIdentityInput } from './visual.ts'\n\nexport type ItemId = number\n\n/** Whether a container can be got into. */\nexport const CONTAINER_STATES = ['open', 'closed', 'locked'] as const\nexport type ContainerState = (typeof CONTAINER_STATES)[number]\n\n/** A place on the body something can be worn. Worlds can have their own; these are what a world starts with. */\nexport interface Slot {\n /** Short and lowercase: how items and tools name it. */\n id: string\n name: string\n /** How many things can be worn there at once. */\n capacity: number\n}\n\nexport const SLOT_ID = /^[a-z][a-z0-9_-]{0,39}$/\n\nexport const DEFAULT_SLOTS: readonly Slot[] = [\n { id: 'head', name: 'head', capacity: 1 },\n { id: 'face', name: 'face', capacity: 1 },\n { id: 'neck', name: 'neck', capacity: 1 },\n { id: 'torso', name: 'torso', capacity: 2 },\n { id: 'back', name: 'back', capacity: 1 },\n { id: 'waist', name: 'waist', capacity: 1 },\n { id: 'hands', name: 'hands', capacity: 1 },\n { id: 'wrists', name: 'wrists', capacity: 2 },\n { id: 'fingers', name: 'fingers', capacity: 4 },\n { id: 'legs', name: 'legs', capacity: 1 },\n { id: 'feet', name: 'feet', capacity: 1 },\n]\n\n/** What can hold other things: a chest, a satchel, a drawer. */\nexport interface ContainerSpec {\n state: ContainerState\n}\n\n/**\n * A thing that can be moved, held, worn, opened or used: one kind for everything physical. What it\n * can do is what it has: a slot it is worn in, a container it holds things in, a quantity when there\n * are several alike. Scenery that cannot be moved (a desk, a window) is a feature of its place instead.\n */\nexport interface Item {\n id: ItemId\n /** The id in the world's files; absent for something made up in play. */\n sourceId?: string\n name: string\n description: string\n /** How many there are, for things that come in numbers (coins, arrows). */\n quantity: number\n /** Only one exists in the story: it is never split or merged. */\n unique: boolean\n /** Its condition, in words: \"worn\", \"freshly oiled\". */\n quality: string\n /** Matters to the story: told first and never left out of a short list. */\n notable: boolean\n /** Not seen by anyone until it is found. */\n hidden: boolean\n /** The slot it is worn in, when it can be worn. */\n wearableSlot?: string\n container?: ContainerSpec\n /** Whose it is, which is not the same as who has it. */\n ownerId?: CharacterId\n createdAt: string\n}\n\nexport type NewItem = Omit<Item, 'id' | 'createdAt'>\n/** What may change about a thing. `ownerId: null` says it belongs to no one. */\nexport type ItemPatch = Partial<Pick<Item, 'name' | 'description' | 'quantity' | 'quality' | 'notable' | 'hidden'>> & { ownerId?: CharacterId | null; container?: ContainerSpec }\n\n/** What holds an item: a place, a character (in its hands, or worn) or another item (inside it). */\nexport type Holder =\n | { kind: 'location'; locationId: LocationId; position?: string; featureKey?: string }\n | { kind: 'character'; characterId: CharacterId; mode: 'held' }\n | { kind: 'character'; characterId: CharacterId; mode: 'worn'; slot: string; position?: string }\n | { kind: 'item'; itemId: ItemId; position?: string }\n\nexport interface Holding {\n itemId: ItemId\n holder: Holder\n}\n\n/** What an item is, as the world's files write it, before it is put in a session. */\nexport interface ItemDefinition {\n id: string\n name: string\n description: string\n visualIdentity?: VisualIdentityInput\n quantity: number\n unique: boolean\n quality: string\n notable: boolean\n hidden: boolean\n wearable?: string\n container?: { state: ContainerState; openedBy: string[] }\n owner?: string\n /** What it starts with of what the world tracks, by variable key. */\n variables?: Record<string, import('./variable.ts').VariableValue>\n /** Where it starts: one of these. */\n start:\n | { kind: 'location'; location: string; position?: string; feature?: string }\n | { kind: 'held'; character: string }\n | { kind: 'worn'; character: string; slot?: string; position?: string }\n | { kind: 'inside'; item: string; position?: string }\n /** For an exit: which of the item's ways it opens is written on the exit; here only what opens this item, if it is a container. */\n}\n\n/** The things the world says open its exits, by place and the id of the place it leads to. */\nexport interface ExitOpener {\n from: string\n to: string\n items: string[]\n}\n","import type { CharacterId } from './session.ts'\nimport type { VisualIdentityInput } from './visual.ts'\n\nexport type LocationId = number\nexport type ExitId = number\n\n/** A named thing in a place that a story can point at: a desk, a window, a notice board. */\nexport interface LocationFeature {\n /** Unique within its location; how authors and tools refer to it. */\n key: string\n name: string\n description: string\n}\n\n/** At most this many features describe one place, so that a place never overwhelms a prompt. */\nexport const MAX_LOCATION_FEATURES = 30\n\nexport interface Location {\n id: LocationId\n /** The id of the place in the world's files; absent for a place made up in play. */\n sourceId?: string\n name: string\n description: string\n /** The place this one is in (a room in a building, a building in a district). Containment only: it does not say how to get from one to the other. */\n parentId?: LocationId\n features: LocationFeature[]\n createdAt: string\n}\n\nexport type NewLocation = Omit<Location, 'id' | 'createdAt'>\n\n/** What may change about a place once it exists. `parentId: null` takes it out of the place that contains it. */\nexport type LocationPatch = Partial<Pick<Location, 'name' | 'description' | 'features'>> & { parentId?: LocationId | null }\n\n/** Whether people can go through an exit now. */\nexport const EXIT_STATES = ['open', 'locked', 'blocked'] as const\nexport type ExitState = (typeof EXIT_STATES)[number]\n\n/** A way from one place to another, one direction at a time; a door usually has one each way. */\nexport interface Exit {\n id: ExitId\n fromId: LocationId\n toId: LocationId\n /** What it looks like from the place it leaves: \"a narrow stair down to the cellar\". */\n description: string\n /** How long going through takes, when it is known. Authored data; nothing here runs a clock. */\n travelSeconds?: number\n /** Open to use; locked until something unlocks it; blocked until the way is cleared. */\n state: ExitState\n /** Why it is locked or blocked, or what opens it. */\n note: string\n}\n\nexport type NewExit = Omit<Exit, 'id' | 'state' | 'note'> & { state?: ExitState; note?: string }\nexport type ExitPatch = Partial<Omit<Pick<Exit, 'description' | 'travelSeconds' | 'state' | 'note'>, 'travelSeconds'> & { travelSeconds: number | null }>\n\n/** The kinds of thing that can stand in a place. Characters now; items and containers are placed the same way. */\nexport const PLACEABLE_KINDS = ['character'] as const\nexport type PlaceableKind = (typeof PLACEABLE_KINDS)[number]\n\nexport interface Placement {\n kind: PlaceableKind\n entityId: CharacterId\n locationId: LocationId\n /** Where in the place, in words: \"at the bar\", \"by the door\". */\n position: string\n /** The feature of the place it is at or by, when it is one. */\n featureKey?: string\n}\n\nexport interface NewPlacement {\n locationId: LocationId\n position?: string\n featureKey?: string\n}\n\n/** A request to go somewhere. */\nexport interface Move {\n to: LocationId\n position?: string\n featureKey?: string\n /** Skip the exits: the story itself carries the character (carried off, teleported, falls). */\n ignoreExits?: boolean\n}\n\n/** How a move would go: the places passed through, in order, ending at the destination. */\nexport interface MovePlan {\n from?: LocationId\n to: LocationId\n via: LocationId[]\n /** The summed travel time when every exit on the way has one. */\n travelSeconds?: number\n}\n\n/** One way out of a place as the world's files write it. */\nexport interface ExitDefinition {\n /** The id of the place it leads to. */\n to: string\n description: string\n /** Whether there is no way back; otherwise the way back is made too. */\n oneWay: boolean\n backDescription?: string\n travelSeconds?: number\n state: ExitState\n note: string\n /** The ids of the items that open it when it is locked. */\n openedBy?: string[]\n}\n\n/** A place as the world's files write it, before it is put in a session. */\nexport interface LocationDefinition {\n id: string\n name: string\n description: string\n visualIdentity?: VisualIdentityInput\n /** The id of the place it is in. */\n parent?: string\n features: LocationFeature[]\n exits: ExitDefinition[]\n /** What it starts with of what the world tracks, by variable key. */\n variables?: Record<string, import('./variable.ts').VariableValue>\n}\n","import type { CharacterDefinition } from './character.ts'\nimport type { JsonValue } from './json.ts'\nimport type { CharacterStart } from './state.ts'\nimport type { Intent } from './intent.ts'\n\nexport const CHARACTER_CONTROLS = ['player', 'agent'] as const\n\nexport type CharacterId = number\nexport type IntentId = number\n\n/** Who decides what a character does in a session. */\nexport type CharacterControl = typeof CHARACTER_CONTROLS[number]\n\n/**\n * Where a session's world came from. The session keeps no copy of the world,\n * so this is only a reference; further provenance can go in `extra` without a\n * schema change.\n */\nexport interface WorldReference {\n /** The world's stable id, kept in its `world.json`; not a database id. */\n id: string\n name: string\n version?: string\n /** Identifies the exact world content the session was started from. */\n fingerprint?: string\n source?: string\n extra?: Record<string, JsonValue>\n}\n\nexport interface NewSession {\n /** Also the name of the session's folder. */\n id: string\n /** What the player calls the session; usually starts as the world's name. */\n name: string\n world: WorldReference\n}\n\nexport interface SessionMetadata extends NewSession {\n createdAt: string\n /** When the last turn was played; absent for a session that has not been played yet. */\n lastPlayedAt?: string\n /** Turns played so far. */\n turns: number\n}\n\n/** A character in a session: the definition without its start state, under a session-local id. */\nexport interface Character extends Omit<CharacterDefinition, 'id' | 'start'> {\n id: CharacterId\n /** The character's provisional id in the world it came from; absent when created during play. */\n sourceId?: string\n control: CharacterControl\n createdAt: string\n}\n\nexport type NewCharacter = Omit<Character, 'id' | 'createdAt'>\n\n/** What of a character can be edited: who it is, not who controls it. A field left out stays; `null` takes an optional one away. */\nexport interface CharacterPatch {\n name?: string\n aliases?: string[]\n age?: string | null\n gender?: string | null\n pronouns?: string | null\n kind?: Character['kind']\n tier?: Character['tier']\n role?: Character['role']\n summary?: string\n personality?: string\n background?: string\n appearance?: string\n speech?: Character['speech']\n voice?: string | null\n}\n\nexport interface CharacterFilter {\n role?: Character['role']\n tier?: Character['tier']\n kind?: Character['kind']\n control?: CharacterControl\n}\n\n/** A character's current state; it starts as the world's `start` block and changes during play. */\nexport interface CharacterState extends Omit<CharacterStart, 'intents' | 'emotion'> {\n characterId: CharacterId\n /** Increases with every change, for detecting conflicting updates. */\n version: number\n updatedAt: string\n}\n\nexport type NewCharacterState = Omit<CharacterStart, 'intents' | 'emotion'>\n\n/** Fields left out stay as they are. */\nexport interface CharacterStatePatch {\n publicState?: string\n innerState?: string\n activity?: string\n}\n\nexport interface CharacterIntent extends Intent {\n id: IntentId\n characterId: CharacterId\n createdAt: string\n updatedAt: string\n}\n\n/** Fields left out stay as they are; `null` removes the deadline. */\nexport type IntentPatch = Partial<Omit<Intent, 'deadline'>> & { deadline?: string | null }\n\nexport interface IntentFilter {\n status?: Intent['status']\n}\n","import type { CharacterId } from './session.ts'\nimport type { JsonValue } from './json.ts'\nimport type { ItemId } from './item.ts'\nimport type { LocationId } from './location.ts'\n\n/** How a character came to take in an event. */\nexport const PERCEPTION_MODES = ['witnessed', 'heard', 'told', 'inferred'] as const\nexport type PerceptionMode = (typeof PERCEPTION_MODES)[number]\n\n/** How well what a character took in matches what happened; recorded for checking, never shown to the character. */\nexport const ACCURACIES = ['accurate', 'partial', 'mistaken'] as const\nexport type Accuracy = (typeof ACCURACIES)[number]\n\nexport const MEMORY_KINDS = ['belief', 'relationship', 'knowledge'] as const\nexport type MemoryKind = (typeof MEMORY_KINDS)[number]\n\nexport const THREAD_STATUSES = ['open', 'resolved'] as const\nexport type ThreadStatus = (typeof THREAD_STATUSES)[number]\n\n/** A digest covers a stretch of recent turns closely; a chapter covers older turns briefly. */\nexport const SUMMARY_LEVELS = ['digest', 'chapter'] as const\nexport type SummaryLevel = (typeof SUMMARY_LEVELS)[number]\n\nexport const IMPORTANCE_MIN = 1\nexport const IMPORTANCE_MAX = 5\n\nexport type EventId = number\nexport type PerceptionId = number\nexport type MemoryId = number\nexport type ThreadId = number\nexport type SummaryId = number\n\n/** Something that objectively happened in the story: the ground truth the rest is derived from. */\nexport interface StoryEvent {\n id: EventId\n turn: number\n round: number\n text: string\n /** From 1 (passing) to 5 (turns the story). */\n importance: number\n tags: string[]\n /** The characters the event is about: who acted, and who it was done to. */\n involves: CharacterId[]\n /** The things it is about: what was taken, opened, found. */\n items: ItemId[]\n /** Where it happened, when that is known. */\n locationId?: LocationId\n /**\n * Events are ground truth and cannot change once sealed, which happens when the records of the rounds they\n * belong to are complete. Until then they are a draft that its writer may still correct.\n */\n sealed: boolean\n createdAt: string\n}\n\nexport type NewStoryEvent = Omit<StoryEvent, 'id' | 'createdAt' | 'sealed' | 'items'> & { items?: ItemId[] }\n\nexport interface StoryEventPatch {\n text?: string\n importance?: number\n tags?: string[]\n involves?: CharacterId[]\n locationId?: LocationId\n items?: ItemId[]\n}\n\nexport interface StoryEventFilter {\n /** Only events that happened in this place. */\n locationId?: LocationId\n turn?: number\n round?: number\n fromTurn?: number\n toTurn?: number\n involving?: CharacterId\n /** Only events about this item. */\n aboutItem?: ItemId\n minImportance?: number\n}\n\n/** What one character took in of an event: its own version, which may be partial or wrong. */\nexport interface Perception {\n id: PerceptionId\n eventId: EventId\n characterId: CharacterId\n mode: PerceptionMode\n /** What the character took in, in full. */\n content: string\n /** The essence of it in a few words, which is what is left of it as it fades. */\n gist: string\n accuracy: Accuracy\n recalls: number\n lastRecalledTurn?: number\n createdAt: string\n}\n\n/** What may change about a perception: a character's version of an event is revised as it learns more or remembers it differently. */\nexport type PerceptionPatch = Partial<Pick<Perception, 'mode' | 'content' | 'gist' | 'accuracy'>>\n\nexport interface NewPerception {\n characterId: CharacterId\n mode: PerceptionMode\n content: string\n gist: string\n accuracy: Accuracy\n}\n\nexport interface PerceivedEvent {\n perception: Perception\n event: StoryEvent\n}\n\n/** What a character has come to believe or know, beyond single events. */\nexport interface CharacterMemory {\n id: MemoryId\n characterId: CharacterId\n kind: MemoryKind\n text: string\n /** The characters it is about. */\n about: CharacterId[]\n importance: number\n /** The turn it was formed in. */\n turn: number\n recalls: number\n lastRecalledTurn?: number\n createdAt: string\n}\n\nexport type NewCharacterMemory = Omit<CharacterMemory, 'id' | 'createdAt' | 'recalls' | 'lastRecalledTurn'>\n\nexport interface CharacterMemoryPatch {\n text?: string\n about?: CharacterId[]\n importance?: number\n}\n\n/** Something in the story that is not settled yet: a promise, a mystery, a goal. */\nexport interface StoryThread {\n id: ThreadId\n text: string\n status: ThreadStatus\n openedTurn: number\n resolvedTurn?: number\n}\n\n/** A written account of a stretch of turns, built from the events in it. */\nexport interface Summary {\n id: SummaryId\n level: SummaryLevel\n fromTurn: number\n toTurn: number\n text: string\n createdAt: string\n}\n\nexport type NewSummary = Omit<Summary, 'id' | 'createdAt'>\n\n/** One recorded round whose events and memories have not been written yet. */\nexport interface PendingCommit {\n turn: number\n round: number\n payload: JsonValue\n createdAt: string\n}\n\n/** What a stored text belongs to: what a character took in, what it believes, or what happened (not any character's). */\nexport const RECALL_ITEM_KINDS = ['perception', 'memory', 'event'] as const\nexport type RecallItemKind = (typeof RECALL_ITEM_KINDS)[number]\n\n/** One thing found by a search, by the key the recall uses for it: `p:<id>`, `m:<id>`, `e:<id>`. */\nexport interface RecallHit {\n key: string\n kind: RecallItemKind\n /** The id of the perception, memory or event. */\n refId: number\n /** From 0 (not related) to 1 (the best match of the search); for a lexical search relative to the best hit, for a vector search the cosine similarity. */\n score: number\n}\n\n/** What the vectors of a session were made by. They are only comparable with each other. */\nexport interface EmbeddingIndexInfo {\n model: string\n dimensions: number\n /** How many texts have a vector. */\n embedded: number\n /** How many texts still wait for one. */\n pending: number\n}\n\n/** A text that has no vector yet. */\nexport interface PendingEmbedding {\n /** The id to give back with its vector. */\n id: number\n kind: RecallItemKind\n text: string\n}\n","import type { CharacterId } from './session.ts'\n\nexport type RelationshipId = number\n\n/** How a character stands towards another: a short profile, not a single edge. Each direction is its own profile. */\nexport interface Relationship {\n id: RelationshipId\n /** Whose view it is. */\n fromId: CharacterId\n toId: CharacterId\n /** What the other is to this character, in a word or two: \"sister\", \"rival\", \"landlord\". */\n label: string\n /** The relationship in a sentence or two: how it came about, what it is like now. */\n summary: string\n /** How well it knows the other, from 0 (a stranger) to 1 (intimately). */\n familiarity: number\n /** From -1 (distrusts) to 1 (trusts completely). */\n trust: number\n /** From -1 (dislikes) to 1 (is fond of). */\n affinity: number\n /** How strained it is right now, from 0 to 1. */\n tension: number\n /** The turn it last changed. */\n updatedTurn: number\n createdAt: string\n}\n\nexport interface NewRelationship {\n fromId: CharacterId\n toId: CharacterId\n label: string\n summary?: string\n familiarity?: number\n trust?: number\n affinity?: number\n tension?: number\n}\n\nexport type RelationshipPatch = Partial<Pick<Relationship, 'label' | 'summary' | 'familiarity' | 'trust' | 'affinity' | 'tension'>>\n\n/** A relationship as the world's files write it: from the character whose file it is in, to another by its id in the world. */\nexport interface RelationshipDefinition {\n to: string\n label: string\n summary: string\n familiarity: number\n trust: number\n affinity: number\n tension: number\n}\n\n/** What was made up in play and still has to be fitted into the rest of the world. */\nexport const CONSOLIDATION_KINDS = ['character', 'location', 'item'] as const\nexport type ConsolidationKind = (typeof CONSOLIDATION_KINDS)[number]\n\nexport type ConsolidationItemId = number\n\nexport interface ConsolidationItem {\n id: ConsolidationItemId\n kind: ConsolidationKind\n /** The id of the character or place. */\n subjectId: number\n /** Why it was made, in the words of whoever asked for it. */\n note: string\n createdTurn: number\n resolvedTurn?: number\n /** What was done to fit it in, when it is resolved. */\n resolution?: string\n}\n","import type { CharacterId } from './session.ts'\n\nexport const KNOWLEDGE_KINDS = ['location', 'item', 'exit', 'lore'] as const\nexport type KnowledgeKind = typeof KNOWLEDGE_KINDS[number]\n\n/** That a character knows a place, thing or way exists. Current facts about it come from perception and memory. */\nexport interface EntityKnowledge {\n characterId: CharacterId\n subjectKind: KnowledgeKind\n subjectId: number\n learnedTurn: number\n lastObservedTurn?: number\n}\n\n/** What a character file says the character knows when the story starts. */\nexport interface KnowledgeDefinition {\n locations: string[]\n items: string[]\n exits: { from: string; to: string }[]\n lore?: string[]\n}\n","import type { Intent } from './intent.ts'\nimport type { RelationshipPatch } from './relationship.ts'\n\nexport type FactionId = number\n\nexport interface Faction {\n id: FactionId\n sourceId?: string\n name: string\n aliases: string[]\n summary: string\n description: string\n values: string[]\n structure: string\n createdAt: string\n}\n\nexport type NewFaction = Omit<Faction, 'id' | 'createdAt'>\nexport type FactionPatch = Partial<Pick<Faction, 'name' | 'aliases' | 'summary' | 'description' | 'values' | 'structure'>>\n\nexport interface FactionState {\n factionId: FactionId\n publicState: string\n innerState: string\n version: number\n updatedAt: string\n}\n\nexport interface NewFactionState {\n publicState?: string\n innerState?: string\n}\n\nexport type FactionStatePatch = Partial<NewFactionState>\n\nexport const MEMBERSHIP_STATUSES = ['active', 'inactive', 'former'] as const\nexport type MembershipStatus = typeof MEMBERSHIP_STATUSES[number]\n\nexport interface FactionMembership {\n factionId: FactionId\n characterId: number\n role: string\n rank: string\n status: MembershipStatus\n public: boolean\n commitment: number\n joinedTurn: number\n leftTurn?: number\n}\n\nexport type MembershipPatch = Partial<Pick<FactionMembership, 'role' | 'rank' | 'status' | 'public' | 'commitment' | 'leftTurn'>>\n\nexport type SocialSubjectKind = 'character' | 'faction'\n\nexport interface FactionRelationship {\n id: number\n fromKind: SocialSubjectKind\n fromId: number\n toKind: SocialSubjectKind\n toId: number\n label: string\n summary: string\n familiarity: number\n trust: number\n affinity: number\n tension: number\n updatedTurn: number\n createdAt: string\n}\n\nexport interface FactionIntent extends Intent {\n id: number\n factionId: FactionId\n createdAt: string\n updatedAt: string\n}\n\nexport interface FactionRelationshipDefinition extends RelationshipPatch {\n to: { kind: SocialSubjectKind; id: string }\n label: string\n}\n\nexport interface FactionMembershipDefinition {\n character: string\n role: string\n rank: string\n status: MembershipStatus\n public: boolean\n commitment: number\n}\n\nexport interface FactionDefinition {\n id: string\n name: string\n aliases: string[]\n summary: string\n description: string\n values: string[]\n structure: string\n start: {\n publicState: string\n innerState: string\n goals: Intent[]\n }\n members: FactionMembershipDefinition[]\n relationships: FactionRelationshipDefinition[]\n}\n","/**\n * How the story's time passes: `simulated` moves only when the story does (the game master says how\n * long things take and may skip ahead), `real` follows the wall clock.\n */\nexport const CLOCK_MODES = ['simulated', 'real'] as const\nexport type ClockMode = (typeof CLOCK_MODES)[number]\n\n/** The story's clock: the instant it is in the story, in milliseconds since the Unix epoch (UTC). */\nexport interface ClockState {\n mode: ClockMode\n now: number\n}\n\n/** Why the story's time moved. */\nexport const TIME_CHANGE_KINDS = ['start', 'elapsed', 'real', 'skip', 'resync'] as const\nexport type TimeChangeKind = (typeof TIME_CHANGE_KINDS)[number]\n\n/** One step of the story's time. `round` is 0 for what happens outside a round. */\nexport interface TimeChange {\n id: number\n turn: number\n round: number\n kind: TimeChangeKind\n from: number\n to: number\n reason: string\n}\n\nexport interface TimeChangeFilter {\n turn?: number\n round?: number\n fromTurn?: number\n toTurn?: number\n kind?: TimeChangeKind\n}\n","import type { CharacterId } from './session.ts'\nimport type { LocationId } from './location.ts'\n\n/** A recurring stretch of the day in which a character is occupied with something, in a place. */\nexport interface RoutineWindow {\n /** The days of the week it applies on, 0 for Sunday; every day when empty. A window past midnight belongs to the day it starts on. */\n days: number[]\n /** The minute of the day it starts, 0 to 1439. */\n start: number\n /** The minute it ends (exclusive); before `start` it ends the next day. Equal to `start` is not a window. */\n end: number\n activity: string\n locationId?: LocationId\n featureKey?: string\n /** Where in the place, in words. */\n position?: string\n /** Whether the character will drop it to join something that comes up; a shift at work may not be. */\n interruptible: boolean\n}\n\nexport interface StoredRoutineWindow extends RoutineWindow {\n id: number\n characterId: CharacterId\n}\n\n/** A routine window as a world's files write it. */\nexport interface RoutineDefinition {\n /** Three-letter days (`mon` to `sun`); every day when left out. */\n days: string[]\n /** `HH:MM`. */\n from: string\n to: string\n activity: string\n /** The id of a place in the world. */\n location?: string\n feature?: string\n position?: string\n interruptible: boolean\n}\n\nexport const WEEKDAY_NAMES = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] as const\n\nexport type EngagementId = number\n\nexport const ENGAGEMENT_STATUSES = ['pending', 'kept', 'missed', 'cancelled'] as const\nexport type EngagementStatus = (typeof ENGAGEMENT_STATUSES)[number]\n\n/** Something dated that characters have committed to: a meeting, an errand, an event they are to attend. */\nexport interface Engagement {\n id: EngagementId\n title: string\n /** When it is due, in UTC milliseconds. */\n at: number\n /** When it is over, when that is not simply soon after `at`. */\n until?: number\n locationId?: LocationId\n participants: CharacterId[]\n status: EngagementStatus\n note: string\n createdTurn: number\n updatedTurn: number\n}\n\nexport interface NewEngagement {\n title: string\n at: number\n until?: number\n locationId?: LocationId\n participants: CharacterId[]\n note?: string\n turn: number\n}\n\nexport interface EngagementPatch {\n title?: string\n at?: number\n until?: number\n locationId?: LocationId\n participants?: CharacterId[]\n status?: EngagementStatus\n note?: string\n turn: number\n}\n\nexport interface EngagementFilter {\n status?: EngagementStatus\n participant?: CharacterId\n /** Only those due at or after this instant. */\n from?: number\n /** Only those due before this instant. */\n to?: number\n}\n","/** What a variable holds: a number within bounds, a yes or no, or one of a list of words. */\nexport const VARIABLE_KINDS = ['number', 'flag', 'choice'] as const\nexport type VariableKind = (typeof VARIABLE_KINDS)[number]\n\n/** What a variable is about: each character, item or place has its own value; `world` has one value for the whole story. */\nexport const VARIABLE_SUBJECTS = ['character', 'item', 'location', 'world'] as const\nexport type VariableSubject = (typeof VARIABLE_SUBJECTS)[number]\n\n/**\n * Who can tell what the value is. `public`: anyone present (what shows). `private`: the character it belongs to, and the\n * game master (what it feels or knows of itself). `hidden`: only the game master and the record keeper.\n */\nexport const VARIABLE_VISIBILITIES = ['public', 'private', 'hidden'] as const\nexport type VariableVisibility = (typeof VARIABLE_VISIBILITIES)[number]\n\nexport type VariableValue = number | boolean | string\n\n/** The word for a number up to a bound: values up to `upTo` (and above the previous band) are called `label`. */\nexport interface VariableBand {\n upTo: number\n label: string\n}\n\n/** A kind of thing the story keeps track of, declared by a world, by the story, or built in. */\nexport interface VariableDefinition {\n /** Lowercase letters, digits and underscores, starting with a letter. */\n key: string\n name: string\n /** What it measures or means, for the models that read and change it. */\n description: string\n kind: VariableKind\n subject: VariableSubject\n /** The subjects it applies to, by their keys; every subject of its kind when empty. */\n only: string[]\n /** The bounds of a number. */\n min?: number\n max?: number\n /** Whether a number is a whole number. */\n integer: boolean\n /** The words a choice is one of. */\n options: string[]\n /** What it is for a subject that has no value of its own yet. */\n default: VariableValue\n /** Whether each value has a baseline beside the current one: the slow-moving temperament the current value is measured from (feelings). */\n baseline: boolean\n visibility: VariableVisibility\n /** Words for ranges of a number, lowest first; the last one covers whatever is above. */\n bands: VariableBand[]\n /** Whether it is always told, even at its default; otherwise only once it differs from it. */\n always: boolean\n /** Built in: it cannot be removed, and what it is cannot be changed. */\n builtin: boolean\n}\n\n/** A variable as the world's files write it: what is left out takes its default. */\nexport type VariableDefinitionInput = Pick<VariableDefinition, 'key' | 'name' | 'kind' | 'subject'> & Partial<Omit<VariableDefinition, 'key' | 'name' | 'kind' | 'subject' | 'builtin'>>\n\nexport interface StoredVariable {\n variable: string\n subject: VariableSubject\n /** 0 for the world. */\n subjectId: number\n value: VariableValue\n baseline?: VariableValue\n updatedTurn: number\n}\n\nexport const VARIABLE_KEY = /^[a-z][a-z0-9_]{0,39}$/\n/** At most this many variables in a story, so that what is tracked stays something a model can hold. */\nexport const MAX_VARIABLES = 60\n\n/** The feelings every character has: built in, from -1 to 1, with a temperament beside the current value. */\nexport const EMOTION_VARIABLES: readonly VariableDefinition[] = [\n { key: 'valence', name: 'Valence', description: 'How pleasant its mood is: -1 very unpleasant, 0 neutral, 1 very pleasant.', labels: [{ upTo: -0.6, label: 'miserable' }, { upTo: -0.25, label: 'unhappy' }, { upTo: 0.25, label: 'even' }, { upTo: 0.6, label: 'pleased' }, { upTo: 1, label: 'delighted' }] },\n { key: 'arousal', name: 'Arousal', description: 'How worked up it is: -1 drowsy, 0 ordinary, 1 frantic.', labels: [{ upTo: -0.6, label: 'drowsy' }, { upTo: -0.25, label: 'calm' }, { upTo: 0.25, label: 'alert' }, { upTo: 0.6, label: 'keyed up' }, { upTo: 1, label: 'frantic' }] },\n { key: 'dominance', name: 'Dominance', description: 'How much in control it feels: -1 helpless, 0 even, 1 commanding.', labels: [{ upTo: -0.6, label: 'helpless' }, { upTo: -0.25, label: 'uneasy' }, { upTo: 0.25, label: 'steady' }, { upTo: 0.6, label: 'confident' }, { upTo: 1, label: 'commanding' }] },\n].map(({ labels, ...rest }): VariableDefinition => ({\n ...rest, kind: 'number', subject: 'character', only: [], min: -1, max: 1, integer: false, options: [], default: 0, baseline: true, visibility: 'private',\n bands: labels.map(band => ({ upTo: band.upTo, label: band.label })), always: false, builtin: true,\n}))\n","import type { VariableValue } from './variable.ts'\n\nexport type TriggerId = number\n\nexport const COMPARISONS = ['eq', 'ne', 'lt', 'le', 'gt', 'ge'] as const\nexport type Comparison = (typeof COMPARISONS)[number]\n\n/**\n * When something happens, decided in code from what the story has recorded; only `judged` is a model's reading of the story, kept as a verdict that the code reads.\n * Keys name characters, places, items and variables as the world's files and the tools do. Times are local to\n * the story's zone: `YYYY-MM-DDTHH:MM`, and `HH:MM` for a time of day.\n */\nexport type TriggerCondition =\n /** True from `from` on, until `to`; or while the time of day is in `window` (past midnight when it ends before it starts), on `days` (`mon` to `sun`) when given. */\n | { type: 'time'; from?: string; to?: string; window?: { from: string; to: string }; days?: string[] }\n /** A character is in a place, at a feature of it when given. */\n | { type: 'place'; character: string; location: string; feature?: string }\n /** A variable compares to a value; `subject` is the key of the character, item or place it is about, none for a world variable. */\n | { type: 'variable'; variable: string; subject?: string; op: Comparison; value: VariableValue }\n /** An item is held by a character, or lies in a place (also inside something there). */\n | { type: 'item'; item: string; heldBy?: string; at?: string }\n /** An event with this tag was recorded. */\n | { type: 'event'; tag: string }\n /** Another trigger has fired. */\n | { type: 'fired'; trigger: string }\n /** A statement about the story that a model judges true or false after each turn, for what no record can say (\"the mayor has lost the town's trust\"); false until judged. */\n | { type: 'judged'; text: string }\n | { type: 'all'; conditions: TriggerCondition[] }\n | { type: 'any'; conditions: TriggerCondition[] }\n | { type: 'not'; condition: TriggerCondition }\n\n/** Who a cue is for, or who knows of something coming: everyone, named characters, or whoever is in a place at that moment. */\nexport type TriggerAudience = 'everyone' | { characters: string[] } | { place: string }\n\n/**\n * What is known before a trigger fires, and by whom: a scheduled event that is no secret (an exam, a ball, a deadline).\n * Without it a trigger is a secret until it fires.\n */\nexport interface TriggerAnnouncement {\n audience: TriggerAudience\n /** What is known beforehand: the public side of it, never what the effects do. */\n text: string\n /** When it becomes known, a local time; known from the start when left out. */\n from?: string\n /** When it is to happen, a local time, as told with the announcement; the time the condition waits for when it is a plain one, if left out. */\n at?: string\n}\n\n/** In a cue, the key of the character it is said to: in a `while` condition and in the words of the cue. */\nexport const SELF = '@self'\n\n/** What happens when a trigger fires. */\nexport type TriggerEffect =\n /** A checked change of the story's records, in the format of an edit (events, variable changes, exit and item changes, moves, goals, engagements). */\n | { type: 'edit'; edit: Record<string, unknown> }\n /**\n * Something the game master is told to weave into the story, until it says it did or a few turns pass. It is written when it is told, not when\n * the trigger fired: `text` may name things the story has by `{kind:key}` and so is said as the story stands then (see `TEMPLATE_KINDS`), and\n * `while` is a condition that must still hold then, or the beat is withdrawn instead.\n */\n | { type: 'beat'; text: string; while?: TriggerCondition }\n /** Something the audience notices, said to each of them the next time they act; written, and withdrawn, as a beat is, for each of them (`SELF` is the one it is said to). */\n | { type: 'cue'; audience: TriggerAudience; text: string; while?: TriggerCondition }\n\nexport const TRIGGER_STATUSES = ['dormant', 'fired', 'failed', 'expired'] as const\nexport type TriggerStatus = (typeof TRIGGER_STATUSES)[number]\n\n/** A trigger as a world's files, or the world author, write it. */\nexport interface TriggerDefinition {\n key: string\n name: string\n condition: TriggerCondition\n effects: TriggerEffect[]\n /** Whether it can fire again after it fired and its condition went false and true again. */\n repeat: boolean\n /** With `repeat`, the least story time between two firings, in seconds. */\n cooldownSeconds?: number\n /** The chance, 0 to 1, that a rising condition fires; a failed roll uses that rise up. */\n chance?: number\n /** The higher goes first when several are due at once. */\n priority: number\n /** After this local time it never fires. */\n expires?: string\n /** Known beforehand by whom, and what; without it, nobody knows until it fires. */\n announce?: TriggerAnnouncement\n}\n\nexport interface Trigger extends TriggerDefinition {\n id: TriggerId\n status: TriggerStatus\n fireCount: number\n lastFiredMs?: number\n /** What the condition was when it was last looked at, to see it rise. */\n lastResult: boolean\n /** Why it failed, when it did. */\n problem?: string\n origin: 'world' | 'story'\n createdTurn: number\n}\n\nexport const TRIGGER_NOTE_KINDS = ['beat', 'cue'] as const\nexport type TriggerNoteKind = (typeof TRIGGER_NOTE_KINDS)[number]\n\n/** What a fired trigger leaves to be told: a beat for the game master, a cue for characters. */\nexport interface TriggerNote {\n id: number\n triggerId: TriggerId\n kind: TriggerNoteKind\n text: string\n /** The characters a cue is for. */\n characterIds: number[]\n turn: number\n status: 'pending' | 'done' | 'lapsed'\n}\n\nexport interface NewTriggerNote {\n triggerId: TriggerId\n kind: TriggerNoteKind\n text: string\n characterIds?: number[]\n turn: number\n}\n\n/** At most this many triggers in a story. */\nexport const MAX_TRIGGERS = 200\n","export const VISUAL_SUBJECT_KINDS = ['character', 'location', 'item'] as const\nexport type VisualSubjectKind = typeof VISUAL_SUBJECT_KINDS[number]\n\n/** Stable, provider-neutral visual facts that every image of an entity should preserve. */\nexport interface VisualIdentityInput {\n description: string\n tags: string[]\n negativeTags: string[]\n /** A globally unique identity when the entity has one; world-local ids remain valid without it. */\n globalId?: string\n}\n\n/** A visual identity attached to one entity of a session. */\nexport interface VisualIdentity extends VisualIdentityInput {\n subjectKind: VisualSubjectKind\n subjectId: number\n /** Increases when the canonical identity changes, so an image can name what it was made from. */\n version: number\n updatedAt: string\n}\n\nexport type VisualIdentityPatch = Partial<VisualIdentityInput>\n","export type LoreId = number\n\nexport const LORE_KINDS = ['history', 'culture', 'religion', 'politics', 'geography', 'science', 'custom', 'legend', 'other'] as const\nexport type LoreKind = typeof LORE_KINDS[number]\n\nexport const LORE_SUBJECT_KINDS = ['character', 'faction', 'location', 'item', 'lore'] as const\nexport type LoreSubjectKind = typeof LORE_SUBJECT_KINDS[number]\n\nexport interface LoreSubject {\n kind: LoreSubjectKind\n id: number\n}\n\nexport interface Lore {\n id: LoreId\n sourceId?: string\n title: string\n kind: LoreKind\n summary: string\n body: string\n startsAt?: number\n endsAt?: number\n subjects: LoreSubject[]\n related: LoreId[]\n sources: string[]\n createdAt: string\n}\n\nexport type NewLore = Omit<Lore, 'id' | 'createdAt'>\nexport type LorePatch = Partial<Pick<Lore, 'title' | 'kind' | 'summary' | 'body' | 'subjects' | 'related' | 'sources'>> & { startsAt?: number | null; endsAt?: number | null }\n\nexport interface LoreSubjectDefinition {\n kind: LoreSubjectKind\n id: string\n}\n\n/** One independently addressable piece of canonical world lore. */\nexport interface LoreDefinition {\n id: string\n title: string\n kind: LoreKind\n summary: string\n body: string\n startsAt?: number\n endsAt?: number\n subjects: LoreSubjectDefinition[]\n related: string[]\n sources: string[]\n}\n","export const PLOT_STATUSES = ['dormant', 'available', 'engaged', 'cooling', 'resolved', 'abandoned'] as const\nexport type PlotStatus = (typeof PLOT_STATUSES)[number]\n\nexport const PLOT_NUDGE_MODES = ['opportunity', 'reminder', 'character', 'consequence', 'escalation', 'breathing_room'] as const\nexport type PlotNudgeMode = (typeof PLOT_NUDGE_MODES)[number]\n\nexport interface PlotDevelopment {\n id: string\n text: string\n mode: PlotNudgeMode\n prerequisites: string[]\n guidance: string\n avoid: string[]\n}\n\nexport interface PlotDefinition {\n id: string\n name: string\n premise: string\n themes: string[]\n hooks: PlotDevelopment[]\n developments: PlotDevelopment[]\n stakes: string[]\n resolutions: string[]\n participants: string[]\n start: PlotStatus\n pacing: {\n quietTurns: number\n cooldownTurns: number\n cooldownDays: number\n }\n}\n\nexport interface PlotProgress {\n plot: PlotDefinition\n status: PlotStatus\n introduced: string[]\n rejected: string[]\n lastNudgeTurn: number\n lastNudgeAt?: number\n}\n","export type Clock = () => Date\n\nexport const systemClock: Clock = () => new Date()\n","import { DatabaseSync, type StatementSync } from 'node:sqlite'\nimport type { OpenOptions, RunResult, SqlDatabase, SqlDriver, SqlValue } from './types.ts'\n\nclass NodeSqliteDatabase implements SqlDatabase {\n private readonly statements = new Map<string, StatementSync>()\n private depth = 0\n\n constructor(private readonly db: DatabaseSync) {}\n\n exec(sql: string): void {\n this.db.exec(sql)\n }\n\n run(sql: string, params: readonly SqlValue[] = []): RunResult {\n const result = this.statement(sql).run(...params)\n return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) }\n }\n\n get<Row>(sql: string, params: readonly SqlValue[] = []): Row | undefined {\n return this.statement(sql).get(...params) as Row | undefined\n }\n\n all<Row>(sql: string, params: readonly SqlValue[] = []): Row[] {\n return this.statement(sql).all(...params) as Row[]\n }\n\n transaction<T>(fn: () => T): T {\n const outermost = this.depth === 0\n const savepoint = `nested_${this.depth}`\n this.db.exec(outermost ? 'BEGIN IMMEDIATE' : `SAVEPOINT ${savepoint}`)\n this.depth++\n let result: T\n try {\n result = fn()\n // A promise would settle after the transaction has ended.\n if (result instanceof Promise) throw new TypeError('a transaction callback must be synchronous')\n } catch (error) {\n this.depth--\n this.db.exec(outermost ? 'ROLLBACK' : `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}`)\n throw error\n }\n this.depth--\n this.db.exec(outermost ? 'COMMIT' : `RELEASE ${savepoint}`)\n return result\n }\n\n close(): void {\n this.statements.clear()\n this.db.close()\n }\n\n private statement(sql: string): StatementSync {\n let statement = this.statements.get(sql)\n if (statement === undefined) {\n statement = this.db.prepare(sql)\n this.statements.set(sql, statement)\n }\n return statement\n }\n}\n\n/** The driver built on Node's bundled SQLite (`node:sqlite`); it needs no native dependency. */\nexport const nodeSqliteDriver: SqlDriver = {\n open(location: string, options: OpenOptions = {}): SqlDatabase {\n const busyTimeout = options.busyTimeoutMs ?? 5000\n if (!Number.isInteger(busyTimeout) || busyTimeout < 0) throw new RangeError('busyTimeoutMs must be a non-negative integer')\n const extensions = options.extensions ?? []\n const db = new DatabaseSync(location, { allowExtension: extensions.length > 0 })\n try {\n for (const path of extensions) db.loadExtension(path)\n db.exec('PRAGMA foreign_keys = ON')\n db.exec(`PRAGMA busy_timeout = ${busyTimeout}`)\n if (location !== ':memory:') db.exec(`PRAGMA journal_mode = ${options.journalMode === 'wal' ? 'WAL' : 'DELETE'}`)\n } catch (error) {\n db.close()\n throw error\n }\n return new NodeSqliteDatabase(db)\n },\n}\n","export class StateError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = new.target.name\n }\n}\n\n/** The requested row does not exist. */\nexport class NotFoundError extends StateError {}\n\n/** The change clashes with existing data, such as a repeated id or a stale version. */\nexport class ConflictError extends StateError {}\n\n/** A value is outside what the schema allows. */\nexport class InvalidValueError extends StateError {}\n\n/** The file is not a session database, or was written by a newer version. */\nexport class SchemaError extends StateError {}\n\n/** Stored data cannot be read back as a canonical model. */\nexport class CorruptDataError extends StateError {}\n\n/** An edit of the story's records cannot be applied; it names every problem, and nothing was written. */\nexport class InvalidEditError extends StateError {\n constructor(readonly problems: readonly string[]) {\n super(`the edit is not acceptable: ${problems.join('; ')}`)\n }\n}\n\n/** A character cannot go where it was sent; it names every reason, and nothing changed. */\nexport class InvalidMoveError extends StateError {\n constructor(readonly problems: readonly string[]) {\n super(`the move is not possible: ${problems.join('; ')}`)\n }\n}\n","import { ConflictError, CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\n\n/** Keys for case-insensitive lookup; they fold compatibility forms, which SQLite's own NOCASE does not. */\nexport function lookupKey(text: string): string {\n return text.normalize('NFKC').trim().toLowerCase()\n}\n\n/** Run a statement, turning constraint failures into the errors callers know. */\nexport function guard<T>(fn: () => T): T {\n try {\n return fn()\n } catch (error) {\n const message = error instanceof Error ? error.message : ''\n if (message.includes('UNIQUE constraint failed')) throw new ConflictError(message, { cause: error })\n if (message.includes('FOREIGN KEY constraint failed')) throw new NotFoundError('a referenced row does not exist', { cause: error })\n if (message.includes('CHECK constraint failed')) throw new InvalidValueError(message, { cause: error })\n throw error\n }\n}\n\nexport function toJson(value: unknown): string {\n return JSON.stringify(value)\n}\n\nexport function parseStringList(text: string, column: string): string[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(entry => typeof entry === 'string')) return value as string[]\n } catch {\n // reported below\n }\n throw new CorruptDataError(`${column} does not hold a list of strings`)\n}\n\nexport function parseNumberList(text: string, column: string): number[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(entry => typeof entry === 'number')) return value as number[]\n } catch {\n // reported below\n }\n throw new CorruptDataError(`${column} does not hold a list of numbers`)\n}\n","import type {\n VariableDefinitionInput, TriggerDefinition,\n Accuracy, Character, CharacterKind, CharacterStatePatch, CharacterTier, ContainerState, EngagementStatus, ExitState, IntentHorizon, IntentStatus, IntentType, KnowledgeKind, Location, MemoryKind, PerceptionMode, Slot,\n} from 'dsh-roleplay-model'\nimport type {\n CharacterRepository, CharacterStateRepository, ConsolidationRepository, EngagementRepository, EventRepository, IntentRepository, ItemRepository, LocationRepository, MemoryRepository,\n KnowledgeRepository, PlacementRepository, RelationshipRepository, RoutineRepository, SlotRepository, ThreadRepository, TriggerRepository, VariableRepository,\n FactionRepository, FactionStateRepository, FactionMembershipRepository, FactionRelationshipRepository, FactionIntentRepository,\n} from '../repositories.ts'\nimport type { ItemChangeSpec } from './items.ts'\nimport type { VariableChangeSpec } from './variables.ts'\n\n/** The name by which models and other plugins refer to a place: its id in the world, or its number when it was made up in play. */\n\nexport const locationKey = (location: Pick<Location, 'id' | 'sourceId'>): string => location.sourceId ?? String(location.id)\n\n/** The name by which models and other plugins refer to a character: its id in the world, or its number when it has none. */\nexport const characterKey = (character: Pick<Character, 'id' | 'sourceId'>): string => character.sourceId ?? String(character.id)\n\n/** What an edit of the story's records can touch. */\nexport interface RecordsTarget {\n characters: CharacterRepository\n characterStates: CharacterStateRepository\n events: EventRepository\n memories: MemoryRepository\n threads: ThreadRepository\n locations: LocationRepository\n placements: PlacementRepository\n relationships: RelationshipRepository\n factions: FactionRepository\n factionStates: FactionStateRepository\n factionMemberships: FactionMembershipRepository\n factionRelationships: FactionRelationshipRepository\n factionIntents: FactionIntentRepository\n knowledge: KnowledgeRepository\n consolidation: ConsolidationRepository\n items: ItemRepository\n slots: SlotRepository\n intents: IntentRepository\n variables: VariableRepository\n routines: RoutineRepository\n engagements: EngagementRepository\n triggers: TriggerRepository\n transaction<T>(fn: () => T): T\n}\n\nexport interface PerceivedBy {\n character: string\n mode: PerceptionMode\n /** What the character took in, when it is not exactly the event. */\n content?: string\n gist?: string\n accuracy?: Accuracy\n}\n\nexport interface StatePatch extends Pick<CharacterStatePatch, 'publicState' | 'innerState' | 'activity'> {\n character: string\n}\n\nexport interface NewEvent {\n /** The key of the place it happened in. */\n location?: string\n /** The keys of the items it is about. */\n items?: string[]\n turn: number\n round: number\n text: string\n importance: number\n tags?: string[]\n involves?: string[]\n perceivedBy?: PerceivedBy[]\n}\n\nexport interface EventEdit {\n id: number\n location?: string\n text?: string\n importance?: number\n tags?: string[]\n involves?: string[]\n /** Replaces who took the event in. */\n perceivedBy?: PerceivedBy[]\n}\n\n/** A character's version of an event, revised: it learned more, or remembers it differently. Works on sealed events too. */\nexport interface PerceptionEdit {\n id: number\n mode?: PerceptionMode\n content?: string\n gist?: string\n accuracy?: Accuracy\n}\n\n/** One more character took in an event, possibly long after: it was told, or worked it out. Works on sealed events too. */\nexport interface PerceptionAddition extends PerceivedBy {\n event: number\n}\n\nexport interface NewExit {\n /** The key of the place it leads to. */\n to: string\n description?: string\n /** Also make the way back, with `backDescription`; on by default. */\n oneWay?: boolean\n backDescription?: string\n travelSeconds?: number\n state?: ExitState\n note?: string\n}\n\n/** A place made up in play (or arriving with a plugin): a hidden passage, a room the story opens. */\nexport interface NewPlace {\n key: string\n name: string\n description?: string\n /** The key of the place it is in. */\n parent?: string\n features?: { key: string; name: string; description?: string }[]\n exits?: NewExit[]\n /** Why it was made, for whoever fits it into the world later. */\n note?: string\n}\n\n/** A character the story makes up: someone who arrives, is introduced, or turns out to be needed. Always played by an agent. */\nexport interface NewCharacterSpec {\n key: string\n name: string\n aliases?: string[]\n age?: string\n gender?: string\n pronouns?: string\n kind?: CharacterKind\n tier?: CharacterTier\n summary: string\n personality?: string\n background?: string\n appearance?: string\n speech?: { style: string; examples?: string[] }\n state?: { publicState?: string; innerState?: string; activity?: string }\n place?: { location: string; position?: string; feature?: string }\n /** Why it was made, for whoever fits it into the world later. */\n note?: string\n}\n\n/** A character's profile of another, made or changed; what is not given stays as it was. */\nexport interface RelationshipSet {\n from: string\n to: string\n label?: string\n summary?: string\n familiarity?: number\n trust?: number\n affinity?: number\n tension?: number\n}\n\nexport interface RelationshipRetraction {\n from: string\n to: string\n}\n\n/** A place, item or directed exit a character learns exists. */\nexport interface KnowledgeSet {\n character: string\n kind: KnowledgeKind\n /** The location or item key. */\n subject?: string\n /** For an exit, its directed endpoints. */\n from?: string\n to?: string\n observed?: boolean\n}\n\nexport interface FactionStateSet { faction: string; publicState?: string; innerState?: string }\nexport interface FactionMembershipSet { faction: string; character: string; role?: string; rank?: string; status?: 'active' | 'inactive' | 'former'; public?: boolean; commitment?: number; leftTurn?: number }\nexport interface FactionRelationshipSet extends Omit<RelationshipSet, 'from' | 'to'> { fromKind: 'character' | 'faction'; from: string; toKind: 'character' | 'faction'; to: string }\nexport interface NewFactionIntentSpec extends Omit<NewIntentSpec, 'character'> { faction: string }\n\nexport type KnowledgeRetraction = Omit<KnowledgeSet, 'observed'>\n\n/** A new way between two places that already exist (or are made in the same edit). */\nexport interface NewExitBetween {\n from: string\n to: string\n description?: string\n /** Also make the way back, with `backDescription`; on by default. */\n oneWay?: boolean\n backDescription?: string\n travelSeconds?: number\n state?: ExitState\n note?: string\n}\n\n/** A thing the story makes up (or that arrives with a plugin): an object that matters, handed over or found. It starts in exactly one of `at`, `heldBy`, `wornBy` or `inside`. */\nexport interface NewItemSpec {\n key: string\n name: string\n description?: string\n quantity?: number\n unique?: boolean\n quality?: string\n notable?: boolean\n hidden?: boolean\n /** The slot it is worn in. */\n wearable?: string\n container?: { state?: ContainerState; openedBy?: string[] }\n owner?: string\n at?: { location: string; position?: string; feature?: string }\n heldBy?: string\n wornBy?: string\n wornPosition?: string\n inside?: string\n insidePosition?: string\n /** Why it was made, for whoever fits it into the world later. */\n note?: string\n}\n\n/** What a character does with an item; the engine decides it, this is for plugins and tools. */\nexport interface ItemChange extends ItemChangeSpec {\n character: string\n}\n\nexport interface ItemEditSpec {\n item: string\n description?: string\n quality?: string\n quantity?: number\n notable?: boolean\n hidden?: boolean\n /** The state of a container, when it is changed by the story rather than by a character's action. */\n state?: ContainerState\n owner?: string\n /** Replaces the items that open it (a container or the way named by `exit`). */\n openedBy?: string[]\n}\n\nexport interface PlaceEdit {\n place: string\n name?: string\n description?: string\n /** Replaces the list of features. */\n features?: { key: string; name: string; description?: string }[]\n}\n\n/** A door is unlocked, a passage collapses: the way between two places changes, both ways unless told otherwise. */\nexport interface ExitChange {\n from: string\n to: string\n state?: ExitState\n description?: string\n note?: string\n travelSeconds?: number\n oneWay?: boolean\n}\n\nexport interface CharacterMove {\n character: string\n to: string\n position?: string\n feature?: string\n ignoreExits?: boolean\n}\n\nexport interface NewBelief {\n character: string\n kind: MemoryKind\n text: string\n about?: string[]\n importance: number\n}\n\nexport interface BeliefEdit {\n id: number\n text?: string\n about?: string[]\n importance?: number\n}\n\n/**\n * A change to the story's records, applied together or not at all: the unit in which the\n * record keeper, the model-facing tools and other plugins write what happened.\n */\n/** A new goal of a character, which the story gave it: a promise made, a task taken on. */\nexport interface NewIntentSpec {\n character: string\n type: IntentType\n name: string\n description?: string\n horizon: IntentHorizon\n priority: number\n urgency: number\n plan?: string[]\n constraints?: string[]\n /** A date and time, in the time zone of the story unless it carries an offset. */\n deadline?: string\n}\n\nexport interface IntentEditSpec {\n id: number\n status?: IntentStatus\n description?: string\n horizon?: IntentHorizon\n priority?: number\n urgency?: number\n plan?: string[]\n openThreads?: string[]\n deadline?: string\n}\n\n/** Something characters have committed to, at a time. */\nexport interface NewEngagementSpec {\n title: string\n /** When it is due: a date and time, in the time zone of the story unless it carries an offset. */\n at: string\n until?: string\n /** The key of the place. */\n location?: string\n participants: string[]\n note?: string\n}\n\nexport interface EngagementEditSpec {\n id: number\n status?: EngagementStatus\n title?: string\n at?: string\n until?: string\n location?: string\n participants?: string[]\n note?: string\n}\n\nexport interface RoutineWindowSpec {\n /** `mon` to `sun`; every day when left out. */\n days?: string[]\n /** `HH:MM`. */\n from: string\n to: string\n activity: string\n location?: string\n feature?: string\n position?: string\n interruptible?: boolean\n}\n\n/** Sets the recurring day of a character, replacing what it had. */\nexport interface RoutineSet {\n character: string\n windows: RoutineWindowSpec[]\n}\n\nexport interface RecordsEdit {\n /** The turn new beliefs and threads belong to. */\n turn: number\n /** The time zone the dates of the edit are written in; UTC when not given. */\n timeZone?: string\n /** Changes to what the story tracks: a feeling, a debt, a flag. */\n variableChanges?: VariableChangeSpec[]\n /** Variables the story declares, only by the agent whose work that is. */\n variables?: VariableDefinitionInput[]\n intentsAdded?: NewIntentSpec[]\n intentEdits?: IntentEditSpec[]\n engagements?: NewEngagementSpec[]\n engagementEdits?: EngagementEditSpec[]\n routines?: RoutineSet[]\n /** Things the world does when their conditions come true, only by the agent whose work that is. */\n triggers?: TriggerDefinition[]\n states?: StatePatch[]\n events?: NewEvent[]\n eventEdits?: EventEdit[]\n eventRetractions?: number[]\n perceptionEdits?: PerceptionEdit[]\n perceptionsAdded?: PerceptionAddition[]\n characters?: NewCharacterSpec[]\n items?: NewItemSpec[]\n slots?: Slot[]\n itemChanges?: ItemChange[]\n itemEdits?: ItemEditSpec[]\n places?: NewPlace[]\n exits?: NewExitBetween[]\n relationships?: RelationshipSet[]\n relationshipRetractions?: RelationshipRetraction[]\n knowledge?: KnowledgeSet[]\n knowledgeRetractions?: KnowledgeRetraction[]\n factionStates?: FactionStateSet[]\n factionMemberships?: FactionMembershipSet[]\n factionRelationships?: FactionRelationshipSet[]\n factionIntentsAdded?: NewFactionIntentSpec[]\n placeEdits?: PlaceEdit[]\n exitChanges?: ExitChange[]\n moves?: CharacterMove[]\n beliefs?: NewBelief[]\n beliefEdits?: BeliefEdit[]\n beliefRetractions?: number[]\n threadsOpened?: string[]\n threadsResolved?: number[]\n}\n\nexport interface EditResult {\n /** The ids of the events and beliefs the edit added, in order. */\n eventIds: number[]\n /** The keys of the characters and places the edit made up. */\n characterKeys?: string[]\n placeKeys?: string[]\n triggerKeys?: string[]\n itemKeys?: string[]\n /** The keys of the variables the edit declared. */\n variableKeys?: string[]\n beliefIds: number[]\n /** How many rows were added, changed or removed. */\n writes: number\n}\n","import type { CharacterId, Engagement, EngagementFilter, EngagementId, EngagementPatch, EngagementStatus, NewEngagement, RoutineWindow, StoredRoutineWindow } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { EngagementRepository, RoutineRepository } from '../repositories.ts'\nimport { guard, parseNumberList, toJson } from './support.ts'\n\n/** At most this many windows for one character, so that a day stays something a model can hold. */\nexport const MAX_ROUTINE_WINDOWS = 24\nconst MAX_TITLE = 200\n\ninterface WindowRow {\n id: number\n character_id: number\n days: string\n start_minute: number\n end_minute: number\n activity: string\n location_id: number | null\n feature_key: string | null\n position: string\n interruptible: number\n}\n\nconst toWindow = (row: WindowRow): StoredRoutineWindow => ({\n id: row.id,\n characterId: row.character_id,\n days: parseNumberList(row.days, 'routine_windows.days'),\n start: row.start_minute,\n end: row.end_minute,\n activity: row.activity,\n ...(row.location_id === null ? {} : { locationId: row.location_id }),\n ...(row.feature_key === null ? {} : { featureKey: row.feature_key }),\n ...(row.position === '' ? {} : { position: row.position }),\n interruptible: row.interruptible === 1,\n})\n\nconst isMinute = (value: number): boolean => Number.isInteger(value) && value >= 0 && value < 1440\n\nexport class SqliteRoutineRepository implements RoutineRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n list(characterId: CharacterId): StoredRoutineWindow[] {\n return this.db.all<WindowRow>('SELECT * FROM routine_windows WHERE character_id = ? ORDER BY ordinal', [characterId]).map(toWindow)\n }\n\n all(): StoredRoutineWindow[] {\n return this.db.all<WindowRow>('SELECT * FROM routine_windows ORDER BY character_id, ordinal').map(toWindow)\n }\n\n replace(characterId: CharacterId, windows: readonly RoutineWindow[]): StoredRoutineWindow[] {\n if (windows.length > MAX_ROUTINE_WINDOWS) throw new InvalidValueError(`a character has at most ${MAX_ROUTINE_WINDOWS} windows in its day`)\n windows.forEach((window, index) => {\n const at = `window ${index + 1}`\n if (!isMinute(window.start) || !isMinute(window.end)) throw new InvalidValueError(`${at}: a minute of the day is from 0 to 1439`)\n if (window.start === window.end) throw new InvalidValueError(`${at}: it starts and ends at the same minute`)\n if (window.days.some(day => !Number.isInteger(day) || day < 0 || day > 6)) throw new InvalidValueError(`${at}: a day of the week is from 0 (Sunday) to 6`)\n if (window.activity.trim() === '') throw new InvalidValueError(`${at}: say what the character is doing`)\n })\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) throw new NotFoundError(`character ${characterId} does not exist`)\n this.db.run('DELETE FROM routine_windows WHERE character_id = ?', [characterId])\n windows.forEach((window, index) => {\n this.db.run(\n 'INSERT INTO routine_windows (character_id, ordinal, days, start_minute, end_minute, activity, location_id, feature_key, position, interruptible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [characterId, index, toJson([...new Set(window.days)].sort()), window.start, window.end, window.activity.trim(), window.locationId ?? null, window.featureKey ?? null, window.position ?? '', window.interruptible ? 1 : 0],\n )\n })\n return this.list(characterId)\n }))\n }\n}\n\ninterface EngagementRow {\n id: number\n title: string\n at_ms: number\n until_ms: number | null\n location_id: number | null\n status: EngagementStatus\n note: string\n created_turn: number\n updated_turn: number\n}\n\nexport class SqliteEngagementRepository implements EngagementRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n add(engagement: NewEngagement): Engagement {\n this.check(engagement.title, engagement.at, engagement.until, engagement.participants)\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO engagements (title, at_ms, until_ms, location_id, status, note, created_turn, updated_turn) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',\n [engagement.title.trim(), engagement.at, engagement.until ?? null, engagement.locationId ?? null, 'pending', engagement.note ?? '', engagement.turn, engagement.turn],\n )\n const id = Number(lastInsertRowid)\n this.setParticipants(id, engagement.participants)\n return this.require(id)\n }))\n }\n\n get(id: EngagementId): Engagement | undefined {\n const row = this.db.get<EngagementRow>('SELECT * FROM engagements WHERE id = ?', [id])\n return row === undefined ? undefined : this.toEngagement(row)\n }\n\n list(filter: EngagementFilter = {}): Engagement[] {\n const where: string[] = []\n const params: SqlValue[] = []\n const add = (clause: string, value: SqlValue): void => { where.push(clause); params.push(value) }\n if (filter.status !== undefined) add('status = ?', filter.status)\n if (filter.participant !== undefined) add('id IN (SELECT engagement_id FROM engagement_participants WHERE character_id = ?)', filter.participant)\n if (filter.from !== undefined) add('at_ms >= ?', filter.from)\n if (filter.to !== undefined) add('at_ms < ?', filter.to)\n return this.db.all<EngagementRow>(`SELECT * FROM engagements ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`} ORDER BY at_ms, id`, params).map(row => this.toEngagement(row))\n }\n\n update(id: EngagementId, patch: EngagementPatch): Engagement {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const at = patch.at ?? current.at\n const until = patch.until ?? current.until\n const participants = patch.participants ?? current.participants\n this.check(patch.title ?? current.title, at, until, participants)\n this.db.run('UPDATE engagements SET title = ?, at_ms = ?, until_ms = ?, location_id = ?, status = ?, note = ?, updated_turn = ? WHERE id = ?', [\n (patch.title ?? current.title).trim(), at, until ?? null, patch.locationId ?? current.locationId ?? null, patch.status ?? current.status, patch.note ?? current.note, patch.turn, id,\n ])\n if (patch.participants !== undefined) this.setParticipants(id, patch.participants)\n return this.require(id)\n }))\n }\n\n remove(id: EngagementId): boolean {\n return this.db.run('DELETE FROM engagements WHERE id = ?', [id]).changes > 0\n }\n\n private check(title: string, at: number, until: number | undefined, participants: readonly CharacterId[]): void {\n if (title.trim() === '' || title.trim().length > MAX_TITLE) throw new InvalidValueError(`an engagement needs a title of at most ${MAX_TITLE} characters`)\n if (!Number.isSafeInteger(at)) throw new InvalidValueError('an engagement needs the instant it is due')\n if (until !== undefined && (!Number.isSafeInteger(until) || until < at)) throw new InvalidValueError('an engagement cannot end before it is due')\n if (participants.length === 0) throw new InvalidValueError('an engagement needs at least one character who has committed to it')\n }\n\n private setParticipants(id: EngagementId, participants: readonly CharacterId[]): void {\n this.db.run('DELETE FROM engagement_participants WHERE engagement_id = ?', [id])\n for (const characterId of new Set(participants)) this.db.run('INSERT INTO engagement_participants (engagement_id, character_id) VALUES (?, ?)', [id, characterId])\n }\n\n private toEngagement(row: EngagementRow): Engagement {\n return {\n id: row.id, title: row.title, at: row.at_ms,\n ...(row.until_ms === null ? {} : { until: row.until_ms }),\n ...(row.location_id === null ? {} : { locationId: row.location_id }),\n participants: this.db.all<{ character_id: number }>('SELECT character_id FROM engagement_participants WHERE engagement_id = ? ORDER BY character_id', [row.id]).map(entry => entry.character_id),\n status: row.status, note: row.note, createdTurn: row.created_turn, updatedTurn: row.updated_turn,\n }\n }\n\n private require(id: EngagementId): Engagement {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`engagement ${id} does not exist`)\n return found\n }\n}\n","/** Instants are UTC milliseconds; a time zone only decides how they read. */\n\nexport const SECOND = 1000\nexport const MINUTE = 60 * SECOND\nexport const HOUR = 60 * MINUTE\nexport const DAY = 24 * HOUR\n\nconst formatters = new Map<string, Intl.DateTimeFormat>()\n\nfunction formatterFor(zone: string): Intl.DateTimeFormat {\n let formatter = formatters.get(zone)\n if (formatter === undefined) {\n formatter = new Intl.DateTimeFormat('en-GB', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', weekday: 'short' })\n formatters.set(zone, formatter)\n }\n return formatter\n}\n\n/** Whether a name is a time zone this runtime knows (an IANA name such as `Europe/London`, or `UTC`). */\nexport function isTimeZone(zone: string): boolean {\n if (zone.trim() === '' || zone !== zone.trim()) return false\n try {\n formatterFor(zone)\n return true\n } catch {\n return false\n }\n}\n\n/** The time zone of this computer. */\nexport const systemTimeZone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone\n\nexport interface LocalTime {\n year: number\n /** 1 to 12. */\n month: number\n day: number\n hour: number\n minute: number\n second: number\n /** 0 for Sunday to 6 for Saturday. */\n weekday: number\n minuteOfDay: number\n}\n\nconst WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] as const\nconst MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] as const\n\n/** What the wall clock of a zone reads at an instant. */\nexport function localTime(instant: number, zone: string): LocalTime {\n const parts = Object.fromEntries(formatterFor(zone).formatToParts(new Date(instant)).map(part => [part.type, part.value]))\n const hour = Number(parts['hour'])\n const minute = Number(parts['minute'])\n return {\n year: Number(parts['year']), month: Number(parts['month']), day: Number(parts['day']), hour, minute, second: Number(parts['second']),\n weekday: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(String(parts['weekday'])),\n minuteOfDay: hour * 60 + minute,\n }\n}\n\nfunction utcOf(fields: { year: number; month: number; day: number; hour?: number; minute?: number; second?: number }): number {\n const date = new Date(0)\n date.setUTCFullYear(fields.year, fields.month - 1, fields.day)\n date.setUTCHours(fields.hour ?? 0, fields.minute ?? 0, fields.second ?? 0, 0)\n return date.getTime()\n}\n\n/** The instant at which the wall clock of a zone reads this; a time that does not exist (the clocks jumped over it) is moved on by the length of the jump. */\nexport function zonedInstant(fields: { year: number; month: number; day: number; hour?: number; minute?: number; second?: number }, zone: string): number {\n const asUtc = utcOf(fields)\n const offsetAt = (instant: number): number => {\n const local = localTime(instant, zone)\n return utcOf(local) - Math.floor(instant / SECOND) * SECOND\n }\n const first = asUtc - offsetAt(asUtc)\n const second = asUtc - offsetAt(first)\n return second\n}\n\nconst LOCAL = /^(-?\\d{1,6})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?$/\n\n/**\n * An instant from text: an ISO 8601 date and time with an offset or `Z` is taken as written; without one\n * it is the wall clock of `zone`. A date alone is that day at midnight.\n * @throws {RangeError} when it is not a date and time.\n */\nexport function parseInstant(text: string, zone: string): number {\n const trimmed = text.trim()\n const local = LOCAL.exec(trimmed)\n if (local !== null) {\n const [, year, month, day, hour, minute, second] = local\n const fields = { year: Number(year), month: Number(month), day: Number(day), hour: Number(hour ?? 0), minute: Number(minute ?? 0), second: Number(second ?? 0) }\n const check = new Date(utcOf(fields))\n if (check.getUTCMonth() !== fields.month - 1 || check.getUTCDate() !== fields.day || fields.hour > 23 || fields.minute > 59 || fields.second > 59) throw new RangeError(`\"${text}\" is not a date and time`)\n return zonedInstant(fields, zone)\n }\n if (/^-?\\d{4,6}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})$/.test(trimmed)) {\n const instant = Date.parse(trimmed.replace(' ', 'T'))\n if (!Number.isNaN(instant)) return instant\n }\n throw new RangeError(`\"${text}\" is not a date and time: write it as 1912-10-04T19:30 (or with an offset, 1912-10-04T19:30+01:00)`)\n}\n\n/** `Tuesday 4 October 1912, 21:40`. */\nexport function describeInstant(instant: number, zone: string): string {\n const local = localTime(instant, zone)\n return `${WEEKDAYS[local.weekday]} ${local.day} ${MONTHS[local.month - 1]} ${local.year}, ${pad(local.hour)}:${pad(local.minute)}`\n}\n\n/** `1912-10-04T21:40:00` as the wall clock of a zone reads, the form a file or a person can write back. */\nexport function localIso(instant: number, zone: string): string {\n const local = localTime(instant, zone)\n return `${String(local.year).padStart(4, '0')}-${pad(local.month)}-${pad(local.day)}T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}`\n}\n\nconst pad = (value: number): string => String(value).padStart(2, '0')\n\nexport const DAY_PARTS = ['night', 'morning', 'afternoon', 'evening'] as const\nexport type DayPart = (typeof DAY_PARTS)[number]\n\n/** Night is from 22:00 to 05:00, morning to 12:00, afternoon to 17:00, evening after. */\nexport function dayPart(minuteOfDay: number): DayPart {\n const hour = Math.floor(minuteOfDay / 60)\n return hour < 5 || hour >= 22 ? 'night' : hour < 12 ? 'morning' : hour < 17 ? 'afternoon' : 'evening'\n}\n\n/** In words and rounded to what matters: `45 seconds`, `3 hours 12 minutes`, `2 days 3 hours`. */\nexport function describeDuration(milliseconds: number): string {\n const total = Math.max(0, Math.round(milliseconds / SECOND))\n if (total < 60) return `${total} second${total === 1 ? '' : 's'}`\n const units: [string, number][] = [['day', 86_400], ['hour', 3600], ['minute', 60]]\n const parts: string[] = []\n let left = total\n for (const [name, size] of units) {\n const count = Math.floor(left / size)\n left -= count * size\n if (count > 0) parts.push(`${count} ${name}${count === 1 ? '' : 's'}`)\n if (parts.length === 2) break\n }\n return parts.join(' ')\n}\n\n/** The minute of the day for `HH:MM` (24-hour), or nothing when it is not one. */\nexport function parseTimeOfDay(text: string): number | undefined {\n const match = /^(\\d{1,2}):(\\d{2})$/.exec(text.trim())\n if (match === null) return undefined\n const hour = Number(match[1])\n const minute = Number(match[2])\n return hour < 24 && minute < 60 ? hour * 60 + minute : undefined\n}\n\n/**\n * The instant the wall clock of a zone next reads `HH:MM` after `now`; with `daysLater`, that time on the day\n * that many days after today (it must still be after `now`).\n * @throws {RangeError} when the time is not `HH:MM` or is not after `now`.\n */\nexport function nextTimeOfDay(now: number, zone: string, time: string, daysLater?: number): number {\n const minuteOfDay = parseTimeOfDay(time)\n if (minuteOfDay === undefined) throw new RangeError(`\"${time}\" is not a time of day: write it as 07:30 (24-hour)`)\n const today = localTime(now, zone)\n const at = (extraDays: number): number => {\n const day = new Date(utcOf({ year: today.year, month: today.month, day: today.day }) + extraDays * DAY)\n return zonedInstant({ year: day.getUTCFullYear(), month: day.getUTCMonth() + 1, day: day.getUTCDate(), hour: Math.floor(minuteOfDay / 60), minute: minuteOfDay % 60 }, zone)\n }\n if (daysLater !== undefined) {\n const target = at(daysLater)\n if (target <= now) throw new RangeError(`${time} ${daysLater === 0 ? 'today' : `${daysLater} day${daysLater === 1 ? '' : 's'} later`} is not after now (${describeInstant(now, zone)})`)\n return target\n }\n const sameDay = at(0)\n return sameDay > now ? sameDay : at(1)\n}\n\n/** Whether a minute of the day is inside a window; `start` to `end` is half open and wraps past midnight, and equal ends make an empty window. */\nexport function inWindow(minuteOfDay: number, start: number, end: number): boolean {\n for (const value of [minuteOfDay, start, end]) if (!Number.isInteger(value) || value < 0 || value >= 1440) throw new RangeError('a minute of the day is from 0 to 1439')\n return start <= end ? minuteOfDay >= start && minuteOfDay < end : minuteOfDay >= start || minuteOfDay < end\n}\n\n/**\n * What to catch up on after being away: only the newest `maxMs` of the gap, in at most `maxSteps` equal\n * steps, so that a long absence costs a bounded amount of work.\n */\nexport function catchUpPlan(cursor: number, now: number, limits: { maxMs?: number; maxSteps?: number } = {}): { from: number; to: number; skipped: number; steps: { from: number; to: number }[] } {\n const maxMs = limits.maxMs ?? 6 * HOUR\n const maxSteps = limits.maxSteps ?? 360\n if (!Number.isInteger(maxMs) || maxMs <= 0 || !Number.isInteger(maxSteps) || maxSteps <= 0) throw new RangeError('the limits of a catch-up are positive whole numbers')\n const to = Math.max(cursor, now)\n const from = Math.max(cursor, to - maxMs)\n const span = to - from\n const count = Math.min(maxSteps, Math.ceil(span / MINUTE))\n return { from, to, skipped: from - cursor, steps: Array.from({ length: count }, (_, index) => ({ from: from + Math.floor(span * index / count), to: from + Math.floor(span * (index + 1) / count) })) }\n}\n\n/** `21:40`: the clock of a zone at an instant. */\nexport function clockTime(instant: number, zone: string): string {\n const local = localTime(instant, zone)\n return `${pad(local.hour)}:${pad(local.minute)}`\n}\n\n/** The local calendar day `days` after the one the instant falls on, as year, month and day. */\nexport function addLocalDays(instant: number, zone: string, days: number): { year: number; month: number; day: number; weekday: number } {\n const today = localTime(instant, zone)\n const moved = new Date(utcOf({ year: today.year, month: today.month, day: today.day }) + days * DAY)\n return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate(), weekday: moved.getUTCDay() }\n}\n\n/** `07:30` for a minute of the day. */\nexport const minuteText = (minute: number): string => `${pad(Math.floor(minute / 60))}:${pad(minute % 60)}`\n","import { ENGAGEMENT_STATUSES, INTENT_HORIZONS, INTENT_STATUSES, INTENT_TYPES, WEEKDAY_NAMES, type CharacterId, type Intent, type IntentPatch, type Location, type RoutineWindow } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport { MAX_ROUTINE_WINDOWS } from '../sqlite/agenda-repositories.ts'\nimport type { RecordsEdit, RecordsTarget } from './edit-types.ts'\nimport { isTimeZone, parseInstant, parseTimeOfDay } from './time.ts'\n\nconst MAX_PLAN_STEPS = 8\nconst MAX_LIST_ENTRY = 240\nconst present = (value: string | undefined): boolean => value !== undefined && value.trim() !== ''\nconst list = <T>(value: readonly T[] | undefined): readonly T[] => value ?? []\n\n/** What the agenda part of an edit comes to, once every part of it is known to be acceptable. */\nexport interface PreparedAgenda {\n intents: { character: CharacterId; intent: Intent }[]\n intentEdits: { id: number; patch: IntentPatch }[]\n engagements: { title: string; at: number; until?: number; location?: string; participants: CharacterId[]; note?: string }[]\n engagementEdits: { id: number; patch: { status?: (typeof ENGAGEMENT_STATUSES)[number]; title?: string; at?: number; until?: number; location?: string; participants?: CharacterId[]; note?: string } }[]\n routines: { character: CharacterId; windows: (Omit<RoutineWindow, 'locationId'> & { location?: string })[] }[]\n}\n\ninterface Context {\n idOf: (key: string, where: string) => CharacterId | undefined\n placeKnown: (key: string, where: string) => void\n /** The existing places by key, to check the features of a place. */\n places: ReadonlyMap<string, Location>\n problems: string[]\n}\n\n/** Checks the goals, engagements and routines of an edit, and says what they would write. Problems are added to the context's. */\nexport function prepareAgenda(target: RecordsTarget, edit: RecordsEdit, context: Context): PreparedAgenda {\n const { idOf, placeKnown, problems } = context\n const zone = edit.timeZone ?? 'UTC'\n if (!isTimeZone(zone)) problems.push(`time_zone: \"${zone}\" is not a time zone`)\n const instant = (text: string | undefined, where: string): number | undefined => {\n if (text === undefined) return undefined\n try {\n return parseInstant(text, isTimeZone(zone) ? zone : 'UTC')\n } catch (error) {\n problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`)\n return undefined\n }\n }\n const unit = (value: number | undefined, where: string): void => {\n if (value !== undefined && (!Number.isFinite(value) || value < 0 || value > 1)) problems.push(`${where} must be a number from 0 to 1`)\n }\n const steps = (given: readonly string[] | undefined, where: string): string[] | undefined => {\n if (given === undefined) return undefined\n if (given.length > MAX_PLAN_STEPS) problems.push(`${where}: at most ${MAX_PLAN_STEPS} entries`)\n if (given.some(step => !present(step) || step.length > MAX_LIST_ENTRY)) problems.push(`${where}: each entry is a sentence of at most ${MAX_LIST_ENTRY} characters`)\n return given.map(step => step.trim())\n }\n\n const intents = list(edit.intentsAdded).flatMap((spec, index) => {\n const where = `intents_added[${index}]`\n const character = idOf(spec.character, where)\n if (!INTENT_TYPES.includes(spec.type)) problems.push(`${where}: unknown type \"${String(spec.type)}\" (${INTENT_TYPES.join(', ')})`)\n if (!INTENT_HORIZONS.includes(spec.horizon)) problems.push(`${where}: unknown horizon \"${String(spec.horizon)}\" (${INTENT_HORIZONS.join(', ')})`)\n if (!present(spec.name) || spec.name.length > 120) problems.push(`${where}: give the goal a name of at most 120 characters`)\n unit(spec.priority, `${where}.priority`)\n unit(spec.urgency, `${where}.urgency`)\n const plan = steps(spec.plan, `${where}.plan`)\n const constraints = steps(spec.constraints, `${where}.constraints`)\n const deadline = spec.deadline === undefined ? undefined : instant(spec.deadline, `${where}.deadline`)\n if (character === undefined) return []\n return [{ character, intent: {\n type: spec.type, name: spec.name.trim(), description: spec.description?.trim() ?? '', status: 'active' as const, horizon: spec.horizon, priority: spec.priority, urgency: spec.urgency,\n plan: plan ?? [], openThreads: [], constraints: constraints ?? [], ...(deadline === undefined ? {} : { deadline: new Date(deadline).toISOString() }),\n } }]\n })\n\n const intentEdits = list(edit.intentEdits).map((change, index) => {\n const where = `intent_edits[${index}]`\n if (target.intents.get(change.id) === undefined) problems.push(`${where}: there is no goal ${change.id} (read_records shows the ids)`)\n if (change.status !== undefined && !INTENT_STATUSES.includes(change.status)) problems.push(`${where}: unknown status \"${String(change.status)}\" (${INTENT_STATUSES.join(', ')})`)\n if (change.horizon !== undefined && !INTENT_HORIZONS.includes(change.horizon)) problems.push(`${where}: unknown horizon \"${String(change.horizon)}\"`)\n unit(change.priority, `${where}.priority`)\n unit(change.urgency, `${where}.urgency`)\n const plan = steps(change.plan, `${where}.plan`)\n const openThreads = steps(change.openThreads, `${where}.open_threads`)\n const deadline = change.deadline === undefined ? undefined : instant(change.deadline, `${where}.deadline`)\n const patch: IntentPatch = {\n ...(change.status === undefined ? {} : { status: change.status }), ...(change.horizon === undefined ? {} : { horizon: change.horizon }),\n ...(change.description === undefined ? {} : { description: change.description.trim() }),\n ...(change.priority === undefined ? {} : { priority: change.priority }), ...(change.urgency === undefined ? {} : { urgency: change.urgency }),\n ...(plan === undefined ? {} : { plan }), ...(openThreads === undefined ? {} : { openThreads }),\n ...(deadline === undefined ? {} : { deadline: new Date(deadline).toISOString() }),\n }\n if (Object.keys(patch).length === 0) problems.push(`${where}: nothing to change`)\n return { id: change.id, patch }\n })\n\n const engagements = list(edit.engagements).flatMap((spec, index) => {\n const where = `engagements[${index}]`\n if (!present(spec.title) || spec.title.length > 200) problems.push(`${where}: give it a title of at most 200 characters`)\n const at = instant(spec.at, `${where}.at`)\n const until = spec.until === undefined ? undefined : instant(spec.until, `${where}.until`)\n if (at !== undefined && until !== undefined && until < at) problems.push(`${where}: it cannot end before it is due`)\n if (spec.location !== undefined) placeKnown(spec.location, `${where}.location`)\n const participants = list(spec.participants).flatMap(key => idOf(key, `${where}.participants`) ?? [])\n if (list(spec.participants).length === 0) problems.push(`${where}: say who has committed to it (participants)`)\n return at === undefined ? [] : [{ title: spec.title.trim(), at, ...(until === undefined ? {} : { until }), ...(spec.location === undefined ? {} : { location: spec.location }), participants, ...(spec.note === undefined ? {} : { note: spec.note.trim() }) }]\n })\n\n const engagementEdits = list(edit.engagementEdits).map((change, index) => {\n const where = `engagement_edits[${index}]`\n const current = target.engagements.get(change.id)\n if (current === undefined) problems.push(`${where}: there is no engagement ${change.id} (read_records shows the ids)`)\n if (change.status !== undefined && !ENGAGEMENT_STATUSES.includes(change.status)) problems.push(`${where}: unknown status \"${String(change.status)}\" (${ENGAGEMENT_STATUSES.join(', ')})`)\n if (change.title !== undefined && !present(change.title)) problems.push(`${where}: the title cannot be empty`)\n const at = change.at === undefined ? undefined : instant(change.at, `${where}.at`)\n const until = change.until === undefined ? undefined : instant(change.until, `${where}.until`)\n if ((at ?? current?.at) !== undefined && until !== undefined && until < (at ?? current!.at)) problems.push(`${where}: it cannot end before it is due`)\n if (change.location !== undefined) placeKnown(change.location, `${where}.location`)\n const participants = change.participants === undefined ? undefined : change.participants.flatMap(key => idOf(key, `${where}.participants`) ?? [])\n if (change.participants !== undefined && change.participants.length === 0) problems.push(`${where}: it needs at least one participant`)\n const patch = {\n ...(change.status === undefined ? {} : { status: change.status }), ...(change.title === undefined ? {} : { title: change.title.trim() }),\n ...(at === undefined ? {} : { at }), ...(until === undefined ? {} : { until }), ...(change.location === undefined ? {} : { location: change.location }),\n ...(participants === undefined ? {} : { participants }), ...(change.note === undefined ? {} : { note: change.note.trim() }),\n }\n if (Object.keys(patch).length === 0) problems.push(`${where}: nothing to change`)\n return { id: change.id, patch }\n })\n\n const routines = list(edit.routines).flatMap((set, index) => {\n const where = `routines[${index}]`\n const character = idOf(set.character, where)\n if (list(set.windows).length > MAX_ROUTINE_WINDOWS) problems.push(`${where}: at most ${MAX_ROUTINE_WINDOWS} windows in a day`)\n const windows = list(set.windows).flatMap((window, at) => {\n const here = `${where}.windows[${at}]`\n const start = parseTimeOfDay(window.from)\n const end = parseTimeOfDay(window.to)\n if (start === undefined) problems.push(`${here}.from: \"${window.from}\" is not a time of day (HH:MM)`)\n if (end === undefined) problems.push(`${here}.to: \"${window.to}\" is not a time of day (HH:MM)`)\n if (start !== undefined && start === end) problems.push(`${here}: it starts and ends at the same time`)\n if (!present(window.activity)) problems.push(`${here}: say what the character is doing`)\n const days = list(window.days).flatMap((day) => {\n const found = WEEKDAY_NAMES.indexOf(day as (typeof WEEKDAY_NAMES)[number])\n if (found < 0) problems.push(`${here}.days: \"${day}\" is not a day (${WEEKDAY_NAMES.join(', ')})`)\n return found < 0 ? [] : [found]\n })\n if (window.location !== undefined) {\n placeKnown(window.location, `${here}.location`)\n const place = context.places.get(window.location)\n if (window.feature !== undefined && place !== undefined && !place.features.some(feature => feature.key === window.feature)) problems.push(`${here}: ${place.name} has no feature \"${window.feature}\"`)\n } else if (window.feature !== undefined) problems.push(`${here}: a feature needs a location`)\n if (start === undefined || end === undefined) return []\n return [{\n days, start, end, activity: window.activity.trim(), interruptible: window.interruptible ?? true,\n ...(window.location === undefined ? {} : { location: window.location }), ...(window.feature === undefined ? {} : { featureKey: window.feature }),\n ...(window.position === undefined || window.position.trim() === '' ? {} : { position: window.position.trim() }),\n }]\n })\n return character === undefined ? [] : [{ character, windows }]\n })\n\n return { intents, intentEdits, engagements, engagementEdits, routines }\n}\n\n/** Writes what {@link prepareAgenda} found acceptable; returns how many rows were written. */\nexport function writeAgenda(target: RecordsTarget, prepared: PreparedAgenda, turn: number, placeId: (key: string) => number): number {\n let writes = 0\n for (const { character, intent } of prepared.intents) { target.intents.add(character, intent); writes += 1 }\n for (const { id, patch } of prepared.intentEdits) { target.intents.update(id, patch); writes += 1 }\n for (const spec of prepared.engagements) {\n target.engagements.add({ title: spec.title, at: spec.at, ...(spec.until === undefined ? {} : { until: spec.until }), ...(spec.location === undefined ? {} : { locationId: placeId(spec.location) }), participants: spec.participants, ...(spec.note === undefined ? {} : { note: spec.note }), turn })\n writes += 1\n }\n for (const { id, patch } of prepared.engagementEdits) {\n const { location, ...rest } = patch\n try {\n target.engagements.update(id, { ...rest, ...(location === undefined ? {} : { locationId: placeId(location) }), turn })\n } catch (error) {\n throw error instanceof Error ? new InvalidEditError([`engagement_edits: ${error.message}`]) : error\n }\n writes += 1\n }\n for (const set of prepared.routines) {\n target.routines.replace(set.character, set.windows.map(({ location, ...window }) => ({ ...window, ...(location === undefined ? {} : { locationId: placeId(location) }) })))\n writes += 1\n }\n return writes\n}\n","import type { CharacterId, ExitState, Holder, Item, ItemId, LocationId } from 'dsh-roleplay-model'\nimport { InvalidMoveError } from '../errors.ts'\nimport type { CharacterRepository, ItemRepository, LocationRepository, PlacementRepository } from '../repositories.ts'\nimport { characterKey, locationKey } from './edit-types.ts'\n\n/** The name by which models and tools refer to an item: its id in the world, or its number when it was made up in play. */\nexport const itemKey = (item: Pick<Item, 'id' | 'sourceId'>): string => item.sourceId ?? String(item.id)\n\nexport const ITEM_ACTIONS = ['take', 'drop', 'give', 'put', 'wear', 'remove', 'open', 'close', 'lock', 'unlock', 'reveal'] as const\nexport type ItemAction = (typeof ITEM_ACTIONS)[number]\n\n/** What a character does with an item, by keys. */\nexport interface ItemChangeSpec {\n item: string\n action: ItemAction\n /** For give: the character it goes to. For put: the container it goes into. */\n to?: string\n /** For wear: the slot, when it has to be named. */\n slot?: string\n /** How many, of something that comes in numbers; all of it when left out. */\n quantity?: number\n /** For drop and put: where in the place or container. */\n position?: string\n /** For drop: the feature of the place it is left at. */\n feature?: string\n /** For lock and unlock: the item used. */\n with?: string\n /** For lock and unlock of a way instead of an item: the key of the place the way leads to. */\n exit?: string\n /** For open, lock and unlock: the story breaks it open or shut instead (picked, smashed). */\n forced?: boolean\n}\n\nexport interface ItemContext {\n items: ItemRepository\n locations: Pick<LocationRepository, 'get' | 'getExit' | 'list' | 'updateExit'>\n placements: Pick<PlacementRepository, 'get'>\n characters: Pick<CharacterRepository, 'get' | 'list'>\n}\n\n/** What changes if the action is done. */\nexport type ItemPlan =\n | { action: 'move'; spec: ItemChangeSpec; item: Item; quantity: number; holder: Holder; summary: string }\n | { action: 'container'; spec: ItemChangeSpec; item: Item; state: 'open' | 'closed' | 'locked'; summary: string }\n | { action: 'exit'; spec: ItemChangeSpec; from: LocationId; to: LocationId; state: ExitState; summary: string }\n | { action: 'reveal'; spec: ItemChangeSpec; item: Item; summary: string }\n\n/** What was done, for the record of the round. */\nexport interface ItemEffect {\n item: { key: string; name: string }\n action: ItemAction\n /** In words: \"now carried by Bob\", \"now in the chest\". */\n summary: string\n}\n\ntype Reach = { kind: 'held' } | { kind: 'here' } | { kind: 'other'; by: string } | { kind: 'blocked'; why: string } | { kind: 'elsewhere' }\n\n/** How a character can get at an item: carrying it, with it in the place it is in, or not at all and why. */\nfunction reach(ctx: ItemContext, actor: CharacterId, item: Item, options: { allowHidden?: boolean; selfClosed?: boolean } = {}): Reach {\n const place = ctx.placements.get('character', actor)?.locationId\n if (item.hidden && options.allowHidden !== true) return { kind: 'blocked', why: `${item.name} cannot be seen` }\n let current: Item = item\n for (let hop = 0; hop < 32; hop++) {\n const holding = ctx.items.holding(current.id)\n if (holding === undefined) return { kind: 'elsewhere' }\n const { holder } = holding\n if (holder.kind === 'item') {\n const container = ctx.items.get(holder.itemId)\n if (container === undefined) return { kind: 'elsewhere' }\n if (container.hidden && options.allowHidden !== true) return { kind: 'blocked', why: `${item.name} cannot be seen` }\n if (container.container?.state !== 'open') return { kind: 'blocked', why: `${item.name} is inside ${container.name}, which is ${container.container?.state ?? 'closed'}` }\n current = container\n continue\n }\n if (holder.kind === 'character') {\n if (holder.characterId === actor) return { kind: 'held' }\n return { kind: 'other', by: ctx.characters.get(holder.characterId)?.name ?? String(holder.characterId) }\n }\n return holder.locationId === place ? { kind: 'here' } : { kind: 'elsewhere' }\n }\n return { kind: 'elsewhere' }\n}\n\nconst resolveItem = (ctx: ItemContext, key: string): Item | undefined => ctx.items.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? ctx.items.get(Number(key)) : undefined)\nconst resolveCharacter = (ctx: ItemContext, key: string) => ctx.characters.list().find(character => characterKey(character) === key)\nconst resolvePlace = (ctx: ItemContext, key: string) => ctx.locations.list().find(place => locationKey(place) === key)\n\n/**\n * Whether a character can do what the spec says with an item right now, and what it would come to. The\n * rules are the ones the story would expect, decided in code: it can only act on what it can get at (carried,\n * or here and in plain sight, in open containers only), it cannot take what someone else holds, a lock needs\n * the key it fits, a slot holds only so many.\n * @returns the plan, or every reason it cannot be done.\n */\nexport function planItemChange(ctx: ItemContext, actorId: CharacterId, spec: ItemChangeSpec): { ok: true; plan: ItemPlan } | { ok: false; problems: string[] } {\n const fail = (...problems: string[]): { ok: false; problems: string[] } => ({ ok: false, problems })\n const actor = ctx.characters.get(actorId)\n if (actor === undefined) return fail(`there is no character ${actorId}`)\n if (!ITEM_ACTIONS.includes(spec.action)) return fail(`unknown action \"${String(spec.action)}\" (the actions are: ${ITEM_ACTIONS.join(', ')})`)\n const place = ctx.placements.get('character', actorId)?.locationId\n\n if ((spec.action === 'lock' || spec.action === 'unlock' || spec.action === 'open') && spec.exit !== undefined) {\n if (spec.action === 'open') return fail('a way is open or locked, not opened: use unlock for a locked way')\n const to = resolvePlace(ctx, spec.exit)\n if (to === undefined) return fail(`there is no place \"${spec.exit}\"`)\n if (place === undefined) return fail(`${actor.name} is not in any place`)\n const exit = ctx.locations.getExit(place, to.id)\n if (exit === undefined) return fail(`there is no way from here to ${to.name}`)\n if (exit.state === 'blocked') return fail(`the way to ${to.name} is blocked, not locked: clearing it is a matter of the story, not a key`)\n const wanted = spec.action === 'lock' ? 'locked' : 'open'\n if (exit.state === wanted) return fail(`the way to ${to.name} is already ${wanted}`)\n const keyProblem = keyFor(ctx, actorId, spec, ctx.items.openers({ kind: 'exit', id: exit.id }), `the way to ${to.name}`)\n return keyProblem === undefined ? { ok: true, plan: { action: 'exit', spec, from: place, to: to.id, state: wanted, summary: `the way to ${to.name} is now ${wanted}` } } : fail(keyProblem)\n }\n\n const item = resolveItem(ctx, spec.item)\n if (item === undefined) return fail(`there is no item \"${spec.item}\" (list_items shows the keys)`)\n const quantity = spec.quantity ?? item.quantity\n const countProblems = (): string[] => {\n if (!Number.isInteger(quantity) || quantity < 1) return ['the quantity must be a whole number from 1']\n if (quantity > item.quantity) return [`there ${item.quantity === 1 ? 'is only 1' : `are only ${item.quantity}`} ${item.name}, not ${quantity}`]\n if (quantity < item.quantity && item.unique) return [`${item.name} is one thing and cannot be split`]\n return []\n }\n const reachable = reach(ctx, actorId, item, { allowHidden: spec.action === 'reveal' })\n const blocked = (): string[] => {\n if (reachable.kind === 'blocked') return [reachable.why]\n if (reachable.kind === 'elsewhere') return [`${item.name} is not here, and ${actor.name} does not have it`]\n return []\n }\n const moving = (holder: Holder, summary: string): { ok: true; plan: ItemPlan } => ({ ok: true, plan: { action: 'move', spec, item, quantity, holder, summary } })\n\n switch (spec.action) {\n case 'take': {\n const problems = [...blocked(), ...countProblems()]\n const direct = ctx.items.holding(item.id)?.holder\n if (reachable.kind === 'held' && direct?.kind === 'character') problems.push(`${actor.name} already has ${item.name}`)\n if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}, who has to give it`)\n return problems.length > 0 ? fail(...problems) : moving({ kind: 'character', characterId: actorId, mode: 'held' }, `now carried by ${actor.name}`)\n }\n case 'drop': {\n const problems = [...blocked(), ...countProblems()]\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind === 'character' && holding.holder.mode === 'worn') problems.push(`${item.name} is worn: remove it first`)\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n if (place === undefined) problems.push(`${actor.name} is not in any place, so there is nowhere to leave it`)\n if (problems.length > 0 || place === undefined) return fail(...problems)\n const where = ctx.locations.get(place)\n if (spec.feature !== undefined && !where?.features.some(feature => feature.key === spec.feature)) return fail(`${where?.name ?? 'this place'} has no feature \"${spec.feature}\"`)\n return moving({ kind: 'location', locationId: place, ...(spec.position === undefined ? {} : { position: spec.position }), ...(spec.feature === undefined ? {} : { featureKey: spec.feature }) }, `now left in ${where?.name ?? 'the place'}`)\n }\n case 'give': {\n const problems = [...blocked(), ...countProblems()]\n const to = spec.to === undefined ? undefined : resolveCharacter(ctx, spec.to)\n if (spec.to === undefined) problems.push('say who it is given to')\n else if (to === undefined) problems.push(`there is no character \"${spec.to}\"`)\n else if (to.id === actorId) problems.push(`${actor.name} cannot give something to itself`)\n else if (place === undefined || ctx.placements.get('character', to.id)?.locationId !== place) problems.push(`${to.name} is not here`)\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind === 'character' && holding.holder.mode === 'worn') problems.push(`${item.name} is worn: remove it first`)\n return problems.length > 0 || to === undefined ? fail(...problems) : moving({ kind: 'character', characterId: to.id, mode: 'held' }, `now carried by ${to.name}`)\n }\n case 'put': {\n const problems = [...blocked(), ...countProblems()]\n const container = spec.to === undefined ? undefined : resolveItem(ctx, spec.to)\n if (spec.to === undefined) problems.push('say which container it goes into')\n else if (container === undefined) problems.push(`there is no item \"${spec.to}\"`)\n else if (container.container === undefined) problems.push(`${container.name} cannot hold things`)\n else if (container.id === item.id || ctx.items.ancestors(container.id).includes(item.id)) problems.push(`${item.name} cannot be put inside itself`)\n else {\n const reachContainer = reach(ctx, actorId, container)\n if (reachContainer.kind === 'blocked') problems.push(reachContainer.why)\n else if (reachContainer.kind === 'elsewhere' || reachContainer.kind === 'other') problems.push(`${container.name} is not within reach`)\n else if (container.container?.state !== 'open') problems.push(`${container.name} is ${container.container?.state}: open it first`)\n }\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n return problems.length > 0 || container === undefined ? fail(...problems) : moving({ kind: 'item', itemId: container.id, ...(spec.position === undefined ? {} : { position: spec.position }) }, `now in ${container.name}`)\n }\n case 'wear': {\n const problems = [...blocked()]\n if (item.wearableSlot === undefined) problems.push(`${item.name} cannot be worn`)\n else if (spec.slot !== undefined && spec.slot !== item.wearableSlot) problems.push(`${item.name} is worn on the ${item.wearableSlot}, not the ${spec.slot}`)\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind === 'character' && holding.holder.mode === 'worn') problems.push(`${item.name} is already worn`)\n if (problems.length > 0 || item.wearableSlot === undefined) return fail(...problems)\n const slot = item.wearableSlot\n return moving({ kind: 'character', characterId: actorId, mode: 'worn', slot, ...(spec.position === undefined ? {} : { position: spec.position }) }, `now worn by ${actor.name} on the ${slot}`)\n }\n case 'remove': {\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind !== 'character' || holding.holder.characterId !== actorId || holding.holder.mode !== 'worn') return fail(`${actor.name} is not wearing ${item.name}`)\n return moving({ kind: 'character', characterId: actorId, mode: 'held' }, `now carried by ${actor.name}`)\n }\n case 'open':\n case 'close': {\n const problems = [...blocked()]\n if (item.container === undefined) problems.push(`${item.name} cannot be opened or closed`)\n else if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}`)\n const state = item.container?.state\n if (spec.action === 'open') {\n if (state === 'open') problems.push(`${item.name} is already open`)\n if (state === 'locked' && spec.forced !== true) {\n const keyProblem = keyFor(ctx, actorId, spec, ctx.items.openers({ kind: 'item', id: item.id }), item.name)\n problems.push(keyProblem === undefined ? `${item.name} is locked: unlock it first` : `${item.name} is locked: ${keyProblem}`)\n }\n } else if (state !== 'open') problems.push(`${item.name} is already ${state}`)\n return problems.length > 0 ? fail(...problems) : { ok: true, plan: { action: 'container', spec, item, state: spec.action === 'open' ? 'open' : 'closed', summary: `${item.name} is now ${spec.action === 'open' ? 'open' : 'closed'}` } }\n }\n case 'lock':\n case 'unlock': {\n const problems = [...blocked()]\n const state = item.container?.state\n if (item.container === undefined) problems.push(`${item.name} has no lock`)\n else if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}`)\n if (spec.action === 'lock') {\n if (state === 'locked') problems.push(`${item.name} is already locked`)\n if (state === 'open') problems.push(`${item.name} is open: close it first`)\n } else if (state !== 'locked') problems.push(`${item.name} is not locked`)\n if (problems.length === 0) {\n const keyProblem = spec.forced === true && spec.action === 'unlock' ? undefined : keyFor(ctx, actorId, spec, ctx.items.openers({ kind: 'item', id: item.id }), item.name)\n if (keyProblem !== undefined) problems.push(keyProblem)\n }\n return problems.length > 0 ? fail(...problems) : { ok: true, plan: { action: 'container', spec, item, state: spec.action === 'lock' ? 'locked' : 'closed', summary: `${item.name} is now ${spec.action === 'lock' ? 'locked' : 'unlocked'}` } }\n }\n case 'reveal': {\n if (!item.hidden) return fail(`${item.name} is not hidden`)\n const problems = blocked()\n if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}`)\n return problems.length > 0 ? fail(...problems) : { ok: true, plan: { action: 'reveal', spec, item, summary: `${item.name} is found` } }\n }\n }\n}\n\n/** Why a lock cannot be worked, or nothing when it can: the key must be held and be one that fits. */\nfunction keyFor(ctx: ItemContext, actor: CharacterId, spec: ItemChangeSpec, fits: readonly ItemId[], what: string): string | undefined {\n if (spec.forced === true) return undefined\n if (fits.length === 0) return `nothing is known to fit the lock of ${what}: if the story breaks it, say forced`\n if (spec.with === undefined) return `say which key is used on ${what}`\n const key = resolveItem(ctx, spec.with)\n if (key === undefined) return `there is no item \"${spec.with}\"`\n if (!fits.includes(key.id)) return `${key.name} does not fit the lock of ${what}`\n const reachKey = reach(ctx, actor, key)\n return reachKey.kind === 'held' ? undefined : `${key.name} is not in hand`\n}\n\n/** A copy of an item with another quantity, for splitting off part of a pile. */\nconst sameKind = (a: Item, b: Item): boolean => !a.unique && !b.unique && a.name === b.name && a.quality === b.quality && a.wearableSlot === b.wearableSlot && a.container === undefined && b.container === undefined && a.ownerId === b.ownerId\n\n/** Do what a plan says. Part of a pile is split off, and joins a pile of the same kind where it lands. */\nexport function applyItemPlan(ctx: ItemContext, plan: ItemPlan): ItemEffect {\n const describe = (item: Pick<Item, 'id' | 'sourceId' | 'name'>, action: ItemAction, summary: string): ItemEffect => ({ item: { key: itemKey(item), name: item.name }, action, summary })\n switch (plan.action) {\n case 'reveal':\n ctx.items.update(plan.item.id, { hidden: false })\n return describe(plan.item, 'reveal', plan.summary)\n case 'container':\n ctx.items.update(plan.item.id, { container: { state: plan.state } })\n return describe(plan.item, plan.spec.action, plan.summary)\n case 'exit': {\n for (const [from, to] of [[plan.from, plan.to], [plan.to, plan.from]] as const) {\n const exit = ctx.locations.getExit(from, to)\n if (exit !== undefined) ctx.locations.updateExit(exit.id, { state: plan.state })\n }\n return { item: { key: locationKey(ctx.locations.get(plan.to)!), name: ctx.locations.get(plan.to)!.name }, action: plan.spec.action, summary: plan.summary }\n }\n case 'move': {\n const { item, quantity, holder } = plan\n const joins = holder.kind !== 'character' || holder.mode === 'held'\n const twin = joins ? ctx.items.contents(holderKey(holder)).find(({ item: other }) => other.id !== item.id && sameKind(item, other))?.item : undefined\n if (quantity >= item.quantity) {\n if (twin === undefined) {\n ctx.items.place(item.id, holder)\n return describe(item, plan.spec.action, plan.summary)\n }\n ctx.items.update(twin.id, { quantity: twin.quantity + item.quantity })\n ctx.items.remove(item.id)\n return describe(twin, plan.spec.action, plan.summary)\n }\n ctx.items.update(item.id, { quantity: item.quantity - quantity })\n if (twin !== undefined) {\n ctx.items.update(twin.id, { quantity: twin.quantity + quantity })\n return describe(twin, plan.spec.action, plan.summary)\n }\n const { id: _id, sourceId: _sourceId, createdAt: _createdAt, ...rest } = item\n return describe(ctx.items.add({ ...rest, quantity }, holder), plan.spec.action, plan.summary)\n }\n }\n}\n\nfunction holderKey(holder: Holder): { kind: 'location' | 'character' | 'item'; id: number } {\n return holder.kind === 'location' ? { kind: 'location', id: holder.locationId } : holder.kind === 'character' ? { kind: 'character', id: holder.characterId } : { kind: 'item', id: holder.itemId }\n}\n\n/**\n * Do what a character does with an item.\n * @throws {InvalidMoveError} naming every reason when it cannot, changing nothing.\n */\nexport function changeItem(ctx: ItemContext, actorId: CharacterId, spec: ItemChangeSpec): ItemEffect {\n const planned = planItemChange(ctx, actorId, spec)\n if (!planned.ok) throw new InvalidMoveError(planned.problems)\n return applyItemPlan(ctx, planned.plan)\n}\n","import type { Exit, LocationId, Move, MovePlan } from 'dsh-roleplay-model'\nimport { InvalidMoveError } from '../errors.ts'\nimport type { KnowledgeRepository, LocationRepository, PlacementRepository } from '../repositories.ts'\n\nexport interface MoveContext {\n locations: Pick<LocationRepository, 'get' | 'allExits'>\n placements: Pick<PlacementRepository, 'get' | 'place'>\n}\n\nexport interface KnownMoveContext extends MoveContext {\n knowledge: Pick<KnowledgeRepository, 'knows'>\n}\n\nconst name = (context: MoveContext, id: LocationId): string => context.locations.get(id)?.name ?? String(id)\n\n/** The shortest way over exits that satisfy `usable`, as the exits taken in order, or `undefined` when there is none. */\nfunction shortestWay(exits: readonly Exit[], from: LocationId, to: LocationId, usable: (exit: Exit) => boolean): Exit[] | undefined {\n const reached = new Map<LocationId, Exit[]>([[from, []]])\n const queue: LocationId[] = [from]\n for (let next = queue.shift(); next !== undefined; next = queue.shift()) {\n if (next === to) return reached.get(next)\n for (const exit of exits) {\n if (exit.fromId !== next || reached.has(exit.toId) || !usable(exit)) continue\n reached.set(exit.toId, [...reached.get(next)!, exit])\n queue.push(exit.toId)\n }\n }\n return undefined\n}\n\n/**\n * Whether a character can go where a move says, and the way it would take. Moving to where it\n * already is only changes its position. Otherwise there must be a way over open exits, unless the\n * move ignores them.\n * @returns the plan, or the reasons it cannot be done.\n */\nexport function planMove(context: MoveContext, characterId: number, move: Move): { ok: true; plan: MovePlan } | { ok: false; problems: string[] } {\n const problems: string[] = []\n const destination = context.locations.get(move.to)\n if (destination === undefined) return { ok: false, problems: [`there is no place ${move.to}`] }\n if (move.featureKey !== undefined && !destination.features.some(feature => feature.key === move.featureKey)) {\n problems.push(`${destination.name} has no feature \"${move.featureKey}\" (it has: ${destination.features.map(feature => feature.key).join(', ') || 'none'})`)\n }\n const from = context.placements.get('character', characterId)?.locationId\n if (from === move.to) return problems.length > 0 ? { ok: false, problems } : { ok: true, plan: { from, to: move.to, via: [] } }\n if (from === undefined || move.ignoreExits === true) return problems.length > 0 ? { ok: false, problems } : { ok: true, plan: { ...(from === undefined ? {} : { from }), to: move.to, via: [move.to] } }\n\n const exits = context.locations.allExits()\n const way = shortestWay(exits, from, move.to, exit => exit.state === 'open')\n if (way === undefined) {\n const blocked = shortestWay(exits, from, move.to, () => true)\n if (blocked === undefined) problems.push(`there is no way from ${name(context, from)} to ${destination.name}`)\n else {\n const stopper = blocked.find(exit => exit.state !== 'open')!\n problems.push(`the way from ${name(context, from)} to ${destination.name} is ${stopper.state} at ${name(context, stopper.fromId)} -> ${name(context, stopper.toId)}${stopper.note === '' ? '' : `: ${stopper.note}`}`)\n }\n }\n if (problems.length > 0 || way === undefined) return { ok: false, problems }\n const times = way.map(exit => exit.travelSeconds)\n return { ok: true, plan: { from, to: move.to, via: way.map(exit => exit.toId), ...(times.every(time => time !== undefined) ? { travelSeconds: times.reduce<number>((sum, time) => sum + time!, 0) } : {}) } }\n}\n\n/** Plan only through places and directed ways this character knows; forced movement remains the authoritative planner's job. */\nexport function planKnownMove(context: KnownMoveContext, characterId: number, move: Move): ReturnType<typeof planMove> {\n if (move.ignoreExits !== true && !context.knowledge.knows(characterId, 'location', move.to)) return { ok: false, problems: [`the character does not know place ${move.to}`] }\n if (move.ignoreExits === true) return planMove(context, characterId, move)\n return planMove({\n placements: context.placements,\n locations: { get: id => context.locations.get(id), allExits: () => context.locations.allExits().filter(exit => context.knowledge.knows(characterId, 'exit', exit.id)) },\n }, characterId, move)\n}\n\n/**\n * Move a character: where it stands changes to the destination, at the position or feature given.\n * @throws {InvalidMoveError} naming every reason when it cannot.\n */\nexport function moveCharacter(context: MoveContext, characterId: number, move: Move): MovePlan {\n const result = planMove(context, characterId, move)\n if (!result.ok) throw new InvalidMoveError(result.problems)\n if (result.plan.from === move.to && move.position === undefined && move.featureKey === undefined) return result.plan\n context.placements.place('character', characterId, { locationId: move.to, ...(move.position === undefined ? {} : { position: move.position }), ...(move.featureKey === undefined ? {} : { featureKey: move.featureKey }) })\n return result.plan\n}\n","/**\n * What the words of a cue or a beat may name by `{kind:key}`, filled in from the story when they are told. The key is how the world's files\n * name the thing (`@self` in a cue is the character it is said to), and a name follows the story: a renamed character is renamed in the words.\n */\nexport const TEMPLATE_KINDS = {\n /** The name of a character. */\n character: { args: 1, about: 'a character' },\n /** The name of a place. */\n place: { args: 1, about: 'a place' },\n /** The name of an item. */\n item: { args: 1, about: 'an item' },\n /** The name of the place a character is in now. */\n where: { args: 1, about: 'a character' },\n /** Who holds an item now, or the place it lies in. */\n holder: { args: 1, about: 'an item' },\n /** What a variable is now, in words: `{value:key}` for a world variable, `{value:key:subject}` for the character, item or place it is about. */\n value: { args: 2, about: 'a variable' },\n /** The time of day in the story, as `19:30`. */\n time: { args: 0, about: '' },\n} as const\n\nexport type TemplateKind = keyof typeof TEMPLATE_KINDS\n\nexport interface Placeholder {\n raw: string\n kind: TemplateKind\n args: string[]\n}\n\nconst PATTERN = /\\{([a-z]+)(?::([^{}]*))?\\}/g\n\n/** The placeholders in some words, and what is wrong with any that is not one. Anything that does not look like `{word}` or `{word:key}` is plain text. */\nexport function placeholdersOf(text: string): { found: Placeholder[]; problems: string[] } {\n const found: Placeholder[] = []\n const problems: string[] = []\n for (const match of text.matchAll(PATTERN)) {\n const [raw, word, rest] = match as unknown as [string, string, string | undefined]\n if (!(word in TEMPLATE_KINDS)) { problems.push(`${raw}: there is no \"${word}\"; the words may name ${Object.keys(TEMPLATE_KINDS).join(', ')}`); continue }\n const kind = word as TemplateKind\n const args = rest === undefined ? [] : rest.split(':').map(part => part.trim())\n const { args: wanted } = TEMPLATE_KINDS[kind]\n const ok = kind === 'value' ? args.length >= 1 && args.length <= 2 : args.length === wanted\n if (!ok || args.some(part => part === '')) { problems.push(`${raw}: ${kind === 'time' ? '{time} takes nothing' : kind === 'value' ? '{value:variable} or {value:variable:subject}' : `{${kind}:key} takes the key of ${TEMPLATE_KINDS[kind].about}`}`); continue }\n found.push({ raw, kind, args })\n }\n return { found, problems }\n}\n","import { EMOTION_VARIABLES, MAX_VARIABLES, VARIABLE_KEY, VARIABLE_KINDS, VARIABLE_SUBJECTS, VARIABLE_VISIBILITIES, type StoredVariable, type VariableBand, type VariableDefinition, type VariableDefinitionInput, type VariableSubject, type VariableValue } from 'dsh-roleplay-model'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { VariableRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface DefRow {\n key: string\n ordinal: number\n name: string\n description: string\n kind: VariableDefinition['kind']\n subject: VariableSubject\n only_keys: string\n min_value: number | null\n max_value: number | null\n is_integer: number\n options: string\n default_value: string\n has_baseline: number\n visibility: VariableDefinition['visibility']\n bands: string\n always_shown: number\n builtin: number\n}\n\ninterface ValueRow {\n variable: string\n subject: VariableSubject\n subject_id: number\n value: string\n baseline: string | null\n updated_turn: number\n}\n\nconst MAX_BANDS = 8\nconst MAX_OPTIONS = 12\nconst MAX_ONLY = 50\n\nfunction parseValue(text: string, column: string): VariableValue {\n try {\n const value: unknown = JSON.parse(text)\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string') return value\n } catch {\n // reported below\n }\n throw new CorruptDataError(`${column} does not hold a number, a yes or no, or text`)\n}\n\nfunction parseBands(text: string): VariableBand[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(band => typeof band === 'object' && band !== null && typeof (band as VariableBand).upTo === 'number' && typeof (band as VariableBand).label === 'string')) return value as VariableBand[]\n } catch {\n // reported below\n }\n throw new CorruptDataError('variable_defs.bands does not hold a list of bands')\n}\n\nconst toDef = (row: DefRow): VariableDefinition => ({\n key: row.key, name: row.name, description: row.description, kind: row.kind, subject: row.subject, only: parseStringList(row.only_keys, 'variable_defs.only_keys'),\n ...(row.min_value === null ? {} : { min: row.min_value }), ...(row.max_value === null ? {} : { max: row.max_value }),\n integer: row.is_integer === 1, options: parseStringList(row.options, 'variable_defs.options'), default: parseValue(row.default_value, 'variable_defs.default_value'),\n baseline: row.has_baseline === 1, visibility: row.visibility, bands: parseBands(row.bands), always: row.always_shown === 1, builtin: row.builtin === 1,\n})\n\nconst toStored = (row: ValueRow): StoredVariable => ({\n variable: row.variable, subject: row.subject, subjectId: row.subject_id, value: parseValue(row.value, 'variable_values.value'),\n ...(row.baseline === null ? {} : { baseline: parseValue(row.baseline, 'variable_values.baseline') }), updatedTurn: row.updated_turn,\n})\n\n/** Why a value is not one the variable can have, or nothing when it is. */\nexport function valueIssue(def: Pick<VariableDefinition, 'key' | 'kind' | 'min' | 'max' | 'integer' | 'options'>, value: unknown): string | undefined {\n if (def.kind === 'flag') return typeof value === 'boolean' ? undefined : `${def.key} is a yes or no`\n if (def.kind === 'choice') return typeof value === 'string' && def.options.includes(value) ? undefined : `${def.key} is one of: ${def.options.join(', ')}`\n if (typeof value !== 'number' || !Number.isFinite(value)) return `${def.key} is a number`\n if (def.integer && !Number.isInteger(value)) return `${def.key} is a whole number`\n if ((def.min !== undefined && value < def.min) || (def.max !== undefined && value > def.max)) return `${def.key} is a number ${def.min === undefined ? '' : `from ${def.min} `}${def.max === undefined ? '' : `up to ${def.max}`}`.trim()\n return undefined\n}\n\nconst SUBJECT_TABLES: Record<Exclude<VariableSubject, 'world'>, string> = { character: 'characters', item: 'items', location: 'locations' }\n\nexport class SqliteVariableRepository implements VariableRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n ensureDefaults(): void {\n for (const def of EMOTION_VARIABLES) if (this.def(def.key) === undefined) this.write(def)\n }\n\n defs(): VariableDefinition[] {\n return this.db.all<DefRow>('SELECT * FROM variable_defs ORDER BY ordinal').map(toDef)\n }\n\n def(key: string): VariableDefinition | undefined {\n const row = this.db.get<DefRow>('SELECT * FROM variable_defs WHERE key = ?', [key])\n return row === undefined ? undefined : toDef(row)\n }\n\n define(input: VariableDefinitionInput): VariableDefinition {\n const existing = this.def(input.key)\n if (existing?.builtin === true) {\n const kept: VariableDefinition = { ...existing, name: input.name, description: input.description ?? existing.description, only: input.only ?? existing.only, visibility: input.visibility ?? existing.visibility, bands: input.bands ?? existing.bands, always: input.always ?? existing.always }\n return this.write(this.checked(kept))\n }\n if (existing === undefined && this.defs().length >= MAX_VARIABLES) throw new InvalidValueError(`a story tracks at most ${MAX_VARIABLES} variables`)\n return this.write(this.checked({\n key: input.key, name: input.name, description: input.description ?? '', kind: input.kind, subject: input.subject, only: input.only ?? [],\n ...(input.min === undefined ? {} : { min: input.min }), ...(input.max === undefined ? {} : { max: input.max }),\n integer: input.integer ?? false, options: input.options ?? [], default: input.default ?? (input.kind === 'flag' ? false : input.kind === 'choice' ? input.options?.[0] ?? '' : (input.min ?? 0)),\n baseline: input.baseline ?? false, visibility: input.visibility ?? 'public', bands: input.bands ?? [], always: input.always ?? false, builtin: false,\n }))\n }\n\n remove(key: string): boolean {\n const found = this.def(key)\n if (found?.builtin === true) throw new ConflictError(`${key} is built in and cannot be removed`)\n return this.db.run('DELETE FROM variable_defs WHERE key = ?', [key]).changes > 0\n }\n\n get(variable: string, subject: VariableSubject, subjectId: number): StoredVariable | undefined {\n const row = this.db.get<ValueRow>('SELECT * FROM variable_values WHERE variable = ? AND subject = ? AND subject_id = ?', [variable, subject, subjectId])\n return row === undefined ? undefined : toStored(row)\n }\n\n value(variable: string, subject: VariableSubject, subjectId: number): VariableValue {\n const stored = this.get(variable, subject, subjectId)\n if (stored !== undefined) return stored.value\n const def = this.def(variable)\n if (def === undefined) throw new NotFoundError(`there is no variable \"${variable}\"`)\n return def.default\n }\n\n set(variable: string, subject: VariableSubject, subjectId: number, change: { value?: VariableValue; baseline?: VariableValue }, turn: number): StoredVariable {\n return guard(() => this.db.transaction(() => {\n const def = this.def(variable)\n if (def === undefined) throw new NotFoundError(`there is no variable \"${variable}\"`)\n if (!this.applies(def, subject, subjectId)) throw new InvalidValueError(`${def.name} does not apply to this ${subject}`)\n for (const [what, given] of [['value', change.value], ['baseline', change.baseline]] as const) {\n if (given === undefined) continue\n if (what === 'baseline' && !def.baseline) throw new InvalidValueError(`${def.name} has no baseline`)\n const issue = valueIssue(def, given)\n if (issue !== undefined) throw new InvalidValueError(issue)\n }\n const current = this.get(variable, subject, subjectId)\n const baseline = !def.baseline ? undefined : change.baseline ?? current?.baseline ?? change.value ?? def.default\n const value = change.value ?? current?.value ?? baseline ?? def.default\n this.db.run(\n `INSERT INTO variable_values (variable, subject, subject_id, value, baseline, updated_turn) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (variable, subject, subject_id) DO UPDATE SET value = excluded.value, baseline = excluded.baseline, updated_turn = excluded.updated_turn`,\n [variable, subject, subjectId, toJson(value), baseline === undefined ? null : toJson(baseline), turn],\n )\n return this.get(variable, subject, subjectId)!\n }))\n }\n\n list(subject: VariableSubject, subjectId: number): StoredVariable[] {\n return this.db.all<ValueRow>('SELECT * FROM variable_values WHERE subject = ? AND subject_id = ? ORDER BY variable', [subject, subjectId]).map(toStored)\n }\n\n all(): StoredVariable[] {\n return this.db.all<ValueRow>('SELECT * FROM variable_values ORDER BY updated_turn DESC, variable').map(toStored)\n }\n\n applies(def: VariableDefinition, subject: VariableSubject, subjectId: number): boolean {\n if (def.subject !== subject) return false\n if (def.only.length === 0 || subject === 'world') return true\n const row = this.db.get<{ source_id: string | null }>(`SELECT source_id FROM ${SUBJECT_TABLES[subject]} WHERE id = ?`, [subjectId])\n if (row === undefined) return false\n return def.only.includes(row.source_id ?? String(subjectId))\n }\n\n private checked(def: VariableDefinition): VariableDefinition {\n const bad = (message: string): never => { throw new InvalidValueError(`${def.key}: ${message}`) }\n if (!VARIABLE_KEY.test(def.key)) bad('the key is lowercase letters, digits and underscores, starting with a letter, at most 40 characters')\n if (def.name.trim() === '' || def.name.length > 80) bad('give it a name of at most 80 characters')\n if (def.description.length > 400) bad('the description is at most 400 characters')\n if (!VARIABLE_KINDS.includes(def.kind)) bad(`unknown kind \"${String(def.kind)}\"`)\n if (!VARIABLE_SUBJECTS.includes(def.subject)) bad(`unknown subject \"${String(def.subject)}\"`)\n if (!VARIABLE_VISIBILITIES.includes(def.visibility)) bad(`unknown visibility \"${String(def.visibility)}\"`)\n if (def.visibility === 'private' && def.subject !== 'character') bad('only what belongs to a character can be private')\n if (def.only.length > MAX_ONLY || def.only.some(key => key.trim() === '')) bad(`it applies to at most ${MAX_ONLY} named subjects`)\n if (def.subject === 'world' && def.only.length > 0) bad('there is only one world')\n if (def.kind === 'number') {\n if ((def.min !== undefined && !Number.isFinite(def.min)) || (def.max !== undefined && !Number.isFinite(def.max)) || (def.min !== undefined && def.max !== undefined && def.min > def.max)) bad('its bounds are not acceptable')\n if (def.options.length > 0) bad('a number has no options')\n } else {\n if (def.min !== undefined || def.max !== undefined || def.integer || def.bands.length > 0) bad('only a number has bounds, whole numbers or bands')\n if (def.baseline && def.kind === 'flag') bad('a yes or no has no baseline')\n }\n if (def.kind === 'choice' && (def.options.length < 2 || def.options.length > MAX_OPTIONS || new Set(def.options).size !== def.options.length || def.options.some(option => option.trim() === ''))) bad(`a choice has from 2 to ${MAX_OPTIONS} different options`)\n if (def.kind !== 'choice' && def.options.length > 0) bad('only a choice has options')\n const issue = valueIssue(def, def.default)\n if (issue !== undefined) bad(`the default is not acceptable: ${issue}`)\n if (def.bands.length > MAX_BANDS || def.bands.some((band, index) => !Number.isFinite(band.upTo) || band.label.trim() === '' || (index > 0 && band.upTo <= def.bands[index - 1]!.upTo))) bad(`bands are from 1 to ${MAX_BANDS} words for rising bounds`)\n return def\n }\n\n private write(def: VariableDefinition): VariableDefinition {\n return guard(() => this.db.transaction(() => {\n const ordinal = this.db.get<{ ordinal: number }>('SELECT ordinal FROM variable_defs WHERE key = ?', [def.key])?.ordinal ?? (this.db.get<{ next: number | null }>('SELECT MAX(ordinal) + 1 AS next FROM variable_defs')?.next ?? 0)\n this.db.run(\n `INSERT INTO variable_defs (key, ordinal, name, description, kind, subject, only_keys, min_value, max_value, is_integer, options, default_value, has_baseline, visibility, bands, always_shown, builtin)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (key) DO UPDATE SET name = excluded.name, description = excluded.description, kind = excluded.kind, subject = excluded.subject, only_keys = excluded.only_keys,\n min_value = excluded.min_value, max_value = excluded.max_value, is_integer = excluded.is_integer, options = excluded.options, default_value = excluded.default_value,\n has_baseline = excluded.has_baseline, visibility = excluded.visibility, bands = excluded.bands, always_shown = excluded.always_shown`,\n [def.key, ordinal, def.name.trim(), def.description.trim(), def.kind, def.subject, toJson(def.only), def.min ?? null, def.max ?? null, def.integer ? 1 : 0, toJson(def.options), toJson(def.default), def.baseline ? 1 : 0, def.visibility, toJson(def.bands), def.always ? 1 : 0, def.builtin ? 1 : 0],\n )\n return this.def(def.key)!\n }))\n }\n}\n","import type { VariableDefinition, VariableSubject, VariableValue } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport type { CharacterRepository, ItemRepository, LocationRepository, VariableRepository } from '../repositories.ts'\nimport { valueIssue } from '../sqlite/variable-repository.ts'\nimport { characterKey, locationKey } from './edit-types.ts'\nimport { itemKey } from './items.ts'\n\nexport interface VariableContext {\n variables: VariableRepository\n characters: Pick<CharacterRepository, 'list'>\n items: Pick<ItemRepository, 'list'>\n locations: Pick<LocationRepository, 'list'>\n}\n\n/** A change to what the story tracks, as the game master and the keeper write it. Exactly one of `to`, `by` and `baseline`. */\nexport interface VariableChangeSpec {\n variable: string\n /** The key of the character, item or place; `world` for a variable of the whole story. */\n subject: string\n /** The value it becomes. */\n to?: VariableValue\n /** How much a number goes up (or down, when negative); it stops at its bounds. */\n by?: number\n /** For a variable with a baseline: the new baseline (temperament). */\n baseline?: VariableValue\n}\n\nexport interface VariableEffect {\n variable: VariableDefinition\n subjectName: string\n from: VariableValue\n to: VariableValue\n}\n\nexport type VariablePlan = { ok: true; effect: VariableEffect; subjectId: number; change: { value?: VariableValue; baseline?: VariableValue } } | { ok: false; problems: string[] }\n\n/** The subject a key names, for a kind of subject. */\nexport function subjectOf(context: VariableContext, kind: VariableSubject, key: string): { id: number; name: string } | undefined {\n if (kind === 'world') return key === 'world' ? { id: 0, name: 'the world' } : undefined\n if (kind === 'character') {\n const found = context.characters.list().find(character => characterKey(character) === key)\n return found === undefined ? undefined : { id: found.id, name: found.name }\n }\n if (kind === 'item') {\n const found = context.items.list().find(item => itemKey(item) === key)\n return found === undefined ? undefined : { id: found.id, name: found.name }\n }\n const found = context.locations.list().find(place => locationKey(place) === key)\n return found === undefined ? undefined : { id: found.id, name: found.name }\n}\n\n/** A number as it is told: short, without trailing zeros. */\nconst shortNumber = (value: number): string => String(Math.round(value * 100) / 100)\n\n/** A value in words: a number by its band when the variable has bands (and the number), yes or no, or the word. */\nexport function describeValue(def: Pick<VariableDefinition, 'kind' | 'bands'>, value: VariableValue): string {\n if (typeof value === 'boolean') return value ? 'yes' : 'no'\n if (typeof value === 'string') return value\n const band = def.bands.find(candidate => value <= candidate.upTo) ?? def.bands.at(-1)\n return band === undefined ? shortNumber(value) : `${band.label} (${shortNumber(value)})`\n}\n\n/** A variable written by its name or in other letter case (\"Valence\" for `valence`), when exactly one variable has that name or key. */\nfunction namedVariable(variables: Pick<VariableRepository, 'defs'>, written: string): VariableDefinition | undefined {\n const wanted = written.trim().normalize('NFKC').toLowerCase()\n const found = wanted === '' ? [] : variables.defs().filter(def => def.key.normalize('NFKC').toLowerCase() === wanted || def.name.normalize('NFKC').toLowerCase() === wanted)\n return found.length === 1 ? found[0] : undefined\n}\n\n/** Whether a change can be made, and what it would come to. Nothing is changed. */\nexport function planVariableChange(context: VariableContext, spec: VariableChangeSpec): VariablePlan {\n const def = context.variables.def(spec.variable) ?? namedVariable(context.variables, spec.variable)\n if (def === undefined) return { ok: false, problems: [`there is no variable \"${spec.variable}\" (list_variables shows them)`] }\n const given = [spec.to, spec.by, spec.baseline].filter(value => value !== undefined).length\n if (given !== 1) return { ok: false, problems: [`${def.key}: give exactly one of to, by and baseline`] }\n const subject = subjectOf(context, def.subject, spec.subject)\n if (subject === undefined) return { ok: false, problems: [`${def.key}: there is no ${def.subject === 'world' ? 'world: use \"world\"' : `${def.subject} \"${spec.subject}\"`}`] }\n if (!context.variables.applies(def, def.subject, subject.id)) return { ok: false, problems: [`${def.key} does not apply to ${subject.name} (it applies to: ${def.only.join(', ')})`] }\n const from = context.variables.value(def.key, def.subject, subject.id)\n if (spec.baseline !== undefined) {\n const issue = def.baseline ? valueIssue(def, spec.baseline) : `${def.key} has no baseline`\n return issue === undefined ? { ok: true, subjectId: subject.id, change: { baseline: spec.baseline }, effect: { variable: def, subjectName: subject.name, from, to: from } } : { ok: false, problems: [`${def.key}: ${issue}`] }\n }\n let to: VariableValue\n if (spec.by !== undefined) {\n if (def.kind !== 'number' || typeof from !== 'number') return { ok: false, problems: [`${def.key}: only a number goes up or down by an amount; use to`] }\n if (!Number.isFinite(spec.by)) return { ok: false, problems: [`${def.key}: by is a number`] }\n const moved = from + spec.by\n const bounded = Math.min(def.max ?? moved, Math.max(def.min ?? moved, moved))\n to = def.integer ? Math.round(bounded) : bounded\n } else {\n to = spec.to!\n const issue = valueIssue(def, to)\n if (issue !== undefined) return { ok: false, problems: [`${def.key}: ${issue}`] }\n }\n return { ok: true, subjectId: subject.id, change: { value: to }, effect: { variable: def, subjectName: subject.name, from, to } }\n}\n\n/**\n * Change a variable now.\n * @throws {InvalidEditError} naming every reason it cannot be done.\n */\nexport function changeVariable(context: VariableContext, spec: VariableChangeSpec, turn: number): VariableEffect {\n const planned = planVariableChange(context, spec)\n if (!planned.ok) throw new InvalidEditError(planned.problems)\n context.variables.set(planned.effect.variable.key, planned.effect.variable.subject, planned.subjectId, planned.change, turn)\n return planned.effect\n}\n\n/** Who is reading values: the game master and the keeper see everything, a character sees what is public and what is private to it, anyone else only what is public. */\nexport type VariableAudience = 'story' | 'self' | 'others'\n\nexport interface ShownVariable {\n variable: VariableDefinition\n value: VariableValue\n baseline?: VariableValue\n}\n\n/** At most this many variables are told for one subject. */\nexport const MAX_SHOWN = 8\n\n/** The variables of a subject that are worth telling, in the order they were declared: those whose value is not the default, and those always told. */\nexport function shownVariables(context: VariableContext, kind: VariableSubject, subjectId: number, subjectKey: string, audience: VariableAudience): ShownVariable[] {\n const stored = new Map(context.variables.list(kind, subjectId).map(entry => [entry.variable, entry]))\n return context.variables.defs().flatMap((def): ShownVariable[] => {\n if (def.subject !== kind || !(def.only.length === 0 || def.only.includes(subjectKey))) return []\n if (audience === 'others' ? def.visibility !== 'public' : audience === 'self' ? def.visibility === 'hidden' : false) return []\n const entry = stored.get(def.key)\n const value = entry?.value ?? def.default\n if (value === def.default && !def.always) return []\n return [{ variable: def, value, ...(entry?.baseline === undefined ? {} : { baseline: entry.baseline }) }]\n }).slice(0, MAX_SHOWN)\n}\n","import { COMPARISONS, SELF, WEEKDAY_NAMES, type Comparison, type Trigger, type TriggerAnnouncement, type TriggerAudience, type TriggerCondition, type TriggerDefinition, type TriggerEffect, type VariableValue } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\nimport { inWindow, localTime, parseInstant, parseTimeOfDay } from './time.ts'\nimport { placeholdersOf } from './template.ts'\nimport { subjectOf } from './variables.ts'\n\nexport type Wire = Record<string, unknown>\nconst isObject = (value: unknown): value is Wire => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** How deep a condition may nest and how many parts it may have: a trigger is a rule, not a program. */\nconst MAX_DEPTH = 4\nconst MAX_NODES = 24\nconst MAX_EFFECTS = 6\nconst MAX_TEXT = 1000\nconst MAX_JUDGED = 300\n\nconst text = (entry: Wire, key: string): string | undefined => (typeof entry[key] === 'string' && entry[key].trim() !== '' ? entry[key].trim() : undefined)\n\nfunction parseCondition(value: unknown, path: string, problems: string[], count: { nodes: number }, depth = 0): TriggerCondition | undefined {\n count.nodes += 1\n if (count.nodes > MAX_NODES) { if (count.nodes === MAX_NODES + 1) problems.push(`${path}: a condition has at most ${MAX_NODES} parts`); return undefined }\n if (depth > MAX_DEPTH) { problems.push(`${path}: conditions nest at most ${MAX_DEPTH} deep`); return undefined }\n if (!isObject(value)) { problems.push(`${path}: a condition is an object`); return undefined }\n const need = (key: string): string | undefined => {\n const found = text(value, key)\n if (found === undefined) problems.push(`${path}.${key}: required text`)\n return found\n }\n switch (value['type']) {\n case 'time': {\n const from = text(value, 'from')\n const to = text(value, 'to')\n const window = isObject(value['window']) ? { from: text(value['window'], 'from') ?? '', to: text(value['window'], 'to') ?? '' } : undefined\n const days = Array.isArray(value['days']) ? value['days'].filter((day): day is string => typeof day === 'string') : undefined\n if (from === undefined && to === undefined && window === undefined && days === undefined) { problems.push(`${path}: a time condition needs from, to, window or days`); return undefined }\n if (window !== undefined && (parseTimeOfDay(window.from) === undefined || parseTimeOfDay(window.to) === undefined || window.from === window.to)) problems.push(`${path}.window: from and to are different times of day, HH:MM`)\n for (const day of days ?? []) if (!(WEEKDAY_NAMES as readonly string[]).includes(day)) problems.push(`${path}.days: \"${day}\" is not mon to sun`)\n if (value['days'] !== undefined && days?.length !== (value['days'] as unknown[] | undefined)?.length) problems.push(`${path}.days: a list of mon to sun`)\n return { type: 'time', ...(from === undefined ? {} : { from }), ...(to === undefined ? {} : { to }), ...(window === undefined ? {} : { window }), ...(days === undefined ? {} : { days }) }\n }\n case 'place': {\n const character = need('character'); const location = need('location'); const feature = text(value, 'feature')\n return character === undefined || location === undefined ? undefined : { type: 'place', character, location, ...(feature === undefined ? {} : { feature }) }\n }\n case 'variable': {\n const variable = need('variable'); const subject = text(value, 'subject')\n const op = value['op'] as Comparison\n const found = value['value']\n if (!COMPARISONS.includes(op)) problems.push(`${path}.op: one of ${COMPARISONS.join(', ')}`)\n if (typeof found !== 'number' && typeof found !== 'string' && typeof found !== 'boolean') problems.push(`${path}.value: a number, text or yes/no`)\n return variable === undefined || !COMPARISONS.includes(op) || (typeof found !== 'number' && typeof found !== 'string' && typeof found !== 'boolean')\n ? undefined : { type: 'variable', variable, ...(subject === undefined ? {} : { subject }), op, value: found }\n }\n case 'item': {\n const item = need('item'); const heldBy = text(value, 'held_by'); const at = text(value, 'at')\n if ((heldBy === undefined) === (at === undefined)) { problems.push(`${path}: give exactly one of held_by and at`); return undefined }\n return item === undefined ? undefined : { type: 'item', item, ...(heldBy === undefined ? {} : { heldBy }), ...(at === undefined ? {} : { at }) }\n }\n case 'event': { const tag = need('tag'); return tag === undefined ? undefined : { type: 'event', tag: tag.toLowerCase() } }\n case 'fired': { const trigger = need('trigger'); return trigger === undefined ? undefined : { type: 'fired', trigger } }\n case 'judged': {\n const statement = need('text')\n if (statement !== undefined && statement.length > MAX_JUDGED) { problems.push(`${path}.text: at most ${MAX_JUDGED} characters`); return undefined }\n return statement === undefined ? undefined : { type: 'judged', text: statement }\n }\n case 'all':\n case 'any': {\n if (!Array.isArray(value['conditions']) || value['conditions'].length === 0) { problems.push(`${path}.conditions: a list with at least one condition`); return undefined }\n const parts = value['conditions'].map((part, index) => parseCondition(part, `${path}.conditions[${index}]`, problems, count, depth + 1))\n return parts.every(part => part !== undefined) ? { type: value['type'], conditions: parts as TriggerCondition[] } : undefined\n }\n case 'not': {\n const inner = parseCondition(value['condition'], `${path}.condition`, problems, count, depth + 1)\n return inner === undefined ? undefined : { type: 'not', condition: inner }\n }\n default:\n problems.push(`${path}.type: one of time, place, variable, item, event, fired, judged, all, any, not`)\n return undefined\n }\n}\n\nfunction parseAudience(value: unknown, path: string, problems: string[]): TriggerAudience | undefined {\n if (value === 'everyone') return 'everyone'\n if (isObject(value) && Array.isArray(value['characters']) && value['characters'].length > 0 && value['characters'].every(entry => typeof entry === 'string' && entry.trim() !== '')) return { characters: value['characters'] as string[] }\n if (isObject(value) && typeof value['place'] === 'string' && value['place'].trim() !== '') return { place: value['place'].trim() }\n problems.push(`${path}: \"everyone\", {\"characters\": [the characters]} or {\"place\": the place}`)\n return undefined\n}\n\nconst localTimeProblem = (value: string): boolean => { try { parseInstant(value, 'UTC'); return false } catch { return true } }\n\nfunction parseAnnouncement(value: unknown, path: string, problems: string[]): TriggerAnnouncement | undefined {\n if (!isObject(value)) { problems.push(`${path}: an announcement is an object: who knows, and what is known`); return undefined }\n const audience = parseAudience(value['audience'], `${path}.audience`, problems)\n const words = text(value, 'text')\n if (words === undefined || words.length > 500) problems.push(`${path}.text: required text of at most 500 characters`)\n const from = text(value, 'from')\n const at = text(value, 'at')\n for (const [field, found] of [['from', from], ['at', at]] as const) if (found !== undefined && localTimeProblem(found)) problems.push(`${path}.${field}: a local date and time, 1912-10-04T19:30`)\n return audience === undefined || words === undefined ? undefined : { audience, text: words, ...(from === undefined ? {} : { from }), ...(at === undefined ? {} : { at }) }\n}\n\n/** Checks that an edit effect is shaped as an edit; it throws {@link InvalidEditError} when not. */\nexport type EditChecker = (edit: Wire) => void\n\n/** Whether words or a condition name the character a cue is said to. */\nfunction usesSelf(words: string, condition: TriggerCondition | undefined): boolean {\n const inWords = placeholdersOf(words).found.some(placeholder => placeholder.args.includes(SELF))\n return inWords || (condition !== undefined && mentionsSelf(condition))\n}\n\nfunction mentionsSelf(condition: TriggerCondition): boolean {\n switch (condition.type) {\n case 'place': return condition.character === SELF\n case 'variable': return condition.subject === SELF\n case 'item': return condition.item === SELF || condition.heldBy === SELF\n case 'all': case 'any': return condition.conditions.some(mentionsSelf)\n case 'not': return mentionsSelf(condition.condition)\n default: return false\n }\n}\n\nfunction parseEffect(value: unknown, path: string, problems: string[], checkEdit: EditChecker): TriggerEffect | undefined {\n if (!isObject(value)) { problems.push(`${path}: an effect is an object`); return undefined }\n if (value['type'] === 'edit') {\n if (!isObject(value['edit'])) { problems.push(`${path}.edit: an edit, as the record keeper writes one`); return undefined }\n try { checkEdit({ turn: 0, ...value['edit'] }) } catch (error) { problems.push(`${path}.edit: ${error instanceof InvalidEditError ? error.problems.join('; ') : String(error)}`); return undefined }\n if (value['while'] !== undefined) { problems.push(`${path}.while: only a beat or a cue can wait on a condition when it is told`); return undefined }\n return { type: 'edit', edit: value['edit'] }\n }\n if (value['type'] !== 'beat' && value['type'] !== 'cue') { problems.push(`${path}.type: one of edit, beat, cue`); return undefined }\n const words = text(value, 'text')\n if (words === undefined || words.length > MAX_TEXT) { problems.push(`${path}.text: required text of at most ${MAX_TEXT} characters`); return undefined }\n const template = placeholdersOf(words)\n for (const problem of template.problems) problems.push(`${path}.text: ${problem}`)\n const waiting = value['while'] === undefined ? undefined : parseCondition(value['while'], `${path}.while`, problems, { nodes: 0 })\n if (value['while'] !== undefined && waiting === undefined) return undefined\n if (waiting !== undefined && judgedStatements(waiting).length > 0) problems.push(`${path}.while: a statement a model judges (judged) cannot be waited on when something is told; use what the story records`)\n if (value['type'] === 'beat') {\n if (usesSelf(words, waiting)) problems.push(`${path}: only a cue is said to someone, so only a cue can name ${SELF}`)\n return template.problems.length > 0 ? undefined : { type: 'beat', text: words, ...(waiting === undefined ? {} : { while: waiting }) }\n }\n if (value['type'] === 'cue') {\n const audience = value['audience'] !== undefined ? parseAudience(value['audience'], `${path}.audience`, problems) : parseAudience({ characters: value['characters'] }, `${path}.characters`, problems)\n return audience === undefined || template.problems.length > 0 ? undefined : { type: 'cue', audience, text: words, ...(waiting === undefined ? {} : { while: waiting }) }\n }\n problems.push(`${path}.type: one of edit, beat, cue`)\n return undefined\n}\n\n/**\n * Read a trigger from the JSON a world's files and the world author write (snake_case).\n * @returns the definition, or every problem with where it is.\n */\nexport function parseTriggerDefinition(value: unknown, path: string, checkEdit: EditChecker): { definition: TriggerDefinition } | { problems: string[] } {\n const problems: string[] = []\n if (!isObject(value)) return { problems: [`${path}: a trigger is an object`] }\n const key = text(value, 'key'); const name = text(value, 'name')\n if (key === undefined) problems.push(`${path}.key: required text`)\n if (name === undefined) problems.push(`${path}.name: required text`)\n const condition = parseCondition(value['when'], `${path}.when`, problems, { nodes: 0 })\n const rawEffects = value['effects']\n if (!Array.isArray(rawEffects) || rawEffects.length === 0 || rawEffects.length > MAX_EFFECTS) problems.push(`${path}.effects: a list of one to ${MAX_EFFECTS} effects`)\n const effects = Array.isArray(rawEffects) ? rawEffects.slice(0, MAX_EFFECTS).map((effect, index) => parseEffect(effect, `${path}.effects[${index}]`, problems, checkEdit)) : []\n const number = (field: string): number | undefined => (typeof value[field] === 'number' ? value[field] : undefined)\n if (value['repeat'] !== undefined && typeof value['repeat'] !== 'boolean') problems.push(`${path}.repeat: yes or no`)\n for (const field of ['cooldown_seconds', 'chance', 'priority']) if (value[field] !== undefined && typeof value[field] !== 'number') problems.push(`${path}.${field}: a number`)\n const chance = number('chance'); const cooldown = number('cooldown_seconds')\n if (chance !== undefined && (chance < 0 || chance > 1)) problems.push(`${path}.chance: from 0 to 1`)\n if (cooldown !== undefined && (!Number.isSafeInteger(cooldown) || cooldown < 0)) problems.push(`${path}.cooldown_seconds: a whole number of seconds`)\n const expires = text(value, 'expires')\n const announce = value['announce'] === undefined ? undefined : parseAnnouncement(value['announce'], `${path}.announce`, problems)\n if (expires !== undefined) { try { parseInstant(expires, 'UTC') } catch { problems.push(`${path}.expires: a local date and time, 1912-10-04T19:30`) } }\n if (problems.length > 0 || key === undefined || name === undefined || condition === undefined) return { problems }\n return {\n definition: {\n key, name, condition, effects: effects as TriggerEffect[], repeat: value['repeat'] === true, priority: number('priority') ?? 0,\n ...(cooldown === undefined ? {} : { cooldownSeconds: cooldown }), ...(chance === undefined ? {} : { chance }), ...(expires === undefined ? {} : { expires }), ...(announce === undefined ? {} : { announce }),\n },\n }\n}\n\ntype Reading = Pick<RecordsTarget, 'characters' | 'locations' | 'items' | 'variables' | 'triggers'>\n\nfunction conditionProblems(target: Reading, condition: TriggerCondition, path: string, known: ReadonlySet<string>, self = false): string[] {\n const character = (key: string): string[] => ((self && key === SELF) || target.characters.list().some(entry => characterKey(entry) === key) ? [] : [`${path}: there is no character \"${key}\"`])\n const place = (key: string): string[] => (target.locations.list().some(entry => locationKey(entry) === key) ? [] : [`${path}: there is no place \"${key}\"`])\n switch (condition.type) {\n case 'time': return []\n case 'place': return [...character(condition.character), ...place(condition.location)]\n case 'variable': {\n const def = target.variables.def(condition.variable)\n if (def === undefined) return [`${path}: there is no variable \"${condition.variable}\"`]\n if (def.subject === 'world' ? condition.subject !== undefined : condition.subject === undefined) return [`${path}: ${def.subject === 'world' ? 'a world variable has no subject' : `give the ${def.subject} it is about as subject`}`]\n const subject = condition.subject === undefined || (self && condition.subject === SELF) ? undefined : subjectOf(target, def.subject, condition.subject)\n return [\n ...(condition.subject !== undefined && subject === undefined && !(self && condition.subject === SELF) ? [`${path}: there is no ${def.subject} \"${condition.subject}\"`] : []),\n ...(def.kind !== 'number' && condition.op !== 'eq' && condition.op !== 'ne' ? [`${path}: ${def.kind} variables compare with eq or ne only`] : []),\n ]\n }\n case 'item': return [\n ...((self && condition.item === SELF) || target.items.list().some(entry => itemKey(entry) === condition.item) ? [] : [`${path}: there is no item \"${condition.item}\"`]),\n ...(condition.heldBy === undefined ? [] : character(condition.heldBy)), ...(condition.at === undefined ? [] : place(condition.at)),\n ]\n case 'event': return []\n case 'fired': return known.has(condition.trigger) ? [] : [`${path}: there is no trigger \"${condition.trigger}\"`]\n case 'judged': return []\n case 'all': case 'any': return condition.conditions.flatMap((part, index) => conditionProblems(target, part, `${path}.conditions[${index}]`, known, self))\n case 'not': return conditionProblems(target, condition.condition, `${path}.condition`, known, self)\n }\n}\n\n/** What the words of a cue or beat name by `{kind:key}` that the story does not have. */\nfunction wordsProblems(target: Reading, words: string, path: string, self: boolean): string[] {\n return placeholdersOf(words).found.flatMap((placeholder): string[] => {\n const key = placeholder.args[0]!\n const selfKey = self && key === SELF\n const missing = (what: string): string[] => [`${path}: ${placeholder.raw}: there is no ${what} \"${key}\"`]\n switch (placeholder.kind) {\n case 'character': case 'where': return selfKey || target.characters.list().some(entry => characterKey(entry) === key) ? [] : missing('character')\n case 'place': return target.locations.list().some(entry => locationKey(entry) === key) ? [] : missing('place')\n case 'item': case 'holder': return target.items.list().some(entry => itemKey(entry) === key) ? [] : missing('item')\n case 'value': {\n const def = target.variables.def(key)\n if (def === undefined) return missing('variable')\n const subject = placeholder.args[1]\n if (def.subject === 'world') return subject === undefined ? [] : [`${path}: ${placeholder.raw}: a world variable has no subject`]\n if (subject === undefined) return [`${path}: ${placeholder.raw}: give the ${def.subject} it is about`]\n return (self && subject === SELF) || subjectOf(target, def.subject, subject) !== undefined ? [] : [`${path}: ${placeholder.raw}: there is no ${def.subject} \"${subject}\"`]\n }\n case 'time': return []\n }\n })\n}\n\n/**\n * What in a trigger names something the story does not have: a character, place, item or variable in a condition, the characters of a cue,\n * a trigger it waits for. (What an edit effect touches is checked when it is applied.)\n */\nexport function triggerReferenceProblems(target: Reading, definition: TriggerDefinition, otherKeys: Iterable<string> = []): string[] {\n const known = new Set([...target.triggers.list().map(trigger => trigger.key), ...otherKeys])\n const audience = (who: TriggerAudience, path: string): string[] => {\n if (who === 'everyone') return []\n if ('place' in who) return target.locations.list().some(entry => locationKey(entry) === who.place) ? [] : [`${path}: there is no place \"${who.place}\"`]\n return who.characters.flatMap(key => (target.characters.list().some(entry => characterKey(entry) === key) ? [] : [`${path}: there is no character \"${key}\"`]))\n }\n const cues = definition.effects.flatMap((effect, index) => (effect.type !== 'cue' ? [] : audience(effect.audience, `effects[${index}]`)))\n const said = definition.effects.flatMap((effect, index) => (effect.type === 'edit' ? [] : [\n ...(effect.while === undefined ? [] : conditionProblems(target, effect.while, `effects[${index}].while`, known, effect.type === 'cue')),\n ...wordsProblems(target, effect.text, `effects[${index}].text`, effect.type === 'cue'),\n ]))\n const announced = definition.announce === undefined ? [] : audience(definition.announce.audience, 'announce')\n return [...conditionProblems(target, definition.condition, 'when', known), ...cues, ...said, ...announced].map(problem => `${definition.key}: ${problem}`)\n}\n\nconst COMPARE: Record<Comparison, (a: number, b: number) => boolean> = { eq: (a, b) => a === b, ne: (a, b) => a !== b, lt: (a, b) => a < b, le: (a, b) => a <= b, gt: (a, b) => a > b, ge: (a, b) => a >= b }\n\nfunction compare(op: Comparison, have: VariableValue, want: VariableValue): boolean {\n if (typeof have === 'number' && typeof want === 'number') return COMPARE[op](have, want)\n return op === 'ne' ? have !== want : op === 'eq' ? have === want : false\n}\n\nexport interface TriggerClock {\n now: number\n zone: string\n /** Whether a model has judged a statement true; a statement nobody judged is false. */\n judged?: (statement: string) => boolean\n}\n\n/** The statements of the `judged` parts of a condition, in order, each once. */\nexport function judgedStatements(condition: TriggerCondition): string[] {\n switch (condition.type) {\n case 'judged': return [condition.text]\n case 'all': case 'any': return [...new Set(condition.conditions.flatMap(judgedStatements))]\n case 'not': return judgedStatements(condition.condition)\n default: return []\n }\n}\n\nfunction holds(target: RecordsTarget, condition: TriggerCondition, clock: TriggerClock): boolean {\n switch (condition.type) {\n case 'time': {\n const { now, zone } = clock\n if (condition.from !== undefined && now < parseInstant(condition.from, zone)) return false\n if (condition.to !== undefined && now >= parseInstant(condition.to, zone)) return false\n const local = localTime(now, zone)\n if (condition.window !== undefined) {\n const start = parseTimeOfDay(condition.window.from) ?? 0\n const end = parseTimeOfDay(condition.window.to) ?? 0\n if (!inWindow(local.minuteOfDay, start, end)) return false\n const weekday = start > end && local.minuteOfDay < end ? (local.weekday + 6) % 7 : local.weekday\n return condition.days === undefined || condition.days.length === 0 || condition.days.includes(WEEKDAY_NAMES[weekday] ?? '')\n }\n return condition.days === undefined || condition.days.length === 0 || condition.days.includes(WEEKDAY_NAMES[local.weekday] ?? '')\n }\n case 'place': {\n const who = target.characters.list().find(entry => characterKey(entry) === condition.character)\n const where = target.locations.list().find(entry => locationKey(entry) === condition.location)\n const placement = who === undefined ? undefined : target.placements.get('character', who.id)\n return placement !== undefined && where !== undefined && placement.locationId === where.id && (condition.feature === undefined || placement.featureKey === condition.feature)\n }\n case 'variable': {\n const def = target.variables.def(condition.variable)\n if (def === undefined) return false\n const subject = def.subject === 'world' ? { id: 0 } : condition.subject === undefined ? undefined : subjectOf(target, def.subject, condition.subject)\n return subject !== undefined && compare(condition.op, target.variables.value(condition.variable, def.subject, subject.id), condition.value)\n }\n case 'item': {\n const item = target.items.list().find(entry => itemKey(entry) === condition.item)\n if (item === undefined) return false\n const where = target.items.where(item.id)\n if (condition.heldBy !== undefined) return where.characterId !== undefined && where.characterId === target.characters.list().find(entry => characterKey(entry) === condition.heldBy)?.id\n return where.locationId !== undefined && where.locationId === target.locations.list().find(entry => locationKey(entry) === condition.at)?.id\n }\n case 'event': return target.events.list().some(event => event.tags.includes(condition.tag))\n case 'fired': return (target.triggers.getByKey(condition.trigger)?.fireCount ?? 0) > 0\n case 'judged': return clock.judged?.(condition.text) ?? false\n case 'all': return condition.conditions.every(part => holds(target, part, clock))\n case 'any': return condition.conditions.some(part => holds(target, part, clock))\n case 'not': return !holds(target, condition.condition, clock)\n }\n}\n\n/** Whether a condition holds now, judged only from what the story has recorded. */\nexport const conditionHolds = holds\n\n/** A number from 0 to 1 that depends only on what it is given: a roll that comes out the same when the story is replayed. */\nexport function seededRoll(seed: string): number {\n let hash = 2166136261\n for (const char of seed) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619)\n return ((hash >>> 0) % 1_000_000) / 1_000_000\n}\n\n\n/** When a trigger waits for a plain time, that time: what an announcement says it is to happen at, unless it says so itself. */\nfunction waitedFor(condition: TriggerCondition): string | undefined {\n if (condition.type === 'time') return condition.from\n if (condition.type === 'all') return condition.conditions.map(waitedFor).find(found => found !== undefined)\n return undefined\n}\n\n/** A character is among those an audience names, now. */\nexport function inAudience(target: Pick<RecordsTarget, 'characters' | 'locations' | 'placements'>, audience: TriggerAudience, characterId: number): boolean {\n if (audience === 'everyone') return true\n if ('characters' in audience) return audience.characters.some(key => target.characters.list().find(entry => characterKey(entry) === key)?.id === characterId)\n const place = target.locations.list().find(entry => locationKey(entry) === audience.place)\n return place !== undefined && target.placements.get('character', characterId)?.locationId === place.id\n}\n\n/** The characters an audience is now, those who can be asked to act (the player's own character is told by the game master). */\nexport function audienceIds(target: Pick<RecordsTarget, 'characters' | 'locations' | 'placements'>, audience: TriggerAudience): number[] {\n return target.characters.list().filter(entry => entry.control === 'agent' && inAudience(target, audience, entry.id)).map(entry => entry.id)\n}\n\nexport interface Announcement {\n trigger: Trigger\n text: string\n audience: TriggerAudience\n /** When it is to happen, as an instant, when that is known. */\n at?: number\n}\n\n/** What is known of what is coming: triggers that have not fired and announce themselves, from the time they say, soonest first. */\nexport function announcements(target: Pick<RecordsTarget, 'triggers'>, clock: TriggerClock): Announcement[] {\n return target.triggers.list({ status: 'dormant' }).flatMap((trigger): Announcement[] => {\n const { announce } = trigger\n if (announce === undefined || (announce.from !== undefined && clock.now < parseInstant(announce.from, clock.zone))) return []\n const when = announce.at ?? waitedFor(trigger.condition)\n return [{ trigger, text: announce.text, audience: announce.audience, ...(when === undefined ? {} : { at: parseInstant(when, clock.zone) }) }]\n }).sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity) || a.trigger.id - b.trigger.id)\n}\n","import type { JsonSchemaNode, ObjectJsonSchema } from '@deepseek-ai/dsh-tools'\nimport {\n ACCURACIES, CHARACTER_KINDS, CHARACTER_TIERS, CONTAINER_STATES, ENGAGEMENT_STATUSES, EXIT_STATES, IMPORTANCE_MAX, IMPORTANCE_MIN, INTENT_HORIZONS, INTENT_STATUSES, INTENT_TYPES, KNOWLEDGE_KINDS, MEMORY_KINDS, PERCEPTION_MODES, WEEKDAY_NAMES,\n VARIABLE_KINDS, VARIABLE_SUBJECTS, VARIABLE_VISIBILITIES,\n type VariableDefinitionInput, type VariableKind, type VariableSubject, type VariableValue, type VariableVisibility,\n type TriggerDefinition, type Accuracy, type CharacterKind, type CharacterTier, type ContainerState, type EngagementStatus, type ExitState, type IntentHorizon, type IntentStatus, type IntentType, type KnowledgeKind, type MemoryKind, type PerceptionMode, type Slot,\n} from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport type {\n BeliefEdit, CharacterMove, EngagementEditSpec, EventEdit, ExitChange, IntentEditSpec, ItemChange, NewEngagementSpec, NewIntentSpec, RoutineSet, RoutineWindowSpec, ItemEditSpec, NewBelief, NewCharacterSpec, NewEvent, NewExit, NewExitBetween, NewItemSpec, NewPlace,\n FactionMembershipSet, FactionRelationshipSet, FactionStateSet, KnowledgeRetraction, KnowledgeSet, NewFactionIntentSpec, PerceivedBy, PerceptionAddition, PerceptionEdit, PlaceEdit, RecordsEdit, RelationshipRetraction, RelationshipSet, StatePatch,\n} from './edit-types.ts'\nimport { ITEM_ACTIONS, type ItemAction } from './items.ts'\nimport type { VariableChangeSpec } from './variables.ts'\nimport { parseTriggerDefinition } from './trigger-rules.ts'\n\n/** An edit effect is an edit, but its events may be seen by `\"everyone\"`, which an ordinary edit cannot say. */\nconst checkEdit = (edit: Wire): void => {\n const events = Array.isArray(edit['events']) ? edit['events'].map(event => (isObject(event) && event['perceived_by'] === 'everyone' ? { ...event, perceived_by: [] } : event)) : edit['events']\n parseRecordsEdit({ ...edit, ...(events === undefined ? {} : { events }) })\n}\n\n/** Read a trigger as a world's files write it. @returns the definition, or every problem with where it is. */\nexport const readTriggerDefinition = (value: unknown, path: string): ReturnType<typeof parseTriggerDefinition> => parseTriggerDefinition(value, path, checkEdit)\n\ntype Wire = Record<string, unknown>\nconst isObject = (value: unknown): value is Wire => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Read an edit from the JSON models write (snake_case), the one wire format of the\n * keeper's output and of the write tools.\n * @throws {InvalidEditError} when it is not shaped as an edit.\n */\nexport function parseRecordsEdit(value: unknown): RecordsEdit {\n const problems: string[] = []\n if (!isObject(value)) throw new InvalidEditError(['the edit must be an object'])\n const array = (key: string): Wire[] => {\n const entries = value[key]\n if (entries === undefined || entries === null) return []\n if (!Array.isArray(entries)) { problems.push(`${key} must be a list`); return [] }\n return entries.flatMap((entry, index) => {\n if (isObject(entry)) return [entry]\n problems.push(`${key}[${index}] must be an object`)\n return []\n })\n }\n const numbers = (key: string): number[] => {\n const entries = value[key]\n if (entries === undefined || entries === null) return []\n if (!Array.isArray(entries) || entries.some(entry => typeof entry !== 'number')) { problems.push(`${key} must be a list of numbers`); return [] }\n return entries as number[]\n }\n const strings = (entry: Wire, key: string): string[] | undefined => {\n const found = entry[key]\n if (found === undefined || found === null) return undefined\n if (!Array.isArray(found) || found.some(item => typeof item !== 'string')) { problems.push(`${key} must be a list of text`); return undefined }\n return found as string[]\n }\n const text = (entry: Wire, key: string): string | undefined => (typeof entry[key] === 'string' ? entry[key] : undefined)\n /** A key, slot or position the model may leave blank instead of leaving out: blank is nothing given, not a name that does not exist. */\n const named = (entry: Wire, key: string): string | undefined => { const value = text(entry, key)?.trim(); return value === undefined || value === '' ? undefined : value }\n const num = (entry: Wire, key: string): number | undefined => (typeof entry[key] === 'number' ? entry[key] : undefined)\n const perceived = (entry: Wire): PerceivedBy[] | undefined => {\n const found = entry['perceived_by']\n if (found === undefined || found === null) return undefined\n if (!Array.isArray(found)) { problems.push('perceived_by must be a list'); return undefined }\n return found.filter(isObject).map(item => ({\n character: text(item, 'character') ?? '', mode: (text(item, 'mode') ?? '') as PerceptionMode,\n ...(text(item, 'content') === undefined ? {} : { content: text(item, 'content')! }),\n ...(text(item, 'gist') === undefined ? {} : { gist: text(item, 'gist')! }),\n ...(text(item, 'accuracy') === undefined ? {} : { accuracy: text(item, 'accuracy') as Accuracy }),\n }))\n }\n const scalar = (entry: Wire, key: string): VariableValue | undefined => { const found = entry[key]; return typeof found === 'number' || typeof found === 'string' || typeof found === 'boolean' ? found : undefined }\n const bool = (entry: Wire, key: string): boolean | undefined => (typeof entry[key] === 'boolean' ? entry[key] : undefined)\n const featuresOf = (entry: Wire): { key: string; name: string; description?: string }[] | undefined => {\n const found = entry['features']\n if (found === undefined || found === null) return undefined\n if (!Array.isArray(found)) { problems.push('features must be a list'); return undefined }\n return found.filter(isObject).map(item => ({ key: text(item, 'key') ?? '', name: text(item, 'name') ?? '', ...(text(item, 'description') === undefined ? {} : { description: text(item, 'description')! }) }))\n }\n const defined = <T>(entry: object): T => Object.fromEntries(Object.entries(entry).filter(([, field]) => field !== undefined)) as T\n\n const turn = num(value, 'turn')\n const edit: RecordsEdit = {\n turn: turn ?? 0,\n states: array('states').map((entry): StatePatch => defined<StatePatch>({\n character: text(entry, 'character') ?? '', publicState: text(entry, 'public_state'), innerState: text(entry, 'inner_state'), activity: text(entry, 'activity'),\n })),\n events: array('events').map((entry): NewEvent => defined<NewEvent>({\n turn: num(entry, 'turn') ?? 0, round: num(entry, 'round') ?? 0, text: text(entry, 'text') ?? '', importance: num(entry, 'importance') ?? 0,\n tags: strings(entry, 'tags'), involves: strings(entry, 'involves'), perceivedBy: perceived(entry), location: text(entry, 'location'), items: strings(entry, 'items'),\n })),\n eventEdits: array('event_edits').map((entry): EventEdit => defined<EventEdit>({\n id: num(entry, 'id') ?? 0, text: text(entry, 'text'), importance: num(entry, 'importance'), tags: strings(entry, 'tags'), involves: strings(entry, 'involves'), perceivedBy: perceived(entry), location: text(entry, 'location'),\n })),\n eventRetractions: numbers('event_retractions'),\n perceptionEdits: array('perception_edits').map((entry): PerceptionEdit => defined<PerceptionEdit>({\n id: num(entry, 'id') ?? 0, mode: text(entry, 'mode') as PerceptionMode | undefined, content: text(entry, 'content'), gist: text(entry, 'gist'), accuracy: text(entry, 'accuracy') as Accuracy | undefined,\n })),\n perceptionsAdded: array('perceptions_added').map((entry): PerceptionAddition => defined<PerceptionAddition>({\n event: num(entry, 'event') ?? 0, character: text(entry, 'character') ?? '', mode: (text(entry, 'mode') ?? '') as PerceptionMode,\n content: text(entry, 'content'), gist: text(entry, 'gist'), accuracy: text(entry, 'accuracy') as Accuracy | undefined,\n })),\n characters: array('characters').map((entry): NewCharacterSpec => defined<NewCharacterSpec>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', aliases: strings(entry, 'aliases'), age: text(entry, 'age'), gender: text(entry, 'gender'), pronouns: text(entry, 'pronouns'),\n kind: text(entry, 'kind') as CharacterKind | undefined, tier: text(entry, 'tier') as CharacterTier | undefined, summary: text(entry, 'summary') ?? '',\n personality: text(entry, 'personality'), background: text(entry, 'background'), appearance: text(entry, 'appearance'), note: text(entry, 'note'),\n speech: isObject(entry['speech']) ? defined<NonNullable<NewCharacterSpec['speech']>>({ style: text(entry['speech'], 'style') ?? '', examples: strings(entry['speech'], 'examples') }) : undefined,\n state: isObject(entry['state']) ? defined<NonNullable<NewCharacterSpec['state']>>({ publicState: text(entry['state'], 'public_state'), innerState: text(entry['state'], 'inner_state'), activity: text(entry['state'], 'activity') }) : undefined,\n place: isObject(entry['place']) ? defined<NonNullable<NewCharacterSpec['place']>>({ location: text(entry['place'], 'location') ?? '', position: text(entry['place'], 'position'), feature: text(entry['place'], 'feature') }) : undefined,\n })),\n items: array('items').map((entry): NewItemSpec => defined<NewItemSpec>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', description: text(entry, 'description'), quantity: num(entry, 'quantity'), unique: bool(entry, 'unique'),\n quality: text(entry, 'quality'), notable: bool(entry, 'notable'), hidden: bool(entry, 'hidden'), wearable: named(entry, 'wearable'), owner: named(entry, 'owner'), note: text(entry, 'note'),\n container: isObject(entry['container']) ? defined<NonNullable<NewItemSpec['container']>>({ state: text(entry['container'], 'state') as ContainerState | undefined, openedBy: strings(entry['container'], 'opened_by') }) : undefined,\n at: isObject(entry['at']) && named(entry['at'], 'location') !== undefined ? defined<NonNullable<NewItemSpec['at']>>({ location: named(entry['at'], 'location') ?? '', position: named(entry['at'], 'position'), feature: named(entry['at'], 'feature') }) : undefined,\n heldBy: named(entry, 'held_by'), wornBy: named(entry, 'worn_by'), wornPosition: named(entry, 'worn_position'), inside: named(entry, 'inside'), insidePosition: named(entry, 'inside_position'),\n })),\n slots: array('slots').map((entry): Slot => ({ id: text(entry, 'id') ?? '', name: text(entry, 'name') ?? '', capacity: num(entry, 'capacity') ?? 0 })),\n itemChanges: array('item_changes').map((entry): ItemChange => defined<ItemChange>({\n character: text(entry, 'character') ?? '', item: text(entry, 'item') ?? '', action: (text(entry, 'action') ?? '') as ItemAction, to: text(entry, 'to'), slot: text(entry, 'slot'),\n quantity: num(entry, 'quantity'), position: text(entry, 'position'), feature: text(entry, 'feature'), with: text(entry, 'with'), exit: text(entry, 'exit'), forced: bool(entry, 'forced'),\n })),\n itemEdits: array('item_edits').map((entry): ItemEditSpec => defined<ItemEditSpec>({\n item: text(entry, 'item') ?? '', description: text(entry, 'description'), quality: text(entry, 'quality'), quantity: num(entry, 'quantity'), notable: bool(entry, 'notable'),\n hidden: bool(entry, 'hidden'), state: text(entry, 'state') as ContainerState | undefined, owner: text(entry, 'owner'), openedBy: strings(entry, 'opened_by'),\n })),\n places: array('places').map((entry): NewPlace => defined<NewPlace>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', description: text(entry, 'description'), parent: text(entry, 'parent'), features: featuresOf(entry), note: text(entry, 'note'),\n exits: Array.isArray(entry['exits']) ? entry['exits'].filter(isObject).map((item): NewExit => defined<NewExit>({\n to: text(item, 'to') ?? '', description: text(item, 'description'), oneWay: bool(item, 'one_way'), backDescription: text(item, 'back_description'),\n travelSeconds: num(item, 'travel_time_seconds'), state: text(item, 'state') as ExitState | undefined, note: text(item, 'note'),\n })) : undefined,\n })),\n exits: array('exits').map((entry): NewExitBetween => defined<NewExitBetween>({\n from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '', description: text(entry, 'description'), oneWay: bool(entry, 'one_way'), backDescription: text(entry, 'back_description'),\n travelSeconds: num(entry, 'travel_time_seconds'), state: text(entry, 'state') as ExitState | undefined, note: text(entry, 'note'),\n })),\n relationships: array('relationships').map((entry): RelationshipSet => defined<RelationshipSet>({\n from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '', label: text(entry, 'label'), summary: text(entry, 'summary'),\n familiarity: num(entry, 'familiarity'), trust: num(entry, 'trust'), affinity: num(entry, 'affinity'), tension: num(entry, 'tension'),\n })),\n relationshipRetractions: array('relationship_retractions').map((entry): RelationshipRetraction => ({ from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '' })),\n knowledge: array('knowledge').map((entry): KnowledgeSet => defined<KnowledgeSet>({ character: text(entry, 'character') ?? '', kind: (text(entry, 'kind') ?? '') as KnowledgeKind, subject: text(entry, 'subject'), from: text(entry, 'from'), to: text(entry, 'to'), observed: bool(entry, 'observed') })),\n knowledgeRetractions: array('knowledge_retractions').map((entry): KnowledgeRetraction => defined<KnowledgeRetraction>({ character: text(entry, 'character') ?? '', kind: (text(entry, 'kind') ?? '') as KnowledgeKind, subject: text(entry, 'subject'), from: text(entry, 'from'), to: text(entry, 'to') })),\n factionStates: array('faction_states').map((entry): FactionStateSet => defined<FactionStateSet>({ faction: text(entry, 'faction') ?? '', publicState: text(entry, 'public_state'), innerState: text(entry, 'inner_state') })),\n factionMemberships: array('faction_memberships').map((entry): FactionMembershipSet => defined<FactionMembershipSet>({ faction: text(entry, 'faction') ?? '', character: text(entry, 'character') ?? '', role: text(entry, 'role'), rank: text(entry, 'rank'), status: text(entry, 'status') as FactionMembershipSet['status'], public: bool(entry, 'public'), commitment: num(entry, 'commitment'), leftTurn: num(entry, 'left_turn') })),\n factionRelationships: array('faction_relationships').map((entry): FactionRelationshipSet => defined<FactionRelationshipSet>({ fromKind: (text(entry, 'from_kind') ?? '') as FactionRelationshipSet['fromKind'], from: text(entry, 'from') ?? '', toKind: (text(entry, 'to_kind') ?? '') as FactionRelationshipSet['toKind'], to: text(entry, 'to') ?? '', label: text(entry, 'label'), summary: text(entry, 'summary'), familiarity: num(entry, 'familiarity'), trust: num(entry, 'trust'), affinity: num(entry, 'affinity'), tension: num(entry, 'tension') })),\n factionIntentsAdded: array('faction_intents_added').map((entry): NewFactionIntentSpec => defined<NewFactionIntentSpec>({ faction: text(entry, 'faction') ?? '', type: (text(entry, 'type') ?? '') as IntentType, name: text(entry, 'name') ?? '', description: text(entry, 'description'), horizon: (text(entry, 'horizon') ?? '') as IntentHorizon, priority: num(entry, 'priority') ?? Number.NaN, urgency: num(entry, 'urgency') ?? Number.NaN, plan: strings(entry, 'plan'), constraints: strings(entry, 'constraints'), deadline: text(entry, 'deadline') })),\n placeEdits: array('place_edits').map((entry): PlaceEdit => defined<PlaceEdit>({ place: text(entry, 'place') ?? '', name: text(entry, 'name'), description: text(entry, 'description'), features: featuresOf(entry) })),\n exitChanges: array('exit_changes').map((entry): ExitChange => defined<ExitChange>({\n from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '', state: text(entry, 'state') as ExitState | undefined, description: text(entry, 'description'), note: text(entry, 'note'),\n travelSeconds: num(entry, 'travel_time_seconds'), oneWay: bool(entry, 'one_way'),\n })),\n moves: array('moves').map((entry): CharacterMove => defined<CharacterMove>({\n character: text(entry, 'character') ?? '', to: text(entry, 'to') ?? '', position: text(entry, 'position'), feature: text(entry, 'feature'), ignoreExits: bool(entry, 'ignore_exits'),\n })),\n beliefs: array('beliefs').map((entry): NewBelief => defined<NewBelief>({\n character: text(entry, 'character') ?? '', kind: (text(entry, 'kind') ?? '') as MemoryKind, text: text(entry, 'text') ?? '', about: strings(entry, 'about'), importance: num(entry, 'importance') ?? 0,\n })),\n beliefEdits: array('belief_edits').map((entry): BeliefEdit => defined<BeliefEdit>({ id: num(entry, 'id') ?? 0, text: text(entry, 'text'), about: strings(entry, 'about'), importance: num(entry, 'importance') })),\n beliefRetractions: numbers('belief_retractions'),\n threadsOpened: Array.isArray(value['threads_opened']) ? (value['threads_opened'] as unknown[]).filter((entry): entry is string => typeof entry === 'string') : [],\n threadsResolved: numbers('threads_resolved'),\n variableChanges: array('variable_changes').map((entry): VariableChangeSpec => defined<VariableChangeSpec>({\n variable: text(entry, 'variable') ?? '', subject: text(entry, 'subject') ?? '', to: scalar(entry, 'to'), by: num(entry, 'by'), baseline: scalar(entry, 'baseline'),\n })),\n variables: array('variables').map((entry): VariableDefinitionInput => defined<VariableDefinitionInput>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', description: text(entry, 'description'), kind: (text(entry, 'kind') ?? '') as VariableKind, subject: (text(entry, 'subject') ?? '') as VariableSubject,\n only: strings(entry, 'only'), min: num(entry, 'min'), max: num(entry, 'max'), integer: bool(entry, 'integer'), options: strings(entry, 'options'), default: scalar(entry, 'default'),\n baseline: bool(entry, 'baseline'), visibility: text(entry, 'visibility') as VariableVisibility | undefined, always: bool(entry, 'always'),\n bands: Array.isArray(entry['bands']) ? entry['bands'].filter(isObject).map(band => ({ upTo: num(band, 'up_to') ?? Number.NaN, label: text(band, 'label') ?? '' })) : undefined,\n })),\n intentsAdded: array('intents_added').map((entry): NewIntentSpec => defined<NewIntentSpec>({\n character: text(entry, 'character') ?? '', type: (text(entry, 'type') ?? '') as IntentType, name: text(entry, 'name') ?? '', description: text(entry, 'description'),\n horizon: (text(entry, 'horizon') ?? '') as IntentHorizon, priority: num(entry, 'priority') ?? Number.NaN, urgency: num(entry, 'urgency') ?? Number.NaN,\n plan: strings(entry, 'plan'), constraints: strings(entry, 'constraints'), deadline: text(entry, 'deadline'),\n })),\n intentEdits: array('intent_edits').map((entry): IntentEditSpec => defined<IntentEditSpec>({\n id: num(entry, 'id') ?? 0, status: text(entry, 'status') as IntentStatus | undefined, description: text(entry, 'description'), horizon: text(entry, 'horizon') as IntentHorizon | undefined,\n priority: num(entry, 'priority'), urgency: num(entry, 'urgency'), plan: strings(entry, 'plan'), openThreads: strings(entry, 'open_threads'), deadline: text(entry, 'deadline'),\n })),\n engagements: array('engagements').map((entry): NewEngagementSpec => defined<NewEngagementSpec>({\n title: text(entry, 'title') ?? '', at: text(entry, 'at') ?? '', until: text(entry, 'until'), location: text(entry, 'location'), participants: strings(entry, 'participants') ?? [], note: text(entry, 'note'),\n })),\n engagementEdits: array('engagement_edits').map((entry): EngagementEditSpec => defined<EngagementEditSpec>({\n id: num(entry, 'id') ?? 0, status: text(entry, 'status') as EngagementStatus | undefined, title: text(entry, 'title'), at: text(entry, 'at'), until: text(entry, 'until'),\n location: text(entry, 'location'), participants: strings(entry, 'participants'), note: text(entry, 'note'),\n })),\n triggers: array('triggers').flatMap((entry, index): TriggerDefinition[] => {\n const parsed = parseTriggerDefinition(entry, `triggers[${index}]`, checkEdit)\n if ('problems' in parsed) { problems.push(...parsed.problems); return [] }\n return [parsed.definition]\n }),\n routines: array('routines').map((entry): RoutineSet => ({\n character: text(entry, 'character') ?? '',\n windows: Array.isArray(entry['windows']) ? entry['windows'].filter(isObject).map((window): RoutineWindowSpec => defined<RoutineWindowSpec>({\n days: strings(window, 'days'), from: text(window, 'from') ?? '', to: text(window, 'to') ?? '', activity: text(window, 'activity') ?? '',\n location: text(window, 'location'), feature: text(window, 'feature'), position: text(window, 'position'), interruptible: bool(window, 'interruptible'),\n })) : [],\n })),\n }\n if (problems.length > 0) throw new InvalidEditError(problems)\n return edit\n}\n\nconst scalarValue: JsonSchemaNode = { oneOf: [{ type: 'number' }, { type: 'boolean' }, { type: 'string' }], description: 'A number, true or false, or one of the words of a choice.' }\n\nconst IMPORTANCE: JsonSchemaNode = { type: 'integer', enum: [1, 2, 3, 4, 5], description: `From ${IMPORTANCE_MIN} (a passing detail) to ${IMPORTANCE_MAX} (turns the story).` }\n\n/**\n * The JSON schema of the wire format, for a model's structured output or a tool's parameters.\n * With `characters`, a character can only be named by one of those keys.\n */\nexport function recordsEditSchema(options: { characters?: readonly string[]; changes?: boolean; /** Offer the making of characters, places and ways: only for the agent whose work that is. */ authoring?: boolean } = {}): ObjectJsonSchema {\n const character: JsonSchemaNode = options.characters === undefined || options.characters.length === 0\n ? { type: 'string', description: 'The key of a character.' }\n : { type: 'string', enum: [...options.characters], description: 'The key of a character.' }\n const keys: JsonSchemaNode = { type: 'array', items: character }\n const perceivedBy: JsonSchemaNode = {\n type: 'array',\n description: 'Who took the event in: only characters who could actually have perceived it. A character always perceives what it does or says itself.',\n items: {\n type: 'object',\n properties: {\n character,\n mode: { type: 'string', enum: [...PERCEPTION_MODES], description: 'How: saw it, heard it, was told, or worked it out.' },\n content: { type: 'string', description: 'What this character took in, in its own terms. Leave out when it took in exactly the event.' },\n gist: { type: 'string', description: 'The essence of it in a few words.' },\n accuracy: { type: 'string', enum: [...ACCURACIES], description: 'How well that matches what happened. Never shown to the character. Defaults to accurate.' },\n },\n required: ['character', 'mode'],\n additionalProperties: false,\n },\n }\n const placeKey: JsonSchemaNode = { type: 'string', description: 'The key of a place, as list_locations gives it, or one of the places made in this same edit.' }\n const featureList: JsonSchemaNode = {\n type: 'array',\n description: 'Named things in the place that a story can point at: a desk, a window, a notice board.',\n items: { type: 'object', properties: { key: { type: 'string' }, name: { type: 'string' }, description: { type: 'string' } }, required: ['key', 'name'], additionalProperties: false },\n }\n const properties: ObjectJsonSchema['properties'] = {\n turn: { type: 'integer', description: 'The turn these records belong to.' },\n states: {\n type: 'array',\n description: 'The new state of the characters whose state changed. Give only the fields that changed.',\n items: {\n type: 'object',\n properties: {\n character,\n public_state: { type: 'string', description: 'What anyone present can now see of the character: a short present-tense description, never a log of events.' },\n inner_state: { type: 'string', description: 'What the character now thinks and feels; private.' },\n activity: { type: 'string', description: 'What the character is concretely doing now.' },\n },\n required: ['character'],\n additionalProperties: false,\n },\n },\n events: {\n type: 'array',\n description: 'What objectively happened: short, factual, past-tense statements.',\n items: {\n type: 'object',\n properties: {\n turn: { type: 'integer' },\n round: { type: 'integer' },\n text: { type: 'string' },\n importance: IMPORTANCE,\n tags: { type: 'array', items: { type: 'string' }, description: 'Lowercase words a later search could use: objects, places, topics.' },\n involves: { ...keys, description: 'The characters the event is about: who acted and who it was done to.' },\n perceived_by: perceivedBy,\n location: { ...placeKey, description: 'Where it happened: the key of the place.' },\n items: { type: 'array', items: { type: 'string' }, description: 'The keys of the items it is about: what was taken, opened, handed over, found.' },\n },\n required: ['turn', 'round', 'text', 'importance', 'tags', 'involves', 'perceived_by'],\n additionalProperties: false,\n },\n },\n beliefs: {\n type: 'array',\n description: 'What a character has come to believe or know beyond a single event, from its own point of view.',\n items: {\n type: 'object',\n properties: {\n character,\n kind: { type: 'string', enum: [...MEMORY_KINDS] },\n text: { type: 'string' },\n about: keys,\n importance: IMPORTANCE,\n },\n required: ['character', 'kind', 'text', 'importance'],\n additionalProperties: false,\n },\n },\n relationships: {\n type: 'array',\n description: 'How a character stands towards another: a small profile, one per direction. Give only what changed; a new one needs a label. Record a change when something happened that really changes it, not for every pleasantry.',\n items: {\n type: 'object',\n properties: {\n from: character,\n to: character,\n label: { type: 'string', description: 'What the other is to this character, in a word or two: sister, rival, landlord.' },\n summary: { type: 'string', description: 'The relationship in a sentence or two: how it came about, what it is like now.' },\n familiarity: { type: 'number', description: 'How well it knows the other: 0 a stranger, 1 intimately.' },\n trust: { type: 'number', description: 'From -1 (distrusts) to 1 (trusts completely).' },\n affinity: { type: 'number', description: 'From -1 (dislikes) to 1 (is fond of).' },\n tension: { type: 'number', description: 'How strained it is now: 0 none, 1 about to break.' },\n },\n required: ['from', 'to'],\n additionalProperties: false,\n },\n },\n relationship_retractions: {\n type: 'array',\n description: 'Profiles that no longer describe anything: the two never actually met, or it was made by mistake.',\n items: { type: 'object', properties: { from: character, to: character }, required: ['from', 'to'], additionalProperties: false },\n },\n knowledge: {\n type: 'array',\n description: 'Entities a character learns exist. For a location or item give subject; for a directed exit give from and to. This grants identity only, never current state or whereabouts.',\n items: {\n type: 'object',\n properties: { character, kind: { type: 'string', enum: [...KNOWLEDGE_KINDS] }, subject: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' }, observed: { type: 'boolean' } },\n required: ['character', 'kind'], additionalProperties: false,\n },\n },\n knowledge_retractions: {\n type: 'array',\n description: 'Entity awareness recorded by mistake. Ordinary stale information belongs in beliefs and does not remove awareness.',\n items: { type: 'object', properties: { character, kind: { type: 'string', enum: [...KNOWLEDGE_KINDS] }, subject: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' } }, required: ['character', 'kind'], additionalProperties: false },\n },\n faction_states: {\n type: 'array', description: 'Changes in an organisation itself. Give only fields that changed.',\n items: { type: 'object', properties: { faction: { type: 'string' }, public_state: { type: 'string' }, inner_state: { type: 'string' } }, required: ['faction'], additionalProperties: false },\n },\n faction_memberships: {\n type: 'array', description: 'Membership learned or changed. A character may belong to several factions; public says whether outsiders can ordinarily know it.',\n items: { type: 'object', properties: { faction: { type: 'string' }, character, role: { type: 'string' }, rank: { type: 'string' }, status: { type: 'string', enum: ['active', 'inactive', 'former'] }, public: { type: 'boolean' }, commitment: { type: 'number' }, left_turn: { type: 'integer' } }, required: ['faction', 'character'], additionalProperties: false },\n },\n faction_relationships: {\n type: 'array', description: 'A directional profile involving a faction. This is also the awareness edge: without it, the from-side does not know the target exists.',\n items: { type: 'object', properties: { from_kind: { type: 'string', enum: ['character', 'faction'] }, from: { type: 'string' }, to_kind: { type: 'string', enum: ['character', 'faction'] }, to: { type: 'string' }, label: { type: 'string' }, summary: { type: 'string' }, familiarity: { type: 'number' }, trust: { type: 'number' }, affinity: { type: 'number' }, tension: { type: 'number' } }, required: ['from_kind', 'from', 'to_kind', 'to'], additionalProperties: false },\n },\n faction_intents_added: {\n type: 'array', description: 'A durable strategic goal newly adopted by a faction. This pressures its members but does not directly act for them.',\n items: { type: 'object', properties: { faction: { type: 'string' }, type: { type: 'string', enum: [...INTENT_TYPES] }, name: { type: 'string' }, description: { type: 'string' }, horizon: { type: 'string', enum: [...INTENT_HORIZONS] }, priority: { type: 'number' }, urgency: { type: 'number' }, plan: { type: 'array', items: { type: 'string' } }, constraints: { type: 'array', items: { type: 'string' } }, deadline: { type: 'string' } }, required: ['faction', 'type', 'name', 'horizon', 'priority', 'urgency'], additionalProperties: false },\n },\n item_changes: {\n type: 'array',\n description: 'What characters do with items. Not for what the game master already decided; those are written already.',\n items: {\n type: 'object',\n properties: {\n character,\n item: { type: 'string', description: 'The key of the item, as list_items gives it.' },\n action: { type: 'string', enum: [...ITEM_ACTIONS] },\n to: { type: 'string', description: 'For give: the character; for put: the container item.' },\n slot: { type: 'string' },\n quantity: { type: 'integer' },\n position: { type: 'string' },\n feature: { type: 'string' },\n with: { type: 'string', description: 'For lock and unlock: the key item used.' },\n exit: { type: 'string', description: 'For lock and unlock of a way instead of an item: the key of the place it leads to.' },\n forced: { type: 'boolean' },\n },\n required: ['character', 'item', 'action'],\n additionalProperties: false,\n },\n },\n item_edits: {\n type: 'array',\n description: 'Changes to an item that no character did: its condition, a lock the story breaks, who it belongs to, what opens it. Give only what changes.',\n items: {\n type: 'object',\n properties: {\n item: { type: 'string' },\n description: { type: 'string' },\n quality: { type: 'string' },\n quantity: { type: 'integer' },\n notable: { type: 'boolean' },\n hidden: { type: 'boolean' },\n state: { type: 'string', enum: [...CONTAINER_STATES] },\n owner: character,\n opened_by: { type: 'array', items: { type: 'string' }, description: 'Replaces the items that open it.' },\n },\n required: ['item'],\n additionalProperties: false,\n },\n },\n place_edits: {\n type: 'array',\n description: 'Changes to a known place: it burned down, a feature appeared. Give only what changes; features replaces the list.',\n items: { type: 'object', properties: { place: placeKey, name: { type: 'string' }, description: { type: 'string' }, features: featureList }, required: ['place'], additionalProperties: false },\n },\n exit_changes: {\n type: 'array',\n description: 'The way between two places changed: a door unlocked, a passage collapsed. Applies to both directions unless one_way.',\n items: {\n type: 'object',\n properties: { from: placeKey, to: placeKey, state: { type: 'string', enum: [...EXIT_STATES] }, description: { type: 'string' }, note: { type: 'string' }, travel_time_seconds: { type: 'integer' }, one_way: { type: 'boolean' } },\n required: ['from', 'to'],\n additionalProperties: false,\n },\n },\n moves: {\n type: 'array',\n description: 'Where characters go. Not for what the game master already decided; those moves are written already.',\n items: {\n type: 'object',\n properties: { character, to: placeKey, position: { type: 'string' }, feature: { type: 'string' }, ignore_exits: { type: 'boolean' } },\n required: ['character', 'to'],\n additionalProperties: false,\n },\n },\n variable_changes: {\n type: 'array',\n description: 'What the story tracks changed: a feeling, a debt, a reputation, a flag (list_variables shows what is tracked and what each is about). Give exactly one of to (the new value), by (an amount a number goes up or down; it stops at its bounds) or baseline (the new temperament of a variable that has one). Only what the rounds clearly establish.',\n items: {\n type: 'object',\n properties: {\n variable: { type: 'string', description: 'The key of the variable.' },\n subject: { type: 'string', description: 'The key of the character, item or place it is about; world for a variable of the whole story.' },\n to: scalarValue,\n by: { type: 'number' },\n baseline: scalarValue,\n },\n required: ['variable', 'subject'],\n additionalProperties: false,\n },\n },\n intents_added: {\n type: 'array',\n description: 'A goal the story gave a character: a promise it made, a task it took on, a scheme it set in motion. Only what the rounds clearly establish; never one that is already listed for it.',\n items: {\n type: 'object',\n properties: {\n character,\n type: { type: 'string', enum: [...INTENT_TYPES] },\n name: { type: 'string', description: 'A few words.' },\n description: { type: 'string' },\n horizon: { type: 'string', enum: [...INTENT_HORIZONS] },\n priority: { type: 'number', description: 'How much it matters to the character, 0 to 1.' },\n urgency: { type: 'number', description: 'How soon it has to be dealt with, 0 to 1.' },\n plan: { type: 'array', items: { type: 'string' }, description: 'The next steps, a sentence each.' },\n constraints: { type: 'array', items: { type: 'string' } },\n deadline: { type: 'string', description: 'When it has to be done by: a date and time, 1912-09-22T18:00, in the time zone of the story.' },\n },\n required: ['character', 'type', 'name', 'horizon', 'priority', 'urgency'],\n additionalProperties: false,\n },\n },\n intent_edits: {\n type: 'array',\n description: 'A goal of a character that moved on (the ids are in read_records): done, failed, given up, more or less pressing, a step taken. Give only what changes; plan replaces the steps.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n status: { type: 'string', enum: [...INTENT_STATUSES] },\n description: { type: 'string' },\n horizon: { type: 'string', enum: [...INTENT_HORIZONS] },\n priority: { type: 'number' },\n urgency: { type: 'number' },\n plan: { type: 'array', items: { type: 'string' } },\n open_threads: { type: 'array', items: { type: 'string' } },\n deadline: { type: 'string' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n engagements: {\n type: 'array',\n description: 'Something characters committed to at a time: a meeting arranged, an errand promised, an event they are to attend. Only when the rounds clearly establish a time (or a time of day that can be worked out from the story\\'s clock).',\n items: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'A few words: \"Meet Clara at the bar\".' },\n at: { type: 'string', description: 'When it is due: a date and time, 1912-09-22T21:00, in the time zone of the story.' },\n until: { type: 'string', description: 'When it is over, when that matters.' },\n location: placeKey,\n participants: { ...keys, description: 'Who has committed to it: each character that is to be there.' },\n note: { type: 'string' },\n },\n required: ['title', 'at', 'participants'],\n additionalProperties: false,\n },\n },\n engagement_edits: {\n type: 'array',\n description: 'An engagement that moved on (the ids are in read_records): it was kept, missed, cancelled, or put off. Give only what changes.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n status: { type: 'string', enum: [...ENGAGEMENT_STATUSES] },\n title: { type: 'string' },\n at: { type: 'string' },\n until: { type: 'string' },\n location: placeKey,\n participants: keys,\n note: { type: 'string' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n threads_opened: { type: 'array', items: { type: 'string' }, description: 'Promises made, mysteries raised, goals set that are not settled yet: one sentence each.' },\n threads_resolved: { type: 'array', items: { type: 'integer' }, description: 'The ids of open threads that are now settled.' },\n }\n if (options.authoring === true) {\n Object.assign(properties, {\n variables: {\n type: 'array',\n description: 'A thing the story now tracks, declared only when what it established matters from here on and nothing tracked fits (a debt, a character\\'s health, a reputation, whether a door is known). Declared once; then changed with variable_changes (in the same call too).',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'Lowercase letters, digits and underscores, starting with a letter.' },\n name: { type: 'string' },\n description: { type: 'string', description: 'What it measures or means, for those who read and change it.' },\n kind: { type: 'string', enum: [...VARIABLE_KINDS] },\n subject: { type: 'string', enum: [...VARIABLE_SUBJECTS], description: 'What each value is about: every character, item or place has its own; world has one for the whole story.' },\n only: { type: 'array', items: { type: 'string' }, description: 'Keys of the subjects it applies to; leave out for all of its kind.' },\n min: { type: 'number' },\n max: { type: 'number' },\n integer: { type: 'boolean' },\n options: { type: 'array', items: { type: 'string' }, description: 'For a choice: from 2 to 12 words.' },\n default: scalarValue,\n baseline: { type: 'boolean', description: 'Whether each value has a temperament beside the current value (feelings do).' },\n visibility: { type: 'string', enum: [...VARIABLE_VISIBILITIES], description: 'public: anyone present can tell; private: only the character it belongs to (and the game master); hidden: only the game master.' },\n bands: { type: 'array', items: { type: 'object', properties: { up_to: { type: 'number' }, label: { type: 'string' } }, required: ['up_to', 'label'], additionalProperties: false }, description: 'Words for ranges of a number, lowest first: values up to up_to are called label.' },\n always: { type: 'boolean', description: 'Tell it always, not only once it differs from its default.' },\n },\n required: ['key', 'name', 'kind', 'subject'],\n additionalProperties: false,\n },\n },\n triggers: {\n type: 'array',\n description: 'Things the world does by itself when something comes true, made only when the story has set up a moment that is bound to come (a deadline, a promised arrival, a trap, a storm) and nothing existing covers it. At most two at a time. Each fires once, when its condition turns true.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'Lowercase letters, digits, hyphens and underscores.' },\n name: { type: 'string', description: 'A short label for the author; never shown to any character.' },\n when: {\n type: 'object',\n description: 'The condition, decided in code from what the story has recorded. One of: {type:\"time\", from:\"1912-10-05T21:00\", to?, window?:{from:\"22:00\",to:\"06:00\"}, days?:[\"fri\"]} (story-local times); {type:\"place\", character, location, feature?}; {type:\"variable\", variable, subject? (the key of the character, item or place; none for a world variable), op: eq|ne|lt|le|gt|ge, value}; {type:\"item\", item, held_by? | at?}; {type:\"event\", tag}; {type:\"fired\", trigger}; and {type:\"all\"|\"any\", conditions:[...]} or {type:\"not\", condition}, nested at most 4 deep.',\n properties: { type: { type: 'string', enum: ['time', 'place', 'variable', 'item', 'event', 'fired', 'all', 'any', 'not'] } },\n required: ['type'],\n additionalProperties: true,\n },\n effects: {\n type: 'array',\n description: 'What happens, one to six: {type:\"edit\", edit:{...}} a change of the records in the same format as edit_records (events with a location are seen by those there, variable_changes, exit_changes, item_changes, moves, intents_added, engagements); {type:\"beat\", text, while?} something the game master is told to weave into the story; {type:\"cue\", characters:[keys] (or audience: \"everyone\" | {place:key}), text, while?} something those characters notice; a beat or cue is written when it is told, which may be turns after the trigger fired: its text may name things as {character:key}, {place:key}, {item:key}, {where:character} (the place a character is in), {holder:item} (who has it or where it lies), {value:variable} or {value:variable:subject}, {time}, and is told as the story stands then, and `while` is a condition (as above, nothing judged) that must still hold then or it is withdrawn; in a cue \\\"@self\\\" stands for the character it is said to (for example while:{type:\\\"place\\\", character:\\\"@self\\\", location:\\\"cellar\\\"}); in the events of an edit, perceived_by may be \"everyone\".',\n items: { type: 'object', properties: { type: { type: 'string', enum: ['edit', 'beat', 'cue'] } }, required: ['type'], additionalProperties: true },\n },\n repeat: { type: 'boolean', description: 'Fire again after the condition went false and true again. Default no.' },\n cooldown_seconds: { type: 'integer', description: 'With repeat: the least story time between two firings.' },\n chance: { type: 'number', description: 'From 0 to 1: the chance that it fires when the condition turns true.' },\n priority: { type: 'integer', description: 'The higher goes first when several are due at once.' },\n expires: { type: 'string', description: 'After this story-local time it never fires.' },\n announce: {\n type: 'object',\n description: 'Only for something that is no secret, scheduled and known beforehand (an exam, a ball, a deadline): who knows of it and what they know. Without it nobody knows until it fires. audience is \"everyone\", {characters:[keys]} or {place:key} (whoever is there); text is the public side only, never what the effects do; from is when it becomes known (story-local time; known at once when left out); at is when it happens, when the condition does not say so by a plain time.',\n properties: { audience: { type: 'object', description: '\"everyone\", or {characters:[keys]}, or {place:key}.', additionalProperties: true }, text: { type: 'string' }, from: { type: 'string' }, at: { type: 'string' } },\n required: ['audience', 'text'],\n additionalProperties: false,\n },\n },\n required: ['key', 'name', 'when', 'effects'],\n additionalProperties: false,\n },\n },\n routines: {\n type: 'array',\n description: 'The recurring day of a character who matters off stage and has none: windows of the day with what it is doing and where, in the order they apply (the first that fits applies). Replaces what it had.',\n items: {\n type: 'object',\n properties: {\n character,\n windows: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n days: { type: 'array', items: { type: 'string', enum: [...WEEKDAY_NAMES] }, description: 'Leave out for every day.' },\n from: { type: 'string', description: 'HH:MM, 24-hour.' },\n to: { type: 'string', description: 'HH:MM; a time before from ends the next day (22:00 to 06:00).' },\n activity: { type: 'string', description: 'What it is doing: \"minds the shop\", \"sleeps\".' },\n location: placeKey,\n feature: { type: 'string' },\n position: { type: 'string' },\n interruptible: { type: 'boolean', description: 'Whether it would drop this for something that comes up; true by default.' },\n },\n required: ['from', 'to', 'activity'],\n additionalProperties: false,\n },\n },\n },\n required: ['character', 'windows'],\n additionalProperties: false,\n },\n },\n slots: {\n type: 'array',\n description: 'Places on the body something can be worn, when the world needs one it does not have (a tail, a quiver on the back). The usual ones exist.',\n items: { type: 'object', properties: { id: { type: 'string', description: 'Short and lowercase.' }, name: { type: 'string' }, capacity: { type: 'integer', description: 'How many things can be worn there at once.' } }, required: ['id', 'name', 'capacity'], additionalProperties: false },\n },\n items: {\n type: 'array',\n description: 'Things the story makes up, only when it genuinely needs them: an object handed over, found or drawn. Each starts in exactly one of at (lying in a place), held_by (carried by a character), worn_by (worn by a character) or inside (in a container item). Leave out every field you have nothing to say about; never send an empty string.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'A short lowercase key that does not exist yet.' },\n name: { type: 'string' },\n description: { type: 'string' },\n quantity: { type: 'integer', description: 'How many, for things that come in numbers.' },\n unique: { type: 'boolean' },\n quality: { type: 'string', description: 'Its condition in words.' },\n notable: { type: 'boolean', description: 'Matters to the story.' },\n hidden: { type: 'boolean' },\n wearable: { type: 'string', description: 'The slot it is worn in.' },\n container: { type: 'object', properties: { state: { type: 'string', enum: [...CONTAINER_STATES] }, opened_by: { type: 'array', items: { type: 'string' } } }, additionalProperties: false },\n owner: character,\n at: { type: 'object', description: 'It lies in this place: {\"location\": the place\\'s key, \"feature\": a feature of the place such as its counter, \"position\": in words}.', properties: { location: placeKey, position: { type: 'string' }, feature: { type: 'string' } }, required: ['location'], additionalProperties: false },\n held_by: character,\n worn_by: character,\n worn_position: { type: 'string' },\n inside: { type: 'string', description: 'The key of the container item it is in.' },\n inside_position: { type: 'string' },\n note: { type: 'string', description: 'Why it was made, for whoever fits it into the world later.' },\n },\n required: ['key', 'name'],\n additionalProperties: false,\n },\n },\n places: {\n type: 'array',\n description: 'Places the story makes up or opens: a hidden passage, a room that was behind a door. Only for places that are not already known.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'A short lowercase key that does not exist yet.' },\n name: { type: 'string' },\n description: { type: 'string' },\n parent: placeKey,\n features: featureList,\n exits: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n to: placeKey,\n description: { type: 'string', description: 'What the way looks like from this place.' },\n one_way: { type: 'boolean', description: 'Leave out for a way that works both ways.' },\n back_description: { type: 'string' },\n travel_time_seconds: { type: 'integer' },\n state: { type: 'string', enum: [...EXIT_STATES] },\n note: { type: 'string' },\n },\n required: ['to'],\n additionalProperties: false,\n },\n },\n note: { type: 'string', description: 'Why it was made, for whoever fits it into the world later.' },\n },\n required: ['key', 'name'],\n additionalProperties: false,\n },\n },\n exits: {\n type: 'array',\n description: 'New ways between places that exist (or are made in this edit). Both directions unless one_way.',\n items: {\n type: 'object',\n properties: { from: placeKey, to: placeKey, description: { type: 'string' }, one_way: { type: 'boolean' }, back_description: { type: 'string' }, travel_time_seconds: { type: 'integer' }, state: { type: 'string', enum: [...EXIT_STATES] }, note: { type: 'string' } },\n required: ['from', 'to'],\n additionalProperties: false,\n },\n },\n characters: {\n type: 'array',\n description: 'People the story makes up, only when it genuinely needs them. Played by an agent from what is given here.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'A short lowercase key that does not exist yet.' },\n name: { type: 'string' },\n aliases: { type: 'array', items: { type: 'string' } },\n age: { type: 'string' },\n gender: { type: 'string' },\n pronouns: { type: 'string' },\n kind: { type: 'string', enum: [...CHARACTER_KINDS], description: 'person, or group for a crowd or organisation treated as one.' },\n tier: { type: 'string', enum: [...CHARACTER_TIERS], description: 'supporting by default; background for someone who only reacts.' },\n summary: { type: 'string', description: 'One or two sentences: who they are.' },\n personality: { type: 'string' },\n background: { type: 'string' },\n appearance: { type: 'string' },\n speech: { type: 'object', properties: { style: { type: 'string' }, examples: { type: 'array', items: { type: 'string' } } }, required: ['style'], additionalProperties: false },\n state: { type: 'object', properties: { public_state: { type: 'string' }, inner_state: { type: 'string' }, activity: { type: 'string' } }, additionalProperties: false },\n place: { type: 'object', properties: { location: placeKey, position: { type: 'string' }, feature: { type: 'string' } }, required: ['location'], additionalProperties: false },\n note: { type: 'string', description: 'Why they were made, for whoever fits them into the world later.' },\n },\n required: ['key', 'name', 'summary'],\n additionalProperties: false,\n },\n },\n })\n }\n if (options.changes === true) {\n Object.assign(properties, {\n event_edits: {\n type: 'array',\n description: 'Corrections to draft events of this run (a sealed event cannot change). Give only what changes; perceived_by replaces the whole list.',\n items: {\n type: 'object',\n properties: { id: { type: 'integer' }, text: { type: 'string' }, importance: IMPORTANCE, tags: { type: 'array', items: { type: 'string' } }, involves: keys, perceived_by: perceivedBy, location: placeKey },\n required: ['id'],\n additionalProperties: false,\n },\n },\n event_retractions: { type: 'array', items: { type: 'integer' }, description: 'Ids of recorded events that did not happen or duplicate another.' },\n perception_edits: {\n type: 'array',\n description: 'Revisions of what a character took in of an event (the ids are in read_records): it learned more, or remembers it differently. Allowed on any event.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n mode: { type: 'string', enum: [...PERCEPTION_MODES] },\n content: { type: 'string' },\n gist: { type: 'string' },\n accuracy: { type: 'string', enum: [...ACCURACIES] },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n perceptions_added: {\n type: 'array',\n description: 'A character that took in an earlier event only now (it was told, or worked it out). Allowed on any event.',\n items: {\n type: 'object',\n properties: {\n event: { type: 'integer' },\n character,\n mode: { type: 'string', enum: [...PERCEPTION_MODES] },\n content: { type: 'string' },\n gist: { type: 'string' },\n accuracy: { type: 'string', enum: [...ACCURACIES] },\n },\n required: ['event', 'character', 'mode'],\n additionalProperties: false,\n },\n },\n belief_edits: {\n type: 'array',\n items: { type: 'object', properties: { id: { type: 'integer' }, text: { type: 'string' }, about: keys, importance: IMPORTANCE }, required: ['id'], additionalProperties: false },\n },\n belief_retractions: { type: 'array', items: { type: 'integer' } },\n })\n }\n return { type: 'object', properties, required: ['turn'], additionalProperties: false }\n}\n","import {\n ACCURACIES, CHARACTER_KINDS, CHARACTER_TIERS, CONTAINER_STATES, EXIT_STATES, IMPORTANCE_MAX, IMPORTANCE_MIN, INTENT_HORIZONS, INTENT_TYPES, KNOWLEDGE_KINDS, MAX_LOCATION_FEATURES, MEMBERSHIP_STATUSES, MEMORY_KINDS, PERCEPTION_MODES, SLOT_ID,\n type CharacterId, type CharacterStatePatch, type Holder, type Location, type LocationFeature, type NewPerception, type RelationshipPatch,\n} from 'dsh-roleplay-model'\nimport { InvalidEditError, InvalidMoveError } from '../errors.ts'\nimport { lookupKey } from '../sqlite/support.ts'\nimport { characterKey, locationKey, type EditResult, type NewExit, type NewPlace, type PerceivedBy, type RecordsEdit, type RecordsTarget } from './edit-types.ts'\nimport { prepareAgenda, writeAgenda } from './agenda-edit.ts'\nimport { ITEM_ACTIONS, changeItem } from './items.ts'\nimport { moveCharacter } from './movement.ts'\nimport { triggerReferenceProblems } from './trigger-rules.ts'\nimport { changeVariable, planVariableChange } from './variables.ts'\n\nexport * from './edit-types.ts'\nexport { parseRecordsEdit, recordsEditSchema } from './wire.ts'\n\nconst present = (value: string | undefined): boolean => value !== undefined && value.trim() !== ''\nconst list = <T>(value: readonly T[] | undefined): readonly T[] => value ?? []\n\n/** Makes the triggers of an edit, after everything else in it, so that they can name what it made. @throws {InvalidEditError} naming each problem. */\nfunction createTriggers(target: RecordsTarget, edit: RecordsEdit): string[] {\n const made = list(edit.triggers)\n const keys = made.map(definition => definition.key)\n const problems = [\n ...made.flatMap(definition => triggerReferenceProblems(target, definition, keys)),\n ...keys.flatMap((key, index) => (keys.indexOf(key) === index ? [] : [`${key}: made twice in this edit`])),\n ...keys.flatMap(key => (target.triggers.getByKey(key) === undefined ? [] : [`${key}: there is already a trigger with this key`])),\n ]\n if (problems.length > 0) throw new InvalidEditError(problems)\n for (const definition of made) target.triggers.add(definition, 'story', edit.turn)\n return keys\n}\n\n/**\n * Apply an edit. Every problem is found before anything is written, so a bad edit changes nothing.\n * @throws {InvalidEditError} naming each problem.\n */\nfunction applyChanges(target: RecordsTarget, edit: RecordsEdit): EditResult {\n const characters = target.characters.list()\n const byKey = new Map(characters.map(character => [characterKey(character), character]))\n const problems: string[] = []\n const known = (): string => [...byKey.keys()].join(', ')\n const idOf = (key: string, where: string): CharacterId | undefined => {\n const found = byKey.get(key)\n if (found === undefined) problems.push(`${where}: there is no character \"${key}\" (the characters are: ${known()})`)\n return found?.id\n }\n const ids = (keys: readonly string[] | undefined, where: string): CharacterId[] => list(keys).flatMap(key => idOf(key, where) ?? [])\n const factionByKey = new Map(target.factions.list().map(faction => [faction.sourceId ?? String(faction.id), faction]))\n const factionIdOf = (key: string, where: string): number | undefined => { const found = factionByKey.get(key); if (found === undefined) problems.push(`${where}: there is no faction \"${key}\"`); return found?.id }\n const socialIdOf = (kind: 'character' | 'faction', key: string, where: string): number | undefined => kind === 'character' ? idOf(key, where) : factionIdOf(key, where)\n const importance = (value: number | undefined, where: string): void => {\n if (value !== undefined && (!Number.isInteger(value) || value < IMPORTANCE_MIN || value > IMPORTANCE_MAX)) problems.push(`${where}: importance must be a whole number from ${IMPORTANCE_MIN} to ${IMPORTANCE_MAX}`)\n }\n const perceptions = (text: string, given: readonly PerceivedBy[] | undefined, where: string): NewPerception[] => {\n const seen = new Set<string>()\n return list(given).flatMap((entry, index): NewPerception[] => {\n const at = `${where}.perceived_by[${index}]`\n const characterId = idOf(entry.character, at)\n if (seen.has(entry.character)) problems.push(`${at}: ${entry.character} is listed twice`)\n seen.add(entry.character)\n if (!PERCEPTION_MODES.includes(entry.mode)) problems.push(`${at}: unknown mode \"${String(entry.mode)}\"`)\n if (entry.accuracy !== undefined && !ACCURACIES.includes(entry.accuracy)) problems.push(`${at}: unknown accuracy \"${String(entry.accuracy)}\"`)\n if (characterId === undefined) return []\n const content = present(entry.content) ? entry.content!.trim() : text\n const gist = present(entry.gist) ? entry.gist!.trim() : content.length <= 80 ? content : `${content.slice(0, 77).trimEnd()}…`\n return [{ characterId, mode: entry.mode, content, gist, accuracy: entry.accuracy ?? 'accurate' }]\n })\n }\n const tags = (given: readonly string[] | undefined): string[] => [...new Set(list(given).map(tag => tag.trim().toLowerCase()).filter(tag => tag !== ''))]\n\n const existingPlaces = new Map(target.locations.list().map(place => [locationKey(place), place]))\n const newPlaceKeys = new Set<string>()\n const placeKnown = (key: string, where: string): void => {\n if (!existingPlaces.has(key) && !newPlaceKeys.has(key)) problems.push(`${where}: there is no place \"${key}\" (list_locations shows the keys)`)\n }\n const placeKeys = new Set(list(edit.places).map(place => place.key))\n list(edit.places).forEach((place, index) => {\n const where = `places[${index}]`\n if (!present(place.key)) problems.push(`${where}: give the place a key`)\n else if (existingPlaces.has(place.key) || newPlaceKeys.has(place.key)) problems.push(`${where}: the key \"${place.key}\" is already used by a place`)\n if (!present(place.name)) problems.push(`${where}: give the place a name`)\n if (place.parent !== undefined) placeKnown(place.parent, `${where}.parent`)\n if (list(place.features).length > MAX_LOCATION_FEATURES) problems.push(`${where}: a place has at most ${MAX_LOCATION_FEATURES} features`)\n newPlaceKeys.add(place.key)\n for (const [at, exit] of list(place.exits).entries()) {\n if (!existingPlaces.has(exit.to) && !placeKeys.has(exit.to)) problems.push(`${where}.exits[${at}]: there is no place \"${exit.to}\"`)\n if (exit.to === place.key) problems.push(`${where}.exits[${at}]: an exit must lead to another place`)\n if (exit.state !== undefined && !EXIT_STATES.includes(exit.state)) problems.push(`${where}.exits[${at}]: unknown state \"${String(exit.state)}\"`)\n }\n })\n list(edit.placeEdits).forEach((change, index) => {\n const where = `place_edits[${index}]`\n placeKnown(change.place, where)\n if (change.name !== undefined && !present(change.name)) problems.push(`${where}: a place needs a name`)\n if (list(change.features).length > MAX_LOCATION_FEATURES) problems.push(`${where}: a place has at most ${MAX_LOCATION_FEATURES} features`)\n })\n list(edit.exitChanges).forEach((change, index) => {\n const where = `exit_changes[${index}]`\n placeKnown(change.from, `${where}.from`)\n placeKnown(change.to, `${where}.to`)\n if (change.state !== undefined && !EXIT_STATES.includes(change.state)) problems.push(`${where}: unknown state \"${String(change.state)}\"`)\n const from = existingPlaces.get(change.from)\n const to = existingPlaces.get(change.to)\n if (from !== undefined && to !== undefined && target.locations.getExit(from.id, to.id) === undefined) problems.push(`${where}: there is no exit from \"${change.from}\" to \"${change.to}\"`)\n })\n list(edit.moves).forEach((move, index) => {\n const where = `moves[${index}]`\n idOf(move.character, where)\n placeKnown(move.to, `${where}.to`)\n })\n list(edit.exits).forEach((wanted, index) => {\n const where = `exits[${index}]`\n placeKnown(wanted.from, `${where}.from`)\n placeKnown(wanted.to, `${where}.to`)\n if (wanted.from === wanted.to) problems.push(`${where}: an exit must lead to another place`)\n if (wanted.state !== undefined && !EXIT_STATES.includes(wanted.state)) problems.push(`${where}: unknown state \"${String(wanted.state)}\"`)\n const from = existingPlaces.get(wanted.from)\n const to = existingPlaces.get(wanted.to)\n if (from !== undefined && to !== undefined && target.locations.getExit(from.id, to.id) !== undefined && wanted.oneWay === true) problems.push(`${where}: there already is an exit from \"${wanted.from}\" to \"${wanted.to}\" (change it with exit_changes)`)\n })\n const RELATION_RANGES = { familiarity: [0, 1], trust: [-1, 1], affinity: [-1, 1], tension: [0, 1] } as const\n list(edit.relationships).forEach((relation, index) => {\n const where = `relationships[${index}]`\n const from = idOf(relation.from, `${where}.from`)\n const to = idOf(relation.to, `${where}.to`)\n if (relation.from === relation.to) problems.push(`${where}: a character has no relationship with itself`)\n for (const [axis, [min, max]] of Object.entries(RELATION_RANGES) as [keyof typeof RELATION_RANGES, readonly [number, number]][]) {\n const value = relation[axis]\n if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) problems.push(`${where}: ${axis} must be a number from ${min} to ${max}`)\n }\n if (relation.label !== undefined && !present(relation.label)) problems.push(`${where}: the label cannot be empty`)\n if (from !== undefined && to !== undefined && target.relationships.get(from, to) === undefined && !present(relation.label)) problems.push(`${where}: a new relationship needs a label (\"${relation.from}\" towards \"${relation.to}\")`)\n })\n list(edit.relationshipRetractions).forEach((retraction, index) => {\n const where = `relationship_retractions[${index}]`\n const from = idOf(retraction.from, `${where}.from`)\n const to = idOf(retraction.to, `${where}.to`)\n if (from !== undefined && to !== undefined && target.relationships.get(from, to) === undefined) problems.push(`${where}: \"${retraction.from}\" has no relationship with \"${retraction.to}\"`)\n })\n const itemFor = (key: string) => target.items.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.items.get(Number(key)) : undefined)\n const knowledgeSubject = (entry: { kind: string; subject?: string; from?: string; to?: string }, where: string): { kind: 'location' | 'item' | 'exit'; id: number } | undefined => {\n if (!KNOWLEDGE_KINDS.includes(entry.kind as never)) { problems.push(`${where}: unknown kind \"${entry.kind}\"`); return undefined }\n if (entry.kind === 'location') {\n const place = entry.subject === undefined ? undefined : existingPlaces.get(entry.subject)\n if (place === undefined) problems.push(`${where}.subject: there is no place \"${entry.subject ?? ''}\"`)\n return place === undefined ? undefined : { kind: 'location', id: place.id }\n }\n if (entry.kind === 'item') {\n const item = entry.subject === undefined ? undefined : itemFor(entry.subject)\n if (item === undefined) problems.push(`${where}.subject: there is no item \"${entry.subject ?? ''}\"`)\n return item === undefined ? undefined : { kind: 'item', id: item.id }\n }\n const from = entry.from === undefined ? undefined : existingPlaces.get(entry.from)\n const to = entry.to === undefined ? undefined : existingPlaces.get(entry.to)\n const exit = from === undefined || to === undefined ? undefined : target.locations.getExit(from.id, to.id)\n if (exit === undefined) problems.push(`${where}: there is no exit from \"${entry.from ?? ''}\" to \"${entry.to ?? ''}\"`)\n return exit === undefined ? undefined : { kind: 'exit', id: exit.id }\n }\n const knowledge = list(edit.knowledge).map((entry, index) => ({ entry, character: idOf(entry.character, `knowledge[${index}].character`), subject: knowledgeSubject(entry, `knowledge[${index}]`) }))\n const knowledgeRetractions = list(edit.knowledgeRetractions).map((entry, index) => {\n const character = idOf(entry.character, `knowledge_retractions[${index}].character`)\n const subject = knowledgeSubject(entry, `knowledge_retractions[${index}]`)\n if (character !== undefined && subject !== undefined && !target.knowledge.knows(character, subject.kind, subject.id)) problems.push(`knowledge_retractions[${index}]: the character does not know that entity`)\n return { character, subject }\n })\n const factionStates = list(edit.factionStates).map((entry, index) => {\n const where = `faction_states[${index}]`\n if (entry.publicState === undefined && entry.innerState === undefined) problems.push(`${where}: nothing to change`)\n return { entry, faction: factionIdOf(entry.faction, where) }\n })\n const factionMemberships = list(edit.factionMemberships).map((entry, index) => {\n const where = `faction_memberships[${index}]`\n const faction = factionIdOf(entry.faction, `${where}.faction`)\n const character = idOf(entry.character, `${where}.character`)\n if (entry.status !== undefined && !MEMBERSHIP_STATUSES.includes(entry.status)) problems.push(`${where}: unknown status \"${String(entry.status)}\"`)\n if (entry.commitment !== undefined && (!Number.isFinite(entry.commitment) || entry.commitment < 0 || entry.commitment > 1)) problems.push(`${where}: commitment must be a number from 0 to 1`)\n return { entry, faction, character }\n })\n const factionRelationships = list(edit.factionRelationships).map((entry, index) => {\n const where = `faction_relationships[${index}]`\n if (!['character', 'faction'].includes(entry.fromKind)) problems.push(`${where}.from_kind: must be character or faction`)\n if (!['character', 'faction'].includes(entry.toKind)) problems.push(`${where}.to_kind: must be character or faction`)\n const from = socialIdOf(entry.fromKind, entry.from, `${where}.from`)\n const to = socialIdOf(entry.toKind, entry.to, `${where}.to`)\n if (entry.fromKind === entry.toKind && entry.from === entry.to) problems.push(`${where}: an entity has no relationship with itself`)\n if (from !== undefined && to !== undefined && target.factionRelationships.get(entry.fromKind, from, entry.toKind, to) === undefined && !present(entry.label)) problems.push(`${where}: a new relationship needs a label`)\n for (const [axis, [min, max]] of Object.entries(RELATION_RANGES) as [keyof typeof RELATION_RANGES, readonly [number, number]][]) { const value = entry[axis]; if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) problems.push(`${where}: ${axis} must be a number from ${min} to ${max}`) }\n return { entry, from, to }\n })\n const factionIntents = list(edit.factionIntentsAdded).map((entry, index) => {\n const where = `faction_intents_added[${index}]`\n const faction = factionIdOf(entry.faction, `${where}.faction`)\n if (!INTENT_TYPES.includes(entry.type)) problems.push(`${where}: unknown type \"${String(entry.type)}\"`)\n if (!INTENT_HORIZONS.includes(entry.horizon)) problems.push(`${where}: unknown horizon \"${String(entry.horizon)}\"`)\n if (!present(entry.name)) problems.push(`${where}: give the goal a name`)\n for (const [key, value] of [['priority', entry.priority], ['urgency', entry.urgency]] as const) if (!Number.isFinite(value) || value < 0 || value > 1) problems.push(`${where}.${key}: must be a number from 0 to 1`)\n return { entry, faction }\n })\n list(edit.itemChanges).forEach((change, index) => {\n const where = `item_changes[${index}]`\n idOf(change.character, where)\n if (!ITEM_ACTIONS.includes(change.action)) problems.push(`${where}: unknown action \"${String(change.action)}\" (the actions are: ${ITEM_ACTIONS.join(', ')})`)\n if (change.exit === undefined && itemFor(change.item) === undefined) problems.push(`${where}: there is no item \"${change.item}\" (list_items shows the keys)`)\n })\n list(edit.itemEdits).forEach((change, index) => {\n const where = `item_edits[${index}]`\n const item = itemFor(change.item)\n if (item === undefined) { problems.push(`${where}: there is no item \"${change.item}\"`); return }\n if (change.state !== undefined && (item.container === undefined || !CONTAINER_STATES.includes(change.state))) problems.push(`${where}: ${item.container === undefined ? `${item.name} is not a container` : `unknown container state \"${String(change.state)}\"`}`)\n if (change.quantity !== undefined && (!Number.isInteger(change.quantity) || change.quantity < 1)) problems.push(`${where}: the quantity must be a whole number from 1`)\n if (change.owner !== undefined && !byKey.has(change.owner)) problems.push(`${where}.owner: there is no character \"${change.owner}\"`)\n for (const key of list(change.openedBy)) if (itemFor(key) === undefined) problems.push(`${where}.opened_by: there is no item \"${key}\"`)\n if (change.openedBy !== undefined && item.container === undefined) problems.push(`${where}: ${item.name} is not a container, so nothing opens it`)\n if (change.description !== undefined && !present(change.description)) problems.push(`${where}: the description cannot be empty`)\n })\n list(edit.events).forEach((event, index) => { for (const key of list(event.items)) if (itemFor(key) === undefined) problems.push(`events[${index}].items: there is no item \"${key}\"`) })\n const placeIn = (key: string | undefined, where: string): void => { if (key !== undefined) placeKnown(key, where) }\n list(edit.events).forEach((event, index) => { placeIn(event.location, `events[${index}].location`) })\n list(edit.eventEdits).forEach((change, index) => { placeIn(change.location, `event_edits[${index}].location`) })\n\n if (!Number.isInteger(edit.turn) || edit.turn < 1) problems.push('turn must be a whole number from 1')\n\n const states = list(edit.states).flatMap((patch, index) => {\n const where = `states[${index}]`\n const id = idOf(patch.character, where)\n if (!present(patch.publicState) && !present(patch.innerState) && !present(patch.activity)) problems.push(`${where}: nothing to change`)\n return id === undefined ? [] : [{ id, patch }]\n })\n\n const events = list(edit.events).flatMap((event, index) => {\n const where = `events[${index}]`\n if (!present(event.text)) problems.push(`${where}: say what happened`)\n if (!Number.isInteger(event.turn) || event.turn < 1 || !Number.isInteger(event.round) || event.round < 1) problems.push(`${where}: turn and round must be whole numbers from 1`)\n importance(event.importance, where)\n return [{ event, involves: ids(event.involves, `${where}.involves`), perceived: perceptions(event.text.trim(), event.perceivedBy, where) }]\n })\n\n const eventEdits = list(edit.eventEdits).map((change, index) => {\n const where = `event_edits[${index}]`\n const current = target.events.get(change.id)\n if (current === undefined) problems.push(`${where}: there is no event ${change.id}`)\n else if (current.sealed) problems.push(`${where}: event ${change.id} is sealed and cannot change; what a character took in of it can be revised with perception_edits, and later knowledge added with perceptions_added`)\n if (change.text !== undefined && !present(change.text)) problems.push(`${where}: say what happened`)\n importance(change.importance, where)\n return { change, current, involves: change.involves === undefined ? undefined : ids(change.involves, `${where}.involves`), perceived: change.perceivedBy === undefined ? undefined : perceptions((change.text ?? current?.text ?? '').trim(), change.perceivedBy, where) }\n })\n for (const id of list(edit.eventRetractions)) {\n const current = target.events.get(id)\n if (current === undefined) problems.push(`event_retractions: there is no event ${id}`)\n else if (current.sealed) problems.push(`event_retractions: event ${id} is sealed and cannot be removed`)\n }\n\n const perceptionEdits = list(edit.perceptionEdits).map((change, index) => {\n const where = `perception_edits[${index}]`\n const current = target.events.getPerception(change.id)\n if (current === undefined) problems.push(`${where}: there is no perception ${change.id}`)\n if (change.mode !== undefined && !PERCEPTION_MODES.includes(change.mode)) problems.push(`${where}: unknown mode \"${String(change.mode)}\"`)\n if (change.accuracy !== undefined && !ACCURACIES.includes(change.accuracy)) problems.push(`${where}: unknown accuracy \"${String(change.accuracy)}\"`)\n if (change.content !== undefined && !present(change.content)) problems.push(`${where}: content cannot be empty`)\n return change\n })\n const perceptionsAdded = list(edit.perceptionsAdded).flatMap((added, index) => {\n const where = `perceptions_added[${index}]`\n const event = target.events.get(added.event)\n if (event === undefined) { problems.push(`${where}: there is no event ${added.event}`); return [] }\n const [one] = perceptions(event.text, [added], where)\n const characterId = byKey.get(added.character)?.id\n if (characterId !== undefined && target.events.perceptionsOf(added.event).some(entry => entry.characterId === characterId)) problems.push(`${where}: ${added.character} already has a perception of event ${added.event}: revise it with perception_edits`)\n return one === undefined ? [] : [{ eventId: added.event, perception: one }]\n })\n\n const beliefs = list(edit.beliefs).flatMap((belief, index) => {\n const where = `beliefs[${index}]`\n const character = idOf(belief.character, where)\n if (!MEMORY_KINDS.includes(belief.kind)) problems.push(`${where}: unknown kind \"${String(belief.kind)}\"`)\n if (!present(belief.text)) problems.push(`${where}: say what the character believes or knows`)\n importance(belief.importance, where)\n return character === undefined ? [] : [{ belief, character, about: ids(belief.about, `${where}.about`) }]\n })\n const beliefEdits = list(edit.beliefEdits).map((change, index) => {\n const where = `belief_edits[${index}]`\n if (target.memories.get(change.id) === undefined) problems.push(`${where}: there is no belief ${change.id}`)\n if (change.text !== undefined && !present(change.text)) problems.push(`${where}: say what the character believes or knows`)\n importance(change.importance, where)\n return { change, about: change.about === undefined ? undefined : ids(change.about, `${where}.about`) }\n })\n for (const id of list(edit.beliefRetractions)) if (target.memories.get(id) === undefined) problems.push(`belief_retractions: there is no belief ${id}`)\n for (const [index, text] of list(edit.threadsOpened).entries()) if (!present(text)) problems.push(`threads_opened[${index}]: say what is unsettled`)\n for (const id of list(edit.threadsResolved)) if (target.threads.get(id) === undefined) problems.push(`threads_resolved: there is no thread ${id}`)\n\n list(edit.variableChanges).forEach((change, index) => {\n const where = `variable_changes[${index}]`\n if (list(edit.variables).some(def => def.key === change.variable)) return\n const planned = planVariableChange(target, change)\n if (!planned.ok) problems.push(...planned.problems.map(problem => `${where}: ${problem}`))\n })\n const agenda = prepareAgenda(target, edit, { idOf, placeKnown, places: existingPlaces, problems })\n\n if (problems.length > 0) throw new InvalidEditError(problems)\n\n return target.transaction(() => {\n const result: EditResult = { eventIds: [], beliefIds: [], writes: 0 }\n const learnEventEntities = (event: { turn: number; locationId?: number; items: readonly number[]; involves: readonly number[] }, characterId: number): void => {\n if (event.locationId !== undefined) target.knowledge.learn(characterId, 'location', event.locationId, event.turn)\n for (const itemId of event.items) target.knowledge.learn(characterId, 'item', itemId, event.turn)\n for (const otherId of event.involves) if (otherId !== characterId && target.relationships.get(characterId, otherId) === undefined) target.relationships.upsert(characterId, otherId, { label: 'acquaintance' }, event.turn)\n }\n const placeOf = (key: string): Location => {\n const found = target.locations.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.locations.get(Number(key)) : undefined)\n if (found === undefined) throw new InvalidEditError([`there is no place \"${key}\"`])\n return found\n }\n const features = (given: readonly { key: string; name: string; description?: string }[] | undefined): LocationFeature[] => list(given).map(feature => ({ key: feature.key, name: feature.name, description: feature.description ?? '' }))\n const exit = (from: Location, to: Location, description: string | undefined, rest: Pick<NewExit, 'travelSeconds' | 'state' | 'note'>): void => {\n if (target.locations.getExit(from.id, to.id) !== undefined) return\n target.locations.addExit({ fromId: from.id, toId: to.id, description: description ?? '', ...(rest.travelSeconds === undefined ? {} : { travelSeconds: rest.travelSeconds }), ...(rest.state === undefined ? {} : { state: rest.state }), ...(rest.note === undefined ? {} : { note: rest.note }) })\n result.writes += 1\n }\n result.placeKeys = []\n for (const place of list(edit.places)) {\n const added = target.locations.add({ sourceId: place.key, name: place.name, description: place.description ?? '', ...(place.parent === undefined ? {} : { parentId: placeOf(place.parent).id }), features: features(place.features) })\n target.consolidation.enqueue({ kind: 'location', subjectId: added.id, note: place.note ?? 'made up in play', turn: edit.turn })\n result.placeKeys.push(place.key)\n result.writes += 1\n }\n for (const place of list(edit.places)) {\n const from = placeOf(place.key)\n for (const wanted of list(place.exits)) {\n const to = placeOf(wanted.to)\n exit(from, to, wanted.description, wanted)\n if (wanted.oneWay !== true) exit(to, from, wanted.backDescription ?? wanted.description, wanted)\n }\n }\n for (const wanted of list(edit.exits)) {\n const from = placeOf(wanted.from)\n const to = placeOf(wanted.to)\n exit(from, to, wanted.description, wanted)\n if (wanted.oneWay !== true) exit(to, from, wanted.backDescription ?? wanted.description, wanted)\n }\n for (const relation of list(edit.relationships)) {\n const { from, to, ...fields } = relation\n const patch: RelationshipPatch = {\n ...(fields.label === undefined ? {} : { label: fields.label }), ...(fields.summary === undefined ? {} : { summary: fields.summary }),\n ...(fields.familiarity === undefined ? {} : { familiarity: fields.familiarity }), ...(fields.trust === undefined ? {} : { trust: fields.trust }),\n ...(fields.affinity === undefined ? {} : { affinity: fields.affinity }), ...(fields.tension === undefined ? {} : { tension: fields.tension }),\n }\n target.relationships.upsert(byKey.get(from)!.id, byKey.get(to)!.id, patch, edit.turn)\n result.writes += 1\n }\n for (const retraction of list(edit.relationshipRetractions)) {\n target.relationships.remove(byKey.get(retraction.from)!.id, byKey.get(retraction.to)!.id)\n result.writes += 1\n }\n for (const { entry, character, subject } of knowledge) {\n target.knowledge.learn(character!, subject!.kind, subject!.id, edit.turn, entry.observed === true)\n result.writes += 1\n }\n for (const { character, subject } of knowledgeRetractions) {\n target.knowledge.forget(character!, subject!.kind, subject!.id)\n result.writes += 1\n }\n for (const { entry, faction } of factionStates) {\n target.factionStates.update(faction!, { ...(entry.publicState === undefined ? {} : { publicState: entry.publicState }), ...(entry.innerState === undefined ? {} : { innerState: entry.innerState }) })\n result.writes += 1\n }\n for (const { entry, faction, character } of factionMemberships) {\n const { faction: _faction, character: _character, ...patch } = entry\n target.factionMemberships.upsert(faction!, character!, patch, edit.turn)\n if (target.factionRelationships.get('character', character!, 'faction', faction!) === undefined) target.factionRelationships.upsert('character', character!, 'faction', faction!, { label: entry.role || 'member', familiarity: 1 }, edit.turn)\n result.writes += 1\n }\n for (const { entry, from, to } of factionRelationships) {\n const { fromKind, from: _from, toKind, to: _to, ...patch } = entry\n target.factionRelationships.upsert(fromKind, from!, toKind, to!, patch, edit.turn)\n result.writes += 1\n }\n for (const { entry, faction } of factionIntents) {\n target.factionIntents.add(faction!, { type: entry.type, name: entry.name.trim(), description: entry.description?.trim() ?? '', status: 'active', horizon: entry.horizon, priority: entry.priority, urgency: entry.urgency, plan: entry.plan ?? [], openThreads: [], constraints: entry.constraints ?? [], ...(entry.deadline === undefined ? {} : { deadline: entry.deadline }) })\n result.writes += 1\n }\n for (const change of list(edit.placeEdits)) {\n target.locations.update(placeOf(change.place).id, {\n ...(change.name === undefined ? {} : { name: change.name }),\n ...(change.description === undefined ? {} : { description: change.description }),\n ...(change.features === undefined ? {} : { features: features(change.features) }),\n })\n result.writes += 1\n }\n for (const change of list(edit.exitChanges)) {\n const from = placeOf(change.from)\n const to = placeOf(change.to)\n const sides = change.oneWay === true ? [[from, to]] as const : [[from, to], [to, from]] as const\n let found = false\n for (const [a, b] of sides) {\n const current = target.locations.getExit(a.id, b.id)\n if (current === undefined) continue\n found = true\n target.locations.updateExit(current.id, {\n ...(change.state === undefined ? {} : { state: change.state }),\n ...(change.description === undefined || a !== from ? {} : { description: change.description }),\n ...(change.note === undefined ? {} : { note: change.note }),\n ...(change.travelSeconds === undefined ? {} : { travelSeconds: change.travelSeconds }),\n })\n result.writes += 1\n }\n if (!found) throw new InvalidEditError([`there is no exit from \"${change.from}\" to \"${change.to}\"`])\n }\n for (const [index, change] of list(edit.itemChanges).entries()) {\n const { character: who, ...spec } = change\n try {\n changeItem(target, byKey.get(who)!.id, spec)\n } catch (error) {\n if (error instanceof InvalidMoveError) throw new InvalidEditError(error.problems.map(problem => `item_changes[${index}]: ${problem}`))\n throw error\n }\n result.writes += 1\n }\n for (const change of list(edit.itemEdits)) {\n const item = itemFor(change.item)!\n target.items.update(item.id, {\n ...(change.description === undefined ? {} : { description: change.description }), ...(change.quality === undefined ? {} : { quality: change.quality }),\n ...(change.quantity === undefined ? {} : { quantity: change.quantity }), ...(change.notable === undefined ? {} : { notable: change.notable }),\n ...(change.hidden === undefined ? {} : { hidden: change.hidden }), ...(change.state === undefined ? {} : { container: { state: change.state } }),\n ...(change.owner === undefined ? {} : { ownerId: byKey.get(change.owner)!.id }),\n })\n if (change.openedBy !== undefined) target.items.setOpeners({ kind: 'item', id: item.id }, change.openedBy.map(key => itemFor(key)!.id))\n result.writes += 1\n }\n for (const [index, move] of list(edit.moves).entries()) {\n const character = byKey.get(move.character)!\n try {\n moveCharacter(target, character.id, { to: placeOf(move.to).id, ...(move.position === undefined ? {} : { position: move.position }), ...(move.feature === undefined ? {} : { featureKey: move.feature }), ...(move.ignoreExits === true ? { ignoreExits: true } : {}) })\n } catch (error) {\n if (error instanceof InvalidMoveError) throw new InvalidEditError(error.problems.map(problem => `moves[${index}]: ${problem}`))\n throw error\n }\n result.writes += 1\n }\n for (const { id, patch } of states) {\n const current = target.characterStates.get(id)\n const { character: _character, ...fields } = patch\n const written: CharacterStatePatch = {\n ...(present(fields.publicState) ? { publicState: fields.publicState!.trim() } : {}),\n ...(present(fields.innerState) ? { innerState: fields.innerState!.trim() } : {}),\n ...(present(fields.activity) ? { activity: fields.activity!.trim() } : {}),\n }\n if (current === undefined) {\n target.characterStates.create(id, { publicState: written.publicState ?? '', innerState: written.innerState ?? '', activity: written.activity ?? '' })\n } else {\n target.characterStates.update(id, written)\n }\n result.writes += 1\n }\n for (const { event, involves, perceived } of events) {\n const { event: stored } = target.events.add({ turn: event.turn, round: event.round, text: event.text.trim(), importance: event.importance, tags: tags(event.tags), involves, ...(event.items === undefined ? {} : { items: event.items.map(key => itemFor(key)!.id) }), ...(event.location === undefined ? {} : { locationId: placeOf(event.location).id }) }, perceived)\n for (const perception of perceived) learnEventEntities(stored, perception.characterId)\n result.eventIds.push(stored.id)\n result.writes += 1\n }\n for (const { change, involves, perceived } of eventEdits) {\n target.events.update(change.id, {\n ...(change.text === undefined ? {} : { text: change.text.trim() }),\n ...(change.importance === undefined ? {} : { importance: change.importance }),\n ...(change.tags === undefined ? {} : { tags: tags(change.tags) }),\n ...(involves === undefined ? {} : { involves }),\n ...(change.location === undefined ? {} : { locationId: placeOf(change.location).id }),\n })\n if (perceived !== undefined) target.events.setPerceptions(change.id, perceived)\n result.writes += 1\n }\n for (const id of list(edit.eventRetractions)) { target.events.remove(id); result.writes += 1 }\n for (const change of perceptionEdits) {\n target.events.updatePerception(change.id, {\n ...(change.mode === undefined ? {} : { mode: change.mode }),\n ...(change.content === undefined ? {} : { content: change.content.trim() }),\n ...(change.gist === undefined ? {} : { gist: change.gist.trim() }),\n ...(change.accuracy === undefined ? {} : { accuracy: change.accuracy }),\n })\n result.writes += 1\n }\n for (const { eventId, perception } of perceptionsAdded) {\n target.events.addPerception(eventId, perception)\n learnEventEntities(target.events.get(eventId)!, perception.characterId)\n result.writes += 1\n }\n for (const { belief, character, about } of beliefs) {\n result.beliefIds.push(target.memories.add({ characterId: character, kind: belief.kind, text: belief.text.trim(), about, importance: belief.importance, turn: edit.turn }).id)\n result.writes += 1\n }\n for (const { change, about } of beliefEdits) {\n target.memories.update(change.id, {\n ...(change.text === undefined ? {} : { text: change.text.trim() }),\n ...(about === undefined ? {} : { about }),\n ...(change.importance === undefined ? {} : { importance: change.importance }),\n })\n result.writes += 1\n }\n for (const id of list(edit.beliefRetractions)) { target.memories.remove(id); result.writes += 1 }\n for (const text of list(edit.threadsOpened)) { target.threads.open(text.trim(), edit.turn); result.writes += 1 }\n for (const id of list(edit.threadsResolved)) { target.threads.resolve(id, edit.turn); result.writes += 1 }\n result.variableKeys = []\n for (const [index, spec] of list(edit.variables).entries()) {\n try {\n target.variables.define(spec)\n result.variableKeys.push(spec.key)\n } catch (error) {\n throw error instanceof Error ? new InvalidEditError([`variables[${index}]: ${error.message}`]) : error\n }\n result.writes += 1\n }\n for (const [index, change] of list(edit.variableChanges).entries()) {\n try {\n changeVariable(target, change, edit.turn)\n } catch (error) {\n if (error instanceof InvalidEditError) throw new InvalidEditError(error.problems.map(problem => `variable_changes[${index}]: ${problem}`))\n throw error\n }\n result.writes += 1\n }\n result.writes += writeAgenda(target, agenda, edit.turn, key => placeOf(key).id)\n return result\n })\n}\n\n/**\n * Make up the characters of an edit: validated first, then written with their state and place, and each\n * one is queued to be fitted into the rest of the world. Nothing is written when anything is wrong.\n */\nfunction createCharacters(target: RecordsTarget, edit: RecordsEdit): { keys: string[]; writes: number } {\n const problems: string[] = []\n const taken = new Set(target.characters.list().flatMap(character => [lookupKey(character.name), ...character.aliases.map(lookupKey)]))\n const keys = new Set(target.characters.list().map(characterKey))\n const placeFor = (key: string): Location | undefined => target.locations.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.locations.get(Number(key)) : undefined)\n const wanted = list(edit.characters)\n wanted.forEach((spec, index) => {\n const where = `characters[${index}]`\n if (!present(spec.key) || !/^[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,59}$/u.test(spec.key)) problems.push(`${where}: give the character a key of letters (any script), digits, \"-\" or \"_\"`)\n else if (keys.has(spec.key)) problems.push(`${where}: the key \"${spec.key}\" is already used by a character`)\n keys.add(spec.key)\n if (!present(spec.name)) problems.push(`${where}: give the character a name`)\n if (!present(spec.summary)) problems.push(`${where}: give the character a summary of a sentence or two`)\n for (const name of [spec.name, ...list(spec.aliases)]) {\n const found = lookupKey(name ?? '')\n if (found === '') continue\n if (taken.has(found)) problems.push(`${where}: \"${name}\" is already the name of a character: reuse that one instead of making another`)\n taken.add(found)\n }\n if (spec.kind !== undefined && !CHARACTER_KINDS.includes(spec.kind)) problems.push(`${where}: unknown kind \"${String(spec.kind)}\"`)\n if (spec.tier !== undefined && !CHARACTER_TIERS.includes(spec.tier)) problems.push(`${where}: unknown tier \"${String(spec.tier)}\"`)\n if (spec.place !== undefined) {\n const place = placeFor(spec.place.location)\n if (place === undefined) problems.push(`${where}.place: there is no place \"${spec.place.location}\" (list_locations shows the keys)`)\n else if (spec.place.feature !== undefined && !place.features.some(feature => feature.key === spec.place!.feature)) problems.push(`${where}.place: ${place.name} has no feature \"${spec.place.feature}\"`)\n }\n })\n if (problems.length > 0) throw new InvalidEditError(problems)\n for (const spec of wanted) {\n const character = target.characters.add({\n sourceId: spec.key, name: spec.name.trim(), aliases: list(spec.aliases).map(alias => alias.trim()).filter(alias => alias !== '' && lookupKey(alias) !== lookupKey(spec.name)),\n ...(spec.age === undefined ? {} : { age: spec.age }), ...(spec.gender === undefined ? {} : { gender: spec.gender }), ...(spec.pronouns === undefined ? {} : { pronouns: spec.pronouns }),\n kind: spec.kind ?? 'person', tier: spec.tier ?? 'supporting', role: 'npc', control: 'agent',\n summary: spec.summary.trim(), personality: (spec.personality ?? '').trim(), background: (spec.background ?? '').trim(), appearance: (spec.appearance ?? '').trim(),\n speech: { style: (spec.speech?.style ?? '').trim(), examples: list(spec.speech?.examples) as string[] },\n })\n target.characterStates.create(character.id, { publicState: (spec.state?.publicState ?? '').trim(), innerState: (spec.state?.innerState ?? '').trim(), activity: (spec.state?.activity ?? '').trim() })\n if (spec.place !== undefined) {\n target.placements.place('character', character.id, { locationId: placeFor(spec.place.location)!.id, ...(spec.place.position === undefined ? {} : { position: spec.place.position }), ...(spec.place.feature === undefined ? {} : { featureKey: spec.place.feature }) })\n }\n target.consolidation.enqueue({ kind: 'character', subjectId: character.id, note: spec.note ?? 'made up in play', turn: edit.turn })\n }\n return { keys: wanted.map(spec => spec.key), writes: wanted.length }\n}\n\n/**\n * Make up the slots and items of an edit: validated first, then written, each item put where it starts and\n * queued to be fitted into the world. Containers that hold other new items are made first.\n */\nfunction createItems(target: RecordsTarget, edit: RecordsEdit): { keys: string[]; writes: number } {\n const problems: string[] = []\n const slotsWanted = list(edit.slots)\n slotsWanted.forEach((slot, index) => {\n const where = `slots[${index}]`\n if (!SLOT_ID.test(slot.id)) problems.push(`${where}: the id must be lowercase letters, digits, \"-\" or \"_\"`)\n if (!present(slot.name)) problems.push(`${where}: give the slot a name`)\n if (!Number.isInteger(slot.capacity) || slot.capacity < 1) problems.push(`${where}: the capacity must be a whole number from 1`)\n })\n const slotIds = new Set([...target.slots.list().map(slot => slot.id), ...slotsWanted.map(slot => slot.id)])\n const wanted = list(edit.items)\n const newKeys = new Set(wanted.map(spec => spec.key))\n const known = (key: string): boolean => target.items.getBySourceId(key) !== undefined || (Number.isInteger(Number(key)) && target.items.get(Number(key)) !== undefined) || newKeys.has(key)\n const placeFor = (key: string): Location | undefined => target.locations.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.locations.get(Number(key)) : undefined)\n const characterFor = (key: string) => target.characters.list().find(character => characterKey(character) === key)\n const seen = new Set<string>()\n wanted.forEach((spec, index) => {\n const where = `items[${index}]`\n if (!present(spec.key) || !/^[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,59}$/u.test(spec.key)) problems.push(`${where}: give the item a key of letters (any script), digits, \"-\" or \"_\"`)\n else if (target.items.getBySourceId(spec.key) !== undefined || seen.has(spec.key)) problems.push(`${where}: the key \"${spec.key}\" is already used by an item`)\n seen.add(spec.key)\n if (!present(spec.name)) problems.push(`${where}: give the item a name`)\n if (spec.quantity !== undefined && (!Number.isInteger(spec.quantity) || spec.quantity < 1)) problems.push(`${where}: the quantity must be a whole number from 1`)\n if (spec.unique === true && (spec.quantity ?? 1) > 1) problems.push(`${where}: a unique item is one thing`)\n if (spec.wearable !== undefined && !slotIds.has(spec.wearable)) problems.push(`${where}: there is no slot \"${spec.wearable}\" (the slots are: ${[...slotIds].join(', ')}; make a new one in slots when the world needs it)`)\n if (spec.container?.state !== undefined && !CONTAINER_STATES.includes(spec.container.state)) problems.push(`${where}: unknown container state \"${String(spec.container.state)}\"`)\n for (const key of list(spec.container?.openedBy)) if (!known(key)) problems.push(`${where}.container.opened_by: there is no item \"${key}\"`)\n if (spec.owner !== undefined && characterFor(spec.owner) === undefined) problems.push(`${where}.owner: there is no character \"${spec.owner}\"`)\n const holders = [spec.at, spec.heldBy, spec.wornBy, spec.inside].filter(holder => holder !== undefined).length\n if (holders !== 1) problems.push(`${where}: say where it starts with exactly one of at (lying in a place: {\"location\": place key}), held_by (a character's key), worn_by (a character's key) or inside (a container item's key)${holders === 0 ? '; it has none yet' : '; it has more than one'}`)\n if (spec.at !== undefined) {\n const place = placeFor(spec.at.location)\n if (place === undefined) problems.push(`${where}.at: there is no place \"${spec.at.location}\"`)\n else if (spec.at.feature !== undefined && !place.features.some(feature => feature.key === spec.at!.feature)) problems.push(`${where}.at: ${place.name} has no feature \"${spec.at.feature}\"`)\n }\n for (const [field, key] of [['held_by', spec.heldBy], ['worn_by', spec.wornBy]] as const) {\n if (key !== undefined && characterFor(key) === undefined) problems.push(`${where}.${field}: there is no character \"${key}\"`)\n }\n if (spec.wornBy !== undefined && spec.wearable === undefined) problems.push(`${where}: it is worn but not wearable: give it a wearable slot`)\n if (spec.inside !== undefined && !known(spec.inside)) problems.push(`${where}.inside: there is no item \"${spec.inside}\"`)\n if (spec.inside === spec.key) problems.push(`${where}: an item cannot be inside itself`)\n // The same thing twice in the same hands or place is the same thing: change its quantity instead.\n const duplicate = (holder: Holder | undefined): boolean => holder !== undefined && target.items.contents(holder.kind === 'location' ? { kind: 'location', id: holder.locationId } : holder.kind === 'character' ? { kind: 'character', id: holder.characterId } : { kind: 'item', id: holder.itemId }).some(({ item }) => lookupKey(item.name) === lookupKey(spec.name ?? ''))\n const where2: Holder | undefined = spec.at !== undefined && placeFor(spec.at.location) !== undefined ? { kind: 'location', locationId: placeFor(spec.at.location)!.id } : spec.heldBy !== undefined && characterFor(spec.heldBy) !== undefined ? { kind: 'character', characterId: characterFor(spec.heldBy)!.id, mode: 'held' } : undefined\n if (duplicate(where2)) problems.push(`${where}: \"${spec.name}\" is already there: change its quantity instead of making another`)\n })\n if (problems.length > 0) throw new InvalidEditError(problems)\n\n for (const slot of slotsWanted) target.slots.upsert(slot)\n const made = new Map<string, number>()\n const itemId = (key: string): number => made.get(key) ?? (target.items.getBySourceId(key) ?? target.items.get(Number(key)))!.id\n const pending = [...wanted]\n while (pending.length > 0) {\n const index = pending.findIndex(spec => spec.inside === undefined || !newKeys.has(spec.inside) || made.has(spec.inside))\n if (index < 0) throw new InvalidEditError(['items: they are inside each other in a circle'])\n const [spec] = pending.splice(index, 1)\n const holder: Holder = spec!.at !== undefined\n ? { kind: 'location', locationId: placeFor(spec!.at.location)!.id, ...(spec!.at.position === undefined ? {} : { position: spec!.at.position }), ...(spec!.at.feature === undefined ? {} : { featureKey: spec!.at.feature }) }\n : spec!.heldBy !== undefined ? { kind: 'character', characterId: characterFor(spec!.heldBy)!.id, mode: 'held' }\n : spec!.wornBy !== undefined ? { kind: 'character', characterId: characterFor(spec!.wornBy)!.id, mode: 'worn', slot: spec!.wearable!, ...(spec!.wornPosition === undefined ? {} : { position: spec!.wornPosition }) }\n : { kind: 'item', itemId: itemId(spec!.inside!), ...(spec!.insidePosition === undefined ? {} : { position: spec!.insidePosition }) }\n const added = target.items.add({\n sourceId: spec!.key, name: spec!.name.trim(), description: spec!.description ?? '', quantity: spec!.quantity ?? 1, unique: spec!.unique ?? false, quality: spec!.quality ?? '',\n notable: spec!.notable ?? false, hidden: spec!.hidden ?? false, ...(spec!.wearable === undefined ? {} : { wearableSlot: spec!.wearable }),\n ...(spec!.container === undefined ? {} : { container: { state: spec!.container.state ?? 'closed' } }), ...(spec!.owner === undefined ? {} : { ownerId: characterFor(spec!.owner)!.id }),\n }, holder)\n made.set(spec!.key, added.id)\n target.consolidation.enqueue({ kind: 'item', subjectId: added.id, note: spec!.note ?? 'made up in play', turn: edit.turn })\n }\n for (const spec of wanted) {\n if (spec.container?.openedBy !== undefined && spec.container.openedBy.length > 0) target.items.setOpeners({ kind: 'item', id: made.get(spec.key)! }, spec.container.openedBy.map(itemId))\n }\n return { keys: wanted.map(spec => spec.key), writes: wanted.length + slotsWanted.length }\n}\n\n/**\n * Apply an edit. Every problem is found before anything is written, so a bad edit changes nothing.\n * Characters made up by the edit are created after its places and before everything else, so that the rest\n * of the edit (relationships, events, moves) can name them; the whole is still one transaction.\n * @throws {InvalidEditError} naming each problem.\n */\nexport function applyRecordsEdit(target: RecordsTarget, edit: RecordsEdit): EditResult {\n if (list(edit.triggers).length > 0) {\n return target.transaction(() => {\n const done = applyRecordsEdit(target, { ...edit, triggers: [] })\n return { ...done, triggerKeys: createTriggers(target, edit) }\n })\n }\n if (list(edit.characters).length === 0 && list(edit.items).length === 0 && list(edit.slots).length === 0) return applyChanges(target, edit)\n return target.transaction(() => {\n const placesFirst = applyChanges(target, { turn: edit.turn, places: list(edit.places) as NewPlace[] })\n const people = list(edit.characters).length === 0 ? { keys: [] as string[], writes: 0 } : createCharacters(target, edit)\n const things = list(edit.items).length === 0 && list(edit.slots).length === 0 ? { keys: [] as string[], writes: 0 } : createItems(target, edit)\n const rest = applyChanges(target, { ...edit, places: [], characters: [], items: [], slots: [] })\n return {\n eventIds: rest.eventIds, beliefIds: rest.beliefIds, writes: placesFirst.writes + people.writes + things.writes + rest.writes,\n characterKeys: people.keys, placeKeys: placesFirst.placeKeys ?? [], itemKeys: things.keys,\n }\n })\n}\n","import { type Trigger, type TriggerNote } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport { applyRecordsEdit } from './edit.ts'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { audienceIds, conditionHolds, seededRoll, type TriggerClock, type Wire } from './trigger-rules.ts'\nimport { parseInstant } from './time.ts'\nimport { parseRecordsEdit } from './wire.ts'\n\nconst isObject = (value: unknown): value is Wire => typeof value === 'object' && value !== null && !Array.isArray(value)\n\nexport interface FiredTrigger {\n trigger: Trigger\n /** What the game master is to weave in. */\n beats: string[]\n /** What characters are to notice. */\n cues: { characters: string[]; text: string }[]\n /** The texts of the events an edit effect wrote. */\n events: string[]\n}\n\nexport interface TriggerRun {\n fired: FiredTrigger[]\n /** The triggers whose effects could not be applied: they are not tried again. */\n failed: { trigger: Trigger; problem: string }[]\n}\n\nexport interface TriggerRunOptions extends TriggerClock {\n turn: number\n round: number\n /** The most that fire in one run; the rest wait for the next. */\n maxFires?: number\n}\n\nconst DEFAULT_MAX_FIRES = 3\n\n/** An edit effect, as it is applied at this turn and round: events default to now and to what those in their place saw. */\nfunction editOf(target: RecordsTarget, raw: Wire, options: TriggerRunOptions) {\n // A trigger looked at when a turn begins has no round yet; the events it makes belong to the first.\n const round = Math.max(1, options.round)\n const events = Array.isArray(raw['events']) ? raw['events'].filter(isObject).map((event) => {\n const where = typeof event['location'] === 'string' ? target.locations.list().find(entry => locationKey(entry) === event['location'])?.id : undefined\n if (event['perceived_by'] === 'everyone') return { turn: options.turn, round, importance: 3, tags: [], involves: [], ...event, perceived_by: target.characters.list().map(entry => ({ character: characterKey(entry), mode: 'told' })) }\n const present = where === undefined ? [] : target.characters.list().filter(entry => target.placements.get('character', entry.id)?.locationId === where).map(entry => ({ character: characterKey(entry), mode: 'witnessed' }))\n return { turn: options.turn, round, importance: 3, tags: [], involves: [], ...(present.length === 0 ? {} : { perceived_by: present }), ...event }\n }) : undefined\n return parseRecordsEdit({ ...raw, turn: options.turn, time_zone: options.zone, ...(events === undefined ? {} : { events }) })\n}\n\nfunction applyEffects(target: RecordsTarget, trigger: Trigger, options: TriggerRunOptions): FiredTrigger {\n const fired: FiredTrigger = { trigger, beats: [], cues: [], events: [] }\n for (const effect of trigger.effects) {\n if (effect.type === 'edit') {\n const edit = editOf(target, effect.edit, options)\n const result = applyRecordsEdit(target, edit)\n target.events.seal(result.eventIds)\n fired.events.push(...(edit.events ?? []).map(event => event.text))\n } else if (effect.type === 'beat') {\n target.triggers.addNote({ triggerId: trigger.id, kind: 'beat', text: effect.text, turn: options.turn })\n fired.beats.push(effect.text)\n } else {\n const heard = audienceIds(target, effect.audience)\n for (const id of heard) target.triggers.addNote({ triggerId: trigger.id, kind: 'cue', text: effect.text, characterIds: [id], turn: options.turn })\n fired.cues.push({ characters: target.characters.list().filter(entry => heard.includes(entry.id)).map(characterKey), text: effect.text })\n }\n }\n return fired\n}\n\n/**\n * Look at every trigger that can still fire and fire those whose condition has just become true (not those that stay true), by priority.\n * A trigger that fires once stays fired; one that repeats fires again after its condition went false and true, and its cooldown passed. The\n * effects of one trigger are applied together or not at all; one that cannot be applied is marked failed and not tried again.\n */\nexport function runTriggers(target: RecordsTarget, options: TriggerRunOptions): TriggerRun {\n const run: TriggerRun = { fired: [], failed: [] }\n const limit = options.maxFires ?? DEFAULT_MAX_FIRES\n for (const trigger of target.triggers.list()) {\n if (trigger.status === 'failed' || trigger.status === 'expired' || (trigger.status === 'fired' && !trigger.repeat)) continue\n if (trigger.expires !== undefined && options.now >= parseInstant(trigger.expires, options.zone)) { target.triggers.update(trigger.id, { status: 'expired' }); continue }\n const result = conditionHolds(target, trigger.condition, options)\n const rose = result && !trigger.lastResult\n if (!rose) {\n if (result !== trigger.lastResult) target.triggers.update(trigger.id, { lastResult: result })\n continue\n }\n if (run.fired.length >= limit) continue\n const cooling = trigger.cooldownSeconds !== undefined && trigger.lastFiredMs !== undefined && options.now - trigger.lastFiredMs < trigger.cooldownSeconds * 1000\n const lucky = trigger.chance === undefined || seededRoll(`${trigger.key}:${options.turn}:${options.round}:${trigger.fireCount}`) < trigger.chance\n if (cooling || !lucky) { target.triggers.update(trigger.id, { lastResult: true }); continue }\n try {\n const fired = target.transaction(() => {\n const effects = applyEffects(target, trigger, options)\n effects.trigger = target.triggers.update(trigger.id, { status: trigger.repeat ? 'dormant' : 'fired', fireCount: trigger.fireCount + 1, lastFiredMs: options.now, lastResult: true })\n return effects\n })\n run.fired.push(fired)\n } catch (error) {\n const problem = error instanceof InvalidEditError ? error.problems.join('; ') : error instanceof Error ? error.message : String(error)\n run.failed.push({ trigger: target.triggers.update(trigger.id, { status: 'failed', lastResult: true, problem }), problem })\n }\n }\n return run\n}\n\n/** Notes nobody took up in this many turns are let go: a beat the game master never wove in, a cue nobody acted on. */\nexport function lapseNotes(target: RecordsTarget, turn: number, kept: { beats: number; cues: number }): TriggerNote[] {\n const lapsed = target.triggers.notes({ status: 'pending' }).filter(note => turn - note.turn >= (note.kind === 'beat' ? kept.beats : kept.cues))\n for (const note of lapsed) target.triggers.resolveNote(note.id, 'lapsed')\n return lapsed\n}\n","import { SELF, type Trigger, type TriggerCondition, type TriggerNote } from 'dsh-roleplay-model'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\nimport { localTime } from './time.ts'\nimport { placeholdersOf, type Placeholder } from './template.ts'\nimport { conditionHolds, type TriggerClock } from './trigger-rules.ts'\nimport { describeValue, subjectOf } from './variables.ts'\n\ntype Reading = RecordsTarget\n\n/** The words cannot be written as the story stands: something they name is not there. */\nexport class UnwritableError extends Error {}\n\nconst pad = (value: number): string => String(value).padStart(2, '0')\n\nfunction resolve(target: Reading, placeholder: Placeholder, clock: TriggerClock, self: string | undefined): string {\n const key = (index: number): string => (placeholder.args[index] === SELF ? (self ?? SELF) : placeholder.args[index]!)\n const character = (wanted: string) => {\n const found = target.characters.list().find(entry => characterKey(entry) === wanted)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: there is no character \"${wanted}\"`)\n return found\n }\n const place = (wanted: string) => {\n const found = target.locations.list().find(entry => locationKey(entry) === wanted)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: there is no place \"${wanted}\"`)\n return found\n }\n const item = (wanted: string) => {\n const found = target.items.list().find(entry => itemKey(entry) === wanted)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: there is no item \"${wanted}\"`)\n return found\n }\n switch (placeholder.kind) {\n case 'character': return character(key(0)).name\n case 'place': return place(key(0)).name\n case 'item': return item(key(0)).name\n case 'where': {\n const who = character(key(0))\n const at = target.placements.get('character', who.id)\n const found = at === undefined ? undefined : target.locations.get(at.locationId)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: ${who.name} is nowhere in particular`)\n return found.name\n }\n case 'holder': {\n const thing = item(key(0))\n const where = target.items.where(thing.id)\n const holder = where.characterId !== undefined ? target.characters.get(where.characterId)?.name : where.locationId !== undefined ? target.locations.get(where.locationId)?.name : undefined\n if (holder === undefined) throw new UnwritableError(`${placeholder.raw}: ${thing.name} is nowhere that is known`)\n return holder\n }\n case 'value': {\n const def = target.variables.def(placeholder.args[0]!)\n if (def === undefined) throw new UnwritableError(`${placeholder.raw}: there is no variable \"${placeholder.args[0]}\"`)\n const subject = def.subject === 'world' ? { id: 0 } : placeholder.args[1] === undefined ? undefined : subjectOf(target, def.subject, key(1))\n if (subject === undefined) throw new UnwritableError(`${placeholder.raw}: ${def.subject === 'world' ? 'a world variable has no subject' : `give the ${def.subject} it is about`}`)\n return describeValue(def, target.variables.value(def.key, def.subject, subject.id))\n }\n case 'time': {\n const local = localTime(clock.now, clock.zone)\n return `${pad(local.hour)}:${pad(local.minute)}`\n }\n }\n}\n\n/** Words as the story stands now. @throws {UnwritableError} when something they name is not there. */\nexport function renderWords(target: Reading, text: string, clock: TriggerClock, self?: string): string {\n const { found } = placeholdersOf(text)\n let at = 0\n let out = ''\n for (const placeholder of found) {\n const start = text.indexOf(placeholder.raw, at)\n out += text.slice(at, start) + resolve(target, placeholder, clock, self)\n at = start + placeholder.raw.length\n }\n return out + text.slice(at)\n}\n\n/** A condition with `@self` taken as a character. */\nexport function bindSelf(condition: TriggerCondition, self: string): TriggerCondition {\n const bound = (value: string): string => (value === SELF ? self : value)\n switch (condition.type) {\n case 'place': return { ...condition, character: bound(condition.character) }\n case 'variable': return condition.subject === undefined ? condition : { ...condition, subject: bound(condition.subject) }\n case 'item': return { ...condition, item: bound(condition.item), ...(condition.heldBy === undefined ? {} : { heldBy: bound(condition.heldBy) }) }\n case 'all': case 'any': return { ...condition, conditions: condition.conditions.map(part => bindSelf(part, self)) }\n case 'not': return { ...condition, condition: bindSelf(condition.condition, self) }\n default: return condition\n }\n}\n\n/** The effect of a trigger that a note was made from: the beat or cue whose words it carries. */\nexport function noteEffect(trigger: Trigger | undefined, note: Pick<TriggerNote, 'kind' | 'text'>): (Trigger['effects'][number] & { type: 'beat' | 'cue' }) | undefined {\n return trigger?.effects.find((effect): effect is Trigger['effects'][number] & { type: 'beat' | 'cue' } => effect.type === note.kind && effect.text === note.text)\n}\n\nexport interface Delivery {\n /** What is to be told now, in words as the story stands. */\n shown: { note: TriggerNote; text: string }[]\n /** What is not to be told, and why: the beat or cue no longer applies, or cannot be written. */\n withdrawn: { note: TriggerNote; reason: string }[]\n}\n\n/**\n * Decides, at the moment notes are about to be told, what is still to be told and in what words. A note whose effect says something must\n * still hold and does not hold any more is withdrawn; so is one whose words name something that is not there. Nothing is changed.\n */\nexport function deliverNotes(target: Reading, notes: readonly TriggerNote[], clock: TriggerClock): Delivery {\n const delivery: Delivery = { shown: [], withdrawn: [] }\n for (const note of notes) {\n const effect = noteEffect(target.triggers.get(note.triggerId), note)\n const self = note.kind === 'cue' && note.characterIds[0] !== undefined ? target.characters.list().find(entry => entry.id === note.characterIds[0]) : undefined\n const who = self === undefined ? undefined : characterKey(self)\n if (effect?.while !== undefined && !conditionHolds(target, who === undefined ? effect.while : bindSelf(effect.while, who), clock)) {\n delivery.withdrawn.push({ note, reason: 'what it was waiting on no longer holds' })\n continue\n }\n try {\n delivery.shown.push({ note, text: renderWords(target, note.text, clock, who) })\n } catch (error) {\n if (!(error instanceof UnwritableError)) throw error\n delivery.withdrawn.push({ note, reason: error.message })\n }\n }\n return delivery\n}\n","import type { Character, CharacterId, CharacterMemory, PerceivedEvent } from 'dsh-roleplay-model'\nimport type { ClockRepository, EventRepository, MemoryRepository, RelationshipRepository } from '../repositories.ts'\n\nconst DAY = 86_400_000\n\n/** How a character remembers. */\nexport interface MemoryPolicy {\n /** Whether memories fade with age and unimportance. Off for exact recall. */\n flaky: boolean\n /** The most things a character is reminded of at once. */\n recall: number\n /**\n * How many times `recall` candidates are retrieved before the best are chosen: the wider net is what a\n * reranker judges, and it also gives importance and recency something to choose between. At least 1.\n */\n overRetrieve?: number\n /**\n * How many more things come to mind because they are strongly tied to what the moment recalled (the same people together with the same\n * place or tags) and matter enough. 0 or absent: none.\n */\n associate?: number\n /**\n * How much a memory that says what one already chosen says counts against it, from 0 (the best by score, repeats\n * included) to 1 (only what adds something new): maximal marginal relevance over the pool. 0 or absent: none.\n */\n diversity?: number\n}\n\nexport const DEFAULT_MEMORY_POLICY: MemoryPolicy = { flaky: true, recall: 12, overRetrieve: 4, associate: 2, diversity: 0.3 }\n\n/** How much of a memory is left: what the character is told of it. */\nexport type Clarity = 'clear' | 'faded' | 'vague'\n\n/** One thing a character is reminded of, as it comes back to it. */\nexport interface Recalled {\n clarity: Clarity\n /** What the character remembers; less of it the fainter the memory. */\n text: string\n /** The turn it comes from. */\n turn: number\n /** When it happened in story time, when the story clock records it. */\n at?: number\n source: { kind: 'perception' | 'memory'; id: number }\n /** It did not match the moment itself: it came to mind with something that did ({@link MemoryPolicy.associate}). */\n linked?: true\n /** Why it came back, when the query asked to be told ({@link RecallQuery.explain}). */\n why?: RecallWhy\n}\n\n/** What made one thing come back, for finding out why a character was or was not reminded of something. */\nexport interface RecallWhy {\n /** What the cues of the moment gave, in the units of a cue: people named (a name counts 3, more for social weight), words and tags shared (at most 6), being where it happened. */\n cues: { people: number; words: number; place: number }\n /** What each search scored it, from 0 to 1; absent when that search did not run or did not find it. */\n lexical?: number\n dense?: number\n rerank?: number\n /** What it counted for in the end: the fused retrieval score, blended with the reranker's when there was one. */\n relevance: number\n importance: number\n /** How long ago it was in story days; 0 when the story has no clock. */\n ageDays: number\n /** How much of it is left in mind, from 1 to 0, when memories fade. */\n retention?: number\n /** What it was ranked by, together with how much it matters and how recent it is. */\n score: number\n /** For something that came to mind with another: what it shares with the closest of the things recalled for the moment. */\n linked?: { people: number; tags: number; place: boolean }\n}\n\nexport interface RecallQuery {\n characterId: CharacterId\n /** Everyone in the story, so that names in the situation can be told. */\n characters: readonly Character[]\n /** What is happening now, which is what reminds the character of things. */\n situation: string\n /** Where the character is. What happened in the same place comes back to it more readily. */\n locationId?: number\n turn: number\n policy: MemoryPolicy\n /** Say why each thing came back ({@link Recalled.why}). */\n explain?: boolean\n /** Only what involves or is about one of these people comes back: \"what do I know about her\", which a name in the words would not reliably find. */\n about?: readonly CharacterId[]\n}\n\n/** What recall reads: the events a character took in and what it believes. */\nexport interface RecallSource {\n events: Pick<EventRepository, 'perceivedBy'>\n memories: Pick<MemoryRepository, 'list'>\n clock: Pick<ClockRepository, 'get' | 'log'>\n /** Optional for lightweight callers; a session supplies it so socially charged people are stronger cues. */\n relationships?: Pick<RelationshipRepository, 'from'>\n}\n\n/** Story days for the memory of an unimportant event to halve; each step of importance doubles it. */\nconst HALF_LIFE_DAYS = 6\n/** Beliefs and what a character knows last longer than the memory of single events. */\nconst BELIEF_DURABILITY = 4\n/** Each time something is recalled it lasts longer, up to this many times as long. */\nconst REHEARSAL_STEP = 0.25\nconst MAX_REHEARSAL = 2\n/** What is left of a memory, from 1 (as it happened) to 0 (gone), above which it is clear, faded and vague. */\nconst CLEAR_ABOVE = 0.6\nconst FADED_ABOVE = 0.3\nconst VAGUE_ABOVE = 0.12\n/** A cue in the situation brings back something that was fading. */\nconst CUE_BOOST = 0.25\n/** What is that important stays faded at worst. */\nconst UNFORGETTABLE = 5\n\n/** A number from 0 up to 1 that is always the same for the same input: no two memories fade at quite the same rate. */\nexport function jitter(seed: number): number {\n let h = (seed + 0x9e3779b9) >>> 0\n h = Math.imul(h ^ (h >>> 16), 0x85ebca6b) >>> 0\n h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35) >>> 0\n return ((h ^ (h >>> 16)) >>> 0) / 0x100000000\n}\n\n/** What is left of a memory, from 1 down to 0, given its age, how much it matters and how often it was recalled. */\nexport function retention(input: { ageDays: number; importance: number; recalls: number; seed: number; durability?: number; cue?: boolean }): number {\n const rehearsal = 1 + Math.min(MAX_REHEARSAL, input.recalls * REHEARSAL_STEP)\n const halfLife = HALF_LIFE_DAYS * 2 ** (input.importance - 1) * rehearsal * (input.durability ?? 1)\n const faded = 0.5 ** (Math.max(0, input.ageDays) / halfLife) * (0.85 + 0.3 * jitter(input.seed))\n return Math.min(1, faded + (input.cue === true ? CUE_BOOST : 0))\n}\n\n/** How clear a memory is at a retention, or nothing when it is gone. */\nexport function clarityAt(value: number, importance: number): Clarity | undefined {\n if (value >= CLEAR_ABOVE) return 'clear'\n if (value >= FADED_ABOVE || importance >= UNFORGETTABLE) return 'faded'\n if (value >= VAGUE_ABOVE) return 'vague'\n return undefined\n}\n\nconst CJK = /\\p{Script=Han}|\\p{Script=Hiragana}|\\p{Script=Katakana}|\\p{Script=Hangul}/u\n\n/** Words a text can be matched by: words as they are, and overlapping pairs of characters for scripts written without spaces. */\nexport function tokens(text: string): Set<string> {\n const found = new Set<string>()\n for (const word of text.normalize('NFKC').toLowerCase().split(/[^\\p{L}\\p{N}]+/u)) {\n if (word === '') continue\n if (!CJK.test(word)) {\n if (word.length >= 3) found.add(word)\n continue\n }\n const chars = [...word]\n if (chars.length === 1) found.add(word)\n for (let index = 0; index + 1 < chars.length; index++) found.add(chars[index]! + chars[index + 1]!)\n }\n return found\n}\n\n/** The characters a text mentions by name or alias. */\nexport function mentioned(text: string, characters: readonly Character[]): Set<number> {\n const words = tokens(text)\n const lowered = text.normalize('NFKC').toLowerCase()\n const ids = new Set<number>()\n for (const character of characters) {\n for (const name of [character.name, ...character.aliases]) {\n const needle = name.normalize('NFKC').toLowerCase()\n if (needle.length >= 2 && (lowered.includes(needle) || tokens(needle).size > 0 && [...tokens(needle)].every(token => words.has(token)))) ids.add(character.id)\n }\n }\n return ids\n}\n\n/** What ties a candidate to others: the people it involves (other than the one remembering), its tags and where it happened. */\ninterface Links {\n people: readonly number[]\n tags: readonly string[]\n place?: number\n}\n\ninterface Candidate {\n key: string\n links: Links\n recalled: Omit<Recalled, 'clarity' | 'text' | 'why'> & { clear: string; faded: string; vague: string }\n relevance: number\n cues: RecallWhy['cues']\n importance: number\n ageDays: number\n recalls: number\n seed: number\n durability: number\n}\n\nconst first = (text: string): string => {\n const match = /^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())\n const sentence = (match?.[0] ?? text).trim()\n return sentence === '' ? text.trim() : sentence\n}\n\nexport function overlap(cues: ReadonlySet<string>, text: string, tags: readonly string[]): number {\n let score = 0\n for (const tag of tags) if (cues.has(tag.toLowerCase())) score += 2\n for (const token of tokens(text)) if (cues.has(token)) score += 1\n return Math.min(score, 6)\n}\n\nfunction describeEvent({ perception, event }: PerceivedEvent, names: ReadonlyMap<number, string>, at?: number): Candidate['recalled'] {\n const who = event.involves.map(id => names.get(id)).filter((name): name is string => name !== undefined)\n const about = who.length > 0 ? who.join(', ') : event.tags.join(', ')\n return {\n turn: event.turn, ...(at === undefined ? {} : { at }),\n source: { kind: 'perception', id: perception.id },\n clear: perception.content,\n faded: perception.gist,\n vague: about === '' ? 'something happened, but you cannot say what' : `something to do with ${about}`,\n }\n}\n\nfunction describeBelief(memory: CharacterMemory, at?: number): Candidate['recalled'] {\n return { turn: memory.turn, ...(at === undefined ? {} : { at }), source: { kind: 'memory', id: memory.id }, clear: memory.text, faded: first(memory.text), vague: first(memory.text) }\n}\n\n/** One thing a character could be reminded of, with the text to match it against the moment. */\nexport interface RecallCandidate {\n /** Names the candidate in the `semantic` scores given to {@link recall}: `p:<id>` for something it took in, `m:<id>` for something it believes. */\n key: string\n /** What the character remembers of it in full: what an embedding or a reranker should read. */\n text: string\n turn: number\n importance: number\n}\n\n/**\n * Retrieval is several searches (the cues of the moment, the words of the index, the meaning of the\n * stored vectors) that each score the candidates their own way. Each is brought to a score from 0 to 1\n * and the scores are fused by a weighted average over the searches that ran, so that a candidate one search\n * found and another did not is worth less than one both found; a search that found nothing takes no part,\n * so what is missing never counts against anything.\n */\nconst FUSION_WEIGHTS = { cues: 1, lexical: 1, dense: 1.5 } as const\n/** Cues of the moment add up (a name counts 3 plus up to 2 for social salience, shared words up to 6, a place 2). */\nconst FULL_CUE = 8\n/** What the fused retrieval score counts for next to how much a memory matters and how recent it is (up to about 2.6 and 2). */\nconst RELEVANCE_SCALE = 10\n/** What a reranker's judgement counts for next to the fused retrieval score, when there is one. */\nconst RERANK_BLEND = 0.7\n/** Retrieval is cut to this many candidates however wide the net, so that a reranker is never asked about more. */\nconst MAX_POOL = 60\n/** What fused retrieval has to be for a match to count as a cue for what had faded. */\nconst CUE_RELEVANCE = 0.2\n/** Cosine similarities below this are noise for the models used, and from here to this plus the range they count from nothing to full. */\nconst DENSE_FLOOR = 0.3\nconst DENSE_RANGE = 0.5\n\n/** From a cosine similarity to how much a match counts, from 0 to 1. */\nexport const denseScore = (similarity: number): number => Math.min(1, Math.max(0, (similarity - DENSE_FLOOR) / DENSE_RANGE))\n\n/** What else says how well each candidate matches the moment, by candidate key, each from 0 to 1. */\nexport interface RecallEvidence {\n /** From the search of the session's index by words. */\n lexical?: ReadonlyMap<string, number>\n /** From the search of the session's stored vectors by meaning, already mapped by {@link denseScore}. */\n dense?: ReadonlyMap<string, number>\n /** From a reranker that judged the candidates of the pool (see {@link poolCandidates}). */\n rerank?: ReadonlyMap<string, number>\n}\n\n/** Being where something happened calls it to mind, about as much as sharing two words with it. */\nconst PLACE_CUE = 2\n\nfunction gather(source: RecallSource, { characterId, characters, situation, locationId, about }: Pick<RecallQuery, 'characterId' | 'characters' | 'situation' | 'turn' | 'locationId' | 'about'>): Candidate[] {\n const names = new Map(characters.map(character => [character.id, character.name]))\n const peers = mentioned(situation, characters)\n peers.delete(characterId)\n const social = new Map((source.relationships?.from(characterId) ?? []).map(relation => [relation.toId, Math.min(2, relation.tension + Math.abs(relation.affinity) * 0.5 + Math.max(0, -relation.trust) * 0.5)]))\n const peopleCue = (ids: readonly number[]): number => ids.filter(id => peers.has(id)).reduce((score, id) => score + 3 + (social.get(id) ?? 0), 0)\n const cues = tokens(situation)\n const now = source.clock.get()?.now\n const changes = source.clock.log()\n const start = changes.find(change => change.kind === 'start')?.from\n const turns = new Map<number, number>()\n const rounds = new Map<string, number>()\n for (const change of changes) {\n if (!turns.has(change.turn)) turns.set(change.turn, change.from)\n if ((change.kind === 'elapsed' || change.kind === 'real') && !rounds.has(`${change.turn}:${change.round}`)) rounds.set(`${change.turn}:${change.round}`, change.from)\n }\n const atTurn = (eventTurn: number): number | undefined => turns.get(eventTurn) ?? start\n const ageDays = (at: number | undefined): number => now === undefined || at === undefined ? 0 : Math.max(0, now - at) / DAY\n const concerns = (ids: readonly number[]): boolean => about === undefined || about.length === 0 || ids.some(id => about.includes(id))\n return [\n ...source.events.perceivedBy(characterId).filter(seen => concerns(seen.event.involves)).map((seen): Candidate => {\n const at = rounds.get(`${seen.event.turn}:${seen.event.round}`) ?? atTurn(seen.event.turn)\n const cue = { people: peopleCue(seen.event.involves), words: overlap(cues, `${seen.perception.content} ${seen.event.text}`, seen.event.tags), place: locationId !== undefined && seen.event.locationId === locationId ? PLACE_CUE : 0 }\n return ({\n key: `p:${seen.perception.id}`,\n links: { people: seen.event.involves.filter(id => id !== characterId), tags: seen.event.tags.map(tag => tag.toLowerCase()), ...(seen.event.locationId === undefined ? {} : { place: seen.event.locationId }) },\n recalled: describeEvent(seen, names, at),\n cues: cue,\n relevance: cue.people + cue.words + cue.place,\n importance: seen.event.importance,\n ageDays: ageDays(at),\n recalls: seen.perception.recalls,\n seed: seen.perception.id,\n durability: 1,\n })}),\n ...source.memories.list(characterId).filter(belief => concerns(belief.about)).map((belief): Candidate => {\n const at = atTurn(belief.turn)\n const cue = { people: peopleCue(belief.about), words: overlap(cues, belief.text, []), place: 0 }\n return ({\n key: `m:${belief.id}`,\n links: { people: belief.about.filter(id => id !== characterId), tags: [] },\n recalled: describeBelief(belief, at),\n cues: cue,\n relevance: cue.people + cue.words,\n importance: belief.importance,\n ageDays: ageDays(at),\n recalls: belief.recalls,\n seed: 1_000_000 + belief.id,\n durability: BELIEF_DURABILITY,\n })}),\n ]\n}\n\n/** Everything the character could be reminded of, for a caller that ranks by meaning (an embedding, a reranker) before asking for the recall. */\nexport function recallCandidates(source: RecallSource, query: Pick<RecallQuery, 'characterId' | 'characters' | 'situation' | 'turn' | 'locationId' | 'about'>): RecallCandidate[] {\n return gather(source, query).map(candidate => ({ key: candidate.key, text: candidate.recalled.clear, turn: candidate.recalled.turn, importance: candidate.importance }))\n}\n\n/** Fuse scores from 0 to 1 into one, per key: the weighted average over the searches that ran (those with any score above 0). */\nexport function fuseScores(searches: readonly { weight: number; scores: ReadonlyMap<string, number> | undefined }[]): Map<string, number> {\n const ran = searches.filter(search => [...(search.scores ?? [])].some(([, score]) => score > 0))\n const total = ran.reduce((sum, search) => sum + search.weight, 0)\n const fused = new Map<string, number>()\n for (const { weight, scores } of ran) {\n for (const [key, score] of scores ?? []) fused.set(key, (fused.get(key) ?? 0) + weight * Math.min(1, Math.max(0, score)) / total)\n }\n return fused\n}\n\ninterface PoolEntry {\n candidate: Candidate\n /** How well retrieval alone matches the moment, from 0 to 1. */\n fused: number\n /** What each search scored it, when it was found by it. */\n found: { lexical?: number; dense?: number }\n}\n\n/** What retrieval over-retrieved for one recall, waiting for a reranker's judgement and the final choice. */\nexport interface RecallPool {\n entries: readonly PoolEntry[]\n /** What retrieval left out, which an association may still bring to mind. */\n others: readonly Candidate[]\n query: Pick<RecallQuery, 'policy' | 'explain'>\n}\n\n/** How well a candidate stands once its relevance is known: what the moment calls to mind, how much it matters and how recent it is. */\nfunction judged(candidate: Candidate, relevance: number, policy: MemoryPolicy): { clarity: Clarity; score: number; text: string; retention?: number } | undefined {\n let clarity: Clarity | undefined = 'clear'\n let kept: number | undefined\n if (policy.flaky) {\n kept = retention({ ageDays: candidate.ageDays, importance: candidate.importance, recalls: candidate.recalls, seed: candidate.seed, durability: candidate.durability, cue: relevance >= CUE_RELEVANCE })\n clarity = clarityAt(kept, candidate.importance)\n }\n if (clarity === undefined) return undefined\n const score = RELEVANCE_SCALE * relevance + 0.6 * candidate.importance + 2 / (1 + Math.max(0, candidate.ageDays)) + (clarity === 'vague' ? -1 : 0)\n return { clarity, score, text: candidate.recalled[clarity === 'clear' ? 'clear' : clarity === 'faded' ? 'faded' : 'vague'], ...(kept === undefined ? {} : { retention: kept }) }\n}\n\n/**\n * The first stage of reminding a character of what the moment calls to mind: retrieve, by the cues\n * of the moment (who is named, shared words and tags, where it happened), by the words of the index\n * and by meaning, fuse the scores of each, and keep more than will be used (`policy.overRetrieve` times\n * `policy.recall`, the best by fused relevance together with how much each matters and how recent it\n * is, and not what has faded from memory altogether). A reranker may then judge that pool.\n */\nexport function recallPool(source: RecallSource, query: RecallQuery, evidence: Omit<RecallEvidence, 'rerank'> = {}): RecallPool {\n const { policy, explain } = query\n const candidates = gather(source, query)\n const fused = fuseScores([\n { weight: FUSION_WEIGHTS.cues, scores: new Map(candidates.map(candidate => [candidate.key, candidate.relevance / FULL_CUE])) },\n { weight: FUSION_WEIGHTS.lexical, scores: evidence.lexical },\n { weight: FUSION_WEIGHTS.dense, scores: evidence.dense },\n ])\n const width = Math.min(MAX_POOL, Math.max(policy.recall, Math.ceil(policy.recall * Math.max(1, policy.overRetrieve ?? 1))))\n const ranked = candidates\n .map(candidate => ({ candidate, fused: fused.get(candidate.key) ?? 0, found: { ...(evidence.lexical?.get(candidate.key) === undefined ? {} : { lexical: evidence.lexical.get(candidate.key)! }), ...(evidence.dense?.get(candidate.key) === undefined ? {} : { dense: evidence.dense.get(candidate.key)! }) } }))\n .flatMap((entry) => {\n const standing = judged(entry.candidate, entry.fused, policy)\n return standing === undefined ? [] : [{ entry, score: standing.score }]\n })\n .sort((a, b) => b.score - a.score || b.entry.candidate.recalled.turn - a.entry.candidate.recalled.turn)\n .map(({ entry }) => entry)\n const entries = ranked.slice(0, width)\n const kept = new Set(entries.map(entry => entry.candidate.key))\n return { entries, others: candidates.filter(candidate => !kept.has(candidate.key)), query: { policy, ...(explain === true ? { explain } : {}) } }\n}\n\n/** What a reranker is asked to judge: every candidate of the pool, with the text it would be recalled by. */\nexport function poolCandidates(pool: RecallPool): RecallCandidate[] {\n return pool.entries.map(({ candidate }) => ({ key: candidate.key, text: candidate.recalled.clear, turn: candidate.recalled.turn, importance: candidate.importance }))\n}\n\n/** Two things are tied by the same people, the same tags and the same place; this is how strongly (people count most, tags and place add a little). */\nfunction tie(a: Links, b: Links): { strength: number; people: number; tags: number; place: boolean } {\n const people = a.people.filter(id => b.people.includes(id)).length\n const tags = a.tags.filter(tag => b.tags.includes(tag)).length\n const place = a.place !== undefined && a.place === b.place\n return { strength: 2 * Math.min(people, 2) + Math.min(tags, 2) + (place ? 1 : 0), people, tags, place }\n}\n/** The least a tie has to be for one thing to bring the other to mind. */\nconst STRONG_TIE = 3\n/** What does not matter much is not brought back by association. */\nconst ASSOCIABLE_IMPORTANCE = 3\n\n/** How much two texts say the same, from 0 to 1: the share of their words (or pairs of characters) they have in common. */\nexport function resemblance(a: ReadonlySet<string>, b: ReadonlySet<string>): number {\n if (a.size === 0 || b.size === 0) return 0\n let shared = 0\n for (const word of a) if (b.has(word)) shared++\n return shared / (a.size + b.size - shared)\n}\n\n/**\n * Choose `count` of the ranked entries by maximal marginal relevance: each pick is the one with the best score\n * discounted by how much it resembles what is already chosen, so that three memories of the same moment do not\n * crowd out one of another. `diversity` 0 keeps the ranking as it is.\n */\nfunction diversified<T extends { candidate: Candidate; score: number }>(ranked: readonly T[], count: number, diversity: number): T[] {\n const weight = Math.min(1, Math.max(0, diversity))\n if (weight === 0 || ranked.length <= 1) return ranked.slice(0, count)\n const top = Math.max(...ranked.map(entry => entry.score), Number.EPSILON)\n const words = new Map(ranked.map(entry => [entry, tokens(entry.candidate.recalled.clear)]))\n const left = [...ranked]\n const chosen: T[] = []\n while (chosen.length < count && left.length > 0) {\n let best = 0\n let bestValue = -Infinity\n left.forEach((entry, index) => {\n const repeat = Math.max(0, ...chosen.map(picked => resemblance(words.get(entry)!, words.get(picked)!)))\n const value = (1 - weight) * Math.max(0, entry.score) / top - weight * repeat\n if (value > bestValue) { best = index; bestValue = value }\n })\n chosen.push(left.splice(best, 1)[0]!)\n }\n return chosen\n}\n\n/**\n * The last stage: choose the `policy.recall` best of the pool, spread by `policy.diversity`. With a reranker's judgement each\n * candidate's relevance is mostly that (a candidate it left out counts as 0), and the rest is what\n * retrieval found; without, it is what retrieval found.\n */\nexport function finishRecall(pool: RecallPool, rerank?: ReadonlyMap<string, number>): Recalled[] {\n const { policy } = pool.query\n const standing = pool.entries\n .flatMap(({ candidate, fused, found }) => {\n const relevance = rerank === undefined ? fused : RERANK_BLEND * Math.min(1, Math.max(0, rerank.get(candidate.key) ?? 0)) + (1 - RERANK_BLEND) * fused\n const judgement = judged(candidate, relevance, policy)\n if (judgement === undefined) return []\n const why: RecallWhy | undefined = pool.query.explain === true\n ? { cues: candidate.cues, ...found, ...(rerank === undefined ? {} : { rerank: rerank.get(candidate.key) ?? 0 }), relevance, importance: candidate.importance, ageDays: candidate.ageDays, ...(judgement.retention === undefined ? {} : { retention: judgement.retention }), score: judgement.score }\n : undefined\n return [{ candidate, relevance, ...judgement, why }]\n })\n .sort((a, b) => b.score - a.score || b.candidate.recalled.turn - a.candidate.recalled.turn)\n const chosen = diversified(standing, policy.recall, policy.diversity ?? 0)\n const result = chosen.map(({ candidate, clarity, text, why }): Recalled => ({ clarity, text, turn: candidate.recalled.turn, ...(candidate.recalled.at === undefined ? {} : { at: candidate.recalled.at }), source: candidate.recalled.source, ...(why === undefined ? {} : { why }) }))\n const anchors = chosen.filter(entry => entry.relevance >= CUE_RELEVANCE)\n const wanted = anchors.length === 0 ? 0 : Math.max(0, policy.associate ?? 0)\n if (wanted > 0) {\n const taken = new Set(chosen.map(entry => entry.candidate.key))\n const rest = [...standing.filter(entry => !chosen.includes(entry)).map(entry => entry.candidate), ...pool.others].filter(candidate => !taken.has(candidate.key) && candidate.importance >= ASSOCIABLE_IMPORTANCE)\n const tied = rest.flatMap((candidate) => {\n const best = anchors.map(anchor => tie(anchor.candidate.links, candidate.links)).sort((a, b) => b.strength - a.strength)[0]\n const judgement = best === undefined || best.strength < STRONG_TIE ? undefined : judged(candidate, 0, policy)\n return best === undefined || judgement === undefined || judgement.clarity === 'vague' ? [] : [{ candidate, best, judgement }]\n })\n .sort((a, b) => b.best.strength - a.best.strength || b.candidate.importance - a.candidate.importance || b.candidate.recalled.turn - a.candidate.recalled.turn)\n .slice(0, wanted)\n for (const { candidate, best, judgement } of tied) {\n result.push({\n clarity: judgement.clarity, text: judgement.text, turn: candidate.recalled.turn, ...(candidate.recalled.at === undefined ? {} : { at: candidate.recalled.at }), source: candidate.recalled.source, linked: true,\n ...(pool.query.explain === true ? { why: { cues: candidate.cues, relevance: 0, importance: candidate.importance, ageDays: candidate.ageDays, ...(judgement.retention === undefined ? {} : { retention: judgement.retention }), score: judgement.score, linked: { people: best.people, tags: best.tags, place: best.place } } } : {}),\n })\n }\n }\n return result.sort((a, b) => a.turn - b.turn)\n}\n\n/** Remind a character of what the moment calls to mind, in one call: {@link recallPool}, then {@link finishRecall} with the `rerank` evidence if there is any. */\nexport function recall(source: RecallSource, query: RecallQuery, evidence: RecallEvidence = {}): Recalled[] {\n return finishRecall(recallPool(source, query, evidence), evidence.rerank)\n}\n","import type { CharacterId } from 'dsh-roleplay-model'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\nimport { localIso } from './time.ts'\nimport { describeValue } from './variables.ts'\n\n/** Which part of the story's records to read; all of it when left out. */\nexport interface RecordsScope {\n rounds?: readonly { turn: number; round: number }[]\n /** The time zone times are shown in; UTC when not given. */\n timeZone?: string\n /** Only these parts of the records; the others come back empty. Everything when left out. */\n only?: readonly (keyof RecordsView)[]\n /** Of the relationships, only those that changed in this turn or later. */\n relationshipsSince?: number\n}\n\n/** The records as models read them (snake_case, characters by key), the counterpart of the edit's wire format. */\nexport interface RecordsView {\n factions: { faction: string; name: string; public_state: string; inner_state: string; values: string[]; structure: string; goals: { id: number; name: string; status: string; horizon: string; priority: number; urgency: number; plan: string[] }[]; members: { character: string; role: string; rank: string; status: string; public: boolean; commitment: number }[] }[]\n faction_relationships: { from_kind: string; from: string; to_kind: string; to: string; label: string; summary: string; familiarity: number; trust: number; affinity: number; tension: number; updated_turn: number }[]\n characters: {\n character: string\n name: string\n controlled_by: 'the player' | 'an agent'\n public_state: string\n inner_state: string\n activity: string\n /** The key of the place it is in, and where in it; null while it is nowhere. */\n location: string | null\n position: string\n /** What it is after that is still live (active or paused), with the ids an edit refers to. */\n goals: { id: number; type: string; name: string; status: string; horizon: string; priority: number; urgency: number; deadline: string | null; plan: string[] }[]\n }[]\n events: {\n id: number\n turn: number\n round: number\n text: string\n importance: number\n tags: string[]\n involves: string[]\n /** The key of the place it happened in. */\n location: string | null\n sealed: boolean\n perceived_by: { id: number; character: string; mode: string; accuracy: string; content: string; gist: string }[]\n }[]\n beliefs: { id: number; character: string; kind: string; text: string; about: string[]; importance: number; turn: number }[]\n open_threads: { id: number; text: string; opened_turn: number }[]\n /** How characters stand towards each other, most recently changed first (at most 80). */\n /** Things, notable first (at most 100), each with where it is. */\n items: { key: string; name: string; quantity: number; quality: string; state: string | null; hidden: boolean; notable: boolean; owner: string | null; holder: string }[]\n /** What is tracked: how each kind of variable is declared. */\n variable_defs: { key: string; name: string; description: string; kind: string; subject: string; only: string[]; min: number | null; max: number | null; options: string[]; default: string | number | boolean; visibility: string; baseline: boolean }[]\n /** What each subject holds that is not the default (at most 200, most recently changed first). */\n variables: { variable: string; subject: string; about: string; value: string | number | boolean; described: string; baseline: string | number | boolean | null; visibility: string }[]\n /** What characters have committed to that is still pending, in the order they are due (at most 40); times in the story's time zone. */\n engagements: { id: number; title: string; at: string; until: string | null; location: string | null; participants: string[]; note: string }[]\n relationships: { from: string; to: string; label: string; summary: string; familiarity: number; trust: number; affinity: number; tension: number; updated_turn: number }[]\n knowledge: { character: string; kind: string; subject: string; learned_turn: number; last_observed_turn: number | null }[]\n}\n\nconst MAX_RELATIONSHIPS_SHOWN = 80\nconst MAX_KNOWLEDGE_SHOWN = 200\nconst MAX_ITEMS_SHOWN = 100\nconst MAX_ENGAGEMENTS_SHOWN = 40\nconst MAX_VARIABLES_SHOWN = 200\n\n/** Where an item is, in words. */\nexport function describeHolder(target: Pick<RecordsTarget, 'items' | 'locations' | 'characters'>, id: number, keyOfCharacter: (id: number) => string = String): string {\n const holding = target.items.holding(id)\n if (holding === undefined) return 'nowhere'\n const { holder } = holding\n if (holder.kind === 'location') return `at ${target.locations.get(holder.locationId)?.name ?? holder.locationId}${holder.position === undefined ? '' : ` (${holder.position})`}`\n if (holder.kind === 'item') return `inside ${target.items.get(holder.itemId)?.name ?? holder.itemId}`\n const who = keyOfCharacter(holder.characterId)\n return holder.mode === 'worn' ? `worn by ${who} on the ${holder.slot}` : `carried by ${who}`\n}\n\n/** Read the records back from the database, as the edit wrote them. */\nexport function readRecords(target: Omit<RecordsTarget, 'transaction'>, scope: RecordsScope = {}): RecordsView {\n const characters = target.characters.list()\n const factions = target.factions.list()\n const keyOf = (id: CharacterId): string => {\n const found = characters.find(character => character.id === id)\n return found === undefined ? String(id) : characterKey(found)\n }\n const factionKey = (id: number): string => { const faction = factions.find(entry => entry.id === id); return faction?.sourceId ?? String(id) }\n const socialKey = (kind: 'character' | 'faction', id: number): string => kind === 'character' ? keyOf(id) : factionKey(id)\n const places = new Map(target.locations.list().map(place => [place.id, locationKey(place)]))\n const placeKey = (id: number): string => places.get(id) ?? String(id)\n const where = (id: CharacterId): { location: string | null; position: string } => {\n const placement = target.placements.get('character', id)\n return placement === undefined ? { location: null, position: '' } : { location: placeKey(placement.locationId), position: placement.position }\n }\n const zone = scope.timeZone ?? 'UTC'\n const inScope = (turn: number, round?: number): boolean =>\n scope.rounds === undefined || scope.rounds.some(entry => entry.turn === turn && (round === undefined || entry.round === round))\n const view: RecordsView = {\n factions: factions.map((faction) => {\n const state = target.factionStates.get(faction.id)\n return { faction: factionKey(faction.id), name: faction.name, public_state: state?.publicState ?? '', inner_state: state?.innerState ?? '', values: faction.values, structure: faction.structure, goals: target.factionIntents.list(faction.id).filter(goal => goal.status === 'active' || goal.status === 'paused').map(goal => ({ id: goal.id, name: goal.name, status: goal.status, horizon: goal.horizon, priority: goal.priority, urgency: goal.urgency, plan: goal.plan })), members: target.factionMemberships.ofFaction(faction.id).map(member => ({ character: keyOf(member.characterId), role: member.role, rank: member.rank, status: member.status, public: member.public, commitment: member.commitment })) }\n }),\n faction_relationships: target.factionRelationships.list().filter(relation => scope.relationshipsSince === undefined || relation.updatedTurn >= scope.relationshipsSince).map(relation => ({ from_kind: relation.fromKind, from: socialKey(relation.fromKind, relation.fromId), to_kind: relation.toKind, to: socialKey(relation.toKind, relation.toId), label: relation.label, summary: relation.summary, familiarity: relation.familiarity, trust: relation.trust, affinity: relation.affinity, tension: relation.tension, updated_turn: relation.updatedTurn })),\n characters: characters.map((character) => {\n const state = target.characterStates.get(character.id)\n return {\n character: characterKey(character),\n name: character.name,\n controlled_by: character.control === 'player' ? 'the player' : 'an agent',\n public_state: state?.publicState ?? '',\n inner_state: state?.innerState ?? '',\n activity: state?.activity ?? '',\n ...where(character.id),\n goals: target.intents.list(character.id).filter(goal => goal.status === 'active' || goal.status === 'paused').map(goal => ({ id: goal.id, type: goal.type, name: goal.name, status: goal.status, horizon: goal.horizon, priority: goal.priority, urgency: goal.urgency, deadline: goal.deadline ?? null, plan: goal.plan })),\n }\n }),\n events: target.events.list().filter(event => inScope(event.turn, event.round)).map(event => ({\n id: event.id, turn: event.turn, round: event.round, text: event.text, importance: event.importance, tags: event.tags,\n involves: event.involves.map(keyOf), location: event.locationId === undefined ? null : placeKey(event.locationId), sealed: event.sealed,\n perceived_by: target.events.perceptionsOf(event.id).map(entry => ({ id: entry.id, character: keyOf(entry.characterId), mode: entry.mode, accuracy: entry.accuracy, content: entry.content, gist: entry.gist })),\n })),\n beliefs: characters.flatMap(character => target.memories.list(character.id)\n .filter(belief => inScope(belief.turn))\n .map(belief => ({ id: belief.id, character: characterKey(character), kind: belief.kind, text: belief.text, about: belief.about.map(keyOf), importance: belief.importance, turn: belief.turn }))),\n open_threads: target.threads.list('open').map(thread => ({ id: thread.id, text: thread.text, opened_turn: thread.openedTurn })),\n items: [...target.items.list()].sort((a, b) => Number(b.notable) - Number(a.notable) || a.id - b.id).slice(0, MAX_ITEMS_SHOWN).map(item => ({\n key: itemKey(item), name: item.name, quantity: item.quantity, quality: item.quality, state: item.container?.state ?? null, hidden: item.hidden, notable: item.notable,\n owner: item.ownerId === undefined ? null : keyOf(item.ownerId), holder: describeHolder(target, item.id, keyOf),\n })),\n variable_defs: target.variables.defs().map(def => ({\n key: def.key, name: def.name, description: def.description, kind: def.kind, subject: def.subject, only: def.only, min: def.min ?? null, max: def.max ?? null, options: def.options, default: def.default, visibility: def.visibility, baseline: def.baseline,\n })),\n variables: target.variables.all().flatMap((entry) => {\n const def = target.variables.def(entry.variable)\n if (def === undefined || entry.value === def.default) return []\n const key = entry.subject === 'world' ? 'world' : entry.subject === 'character' ? keyOf(entry.subjectId) : entry.subject === 'item' ? (target.items.get(entry.subjectId) === undefined ? String(entry.subjectId) : itemKey(target.items.get(entry.subjectId)!)) : placeKey(entry.subjectId)\n const about = entry.subject === 'world' ? 'the world' : entry.subject === 'character' ? characters.find(character => character.id === entry.subjectId)?.name ?? key : entry.subject === 'item' ? target.items.get(entry.subjectId)?.name ?? key : target.locations.get(entry.subjectId)?.name ?? key\n return [{ variable: def.key, subject: key, about, value: entry.value, described: describeValue(def, entry.value), baseline: entry.baseline ?? null, visibility: def.visibility }]\n }).slice(0, MAX_VARIABLES_SHOWN),\n engagements: target.engagements.list({ status: 'pending' }).slice(0, MAX_ENGAGEMENTS_SHOWN).map(engagement => ({\n id: engagement.id, title: engagement.title, at: localIso(engagement.at, zone), until: engagement.until === undefined ? null : localIso(engagement.until, zone),\n location: engagement.locationId === undefined ? null : placeKey(engagement.locationId), participants: engagement.participants.map(keyOf), note: engagement.note,\n })),\n relationships: [...target.relationships.list()].filter(relation => scope.relationshipsSince === undefined || relation.updatedTurn >= scope.relationshipsSince).sort((a, b) => b.updatedTurn - a.updatedTurn || b.id - a.id).slice(0, MAX_RELATIONSHIPS_SHOWN).map(relation => ({\n from: keyOf(relation.fromId), to: keyOf(relation.toId), label: relation.label, summary: relation.summary,\n familiarity: relation.familiarity, trust: relation.trust, affinity: relation.affinity, tension: relation.tension, updated_turn: relation.updatedTurn,\n })),\n knowledge: characters.flatMap(character => target.knowledge.list(character.id).flatMap(entry => {\n let subject: string | undefined\n if (entry.subjectKind === 'location') {\n const place = target.locations.get(entry.subjectId)\n subject = place === undefined ? undefined : locationKey(place)\n } else if (entry.subjectKind === 'item') {\n const item = target.items.get(entry.subjectId)\n subject = item === undefined ? undefined : itemKey(item)\n } else {\n const exit = target.locations.allExits().find(candidate => candidate.id === entry.subjectId)\n subject = exit === undefined ? undefined : `${placeKey(exit.fromId)} -> ${placeKey(exit.toId)}`\n }\n return subject === undefined ? [] : [{ character: characterKey(character), kind: entry.subjectKind, subject, learned_turn: entry.learnedTurn, last_observed_turn: entry.lastObservedTurn ?? null }]\n })).slice(0, MAX_KNOWLEDGE_SHOWN),\n }\n return scope.only === undefined ? view : Object.fromEntries(Object.entries(view).map(([key, part]) => [key, scope.only!.includes(key as keyof RecordsView) ? part : []])) as unknown as RecordsView\n}\n","import type { CharacterId, EventId, LocationId, NewPerception, NewStoryEvent, PerceivedEvent, Perception, PerceptionId, PerceptionPatch, StoryEvent, StoryEventFilter, StoryEventPatch } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, NotFoundError } from '../errors.ts'\nimport type { EventRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface EventRow {\n id: number\n turn: number\n round: number\n text: string\n importance: number\n tags: string\n sealed: number\n location_id: number | null\n created_at: string\n}\n\ninterface PerceptionRow {\n id: number\n event_id: number\n character_id: number\n mode: Perception['mode']\n content: string\n gist: string\n accuracy: Perception['accuracy']\n recalls: number\n last_recalled_turn: number | null\n created_at: string\n}\n\nconst toPerception = (row: PerceptionRow): Perception => ({\n id: row.id,\n eventId: row.event_id,\n characterId: row.character_id,\n mode: row.mode,\n content: row.content,\n gist: row.gist,\n accuracy: row.accuracy,\n recalls: row.recalls,\n ...(row.last_recalled_turn === null ? {} : { lastRecalledTurn: row.last_recalled_turn }),\n createdAt: row.created_at,\n})\n\n/** What the repository tells the index about its texts. */\nexport interface IndexWrites {\n put(item: { kind: 'perception' | 'memory' | 'event'; refId: number; characterId: number; text: string; extra?: string }): void\n remove(kind: 'perception' | 'memory' | 'event', refId: number): void\n}\n\nexport class SqliteEventRepository implements EventRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly clock: Clock,\n private readonly index: IndexWrites,\n /** The name of a place, so that what happened there can be found by it. */\n private readonly placeName: (id: LocationId) => string | undefined = () => undefined,\n /** The name of an item, so that what happened to it can be found by it. */\n private readonly itemName: (id: number) => string | undefined = () => undefined,\n ) {}\n\n add(event: NewStoryEvent, perceptions: readonly NewPerception[]): { event: StoryEvent; perceptions: Perception[] } {\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO events (turn, round, text, importance, tags, location_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n [event.turn, event.round, event.text, event.importance, toJson(event.tags), event.locationId ?? null, this.clock().toISOString()],\n )\n const id = Number(lastInsertRowid)\n this.setInvolves(id, event.involves)\n this.setItems(id, event.items ?? [])\n const stored = this.replacePerceptions(id, perceptions)\n const kept = this.require(id)\n this.indexEvent(kept, stored)\n return { event: kept, perceptions: stored }\n }))\n }\n\n get(id: EventId): StoryEvent | undefined {\n const row = this.db.get<EventRow>('SELECT * FROM events WHERE id = ?', [id])\n return row === undefined ? undefined : this.toEvent(row)\n }\n\n list(filter: StoryEventFilter = {}): StoryEvent[] {\n const where: string[] = []\n const params: SqlValue[] = []\n const add = (clause: string, value: SqlValue): void => { where.push(clause); params.push(value) }\n if (filter.turn !== undefined) add('turn = ?', filter.turn)\n if (filter.round !== undefined) add('round = ?', filter.round)\n if (filter.fromTurn !== undefined) add('turn >= ?', filter.fromTurn)\n if (filter.toTurn !== undefined) add('turn <= ?', filter.toTurn)\n if (filter.minImportance !== undefined) add('importance >= ?', filter.minImportance)\n if (filter.locationId !== undefined) add('location_id = ?', filter.locationId)\n if (filter.aboutItem !== undefined) add('id IN (SELECT event_id FROM event_items WHERE item_id = ?)', filter.aboutItem)\n if (filter.involving !== undefined) add('id IN (SELECT event_id FROM event_involves WHERE character_id = ?)', filter.involving)\n const clause = where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`\n return this.db.all<EventRow>(`SELECT * FROM events ${clause} ORDER BY turn, round, id`, params).map(row => this.toEvent(row))\n }\n\n update(id: EventId, patch: StoryEventPatch): StoryEvent {\n return guard(() => this.db.transaction(() => {\n const current = this.draft(id)\n this.db.run('UPDATE events SET text = ?, importance = ?, tags = ?, location_id = ? WHERE id = ?', [\n patch.text ?? current.text, patch.importance ?? current.importance, toJson(patch.tags ?? current.tags), patch.locationId ?? current.locationId ?? null, id,\n ])\n if (patch.involves !== undefined) this.setInvolves(id, patch.involves)\n if (patch.items !== undefined) this.setItems(id, patch.items)\n const kept = this.require(id)\n this.indexEvent(kept, this.perceptionsOf(id))\n return kept\n }))\n }\n\n setPerceptions(id: EventId, perceptions: readonly NewPerception[]): Perception[] {\n return guard(() => this.db.transaction(() => {\n const event = this.draft(id)\n const stored = this.replacePerceptions(id, perceptions)\n this.indexEvent(event, stored)\n return stored\n }))\n }\n\n seal(ids?: readonly EventId[]): number {\n if (ids === undefined) return this.db.run('UPDATE events SET sealed = 1 WHERE sealed = 0').changes\n return this.db.transaction(() => ids.reduce((count, id) => count + this.db.run('UPDATE events SET sealed = 1 WHERE id = ? AND sealed = 0', [id]).changes, 0))\n }\n\n getPerception(id: PerceptionId): Perception | undefined {\n const row = this.db.get<PerceptionRow>('SELECT * FROM perceptions WHERE id = ?', [id])\n return row === undefined ? undefined : toPerception(row)\n }\n\n addPerception(id: EventId, perception: NewPerception): Perception {\n return guard(() => this.db.transaction(() => {\n const event = this.require(id)\n if (this.db.get('SELECT 1 FROM perceptions WHERE event_id = ? AND character_id = ?', [id, perception.characterId]) !== undefined) {\n throw new ConflictError(`character ${perception.characterId} already has a perception of event ${id}: revise that one`)\n }\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO perceptions (event_id, character_id, mode, content, gist, accuracy, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n [id, perception.characterId, perception.mode, perception.content, perception.gist, perception.accuracy, this.clock().toISOString()],\n )\n const added = this.requirePerception(Number(lastInsertRowid))\n this.indexPerception(event, added)\n return added\n }))\n }\n\n updatePerception(id: PerceptionId, patch: PerceptionPatch): Perception {\n return guard(() => this.db.transaction(() => {\n const current = this.requirePerception(id)\n this.db.run('UPDATE perceptions SET mode = ?, content = ?, gist = ?, accuracy = ? WHERE id = ?', [\n patch.mode ?? current.mode, patch.content ?? current.content, patch.gist ?? current.gist, patch.accuracy ?? current.accuracy, id,\n ])\n const revised = this.requirePerception(id)\n this.indexPerception(this.require(revised.eventId), revised)\n return revised\n }))\n }\n\n perceptionsOf(id: EventId): Perception[] {\n return this.db.all<PerceptionRow>('SELECT * FROM perceptions WHERE event_id = ? ORDER BY id', [id]).map(toPerception)\n }\n\n perceivedBy(characterId: CharacterId, filter: { fromTurn?: number; toTurn?: number } = {}): PerceivedEvent[] {\n const params: SqlValue[] = [characterId]\n let extra = ''\n if (filter.fromTurn !== undefined) { extra += ' AND e.turn >= ?'; params.push(filter.fromTurn) }\n if (filter.toTurn !== undefined) { extra += ' AND e.turn <= ?'; params.push(filter.toTurn) }\n const rows = this.db.all<PerceptionRow & { e_id: number }>(\n `SELECT p.*, e.id AS e_id FROM perceptions p JOIN events e ON e.id = p.event_id\n WHERE p.character_id = ?${extra} ORDER BY e.turn, e.round, e.id`,\n params,\n )\n return rows.flatMap((row) => {\n const event = this.get(row.e_id)\n return event === undefined ? [] : [{ perception: toPerception(row), event }]\n })\n }\n\n touchPerceptions(ids: readonly number[], turn: number): void {\n this.db.transaction(() => {\n for (const id of ids) this.db.run('UPDATE perceptions SET recalls = recalls + 1, last_recalled_turn = ? WHERE id = ?', [turn, id])\n })\n }\n\n remove(id: EventId): boolean {\n return this.db.transaction(() => {\n if (this.get(id)?.sealed === true) throw new ConflictError(`event ${id} is sealed: events cannot be removed once their records are complete`)\n for (const perception of this.perceptionsOf(id)) this.index.remove('perception', perception.id)\n this.index.remove('event', id)\n return this.db.run('DELETE FROM events WHERE id = ?', [id]).changes > 0\n })\n }\n\n /** Index again what happened in a place, after the place was renamed. */\n reindexPlace(id: LocationId): void {\n for (const event of this.list({ locationId: id })) this.indexEvent(event, this.perceptionsOf(event.id))\n }\n\n /** What an event is found by besides its text: its tags and where it happened. */\n private extraOf(event: StoryEvent): string {\n const place = event.locationId === undefined ? undefined : this.placeName(event.locationId)\n const things = event.items.flatMap(id => this.itemName(id) ?? [])\n return [...event.tags, ...(place === undefined ? [] : [place]), ...things].join(' ')\n }\n\n /** Keep the index of an event and of what each character took in of it up to date. */\n private indexEvent(event: StoryEvent, perceptions: readonly Perception[]): void {\n this.index.put({ kind: 'event', refId: event.id, characterId: 0, text: event.text, extra: this.extraOf(event) })\n for (const perception of perceptions) this.indexPerception(event, perception)\n }\n\n private indexPerception(event: StoryEvent, perception: Perception): void {\n this.index.put({ kind: 'perception', refId: perception.id, characterId: perception.characterId, text: perception.content, extra: this.extraOf(event) })\n }\n\n private toEvent(row: EventRow): StoryEvent {\n const involves = this.db.all<{ character_id: number }>('SELECT character_id FROM event_involves WHERE event_id = ? ORDER BY character_id', [row.id]).map(entry => entry.character_id)\n const items = this.db.all<{ item_id: number }>('SELECT item_id FROM event_items WHERE event_id = ? ORDER BY item_id', [row.id]).map(entry => entry.item_id)\n return {\n items,\n id: row.id, turn: row.turn, round: row.round, text: row.text, importance: row.importance,\n tags: parseStringList(row.tags, 'events.tags'), involves, ...(row.location_id === null ? {} : { locationId: row.location_id }), sealed: row.sealed === 1, createdAt: row.created_at,\n }\n }\n\n private require(id: EventId): StoryEvent {\n const event = this.get(id)\n if (event === undefined) throw new NotFoundError(`event ${id} does not exist`)\n return event\n }\n\n private draft(id: EventId): StoryEvent {\n const event = this.require(id)\n if (event.sealed) throw new ConflictError(`event ${id} is sealed: events cannot change once their records are complete`)\n return event\n }\n\n private requirePerception(id: PerceptionId): Perception {\n const found = this.getPerception(id)\n if (found === undefined) throw new NotFoundError(`perception ${id} does not exist`)\n return found\n }\n\n private setItems(id: EventId, items: readonly number[]): void {\n this.db.run('DELETE FROM event_items WHERE event_id = ?', [id])\n for (const itemId of new Set(items)) this.db.run('INSERT INTO event_items (event_id, item_id) VALUES (?, ?)', [id, itemId])\n }\n\n private setInvolves(id: EventId, characters: readonly CharacterId[]): void {\n this.db.run('DELETE FROM event_involves WHERE event_id = ?', [id])\n for (const characterId of new Set(characters)) this.db.run('INSERT INTO event_involves (event_id, character_id) VALUES (?, ?)', [id, characterId])\n }\n\n private replacePerceptions(id: EventId, perceptions: readonly NewPerception[]): Perception[] {\n const now = this.clock().toISOString()\n for (const old of this.perceptionsOf(id)) this.index.remove('perception', old.id)\n this.db.run('DELETE FROM perceptions WHERE event_id = ?', [id])\n for (const perception of perceptions) {\n this.db.run(\n 'INSERT INTO perceptions (event_id, character_id, mode, content, gist, accuracy, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n [id, perception.characterId, perception.mode, perception.content, perception.gist, perception.accuracy, now],\n )\n }\n return this.perceptionsOf(id)\n }\n}\n","import type { CharacterMemory, CharacterMemoryPatch, MemoryId, NewCharacterMemory } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { MemoryRepository } from '../repositories.ts'\nimport type { IndexWrites } from './event-repository.ts'\nimport { guard, parseNumberList, toJson } from './support.ts'\n\ninterface MemoryRow {\n id: number\n character_id: number\n kind: CharacterMemory['kind']\n text: string\n about: string\n importance: number\n turn: number\n recalls: number\n last_recalled_turn: number | null\n created_at: string\n}\n\nconst toMemory = (row: MemoryRow): CharacterMemory => ({\n id: row.id,\n characterId: row.character_id,\n kind: row.kind,\n text: row.text,\n about: parseNumberList(row.about, 'memories.about'),\n importance: row.importance,\n turn: row.turn,\n recalls: row.recalls,\n ...(row.last_recalled_turn === null ? {} : { lastRecalledTurn: row.last_recalled_turn }),\n createdAt: row.created_at,\n})\n\nexport class SqliteMemoryRepository implements MemoryRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock, private readonly index: IndexWrites) {}\n\n add(memory: NewCharacterMemory): CharacterMemory {\n return guard(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO memories (character_id, kind, text, about, importance, turn, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n [memory.characterId, memory.kind, memory.text, toJson(memory.about), memory.importance, memory.turn, this.clock().toISOString()],\n )\n const added = this.require(Number(lastInsertRowid))\n this.index.put({ kind: 'memory', refId: added.id, characterId: added.characterId, text: added.text })\n return added\n })\n }\n\n get(id: MemoryId): CharacterMemory | undefined {\n const row = this.db.get<MemoryRow>('SELECT * FROM memories WHERE id = ?', [id])\n return row === undefined ? undefined : toMemory(row)\n }\n\n list(characterId: number): CharacterMemory[] {\n return this.db.all<MemoryRow>('SELECT * FROM memories WHERE character_id = ? ORDER BY id', [characterId]).map(toMemory)\n }\n\n update(id: MemoryId, patch: CharacterMemoryPatch): CharacterMemory {\n return guard(() => {\n const current = this.require(id)\n this.db.run('UPDATE memories SET text = ?, about = ?, importance = ? WHERE id = ?', [\n patch.text ?? current.text, toJson(patch.about ?? current.about), patch.importance ?? current.importance, id,\n ])\n const changed = this.require(id)\n this.index.put({ kind: 'memory', refId: id, characterId: changed.characterId, text: changed.text })\n return changed\n })\n }\n\n touch(ids: readonly MemoryId[], turn: number): void {\n this.db.transaction(() => {\n for (const id of ids) this.db.run('UPDATE memories SET recalls = recalls + 1, last_recalled_turn = ? WHERE id = ?', [turn, id])\n })\n }\n\n remove(id: MemoryId): boolean {\n this.index.remove('memory', id)\n return this.db.run('DELETE FROM memories WHERE id = ?', [id]).changes > 0\n }\n\n private require(id: MemoryId): CharacterMemory {\n const memory = this.get(id)\n if (memory === undefined) throw new NotFoundError(`memory ${id} does not exist`)\n return memory\n }\n}\n","import type { JsonValue, NewSummary, PendingCommit, StoryThread, Summary, SummaryId, SummaryLevel, ThreadId, ThreadStatus } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { CorruptDataError, NotFoundError } from '../errors.ts'\nimport type { PendingCommitRepository, SummaryRepository, ThreadRepository } from '../repositories.ts'\nimport { toJson } from './support.ts'\n\ninterface ThreadRow {\n id: number\n text: string\n status: ThreadStatus\n opened_turn: number\n resolved_turn: number | null\n}\n\nconst toThread = (row: ThreadRow): StoryThread => ({\n id: row.id,\n text: row.text,\n status: row.status,\n openedTurn: row.opened_turn,\n ...(row.resolved_turn === null ? {} : { resolvedTurn: row.resolved_turn }),\n})\n\nexport class SqliteThreadRepository implements ThreadRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n open(text: string, turn: number): StoryThread {\n const { lastInsertRowid } = this.db.run('INSERT INTO story_threads (text, status, opened_turn, created_at) VALUES (?, ?, ?, ?)', [text, 'open', turn, this.clock().toISOString()])\n return this.require(Number(lastInsertRowid))\n }\n\n get(id: ThreadId): StoryThread | undefined {\n const row = this.db.get<ThreadRow>('SELECT * FROM story_threads WHERE id = ?', [id])\n return row === undefined ? undefined : toThread(row)\n }\n\n list(status?: ThreadStatus): StoryThread[] {\n const rows = status === undefined\n ? this.db.all<ThreadRow>('SELECT * FROM story_threads ORDER BY id')\n : this.db.all<ThreadRow>('SELECT * FROM story_threads WHERE status = ? ORDER BY id', [status])\n return rows.map(toThread)\n }\n\n resolve(id: ThreadId, turn: number): StoryThread {\n this.require(id)\n this.db.run(\"UPDATE story_threads SET status = 'resolved', resolved_turn = ? WHERE id = ?\", [turn, id])\n return this.require(id)\n }\n\n remove(id: ThreadId): boolean {\n return this.db.run('DELETE FROM story_threads WHERE id = ?', [id]).changes > 0\n }\n\n private require(id: ThreadId): StoryThread {\n const thread = this.get(id)\n if (thread === undefined) throw new NotFoundError(`thread ${id} does not exist`)\n return thread\n }\n}\n\ninterface SummaryRow {\n id: number\n level: SummaryLevel\n from_turn: number\n to_turn: number\n text: string\n created_at: string\n}\n\nconst toSummary = (row: SummaryRow): Summary => ({ id: row.id, level: row.level, fromTurn: row.from_turn, toTurn: row.to_turn, text: row.text, createdAt: row.created_at })\n\nexport class SqliteSummaryRepository implements SummaryRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(summary: NewSummary): Summary {\n const { lastInsertRowid } = this.db.run('INSERT INTO summaries (level, from_turn, to_turn, text, created_at) VALUES (?, ?, ?, ?, ?)', [summary.level, summary.fromTurn, summary.toTurn, summary.text, this.clock().toISOString()])\n const row = this.db.get<SummaryRow>('SELECT * FROM summaries WHERE id = ?', [Number(lastInsertRowid)])\n if (row === undefined) throw new NotFoundError('the summary was not stored')\n return toSummary(row)\n }\n\n list(level?: SummaryLevel): Summary[] {\n const rows = level === undefined\n ? this.db.all<SummaryRow>('SELECT * FROM summaries ORDER BY from_turn, id')\n : this.db.all<SummaryRow>('SELECT * FROM summaries WHERE level = ? ORDER BY from_turn, id', [level])\n return rows.map(toSummary)\n }\n\n remove(ids: readonly SummaryId[]): void {\n this.db.transaction(() => { for (const id of ids) this.db.run('DELETE FROM summaries WHERE id = ?', [id]) })\n }\n}\n\nexport class SqlitePendingCommitRepository implements PendingCommitRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n enqueue(turn: number, round: number, payload: JsonValue): void {\n this.db.run('INSERT OR REPLACE INTO pending_commits (turn, round, payload, created_at) VALUES (?, ?, ?, ?)', [turn, round, toJson(payload), this.clock().toISOString()])\n }\n\n list(): PendingCommit[] {\n return this.db.all<{ turn: number; round: number; payload: string; created_at: string }>('SELECT * FROM pending_commits ORDER BY turn, round').map((row) => {\n try {\n return { turn: row.turn, round: row.round, payload: JSON.parse(row.payload) as JsonValue, createdAt: row.created_at }\n } catch (error) {\n throw new CorruptDataError(`pending commit ${row.turn}.${row.round} does not hold JSON`, { cause: error })\n }\n })\n }\n\n complete(rounds: readonly { turn: number; round: number }[]): void {\n this.db.transaction(() => { for (const { turn, round } of rounds) this.db.run('DELETE FROM pending_commits WHERE turn = ? AND round = ?', [turn, round]) })\n }\n}\n","import type { EmbeddingIndexInfo, PendingEmbedding, RecallHit, RecallItemKind } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError } from '../errors.ts'\nimport { tokens } from '../memory/recall.ts'\nimport type { MetadataRepository, RecallIndexRepository, RecallSearch, VectorSearch, VectorSupport } from '../repositories.ts'\n\nconst METADATA_KEY = 'embedding.index'\nconst KEY_LETTER: Record<RecallItemKind, string> = { perception: 'p', memory: 'm', event: 'e' }\n/** The most terms a lexical query uses: a long situation would otherwise match nearly everything. */\nconst MAX_QUERY_TERMS = 32\n/** A term in more than this share of the indexed texts says little about any of them (\"the\", a character's name in a story about them). */\nconst COMMON_SHARE = 0.5\n/** The common terms are only dropped once there are enough texts to tell, and never all of them. */\nconst MIN_TEXTS_FOR_COMMON = 6\n/** Hits scoring less than this against the best hit are noise from a shared word. */\nconst MIN_RELATIVE_SCORE = 0.2\n\ninterface ItemRow { id: number; kind: RecallItemKind; ref_id: number; character_id: number; text: string; embedded: number }\n\nconst keyOf = (kind: RecallItemKind, refId: number): string => `${KEY_LETTER[kind]}:${refId}`\nconst blob = (vector: readonly number[]): Uint8Array => new Uint8Array(new Float32Array(vector).buffer)\n\n/**\n * The texts a session can be searched by, and how: what was said or believed or happened is\n * indexed for lexical search (SQLite FTS5 over the same tokens recall uses, so that scripts written\n * without spaces match too), and, once something gives each text a vector, for dense search\n * (the sqlite-vec extension, one vector per text, with the character as a partition so that a\n * search of one character's memory never sees another's).\n *\n * Vectors are made elsewhere: this keeps the texts, says which still need one, and stores them.\n * A change to a text drops its vector, because it no longer describes it.\n */\nexport class SqliteRecallIndex implements RecallIndexRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly metadata: Pick<MetadataRepository, 'getValue' | 'setValue' | 'deleteValue'>,\n readonly vectors: VectorSupport,\n ) {}\n\n put(item: { kind: RecallItemKind; refId: number; characterId: number; text: string; extra?: string }): void {\n const existing = this.db.get<ItemRow>('SELECT * FROM recall_items WHERE kind = ? AND ref_id = ?', [item.kind, item.refId])\n const terms = [...tokens(`${item.text} ${item.extra ?? ''}`)].join(' ')\n if (existing === undefined) {\n const { lastInsertRowid } = this.db.run('INSERT INTO recall_items (kind, ref_id, character_id, text) VALUES (?, ?, ?, ?)', [item.kind, item.refId, item.characterId, item.text])\n this.db.run('INSERT INTO recall_fts (rowid, tokens) VALUES (?, ?)', [lastInsertRowid, terms])\n return\n }\n const changed = existing.text !== item.text || existing.character_id !== item.characterId\n this.db.run('UPDATE recall_items SET text = ?, character_id = ?, embedded = CASE WHEN ? THEN 0 ELSE embedded END WHERE id = ?', [item.text, item.characterId, changed ? 1 : 0, existing.id])\n this.db.run('DELETE FROM recall_fts WHERE rowid = ?', [existing.id])\n this.db.run('INSERT INTO recall_fts (rowid, tokens) VALUES (?, ?)', [existing.id, terms])\n if (changed) this.dropVector(existing.id)\n }\n\n remove(kind: RecallItemKind, refId: number): void {\n const existing = this.db.get<ItemRow>('SELECT * FROM recall_items WHERE kind = ? AND ref_id = ?', [kind, refId])\n if (existing === undefined) return\n this.db.run('DELETE FROM recall_fts WHERE rowid = ?', [existing.id])\n this.dropVector(existing.id)\n this.db.run('DELETE FROM recall_items WHERE id = ?', [existing.id])\n }\n\n lexical({ text, characterId, kinds, limit }: RecallSearch): RecallHit[] {\n const terms = this.informative([...tokens(text)].slice(0, MAX_QUERY_TERMS))\n if (terms.length === 0) return []\n const params: SqlValue[] = [terms.map(term => `\"${term.replaceAll('\"', '\"\"')}\"`).join(' OR ')]\n let where = ''\n if (characterId !== undefined) { where += ' AND i.character_id = ?'; params.push(characterId) }\n if (kinds !== undefined && kinds.length > 0) { where += ` AND i.kind IN (${kinds.map(() => '?').join(', ')})`; params.push(...kinds) }\n params.push(limit)\n const rows = this.db.all<ItemRow & { rank: number }>(\n `SELECT i.*, bm25(recall_fts) AS rank FROM recall_fts JOIN recall_items i ON i.id = recall_fts.rowid\n WHERE recall_fts MATCH ?${where} ORDER BY rank LIMIT ?`,\n params,\n )\n // bm25 is smaller for a better match, and negative: the best hit counts as 1 and the rest relative to it.\n const best = rows.reduce((top, row) => Math.max(top, -row.rank), 0)\n return rows\n .map(row => ({ key: keyOf(row.kind, row.ref_id), kind: row.kind, refId: row.ref_id, score: best === 0 ? 0 : Math.max(0, -row.rank) / best }))\n .filter(hit => hit.score >= MIN_RELATIVE_SCORE)\n }\n\n /** The terms that tell texts apart: those found in most of the texts are left out, unless that would leave none. */\n private informative(terms: readonly string[]): string[] {\n if (terms.length === 0) return []\n const total = this.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM recall_items')?.n ?? 0\n if (total < MIN_TEXTS_FOR_COMMON) return [...terms]\n const counts = new Map(this.db.all<{ term: string; doc: number }>(\n `SELECT term, doc FROM recall_vocab WHERE term IN (${terms.map(() => '?').join(', ')})`, [...terms],\n ).map(row => [row.term, row.doc]))\n const kept = terms.filter(term => (counts.get(term) ?? 0) <= COMMON_SHARE * total)\n return kept.length > 0 ? kept : [...terms]\n }\n\n vector({ vector, characterId, limit }: VectorSearch): RecallHit[] {\n const info = this.info()\n if (info === undefined || !this.vectors.available) return []\n if (vector.length !== info.dimensions) throw new InvalidValueError(`the query has ${vector.length} dimensions, the vectors of this session have ${info.dimensions}`)\n const params: SqlValue[] = [blob(vector), limit]\n let where = ''\n if (characterId !== undefined) { where = ' AND character_id = ?'; params.push(characterId) }\n const near = this.db.all<{ rowid: number; distance: number }>(`SELECT rowid, distance FROM recall_vec WHERE embedding MATCH ? AND k = ?${where}`, params)\n if (near.length === 0) return []\n const items = this.db.all<ItemRow>(`SELECT * FROM recall_items WHERE id IN (${near.map(() => '?').join(', ')})`, near.map(entry => entry.rowid))\n const byId = new Map(items.map(item => [item.id, item]))\n return near.flatMap((entry) => {\n const item = byId.get(entry.rowid)\n // The vectors are compared by cosine distance, which is 0 for the same direction and 2 for the opposite.\n return item === undefined ? [] : [{ key: keyOf(item.kind, item.ref_id), kind: item.kind, refId: item.ref_id, score: Math.min(1, Math.max(0, 1 - entry.distance)) }]\n })\n }\n\n info(): EmbeddingIndexInfo | undefined {\n const stored = this.metadata.getValue(METADATA_KEY) as { model: string; dimensions: number } | undefined\n if (stored === undefined) return undefined\n const counts = this.db.get<{ embedded: number; pending: number }>(\"SELECT COALESCE(SUM(embedded = 1), 0) AS embedded, COALESCE(SUM(embedded = 0), 0) AS pending FROM recall_items\")\n return { model: stored.model, dimensions: stored.dimensions, embedded: counts?.embedded ?? 0, pending: counts?.pending ?? 0 }\n }\n\n pending(limit: number): PendingEmbedding[] {\n return this.db.all<ItemRow>('SELECT * FROM recall_items WHERE embedded = 0 ORDER BY id LIMIT ?', [limit]).map(row => ({ id: row.id, kind: row.kind, text: row.text }))\n }\n\n store(model: string, vectors: readonly { id: number; vector: readonly number[] }[]): number {\n if (!this.vectors.available) throw new ConflictError(`vector search is not available here: ${this.vectors.error ?? 'the extension is not loaded'}`)\n if (vectors.length === 0) return 0\n const dimensions = vectors[0]!.vector.length\n return this.db.transaction(() => {\n const info = this.info()\n if (info === undefined) {\n if (dimensions < 1) throw new InvalidValueError('a vector has no dimensions')\n this.db.exec(`CREATE VIRTUAL TABLE recall_vec USING vec0(character_id integer partition key, embedding float[${Math.trunc(dimensions)}] distance_metric=cosine)`)\n this.metadata.setValue(METADATA_KEY, { model, dimensions })\n } else if (info.model !== model || info.dimensions !== dimensions) {\n throw new ConflictError(`this session's vectors are from ${info.model} with ${info.dimensions} dimensions, not ${model} with ${dimensions}: reset the vectors to change them`)\n }\n let stored = 0\n for (const { id, vector } of vectors) {\n if (vector.length !== dimensions) throw new InvalidValueError(`vector of text ${id} has ${vector.length} dimensions, not ${dimensions}`)\n const item = this.db.get<ItemRow>('SELECT * FROM recall_items WHERE id = ?', [id])\n if (item === undefined) continue\n this.db.run('DELETE FROM recall_vec WHERE rowid = ?', [BigInt(id)])\n this.db.run('INSERT INTO recall_vec (rowid, character_id, embedding) VALUES (?, ?, ?)', [BigInt(id), BigInt(item.character_id), blob(vector)])\n this.db.run('UPDATE recall_items SET embedded = 1 WHERE id = ?', [id])\n stored++\n }\n return stored\n })\n }\n\n reset(): void {\n this.db.transaction(() => {\n if (this.info() === undefined) return\n this.db.exec('DROP TABLE IF EXISTS recall_vec')\n this.db.run('UPDATE recall_items SET embedded = 0')\n this.metadata.deleteValue(METADATA_KEY)\n })\n }\n\n private dropVector(id: number): void {\n if (this.vectors.available && this.info() !== undefined) this.db.run('DELETE FROM recall_vec WHERE rowid = ?', [BigInt(id)])\n }\n}\n","import { MAX_TRIGGERS, type NewTriggerNote, type Trigger, type TriggerAnnouncement, type TriggerCondition, type TriggerDefinition, type TriggerEffect, type TriggerId, type TriggerNote, type TriggerNoteKind, type TriggerStatus } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { TriggerRepository } from '../repositories.ts'\nimport { guard, parseNumberList, toJson } from './support.ts'\n\ninterface TriggerRow {\n id: number\n key: string\n name: string\n condition: string\n effects: string\n repeat: number\n cooldown_seconds: number | null\n chance: number | null\n priority: number\n expires: string | null\n announce: string | null\n status: TriggerStatus\n fire_count: number\n last_fired_ms: number | null\n last_result: number\n problem: string | null\n origin: Trigger['origin']\n created_turn: number\n}\n\ninterface NoteRow {\n id: number\n trigger_id: number\n kind: TriggerNoteKind\n text: string\n character_ids: string\n turn: number\n status: TriggerNote['status']\n}\n\nconst MAX_TEXT = 2000\n\nfunction parse<T>(text: string, what: string): T {\n try {\n return JSON.parse(text) as T\n } catch (error) {\n throw new CorruptDataError(`a trigger's ${what} is not valid JSON`, { cause: error })\n }\n}\n\nexport class SqliteTriggerRepository implements TriggerRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n add(definition: TriggerDefinition, origin: Trigger['origin'], turn: number): Trigger {\n this.check(definition)\n if ((this.db.get<{ count: number }>('SELECT count(*) AS count FROM triggers')?.count ?? 0) >= MAX_TRIGGERS) throw new InvalidValueError(`a story has at most ${MAX_TRIGGERS} triggers`)\n return guard(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO triggers (key, name, condition, effects, repeat, cooldown_seconds, chance, priority, expires, announce, origin, created_turn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [definition.key, definition.name, toJson(definition.condition), toJson(definition.effects), definition.repeat ? 1 : 0, definition.cooldownSeconds ?? null, definition.chance ?? null, definition.priority, definition.expires ?? null, definition.announce === undefined ? null : toJson(definition.announce), origin, turn],\n )\n return this.require(Number(lastInsertRowid))\n })\n }\n\n get(id: TriggerId): Trigger | undefined {\n const row = this.db.get<TriggerRow>('SELECT * FROM triggers WHERE id = ?', [id])\n return row === undefined ? undefined : this.toTrigger(row)\n }\n\n getByKey(key: string): Trigger | undefined {\n const row = this.db.get<TriggerRow>('SELECT * FROM triggers WHERE key = ?', [key])\n return row === undefined ? undefined : this.toTrigger(row)\n }\n\n list(filter: { status?: TriggerStatus } = {}): Trigger[] {\n const rows = filter.status === undefined\n ? this.db.all<TriggerRow>('SELECT * FROM triggers ORDER BY priority DESC, id')\n : this.db.all<TriggerRow>('SELECT * FROM triggers WHERE status = ? ORDER BY priority DESC, id', [filter.status])\n return rows.map(row => this.toTrigger(row))\n }\n\n update(id: TriggerId, patch: { status?: TriggerStatus; fireCount?: number; lastFiredMs?: number; lastResult?: boolean; problem?: string }): Trigger {\n const current = this.require(id)\n this.db.run('UPDATE triggers SET status = ?, fire_count = ?, last_fired_ms = ?, last_result = ?, problem = ? WHERE id = ?', [\n patch.status ?? current.status, patch.fireCount ?? current.fireCount, patch.lastFiredMs ?? current.lastFiredMs ?? null,\n (patch.lastResult ?? current.lastResult) ? 1 : 0, patch.problem ?? current.problem ?? null, id,\n ])\n return this.require(id)\n }\n\n addNote(note: NewTriggerNote): TriggerNote {\n if (note.text.trim() === '' || note.text.length > MAX_TEXT) throw new InvalidValueError(`a note needs a text of at most ${MAX_TEXT} characters`)\n return guard(() => {\n const { lastInsertRowid } = this.db.run('INSERT INTO trigger_notes (trigger_id, kind, text, character_ids, turn) VALUES (?, ?, ?, ?, ?)', [note.triggerId, note.kind, note.text.trim(), toJson([...new Set(note.characterIds ?? [])]), note.turn])\n return this.requireNote(Number(lastInsertRowid))\n })\n }\n\n notes(filter: { status?: TriggerNote['status']; kind?: TriggerNoteKind } = {}): TriggerNote[] {\n const where: string[] = []\n const params: SqlValue[] = []\n if (filter.status !== undefined) { where.push('status = ?'); params.push(filter.status) }\n if (filter.kind !== undefined) { where.push('kind = ?'); params.push(filter.kind) }\n return this.db.all<NoteRow>(`SELECT * FROM trigger_notes ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`} ORDER BY id`, params).map(row => this.toNote(row))\n }\n\n resolveNote(id: number, status: 'done' | 'lapsed'): void {\n if (this.db.run('UPDATE trigger_notes SET status = ? WHERE id = ?', [status, id]).changes === 0) throw new NotFoundError(`trigger note ${id} does not exist`)\n }\n\n private check(definition: TriggerDefinition): void {\n if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(definition.key)) throw new InvalidValueError('a trigger key is lowercase letters, digits, hyphens and underscores, at most 64')\n if (definition.name.trim() === '' || definition.name.length > 200) throw new InvalidValueError('a trigger needs a name of at most 200 characters')\n if (definition.effects.length === 0) throw new InvalidValueError('a trigger needs at least one effect')\n if (definition.chance !== undefined && !(definition.chance >= 0 && definition.chance <= 1)) throw new InvalidValueError('a chance is from 0 to 1')\n if (definition.cooldownSeconds !== undefined && (!Number.isSafeInteger(definition.cooldownSeconds) || definition.cooldownSeconds < 0)) throw new InvalidValueError('a cooldown is a whole number of seconds')\n if (!Number.isSafeInteger(definition.priority)) throw new InvalidValueError('a priority is a whole number')\n }\n\n private toTrigger(row: TriggerRow): Trigger {\n return {\n id: row.id, key: row.key, name: row.name, condition: parse<TriggerCondition>(row.condition, 'condition'), effects: parse<TriggerEffect[]>(row.effects, 'effects'),\n repeat: row.repeat === 1, ...(row.cooldown_seconds === null ? {} : { cooldownSeconds: row.cooldown_seconds }), ...(row.chance === null ? {} : { chance: row.chance }),\n priority: row.priority, ...(row.expires === null ? {} : { expires: row.expires }), ...(row.announce === null ? {} : { announce: parse<TriggerAnnouncement>(row.announce, 'announcement') }), status: row.status, fireCount: row.fire_count,\n ...(row.last_fired_ms === null ? {} : { lastFiredMs: row.last_fired_ms }), lastResult: row.last_result === 1, ...(row.problem === null ? {} : { problem: row.problem }),\n origin: row.origin, createdTurn: row.created_turn,\n }\n }\n\n private toNote(row: NoteRow): TriggerNote {\n return { id: row.id, triggerId: row.trigger_id, kind: row.kind, text: row.text, characterIds: parseNumberList(row.character_ids, 'trigger_notes.character_ids'), turn: row.turn, status: row.status }\n }\n\n private require(id: TriggerId): Trigger {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`trigger ${id} does not exist`)\n return found\n }\n\n private requireNote(id: number): TriggerNote {\n const row = this.db.get<NoteRow>('SELECT * FROM trigger_notes WHERE id = ?', [id])\n if (row === undefined) throw new NotFoundError(`trigger note ${id} does not exist`)\n return this.toNote(row)\n }\n}\n","import type { ClockMode, ClockState, TimeChange, TimeChangeFilter, TimeChangeKind } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { ClockRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface ClockRow { mode: ClockMode; now_ms: number }\ninterface LogRow { id: number; turn: number; round: number; kind: TimeChangeKind; from_ms: number; to_ms: number; reason: string }\n\nconst toChange = (row: LogRow): TimeChange => ({ id: row.id, turn: row.turn, round: row.round, kind: row.kind, from: row.from_ms, to: row.to_ms, reason: row.reason })\n\nexport class SqliteClockRepository implements ClockRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n get(): ClockState | undefined {\n const row = this.db.get<ClockRow>('SELECT mode, now_ms FROM clock WHERE id = 1')\n return row === undefined ? undefined : { mode: row.mode, now: row.now_ms }\n }\n\n start(mode: ClockMode, now: number): ClockState {\n assertInstant(now)\n return guard(() => this.db.transaction(() => {\n if (this.get() !== undefined) throw new ConflictError('the clock is already started')\n this.db.run('INSERT INTO clock (id, mode, now_ms) VALUES (1, ?, ?)', [mode, now])\n this.db.run('INSERT INTO time_log (turn, round, kind, from_ms, to_ms, reason) VALUES (0, 0, ?, ?, ?, ?)', ['start', now, now, ''])\n return { mode, now }\n }))\n }\n\n advance(step: { to: number; turn: number; round: number; kind: Exclude<TimeChangeKind, 'start' | 'resync'>; reason?: string }): TimeChange {\n assertInstant(step.to)\n return guard(() => this.db.transaction(() => {\n const current = this.require()\n if (step.to < current.now) throw new InvalidValueError(`the story's time cannot go back: it is ${current.now} and ${step.to} is earlier`)\n return this.record(current.mode, current.now, step.to, step.turn, step.round, step.kind, step.reason ?? '')\n }))\n }\n\n resync(mode: ClockMode, now: number, turn: number, reason = ''): TimeChange {\n assertInstant(now)\n return guard(() => this.db.transaction(() => this.record(mode, this.require().now, now, turn, 0, 'resync', reason)))\n }\n\n log(filter: TimeChangeFilter = {}): TimeChange[] {\n const where: string[] = []\n const params: SqlValue[] = []\n const add = (clause: string, value: SqlValue): void => { where.push(clause); params.push(value) }\n if (filter.turn !== undefined) add('turn = ?', filter.turn)\n if (filter.round !== undefined) add('round = ?', filter.round)\n if (filter.fromTurn !== undefined) add('turn >= ?', filter.fromTurn)\n if (filter.toTurn !== undefined) add('turn <= ?', filter.toTurn)\n if (filter.kind !== undefined) add('kind = ?', filter.kind)\n return this.db.all<LogRow>(`SELECT * FROM time_log ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`} ORDER BY id`, params).map(toChange)\n }\n\n at(turn: number, round: number): number | undefined {\n return this.db.get<{ from_ms: number }>(\"SELECT from_ms FROM time_log WHERE turn = ? AND round = ? AND kind IN ('elapsed', 'real') ORDER BY id LIMIT 1\", [turn, round])?.from_ms\n }\n\n private require(): ClockState {\n const state = this.get()\n if (state === undefined) throw new NotFoundError('the clock is not started')\n return state\n }\n\n private record(mode: ClockMode, from: number, to: number, turn: number, round: number, kind: TimeChangeKind, reason: string): TimeChange {\n this.db.run('UPDATE clock SET mode = ?, now_ms = ? WHERE id = 1', [mode, to])\n const { lastInsertRowid } = this.db.run('INSERT INTO time_log (turn, round, kind, from_ms, to_ms, reason) VALUES (?, ?, ?, ?, ?, ?)', [turn, round, kind, from, to, reason])\n return { id: Number(lastInsertRowid), turn, round, kind, from, to, reason }\n }\n}\n\nfunction assertInstant(value: number): void {\n if (!Number.isSafeInteger(value) || Math.abs(value) > 8_640_000_000_000_000) throw new InvalidValueError(`${value} is not an instant (whole milliseconds since 1970)`)\n}\n","import {\n CONTAINER_STATES, DEFAULT_SLOTS, SLOT_ID,\n type CharacterId, type Holder, type Holding, type Item, type ItemId, type ItemPatch, type LocationId, type NewItem, type Slot,\n} from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { ItemRepository, SlotRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface ItemRow {\n id: number\n source_id: string | null\n name: string\n description: string\n quantity: number\n unique_item: number\n quality: string\n notable: number\n hidden: number\n wearable_slot: string | null\n container_state: Item['container'] extends infer C ? (C extends { state: infer S } ? S : never) | null : never\n owner_id: number | null\n created_at: string\n}\n\ninterface HoldingRow {\n item_id: number\n holder_kind: 'location' | 'character' | 'item'\n holder_id: number\n mode: 'at' | 'held' | 'worn' | 'inside'\n slot: string | null\n position: string\n feature_key: string | null\n}\n\nconst toItem = (row: ItemRow): Item => ({\n id: row.id,\n ...(row.source_id === null ? {} : { sourceId: row.source_id }),\n name: row.name,\n description: row.description,\n quantity: row.quantity,\n unique: row.unique_item === 1,\n quality: row.quality,\n notable: row.notable === 1,\n hidden: row.hidden === 1,\n ...(row.wearable_slot === null ? {} : { wearableSlot: row.wearable_slot }),\n ...(row.container_state === null ? {} : { container: { state: row.container_state } }),\n ...(row.owner_id === null ? {} : { ownerId: row.owner_id }),\n createdAt: row.created_at,\n})\n\nconst toHolder = (row: HoldingRow): Holder => {\n switch (row.holder_kind) {\n case 'location': return { kind: 'location', locationId: row.holder_id, ...(row.position === '' ? {} : { position: row.position }), ...(row.feature_key === null ? {} : { featureKey: row.feature_key }) }\n case 'character': return row.mode === 'worn'\n ? { kind: 'character', characterId: row.holder_id, mode: 'worn', slot: row.slot!, ...(row.position === '' ? {} : { position: row.position }) }\n : { kind: 'character', characterId: row.holder_id, mode: 'held' }\n case 'item': return { kind: 'item', itemId: row.holder_id, ...(row.position === '' ? {} : { position: row.position }) }\n }\n}\n\nexport class SqliteSlotRepository implements SlotRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n ensureDefaults(): void {\n for (const slot of DEFAULT_SLOTS) this.db.run('INSERT OR IGNORE INTO slots (id, name, capacity) VALUES (?, ?, ?)', [slot.id, slot.name, slot.capacity])\n }\n\n list(): Slot[] {\n return this.db.all<Slot>('SELECT id, name, capacity FROM slots ORDER BY rowid')\n }\n\n get(id: string): Slot | undefined {\n return this.db.get<Slot>('SELECT id, name, capacity FROM slots WHERE id = ?', [id])\n }\n\n upsert(slot: Slot): Slot {\n if (!SLOT_ID.test(slot.id)) throw new InvalidValueError(`slot id \"${slot.id}\" must be lowercase letters, digits, \"-\" or \"_\"`)\n if (slot.name.trim() === '') throw new InvalidValueError(`slot \"${slot.id}\" needs a name`)\n if (!Number.isInteger(slot.capacity) || slot.capacity < 1) throw new InvalidValueError(`slot \"${slot.id}\" needs a capacity of at least 1`)\n const worn = this.db.get<{ n: number }>(\"SELECT MAX(c) AS n FROM (SELECT COUNT(*) AS c FROM item_holdings WHERE mode = 'worn' AND slot = ? GROUP BY holder_id)\", [slot.id])?.n ?? 0\n if (slot.capacity < worn) throw new ConflictError(`slot \"${slot.id}\" already has ${worn} things worn in it, more than ${slot.capacity}`)\n this.db.run('INSERT INTO slots (id, name, capacity) VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, capacity = excluded.capacity', [slot.id, slot.name.trim(), slot.capacity])\n return this.get(slot.id)!\n }\n}\n\nexport class SqliteItemRepository implements ItemRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(item: NewItem, holder: Holder): Item {\n if (item.name.trim() === '') throw new InvalidValueError('an item needs a name')\n if (!Number.isInteger(item.quantity) || item.quantity < 1) throw new InvalidValueError('the quantity must be a whole number from 1')\n if (item.container !== undefined && !CONTAINER_STATES.includes(item.container.state)) throw new InvalidValueError(`unknown container state \"${String(item.container.state)}\"`)\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO items (source_id, name, description, quantity, unique_item, quality, notable, hidden, wearable_slot, container_state, owner_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [item.sourceId ?? null, item.name.trim(), item.description.trim(), item.quantity, item.unique ? 1 : 0, item.quality.trim(), item.notable ? 1 : 0, item.hidden ? 1 : 0, item.wearableSlot ?? null, item.container?.state ?? null, item.ownerId ?? null, this.clock().toISOString()],\n )\n const id = Number(lastInsertRowid)\n this.place(id, holder)\n return this.require(id)\n }))\n }\n\n get(id: ItemId): Item | undefined {\n const row = this.db.get<ItemRow>('SELECT * FROM items WHERE id = ?', [id])\n return row === undefined ? undefined : toItem(row)\n }\n\n getBySourceId(sourceId: string): Item | undefined {\n const row = this.db.get<ItemRow>('SELECT * FROM items WHERE source_id = ?', [sourceId])\n return row === undefined ? undefined : toItem(row)\n }\n\n list(): Item[] {\n return this.db.all<ItemRow>('SELECT * FROM items ORDER BY id').map(toItem)\n }\n\n update(id: ItemId, patch: ItemPatch): Item {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const name = patch.name === undefined ? current.name : patch.name.trim()\n if (name === '') throw new InvalidValueError('an item needs a name')\n const quantity = patch.quantity ?? current.quantity\n if (!Number.isInteger(quantity) || quantity < 1) throw new InvalidValueError('the quantity must be a whole number from 1')\n if (patch.container !== undefined && current.container === undefined) throw new InvalidValueError(`${current.name} is not a container`)\n if (patch.container !== undefined && !CONTAINER_STATES.includes(patch.container.state)) throw new InvalidValueError(`unknown container state \"${String(patch.container.state)}\"`)\n this.db.run('UPDATE items SET name = ?, description = ?, quantity = ?, quality = ?, notable = ?, hidden = ?, container_state = ?, owner_id = ? WHERE id = ?', [\n name, (patch.description ?? current.description).trim(), quantity, (patch.quality ?? current.quality).trim(), (patch.notable ?? current.notable) ? 1 : 0, (patch.hidden ?? current.hidden) ? 1 : 0,\n patch.container?.state ?? current.container?.state ?? null, patch.ownerId === undefined ? current.ownerId ?? null : patch.ownerId, id,\n ])\n return this.require(id)\n }))\n }\n\n remove(id: ItemId): boolean {\n return this.db.transaction(() => {\n if (this.contents({ kind: 'item', id }).length > 0) throw new ConflictError(`${this.get(id)?.name ?? id} still holds things: take them out first`)\n this.db.run(\"DELETE FROM openers WHERE target_kind = 'item' AND target_id = ?\", [id])\n return this.db.run('DELETE FROM items WHERE id = ?', [id]).changes > 0\n })\n }\n\n holding(id: ItemId): Holding | undefined {\n const row = this.db.get<HoldingRow>('SELECT * FROM item_holdings WHERE item_id = ?', [id])\n return row === undefined ? undefined : { itemId: id, holder: toHolder(row) }\n }\n\n place(id: ItemId, holder: Holder): Holding {\n return guard(() => this.db.transaction(() => {\n const item = this.require(id)\n let slot: string | null = null\n let mode: HoldingRow['mode'] = 'at'\n let holderId: number\n let position = ''\n let feature: string | null = null\n switch (holder.kind) {\n case 'location':\n if (this.db.get('SELECT 1 FROM locations WHERE id = ?', [holder.locationId]) === undefined) throw new NotFoundError(`place ${holder.locationId} does not exist`)\n if (holder.featureKey !== undefined) {\n const features = this.db.get<{ features: string }>('SELECT features FROM locations WHERE id = ?', [holder.locationId])!.features\n if (!(JSON.parse(features) as { key: string }[]).some(feature => feature.key === holder.featureKey)) throw new InvalidValueError(`that place has no feature \"${holder.featureKey}\"`)\n feature = holder.featureKey\n }\n holderId = holder.locationId\n position = holder.position ?? ''\n break\n case 'character':\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [holder.characterId]) === undefined) throw new NotFoundError(`character ${holder.characterId} does not exist`)\n holderId = holder.characterId\n mode = holder.mode\n if (holder.mode === 'worn') {\n if (item.wearableSlot === undefined) throw new InvalidValueError(`${item.name} cannot be worn`)\n if (holder.slot !== item.wearableSlot) throw new InvalidValueError(`${item.name} is worn on the ${item.wearableSlot}, not the ${holder.slot}`)\n const place = this.db.get<{ capacity: number }>('SELECT capacity FROM slots WHERE id = ?', [holder.slot])\n if (place === undefined) throw new NotFoundError(`there is no slot \"${holder.slot}\"`)\n const taken = this.db.get<{ n: number }>(\"SELECT COUNT(*) AS n FROM item_holdings WHERE mode = 'worn' AND holder_id = ? AND slot = ? AND item_id <> ?\", [holder.characterId, holder.slot, id])!.n\n if (taken >= place.capacity) throw new ConflictError(`the ${holder.slot} is full (${place.capacity} worn there already)`)\n slot = holder.slot\n position = holder.position ?? ''\n }\n break\n case 'item': {\n const container = this.get(holder.itemId)\n if (container === undefined) throw new NotFoundError(`item ${holder.itemId} does not exist`)\n if (container.container === undefined) throw new InvalidValueError(`${container.name} cannot hold things`)\n if (holder.itemId === id || this.ancestors(holder.itemId).includes(id)) throw new InvalidValueError(`${item.name} cannot be put inside itself`)\n holderId = holder.itemId\n mode = 'inside'\n position = holder.position ?? ''\n break\n }\n }\n this.db.run(\n `INSERT INTO item_holdings (item_id, holder_kind, holder_id, mode, slot, position, feature_key) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (item_id) DO UPDATE SET holder_kind = excluded.holder_kind, holder_id = excluded.holder_id, mode = excluded.mode, slot = excluded.slot, position = excluded.position, feature_key = excluded.feature_key`,\n [id, holder.kind, holderId, mode, slot, position.trim(), feature],\n )\n return this.holding(id)!\n }))\n }\n\n contents(holder: { kind: 'location' | 'character' | 'item'; id: number }): { item: Item; holding: Holding }[] {\n const rows = this.db.all<HoldingRow>('SELECT * FROM item_holdings WHERE holder_kind = ? AND holder_id = ? ORDER BY item_id', [holder.kind, holder.id])\n return rows.flatMap((row) => {\n const item = this.get(row.item_id)\n return item === undefined ? [] : [{ item, holding: { itemId: row.item_id, holder: toHolder(row) } }]\n })\n }\n\n ancestors(id: ItemId): ItemId[] {\n const chain: ItemId[] = []\n for (let holding = this.holding(id); holding?.holder.kind === 'item'; holding = this.holding(holding.holder.itemId)) {\n if (chain.includes(holding.holder.itemId)) break\n chain.push(holding.holder.itemId)\n }\n return chain\n }\n\n where(id: ItemId): { locationId?: LocationId; characterId?: CharacterId } {\n let holding = this.holding(id)\n for (let guardCount = 0; holding !== undefined && guardCount < 64; guardCount++) {\n const { holder } = holding\n if (holder.kind === 'location') return { locationId: holder.locationId }\n if (holder.kind === 'character') {\n const placement = this.db.get<{ location_id: number }>(\"SELECT location_id FROM placements WHERE kind = 'character' AND entity_id = ?\", [holder.characterId])\n return { characterId: holder.characterId, ...(placement === undefined ? {} : { locationId: placement.location_id }) }\n }\n holding = this.holding(holder.itemId)\n }\n return {}\n }\n\n openers(target: { kind: 'item' | 'exit'; id: number }): ItemId[] {\n return this.db.all<{ key_item_id: number }>('SELECT key_item_id FROM openers WHERE target_kind = ? AND target_id = ? ORDER BY key_item_id', [target.kind, target.id]).map(row => row.key_item_id)\n }\n\n setOpeners(target: { kind: 'item' | 'exit'; id: number }, items: readonly ItemId[]): void {\n this.db.transaction(() => {\n if (target.kind === 'item' && this.get(target.id)?.container === undefined) throw new InvalidValueError(`item ${target.id} is not a container`)\n this.db.run('DELETE FROM openers WHERE target_kind = ? AND target_id = ?', [target.kind, target.id])\n for (const item of new Set(items)) {\n if (this.get(item) === undefined) throw new NotFoundError(`item ${item} does not exist`)\n this.db.run('INSERT INTO openers (target_kind, target_id, key_item_id) VALUES (?, ?, ?)', [target.kind, target.id, item])\n }\n })\n }\n\n private require(id: ItemId): Item {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`item ${id} does not exist`)\n return found\n }\n}\n","import type { CharacterId, ConsolidationItem, ConsolidationItemId, ConsolidationKind, Relationship, RelationshipPatch } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { ConsolidationRepository, RelationshipRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface RelationshipRow {\n id: number\n from_id: number\n to_id: number\n label: string\n summary: string\n familiarity: number\n trust: number\n affinity: number\n tension: number\n updated_turn: number\n created_at: string\n}\n\ninterface ItemRow {\n id: number\n kind: ConsolidationKind\n subject_id: number\n note: string\n created_turn: number\n resolved_turn: number | null\n resolution: string | null\n}\n\nconst toRelationship = (row: RelationshipRow): Relationship => ({\n id: row.id, fromId: row.from_id, toId: row.to_id, label: row.label, summary: row.summary,\n familiarity: row.familiarity, trust: row.trust, affinity: row.affinity, tension: row.tension,\n updatedTurn: row.updated_turn, createdAt: row.created_at,\n})\n\nconst toItem = (row: ItemRow): ConsolidationItem => ({\n id: row.id, kind: row.kind, subjectId: row.subject_id, note: row.note, createdTurn: row.created_turn,\n ...(row.resolved_turn === null ? {} : { resolvedTurn: row.resolved_turn }),\n ...(row.resolution === null ? {} : { resolution: row.resolution }),\n})\n\nconst RANGES = { familiarity: [0, 1], trust: [-1, 1], affinity: [-1, 1], tension: [0, 1] } as const\n\nfunction checked(patch: RelationshipPatch): void {\n for (const [key, [min, max]] of Object.entries(RANGES) as [keyof typeof RANGES, readonly [number, number]][]) {\n const value = patch[key]\n if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) throw new InvalidValueError(`${key} must be a number from ${min} to ${max}`)\n }\n if (patch.label !== undefined && patch.label.trim() === '') throw new InvalidValueError('a relationship needs a label')\n}\n\nexport class SqliteRelationshipRepository implements RelationshipRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n upsert(fromId: CharacterId, toId: CharacterId, patch: RelationshipPatch, turn: number): Relationship {\n if (fromId === toId) throw new InvalidValueError('a character has no relationship with itself')\n checked(patch)\n return guard(() => this.db.transaction(() => {\n const current = this.get(fromId, toId)\n if (current === undefined) {\n if (patch.label === undefined) throw new InvalidValueError('a new relationship needs a label')\n this.db.run(\n 'INSERT INTO relationships (from_id, to_id, label, summary, familiarity, trust, affinity, tension, updated_turn, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [fromId, toId, patch.label.trim(), (patch.summary ?? '').trim(), patch.familiarity ?? 0, patch.trust ?? 0, patch.affinity ?? 0, patch.tension ?? 0, turn, this.clock().toISOString()],\n )\n } else {\n this.db.run('UPDATE relationships SET label = ?, summary = ?, familiarity = ?, trust = ?, affinity = ?, tension = ?, updated_turn = ? WHERE id = ?', [\n (patch.label ?? current.label).trim(), (patch.summary ?? current.summary).trim(), patch.familiarity ?? current.familiarity, patch.trust ?? current.trust,\n patch.affinity ?? current.affinity, patch.tension ?? current.tension, turn, current.id,\n ])\n }\n return this.get(fromId, toId)!\n }))\n }\n\n get(fromId: CharacterId, toId: CharacterId): Relationship | undefined {\n const row = this.db.get<RelationshipRow>('SELECT * FROM relationships WHERE from_id = ? AND to_id = ?', [fromId, toId])\n return row === undefined ? undefined : toRelationship(row)\n }\n\n from(characterId: CharacterId): Relationship[] {\n return this.db.all<RelationshipRow>('SELECT * FROM relationships WHERE from_id = ? ORDER BY id', [characterId]).map(toRelationship)\n }\n\n to(characterId: CharacterId): Relationship[] {\n return this.db.all<RelationshipRow>('SELECT * FROM relationships WHERE to_id = ? ORDER BY id', [characterId]).map(toRelationship)\n }\n\n list(): Relationship[] {\n return this.db.all<RelationshipRow>('SELECT * FROM relationships ORDER BY id').map(toRelationship)\n }\n\n remove(fromId: CharacterId, toId: CharacterId): boolean {\n return this.db.run('DELETE FROM relationships WHERE from_id = ? AND to_id = ?', [fromId, toId]).changes > 0\n }\n}\n\nexport class SqliteConsolidationRepository implements ConsolidationRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n enqueue(item: { kind: ConsolidationKind; subjectId: number; note: string; turn: number }): ConsolidationItem {\n const { lastInsertRowid } = this.db.run('INSERT INTO consolidation_items (kind, subject_id, note, created_turn) VALUES (?, ?, ?, ?)', [item.kind, item.subjectId, item.note.trim(), item.turn])\n return this.require(Number(lastInsertRowid))\n }\n\n get(id: ConsolidationItemId): ConsolidationItem | undefined {\n const row = this.db.get<ItemRow>('SELECT * FROM consolidation_items WHERE id = ?', [id])\n return row === undefined ? undefined : toItem(row)\n }\n\n pending(): ConsolidationItem[] {\n return this.db.all<ItemRow>('SELECT * FROM consolidation_items WHERE resolved_turn IS NULL ORDER BY id').map(toItem)\n }\n\n createdIn(turn: number): ConsolidationItem[] {\n return this.db.all<ItemRow>('SELECT * FROM consolidation_items WHERE created_turn = ? ORDER BY id', [turn]).map(toItem)\n }\n\n resolve(id: ConsolidationItemId, turn: number, resolution: string): ConsolidationItem {\n const current = this.require(id)\n if (current.resolvedTurn !== undefined) return current\n this.db.run('UPDATE consolidation_items SET resolved_turn = ?, resolution = ? WHERE id = ?', [turn, resolution.trim(), id])\n return this.require(id)\n }\n\n private require(id: ConsolidationItemId): ConsolidationItem {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`consolidation item ${id} does not exist`)\n return found\n }\n}\n","import {\n EXIT_STATES, MAX_LOCATION_FEATURES,\n type Exit, type ExitId, type ExitPatch, type ExitState, type Location, type LocationFeature, type LocationId, type LocationPatch, type NewExit, type NewLocation, type NewPlacement, type PlaceableKind, type Placement,\n} from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { LocationRepository, PlacementRepository } from '../repositories.ts'\nimport { guard, toJson } from './support.ts'\n\ninterface LocationRow {\n id: number\n source_id: string | null\n name: string\n description: string\n parent_id: number | null\n features: string\n created_at: string\n}\n\ninterface ExitRow {\n id: number\n from_id: number\n to_id: number\n description: string\n travel_seconds: number | null\n state: ExitState\n note: string\n}\n\ninterface PlacementRow {\n kind: PlaceableKind\n entity_id: number\n location_id: number\n position: string\n feature_key: string | null\n}\n\nconst FEATURE_KEY = /^[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,59}$/u\n\nfunction parseFeatures(text: string): LocationFeature[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(entry => typeof entry === 'object' && entry !== null && typeof (entry as LocationFeature).key === 'string' && typeof (entry as LocationFeature).name === 'string' && typeof (entry as LocationFeature).description === 'string')) return value as LocationFeature[]\n } catch {\n // reported below\n }\n throw new CorruptDataError('locations.features does not hold a list of features')\n}\n\n/** The features, or why they are not acceptable. */\nfunction checkedFeatures(features: readonly LocationFeature[]): LocationFeature[] {\n if (features.length > MAX_LOCATION_FEATURES) throw new InvalidValueError(`a place has at most ${MAX_LOCATION_FEATURES} features`)\n const seen = new Set<string>()\n return features.map((feature) => {\n if (!FEATURE_KEY.test(feature.key)) throw new InvalidValueError(`feature key \"${feature.key}\" must be letters, digits, \"-\" or \"_\"`)\n if (seen.has(feature.key)) throw new ConflictError(`feature key \"${feature.key}\" is used twice`)\n seen.add(feature.key)\n if (feature.name.trim() === '') throw new InvalidValueError(`feature \"${feature.key}\" needs a name`)\n return { key: feature.key, name: feature.name.trim(), description: feature.description.trim() }\n })\n}\n\nconst toLocation = (row: LocationRow): Location => ({\n id: row.id,\n ...(row.source_id === null ? {} : { sourceId: row.source_id }),\n name: row.name,\n description: row.description,\n ...(row.parent_id === null ? {} : { parentId: row.parent_id }),\n features: parseFeatures(row.features),\n createdAt: row.created_at,\n})\n\nconst toExit = (row: ExitRow): Exit => ({\n id: row.id,\n fromId: row.from_id,\n toId: row.to_id,\n description: row.description,\n ...(row.travel_seconds === null ? {} : { travelSeconds: row.travel_seconds }),\n state: row.state,\n note: row.note,\n})\n\nconst toPlacement = (row: PlacementRow): Placement => ({\n kind: row.kind,\n entityId: row.entity_id,\n locationId: row.location_id,\n position: row.position,\n ...(row.feature_key === null ? {} : { featureKey: row.feature_key }),\n})\n\nexport class SqliteLocationRepository implements LocationRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly clock: Clock,\n /** Told when a place is renamed, so that what is indexed by its name can follow. */\n private readonly renamed: (id: LocationId) => void = () => undefined,\n ) {}\n\n add(location: NewLocation): Location {\n if (location.name.trim() === '') throw new InvalidValueError('a place needs a name')\n const features = checkedFeatures(location.features)\n return guard(() => {\n if (location.parentId !== undefined && this.get(location.parentId) === undefined) throw new NotFoundError(`the parent place ${location.parentId} does not exist`)\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO locations (source_id, name, description, parent_id, features, created_at) VALUES (?, ?, ?, ?, ?, ?)',\n [location.sourceId ?? null, location.name.trim(), location.description.trim(), location.parentId ?? null, toJson(features), this.clock().toISOString()],\n )\n return this.require(Number(lastInsertRowid))\n })\n }\n\n get(id: LocationId): Location | undefined {\n const row = this.db.get<LocationRow>('SELECT * FROM locations WHERE id = ?', [id])\n return row === undefined ? undefined : toLocation(row)\n }\n\n getBySourceId(sourceId: string): Location | undefined {\n const row = this.db.get<LocationRow>('SELECT * FROM locations WHERE source_id = ?', [sourceId])\n return row === undefined ? undefined : toLocation(row)\n }\n\n list(): Location[] {\n return this.db.all<LocationRow>('SELECT * FROM locations ORDER BY id').map(toLocation)\n }\n\n childrenOf(id: LocationId): Location[] {\n return this.db.all<LocationRow>('SELECT * FROM locations WHERE parent_id = ? ORDER BY id', [id]).map(toLocation)\n }\n\n update(id: LocationId, patch: LocationPatch): Location {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const name = patch.name === undefined ? current.name : patch.name.trim()\n if (name === '') throw new InvalidValueError('a place needs a name')\n const features = patch.features === undefined ? current.features : checkedFeatures(patch.features)\n const removed = current.features.filter(feature => !features.some(kept => kept.key === feature.key))\n for (const feature of removed) {\n const standing = this.db.get('SELECT 1 FROM placements WHERE location_id = ? AND feature_key = ?', [id, feature.key])\n if (standing !== undefined) throw new ConflictError(`feature \"${feature.key}\" cannot be removed while someone is at it`)\n }\n const parentId = patch.parentId === undefined ? current.parentId ?? null : patch.parentId\n if (parentId !== null && parentId !== (current.parentId ?? null)) {\n if (this.get(parentId) === undefined) throw new NotFoundError(`the parent place ${parentId} does not exist`)\n for (let ancestor: number | null = parentId; ancestor !== null; ancestor = this.get(ancestor)?.parentId ?? null) {\n if (ancestor === id) throw new InvalidValueError(`${current.name} cannot be inside itself or a place within it`)\n }\n }\n this.db.run('UPDATE locations SET name = ?, description = ?, features = ?, parent_id = ? WHERE id = ?', [name, (patch.description ?? current.description).trim(), toJson(features), parentId, id])\n if (name !== current.name) this.renamed(id)\n return this.require(id)\n }))\n }\n\n addExit(exit: NewExit): Exit {\n return guard(() => {\n if (this.get(exit.fromId) === undefined) throw new NotFoundError(`place ${exit.fromId} does not exist`)\n if (this.get(exit.toId) === undefined) throw new NotFoundError(`place ${exit.toId} does not exist`)\n if (exit.fromId === exit.toId) throw new InvalidValueError('an exit must lead to another place')\n if (exit.state !== undefined && !EXIT_STATES.includes(exit.state)) throw new InvalidValueError(`unknown exit state \"${String(exit.state)}\"`)\n if (exit.travelSeconds !== undefined && (!Number.isInteger(exit.travelSeconds) || exit.travelSeconds < 0)) throw new InvalidValueError('travel time must be a whole number of seconds')\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO exits (from_id, to_id, description, travel_seconds, state, note) VALUES (?, ?, ?, ?, ?, ?)',\n [exit.fromId, exit.toId, exit.description.trim(), exit.travelSeconds ?? null, exit.state ?? 'open', (exit.note ?? '').trim()],\n )\n return this.requireExit(Number(lastInsertRowid))\n })\n }\n\n getExit(fromId: LocationId, toId: LocationId): Exit | undefined {\n const row = this.db.get<ExitRow>('SELECT * FROM exits WHERE from_id = ? AND to_id = ?', [fromId, toId])\n return row === undefined ? undefined : toExit(row)\n }\n\n exitsFrom(id: LocationId): Exit[] {\n return this.db.all<ExitRow>('SELECT * FROM exits WHERE from_id = ? ORDER BY id', [id]).map(toExit)\n }\n\n allExits(): Exit[] {\n return this.db.all<ExitRow>('SELECT * FROM exits ORDER BY id').map(toExit)\n }\n\n updateExit(id: ExitId, patch: ExitPatch): Exit {\n return guard(() => {\n const current = this.requireExit(id)\n if (patch.state !== undefined && !EXIT_STATES.includes(patch.state)) throw new InvalidValueError(`unknown exit state \"${String(patch.state)}\"`)\n if (patch.travelSeconds !== undefined && patch.travelSeconds !== null && (!Number.isInteger(patch.travelSeconds) || patch.travelSeconds < 0)) throw new InvalidValueError('travel time must be a whole number of seconds')\n this.db.run('UPDATE exits SET description = ?, travel_seconds = ?, state = ?, note = ? WHERE id = ?', [\n (patch.description ?? current.description).trim(), patch.travelSeconds === undefined ? current.travelSeconds ?? null : patch.travelSeconds, patch.state ?? current.state, (patch.note ?? current.note).trim(), id,\n ])\n return this.requireExit(id)\n })\n }\n\n removeExit(id: ExitId): boolean {\n return this.db.run('DELETE FROM exits WHERE id = ?', [id]).changes > 0\n }\n\n private require(id: LocationId): Location {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`place ${id} does not exist`)\n return found\n }\n\n private requireExit(id: ExitId): Exit {\n const row = this.db.get<ExitRow>('SELECT * FROM exits WHERE id = ?', [id])\n if (row === undefined) throw new NotFoundError(`exit ${id} does not exist`)\n return toExit(row)\n }\n}\n\nexport class SqlitePlacementRepository implements PlacementRepository {\n constructor(private readonly db: SqlDatabase, private readonly locations: Pick<LocationRepository, 'get'>) {}\n\n place(kind: PlaceableKind, entityId: number, placement: NewPlacement): Placement {\n return guard(() => this.db.transaction(() => {\n const location = this.locations.get(placement.locationId)\n if (location === undefined) throw new NotFoundError(`place ${placement.locationId} does not exist`)\n if (kind === 'character' && this.db.get('SELECT 1 FROM characters WHERE id = ?', [entityId]) === undefined) throw new NotFoundError(`character ${entityId} does not exist`)\n if (placement.featureKey !== undefined && !location.features.some(feature => feature.key === placement.featureKey)) {\n throw new InvalidValueError(`${location.name} has no feature \"${placement.featureKey}\" (it has: ${location.features.map(feature => feature.key).join(', ') || 'none'})`)\n }\n this.db.run(\n `INSERT INTO placements (kind, entity_id, location_id, position, feature_key) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT (kind, entity_id) DO UPDATE SET location_id = excluded.location_id, position = excluded.position, feature_key = excluded.feature_key`,\n [kind, entityId, placement.locationId, (placement.position ?? '').trim(), placement.featureKey ?? null],\n )\n return this.require(kind, entityId)\n }))\n }\n\n get(kind: PlaceableKind, entityId: number): Placement | undefined {\n const row = this.db.get<PlacementRow>('SELECT * FROM placements WHERE kind = ? AND entity_id = ?', [kind, entityId])\n return row === undefined ? undefined : toPlacement(row)\n }\n\n at(locationId: LocationId, kind?: PlaceableKind): Placement[] {\n const params: SqlValue[] = [locationId]\n if (kind !== undefined) params.push(kind)\n return this.db.all<PlacementRow>(`SELECT * FROM placements WHERE location_id = ?${kind === undefined ? '' : ' AND kind = ?'} ORDER BY kind, entity_id`, params).map(toPlacement)\n }\n\n list(kind?: PlaceableKind): Placement[] {\n return (kind === undefined\n ? this.db.all<PlacementRow>('SELECT * FROM placements ORDER BY kind, entity_id')\n : this.db.all<PlacementRow>('SELECT * FROM placements WHERE kind = ? ORDER BY entity_id', [kind])).map(toPlacement)\n }\n\n private require(kind: PlaceableKind, entityId: number): Placement {\n const found = this.get(kind, entityId)\n if (found === undefined) throw new NotFoundError(`${kind} ${entityId} is not placed`)\n return found\n }\n}\n","import { createRequire } from 'node:module'\n\n/**\n * Where the sqlite-vec extension is, or why it cannot be used here. The package carries a\n * prebuilt binary for each platform it supports; elsewhere there is none, and a session works\n * without vector search.\n */\nexport function vectorExtension(): { path: string } | { error: string } {\n try {\n const { getLoadablePath } = createRequire(import.meta.url)('sqlite-vec') as { getLoadablePath(): string }\n return { path: getLoadablePath() }\n } catch (error) {\n return { error: error instanceof Error ? error.message : String(error) }\n }\n}\n","import type { Character, CharacterControl, CharacterFilter, CharacterId, CharacterPatch, NewCharacter } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { CharacterRepository } from '../repositories.ts'\nimport { guard, lookupKey, parseStringList, toJson } from './support.ts'\n\ninterface CharacterRow {\n id: number\n source_id: string | null\n name: string\n age: string | null\n gender: string | null\n pronouns: string | null\n kind: Character['kind']\n tier: Character['tier']\n role: Character['role']\n control: CharacterControl\n summary: string\n personality: string\n background: string\n appearance: string\n speech_style: string\n speech_examples: string\n voice: string | null\n created_at: string\n}\n\ninterface AliasRow {\n character_id: number\n alias: string\n}\n\nfunction toCharacter(row: CharacterRow, aliases: string[]): Character {\n return {\n id: row.id,\n ...(row.source_id === null ? {} : { sourceId: row.source_id }),\n name: row.name,\n aliases,\n ...(row.age === null ? {} : { age: row.age }),\n ...(row.gender === null ? {} : { gender: row.gender }),\n ...(row.pronouns === null ? {} : { pronouns: row.pronouns }),\n kind: row.kind,\n tier: row.tier,\n role: row.role,\n control: row.control,\n summary: row.summary,\n personality: row.personality,\n background: row.background,\n appearance: row.appearance,\n speech: { style: row.speech_style, examples: parseStringList(row.speech_examples, 'characters.speech_examples') },\n ...(row.voice === null ? {} : { voice: row.voice }),\n createdAt: row.created_at,\n }\n}\n\nexport class SqliteCharacterRepository implements CharacterRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(character: NewCharacter): Character {\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid: id } = this.db.run(\n `INSERT INTO characters (\n source_id, name, name_key, age, gender, pronouns, kind, tier, role, control,\n summary, personality, background, appearance, speech_style, speech_examples, voice, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n character.sourceId ?? null, character.name, lookupKey(character.name),\n character.age ?? null, character.gender ?? null, character.pronouns ?? null,\n character.kind, character.tier, character.role, character.control,\n character.summary, character.personality, character.background, character.appearance,\n character.speech.style, toJson(character.speech.examples), character.voice ?? null, this.clock().toISOString(),\n ],\n )\n const stored = new Set<string>()\n for (const alias of character.aliases) {\n const key = lookupKey(alias)\n if (stored.has(key)) continue\n this.db.run(\n 'INSERT INTO character_aliases (character_id, position, alias, alias_key) VALUES (?, ?, ?, ?)',\n [id, stored.size, alias, key],\n )\n stored.add(key)\n }\n return this.require(id)\n }))\n }\n\n get(id: CharacterId): Character | undefined {\n return this.read('WHERE id = ?', [id])[0]\n }\n\n getBySourceId(sourceId: string): Character | undefined {\n return this.read('WHERE source_id = ?', [sourceId])[0]\n }\n\n list(filter: CharacterFilter = {}): Character[] {\n const conditions: string[] = []\n const params: SqlValue[] = []\n for (const column of ['role', 'tier', 'kind', 'control'] as const) {\n const value = filter[column]\n if (value === undefined) continue\n conditions.push(`${column} = ?`)\n params.push(value)\n }\n return this.read(conditions.length === 0 ? '' : `WHERE ${conditions.join(' AND ')}`, params)\n }\n\n findByName(name: string): Character[] {\n const key = lookupKey(name)\n return this.read(\n 'WHERE name_key = ?1 OR id IN (SELECT character_id FROM character_aliases WHERE alias_key = ?1)',\n [key],\n )\n }\n\n setControl(id: CharacterId, control: CharacterControl): Character {\n return guard(() => this.db.transaction(() => {\n if (this.db.run('UPDATE characters SET control = ? WHERE id = ?', [control, id]).changes === 0) {\n throw new NotFoundError(`character ${id} does not exist`)\n }\n return this.require(id)\n }))\n }\n\n update(id: CharacterId, patch: CharacterPatch): Character {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const next: Character = {\n ...current,\n ...(patch.name === undefined ? {} : { name: patch.name.trim() }),\n ...(patch.aliases === undefined ? {} : { aliases: patch.aliases }),\n ...(patch.kind === undefined ? {} : { kind: patch.kind }),\n ...(patch.tier === undefined ? {} : { tier: patch.tier }),\n ...(patch.role === undefined ? {} : { role: patch.role }),\n ...(patch.summary === undefined ? {} : { summary: patch.summary }),\n ...(patch.personality === undefined ? {} : { personality: patch.personality }),\n ...(patch.background === undefined ? {} : { background: patch.background }),\n ...(patch.appearance === undefined ? {} : { appearance: patch.appearance }),\n ...(patch.speech === undefined ? {} : { speech: patch.speech }),\n }\n if (patch.voice !== undefined) { if (patch.voice === null || patch.voice.trim() === '') delete next.voice; else next.voice = patch.voice.trim() }\n for (const field of ['age', 'gender', 'pronouns'] as const) {\n const value = patch[field]\n if (value === undefined) continue\n const text = value?.trim()\n if (text === undefined || text === '') delete next[field]\n else next[field] = text\n }\n if (next.name === '') throw new InvalidValueError('a character needs a name')\n if (next.role === 'playable' && (next.kind === 'group' || next.tier === 'background')) throw new InvalidValueError('a playable character cannot be a group or a background character')\n this.db.run(\n `UPDATE characters SET name = ?, name_key = ?, age = ?, gender = ?, pronouns = ?, kind = ?, tier = ?, role = ?, summary = ?, personality = ?, background = ?, appearance = ?, speech_style = ?, speech_examples = ?, voice = ? WHERE id = ?`,\n [next.name, lookupKey(next.name), next.age ?? null, next.gender ?? null, next.pronouns ?? null, next.kind, next.tier, next.role, next.summary, next.personality, next.background, next.appearance, next.speech.style, toJson(next.speech.examples), next.voice ?? null, id],\n )\n if (patch.aliases !== undefined) {\n this.db.run('DELETE FROM character_aliases WHERE character_id = ?', [id])\n const stored = new Set<string>()\n for (const alias of patch.aliases.map(entry => entry.trim()).filter(entry => entry !== '')) {\n const key = lookupKey(alias)\n if (stored.has(key)) continue\n this.db.run('INSERT INTO character_aliases (character_id, position, alias, alias_key) VALUES (?, ?, ?, ?)', [id, stored.size, alias, key])\n stored.add(key)\n }\n }\n return this.require(id)\n }))\n }\n\n private require(id: CharacterId): Character {\n const character = this.get(id)\n if (character === undefined) throw new NotFoundError(`character ${id} does not exist`)\n return character\n }\n\n private read(where: string, params: readonly SqlValue[]): Character[] {\n const rows = this.db.all<CharacterRow>(`SELECT * FROM characters ${where} ORDER BY id`, params)\n if (rows.length === 0) return []\n const aliases = new Map<number, string[]>()\n for (const row of this.db.all<AliasRow>(\n `SELECT character_id, alias FROM character_aliases\n WHERE character_id IN (SELECT id FROM characters ${where}) ORDER BY character_id, position`,\n params,\n )) {\n aliases.set(row.character_id, [...aliases.get(row.character_id) ?? [], row.alias])\n }\n return rows.map(row => toCharacter(row, aliases.get(row.id) ?? []))\n }\n}\n","import type { CharacterId, CharacterIntent, Intent, IntentFilter, IntentId, IntentPatch } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { IntentRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface IntentRow {\n id: number\n character_id: number\n type: Intent['type']\n name: string\n description: string\n status: Intent['status']\n horizon: Intent['horizon']\n priority: number\n urgency: number\n plan: string\n open_threads: string\n constraints: string\n deadline: string | null\n created_at: string\n updated_at: string\n}\n\nfunction toIntent(row: IntentRow): CharacterIntent {\n return {\n id: row.id,\n characterId: row.character_id,\n type: row.type,\n name: row.name,\n description: row.description,\n status: row.status,\n horizon: row.horizon,\n priority: row.priority,\n urgency: row.urgency,\n plan: parseStringList(row.plan, 'intents.plan'),\n openThreads: parseStringList(row.open_threads, 'intents.open_threads'),\n constraints: parseStringList(row.constraints, 'intents.constraints'),\n ...(row.deadline === null ? {} : { deadline: row.deadline }),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n }\n}\n\nexport class SqliteIntentRepository implements IntentRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(characterId: CharacterId, intent: Intent): CharacterIntent {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) {\n throw new NotFoundError(`character ${characterId} does not exist`)\n }\n const now = this.clock().toISOString()\n const { lastInsertRowid } = this.db.run(\n `INSERT INTO intents (\n character_id, type, name, description, status, horizon, priority, urgency,\n plan, open_threads, constraints, deadline, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n characterId, intent.type, intent.name, intent.description, intent.status, intent.horizon,\n intent.priority, intent.urgency, toJson(intent.plan), toJson(intent.openThreads), toJson(intent.constraints),\n intent.deadline ?? null, now, now,\n ],\n )\n return this.require(lastInsertRowid)\n }))\n }\n\n get(id: IntentId): CharacterIntent | undefined {\n const row = this.db.get<IntentRow>('SELECT * FROM intents WHERE id = ?', [id])\n return row === undefined ? undefined : toIntent(row)\n }\n\n list(characterId: CharacterId, filter: IntentFilter = {}): CharacterIntent[] {\n const params: SqlValue[] = [characterId]\n let where = 'character_id = ?'\n if (filter.status !== undefined) {\n where += ' AND status = ?'\n params.push(filter.status)\n }\n return this.db.all<IntentRow>(`SELECT * FROM intents WHERE ${where} ORDER BY id`, params).map(toIntent)\n }\n\n update(id: IntentId, patch: IntentPatch): CharacterIntent {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const deadline = patch.deadline === undefined ? current.deadline ?? null : patch.deadline\n this.db.run(\n `UPDATE intents SET type = ?, name = ?, description = ?, status = ?, horizon = ?, priority = ?, urgency = ?,\n plan = ?, open_threads = ?, constraints = ?, deadline = ?, updated_at = ?\n WHERE id = ?`,\n [\n patch.type ?? current.type, patch.name ?? current.name, patch.description ?? current.description,\n patch.status ?? current.status, patch.horizon ?? current.horizon,\n patch.priority ?? current.priority, patch.urgency ?? current.urgency,\n toJson(patch.plan ?? current.plan), toJson(patch.openThreads ?? current.openThreads),\n toJson(patch.constraints ?? current.constraints), deadline, this.clock().toISOString(), id,\n ],\n )\n return this.require(id)\n }))\n }\n\n remove(id: IntentId): boolean {\n return this.db.run('DELETE FROM intents WHERE id = ?', [id]).changes > 0\n }\n\n private require(id: IntentId): CharacterIntent {\n const intent = this.get(id)\n if (intent === undefined) throw new NotFoundError(`intent ${id} does not exist`)\n return intent\n }\n}\n","import type { JsonValue, NewSession, SessionMetadata, WorldReference } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, CorruptDataError, NotFoundError } from '../errors.ts'\nimport type { MetadataRepository } from '../repositories.ts'\n\nconst SESSION_ID = 'session.id'\nconst SESSION_NAME = 'session.name'\nconst SESSION_CREATED_AT = 'session.created_at'\nconst SESSION_LAST_PLAYED_AT = 'session.last_played_at'\nconst SESSION_TURNS = 'session.turns'\nconst WORLD = 'world'\nconst RESERVED = new Set([SESSION_ID, SESSION_NAME, SESSION_CREATED_AT, SESSION_LAST_PLAYED_AT, SESSION_TURNS, WORLD])\n\nfunction parseJson(text: string, key: string): JsonValue {\n try {\n return JSON.parse(text) as JsonValue\n } catch (error) {\n throw new CorruptDataError(`metadata \"${key}\" is not valid JSON`, { cause: error })\n }\n}\n\nfunction parseWorld(text: string): WorldReference {\n const value = parseJson(text, WORLD)\n if (typeof value !== 'object' || value === null || Array.isArray(value) || typeof value.id !== 'string' || typeof value.name !== 'string') {\n throw new CorruptDataError('metadata \"world\" is not a world reference')\n }\n return value as unknown as WorldReference\n}\n\nexport class SqliteMetadataRepository implements MetadataRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n /** Write the session's identity; only the store does this, once, when the database is created. */\n create(session: NewSession): SessionMetadata {\n if (session.id.trim() === '') throw new RangeError('a session needs an id')\n if (session.name.trim() === '') throw new RangeError('a session needs a name')\n return this.db.transaction(() => {\n if (this.read(SESSION_ID) !== undefined) throw new ConflictError('the session already has metadata')\n this.write(SESSION_ID, session.id)\n this.write(SESSION_NAME, session.name.trim())\n this.write(SESSION_CREATED_AT, this.clock().toISOString())\n this.write(SESSION_TURNS, '0')\n this.write(WORLD, JSON.stringify(session.world))\n return this.get()\n })\n }\n\n get(): SessionMetadata {\n const id = this.read(SESSION_ID)\n const name = this.read(SESSION_NAME)\n const createdAt = this.read(SESSION_CREATED_AT)\n const world = this.read(WORLD)\n if (id === undefined || name === undefined || createdAt === undefined || world === undefined) {\n throw new NotFoundError('the session has no metadata')\n }\n const lastPlayedAt = this.read(SESSION_LAST_PLAYED_AT)\n return {\n id,\n name,\n world: parseWorld(world),\n createdAt,\n ...(lastPlayedAt === undefined ? {} : { lastPlayedAt }),\n turns: this.turns(),\n }\n }\n\n setName(name: string): void {\n if (name.trim() === '') throw new RangeError('a session needs a name')\n this.write(SESSION_NAME, name.trim())\n }\n\n rebrand(id: string, name: string, createdAt?: string): void {\n if (id.trim() === '') throw new RangeError('a session needs an id')\n if (name.trim() === '') throw new RangeError('a session needs a name')\n this.db.transaction(() => {\n this.write(SESSION_ID, id)\n this.write(SESSION_NAME, name.trim())\n this.write(SESSION_CREATED_AT, createdAt ?? this.clock().toISOString())\n })\n }\n\n recordTurn(): SessionMetadata {\n return this.db.transaction(() => {\n this.write(SESSION_TURNS, String(this.turns() + 1))\n this.write(SESSION_LAST_PLAYED_AT, this.clock().toISOString())\n return this.get()\n })\n }\n\n setWorld(world: WorldReference): void {\n this.write(WORLD, JSON.stringify(world))\n }\n\n getValue(key: string): JsonValue | undefined {\n this.assertFree(key)\n const text = this.read(key)\n return text === undefined ? undefined : parseJson(text, key)\n }\n\n setValue(key: string, value: JsonValue): void {\n this.assertFree(key)\n this.write(key, JSON.stringify(value))\n }\n\n deleteValue(key: string): boolean {\n this.assertFree(key)\n return this.db.run('DELETE FROM metadata WHERE key = ?', [key]).changes > 0\n }\n\n private turns(): number {\n const count = Number(this.read(SESSION_TURNS) ?? '0')\n if (!Number.isInteger(count) || count < 0) throw new CorruptDataError('metadata \"session.turns\" is not a count')\n return count\n }\n\n private assertFree(key: string): void {\n if (RESERVED.has(key)) throw new RangeError(`\"${key}\" is reserved for the session`)\n }\n\n private read(key: string): string | undefined {\n return this.db.get<{ value: string }>('SELECT value FROM metadata WHERE key = ?', [key])?.value\n }\n\n private write(key: string, value: string): void {\n this.db.run('INSERT INTO metadata (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value', [key, value])\n }\n}\n","export interface Migration {\n /** Becomes the database's `user_version` once applied. Versions are consecutive from 1. */\n version: number\n sql: string\n}\n\n/**\n * Migrations are applied in order and never edited once released (0.1.0 released\n * versions 1 to 6; tests/sqlite/migrate.spec.ts pins them): a change to the schema\n * is a new entry. Enumerations are spelled out so that a later change to the model\n * cannot alter what an old migration did.\n */\nexport const MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n sql: `\n CREATE TABLE metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE characters (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n name_key TEXT NOT NULL,\n age TEXT,\n gender TEXT,\n pronouns TEXT,\n kind TEXT NOT NULL CHECK (kind IN ('person', 'group')),\n tier TEXT NOT NULL CHECK (tier IN ('principal', 'supporting', 'background')),\n role TEXT NOT NULL CHECK (role IN ('playable', 'npc')),\n control TEXT NOT NULL CHECK (control IN ('player', 'agent')),\n summary TEXT NOT NULL DEFAULT '',\n personality TEXT NOT NULL DEFAULT '',\n background TEXT NOT NULL DEFAULT '',\n appearance TEXT NOT NULL DEFAULT '',\n speech_style TEXT NOT NULL DEFAULT '',\n speech_examples TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX characters_name_key ON characters (name_key);\n\n CREATE TABLE character_aliases (\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n position INTEGER NOT NULL,\n alias TEXT NOT NULL,\n alias_key TEXT NOT NULL,\n PRIMARY KEY (character_id, position),\n UNIQUE (character_id, alias_key)\n ) STRICT;\n CREATE INDEX character_aliases_key ON character_aliases (alias_key);\n\n CREATE TABLE character_state (\n character_id INTEGER PRIMARY KEY REFERENCES characters (id) ON DELETE CASCADE,\n public_state TEXT NOT NULL DEFAULT '',\n inner_state TEXT NOT NULL DEFAULT '',\n activity TEXT NOT NULL DEFAULT '',\n version INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE variable_defs (\n key TEXT PRIMARY KEY,\n ordinal INTEGER NOT NULL,\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n kind TEXT NOT NULL CHECK (kind IN ('number', 'flag', 'choice')),\n subject TEXT NOT NULL CHECK (subject IN ('character', 'item', 'location', 'world')),\n only_keys TEXT NOT NULL DEFAULT '[]',\n min_value REAL,\n max_value REAL,\n is_integer INTEGER NOT NULL DEFAULT 0 CHECK (is_integer IN (0, 1)),\n options TEXT NOT NULL DEFAULT '[]',\n default_value TEXT NOT NULL,\n has_baseline INTEGER NOT NULL DEFAULT 0 CHECK (has_baseline IN (0, 1)),\n visibility TEXT NOT NULL CHECK (visibility IN ('public', 'private', 'hidden')),\n bands TEXT NOT NULL DEFAULT '[]',\n always_shown INTEGER NOT NULL DEFAULT 0 CHECK (always_shown IN (0, 1)),\n builtin INTEGER NOT NULL DEFAULT 0 CHECK (builtin IN (0, 1))\n ) STRICT;\n\n CREATE TABLE variable_values (\n variable TEXT NOT NULL REFERENCES variable_defs (key) ON DELETE CASCADE,\n subject TEXT NOT NULL CHECK (subject IN ('character', 'item', 'location', 'world')),\n subject_id INTEGER NOT NULL,\n value TEXT NOT NULL,\n baseline TEXT,\n updated_turn INTEGER NOT NULL,\n PRIMARY KEY (variable, subject, subject_id)\n ) STRICT;\n CREATE INDEX variable_values_subject ON variable_values (subject, subject_id);\n\n CREATE TABLE intents (\n id INTEGER PRIMARY KEY,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n type TEXT NOT NULL CHECK (type IN ('need', 'obligation', 'quest', 'agenda', 'aspiration', 'relationship', 'habit', 'reaction')),\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n status TEXT NOT NULL CHECK (status IN ('active', 'paused', 'completed', 'failed', 'abandoned')),\n horizon TEXT NOT NULL CHECK (horizon IN ('immediate', 'short', 'day', 'long', 'open_ended')),\n priority REAL NOT NULL CHECK (priority BETWEEN 0 AND 1),\n urgency REAL NOT NULL CHECK (urgency BETWEEN 0 AND 1),\n plan TEXT NOT NULL DEFAULT '[]',\n open_threads TEXT NOT NULL DEFAULT '[]',\n constraints TEXT NOT NULL DEFAULT '[]',\n deadline TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX intents_character ON intents (character_id, status);\n\n CREATE TABLE locations (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n parent_id INTEGER REFERENCES locations (id) ON DELETE RESTRICT,\n features TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX locations_parent ON locations (parent_id);\n\n CREATE TABLE exits (\n id INTEGER PRIMARY KEY,\n from_id INTEGER NOT NULL REFERENCES locations (id) ON DELETE CASCADE,\n to_id INTEGER NOT NULL REFERENCES locations (id) ON DELETE CASCADE,\n description TEXT NOT NULL DEFAULT '',\n travel_seconds INTEGER CHECK (travel_seconds IS NULL OR travel_seconds >= 0),\n state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'locked', 'blocked')),\n note TEXT NOT NULL DEFAULT '',\n UNIQUE (from_id, to_id),\n CHECK (from_id <> to_id)\n ) STRICT;\n\n CREATE TABLE placements (\n kind TEXT NOT NULL CHECK (kind IN ('character')),\n entity_id INTEGER NOT NULL,\n location_id INTEGER NOT NULL REFERENCES locations (id) ON DELETE RESTRICT,\n position TEXT NOT NULL DEFAULT '',\n feature_key TEXT,\n PRIMARY KEY (kind, entity_id)\n ) STRICT;\n CREATE INDEX placements_location ON placements (location_id, kind);\n\n CREATE TABLE relationships (\n id INTEGER PRIMARY KEY,\n from_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n to_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n label TEXT NOT NULL,\n summary TEXT NOT NULL DEFAULT '',\n familiarity REAL NOT NULL DEFAULT 0 CHECK (familiarity BETWEEN 0 AND 1),\n trust REAL NOT NULL DEFAULT 0 CHECK (trust BETWEEN -1 AND 1),\n affinity REAL NOT NULL DEFAULT 0 CHECK (affinity BETWEEN -1 AND 1),\n tension REAL NOT NULL DEFAULT 0 CHECK (tension BETWEEN 0 AND 1),\n updated_turn INTEGER NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE (from_id, to_id),\n CHECK (from_id <> to_id)\n ) STRICT;\n CREATE INDEX relationships_to ON relationships (to_id);\n\n CREATE TABLE consolidation_items (\n id INTEGER PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('character', 'location', 'item')),\n subject_id INTEGER NOT NULL,\n note TEXT NOT NULL DEFAULT '',\n created_turn INTEGER NOT NULL,\n resolved_turn INTEGER,\n resolution TEXT\n ) STRICT;\n CREATE INDEX consolidation_pending ON consolidation_items (resolved_turn, id);\n\n CREATE TABLE clock (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n mode TEXT NOT NULL CHECK (mode IN ('simulated', 'real')),\n now_ms INTEGER NOT NULL\n ) STRICT;\n\n CREATE TABLE time_log (\n id INTEGER PRIMARY KEY,\n turn INTEGER NOT NULL,\n round INTEGER NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('start', 'elapsed', 'real', 'skip', 'resync')),\n from_ms INTEGER NOT NULL,\n to_ms INTEGER NOT NULL,\n reason TEXT NOT NULL DEFAULT ''\n ) STRICT;\n CREATE INDEX time_log_turn ON time_log (turn, round, id);\n\n CREATE TABLE routine_windows (\n id INTEGER PRIMARY KEY,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n ordinal INTEGER NOT NULL,\n days TEXT NOT NULL DEFAULT '[]',\n start_minute INTEGER NOT NULL CHECK (start_minute BETWEEN 0 AND 1439),\n end_minute INTEGER NOT NULL CHECK (end_minute BETWEEN 0 AND 1439 AND end_minute <> start_minute),\n activity TEXT NOT NULL,\n location_id INTEGER REFERENCES locations (id) ON DELETE SET NULL,\n feature_key TEXT,\n position TEXT NOT NULL DEFAULT '',\n interruptible INTEGER NOT NULL DEFAULT 1 CHECK (interruptible IN (0, 1))\n ) STRICT;\n CREATE INDEX routine_windows_character ON routine_windows (character_id, ordinal);\n\n CREATE TABLE engagements (\n id INTEGER PRIMARY KEY,\n title TEXT NOT NULL,\n at_ms INTEGER NOT NULL,\n until_ms INTEGER,\n location_id INTEGER REFERENCES locations (id) ON DELETE SET NULL,\n status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'kept', 'missed', 'cancelled')),\n note TEXT NOT NULL DEFAULT '',\n created_turn INTEGER NOT NULL,\n updated_turn INTEGER NOT NULL\n ) STRICT;\n CREATE INDEX engagements_due ON engagements (status, at_ms);\n CREATE TABLE engagement_participants (\n engagement_id INTEGER NOT NULL REFERENCES engagements (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n PRIMARY KEY (engagement_id, character_id)\n ) STRICT;\n CREATE INDEX engagement_participants_character ON engagement_participants (character_id);\n\n CREATE TABLE slots (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n capacity INTEGER NOT NULL CHECK (capacity >= 1)\n ) STRICT;\n\n CREATE TABLE items (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n quantity INTEGER NOT NULL DEFAULT 1 CHECK (quantity >= 1),\n unique_item INTEGER NOT NULL DEFAULT 0 CHECK (unique_item IN (0, 1)),\n quality TEXT NOT NULL DEFAULT '',\n notable INTEGER NOT NULL DEFAULT 0 CHECK (notable IN (0, 1)),\n hidden INTEGER NOT NULL DEFAULT 0 CHECK (hidden IN (0, 1)),\n wearable_slot TEXT REFERENCES slots (id),\n container_state TEXT CHECK (container_state IS NULL OR container_state IN ('open', 'closed', 'locked')),\n owner_id INTEGER REFERENCES characters (id) ON DELETE SET NULL,\n created_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE item_holdings (\n item_id INTEGER PRIMARY KEY REFERENCES items (id) ON DELETE CASCADE,\n holder_kind TEXT NOT NULL CHECK (holder_kind IN ('location', 'character', 'item')),\n holder_id INTEGER NOT NULL,\n mode TEXT NOT NULL CHECK (mode IN ('at', 'held', 'worn', 'inside')),\n slot TEXT REFERENCES slots (id),\n position TEXT NOT NULL DEFAULT '',\n feature_key TEXT\n ) STRICT;\n CREATE INDEX item_holdings_holder ON item_holdings (holder_kind, holder_id);\n\n CREATE TABLE openers (\n target_kind TEXT NOT NULL CHECK (target_kind IN ('item', 'exit')),\n target_id INTEGER NOT NULL,\n key_item_id INTEGER NOT NULL REFERENCES items (id) ON DELETE CASCADE,\n PRIMARY KEY (target_kind, target_id, key_item_id)\n ) STRICT;\n\n CREATE TABLE events (\n id INTEGER PRIMARY KEY,\n turn INTEGER NOT NULL,\n round INTEGER NOT NULL,\n text TEXT NOT NULL,\n importance INTEGER NOT NULL CHECK (importance BETWEEN 1 AND 5),\n tags TEXT NOT NULL DEFAULT '[]',\n sealed INTEGER NOT NULL DEFAULT 0 CHECK (sealed IN (0, 1)),\n location_id INTEGER REFERENCES locations (id) ON DELETE SET NULL,\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX events_turn ON events (turn, round, id);\n CREATE INDEX events_location ON events (location_id);\n\n CREATE TABLE event_involves (\n event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n PRIMARY KEY (event_id, character_id)\n ) STRICT;\n CREATE INDEX event_involves_character ON event_involves (character_id);\n\n CREATE TABLE event_items (\n event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE CASCADE,\n item_id INTEGER NOT NULL REFERENCES items (id) ON DELETE CASCADE,\n PRIMARY KEY (event_id, item_id)\n ) STRICT;\n\n CREATE TABLE perceptions (\n id INTEGER PRIMARY KEY,\n event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n mode TEXT NOT NULL CHECK (mode IN ('witnessed', 'heard', 'told', 'inferred')),\n content TEXT NOT NULL,\n gist TEXT NOT NULL,\n accuracy TEXT NOT NULL CHECK (accuracy IN ('accurate', 'partial', 'mistaken')),\n recalls INTEGER NOT NULL DEFAULT 0,\n last_recalled_turn INTEGER,\n created_at TEXT NOT NULL,\n UNIQUE (event_id, character_id)\n ) STRICT;\n CREATE INDEX perceptions_character ON perceptions (character_id, event_id);\n\n CREATE TABLE memories (\n id INTEGER PRIMARY KEY,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK (kind IN ('belief', 'relationship', 'knowledge')),\n text TEXT NOT NULL,\n about TEXT NOT NULL DEFAULT '[]',\n importance INTEGER NOT NULL CHECK (importance BETWEEN 1 AND 5),\n turn INTEGER NOT NULL,\n recalls INTEGER NOT NULL DEFAULT 0,\n last_recalled_turn INTEGER,\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX memories_character ON memories (character_id, id);\n\n CREATE TABLE story_threads (\n id INTEGER PRIMARY KEY,\n text TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('open', 'resolved')),\n opened_turn INTEGER NOT NULL,\n resolved_turn INTEGER,\n created_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE summaries (\n id INTEGER PRIMARY KEY,\n level TEXT NOT NULL CHECK (level IN ('digest', 'chapter')),\n from_turn INTEGER NOT NULL,\n to_turn INTEGER NOT NULL,\n text TEXT NOT NULL,\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX summaries_range ON summaries (level, from_turn);\n\n CREATE TABLE recall_items (\n id INTEGER PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('perception', 'memory', 'event')),\n ref_id INTEGER NOT NULL,\n character_id INTEGER NOT NULL DEFAULT 0,\n text TEXT NOT NULL,\n embedded INTEGER NOT NULL DEFAULT 0 CHECK (embedded IN (0, 1)),\n UNIQUE (kind, ref_id)\n ) STRICT;\n CREATE INDEX recall_items_character ON recall_items (character_id, kind);\n CREATE INDEX recall_items_pending ON recall_items (embedded, id);\n\n CREATE VIRTUAL TABLE recall_fts USING fts5(tokens, tokenize = 'unicode61 remove_diacritics 2');\n CREATE VIRTUAL TABLE recall_vocab USING fts5vocab(recall_fts, 'row');\n\n CREATE TABLE pending_commits (\n turn INTEGER NOT NULL,\n round INTEGER NOT NULL,\n payload TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (turn, round)\n ) STRICT;\n\n CREATE TABLE triggers (\n id INTEGER PRIMARY KEY,\n key TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n condition TEXT NOT NULL,\n effects TEXT NOT NULL,\n repeat INTEGER NOT NULL DEFAULT 0 CHECK (repeat IN (0, 1)),\n cooldown_seconds INTEGER,\n chance REAL CHECK (chance IS NULL OR (chance >= 0 AND chance <= 1)),\n priority INTEGER NOT NULL DEFAULT 0,\n expires TEXT,\n announce TEXT,\n status TEXT NOT NULL DEFAULT 'dormant' CHECK (status IN ('dormant', 'fired', 'failed', 'expired')),\n fire_count INTEGER NOT NULL DEFAULT 0,\n last_fired_ms INTEGER,\n last_result INTEGER NOT NULL DEFAULT 0 CHECK (last_result IN (0, 1)),\n problem TEXT,\n origin TEXT NOT NULL CHECK (origin IN ('world', 'story')),\n created_turn INTEGER NOT NULL\n ) STRICT;\n CREATE INDEX triggers_open ON triggers (status, priority DESC, id);\n\n CREATE TABLE trigger_notes (\n id INTEGER PRIMARY KEY,\n trigger_id INTEGER NOT NULL REFERENCES triggers (id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK (kind IN ('beat', 'cue')),\n text TEXT NOT NULL,\n character_ids TEXT NOT NULL DEFAULT '[]',\n turn INTEGER NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'done', 'lapsed'))\n ) STRICT;\n CREATE INDEX trigger_notes_pending ON trigger_notes (status, kind, id);\n `,\n },\n {\n version: 2,\n sql: `\n CREATE TABLE visual_identities (\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('character', 'location', 'item')),\n subject_id INTEGER NOT NULL,\n global_id TEXT UNIQUE,\n description TEXT NOT NULL,\n tags TEXT NOT NULL DEFAULT '[]',\n negative_tags TEXT NOT NULL DEFAULT '[]',\n version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),\n updated_at TEXT NOT NULL,\n PRIMARY KEY (subject_kind, subject_id)\n ) STRICT;\n CREATE INDEX visual_identities_subject ON visual_identities (subject_kind, subject_id);\n `,\n },\n {\n version: 3,\n sql: `\n CREATE TABLE entity_knowledge (\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('location', 'item', 'exit')),\n subject_id INTEGER NOT NULL,\n learned_turn INTEGER NOT NULL,\n last_observed_turn INTEGER,\n PRIMARY KEY (character_id, subject_kind, subject_id)\n ) STRICT;\n CREATE INDEX entity_knowledge_subject ON entity_knowledge (subject_kind, subject_id);\n\n INSERT OR IGNORE INTO entity_knowledge (character_id, subject_kind, subject_id, learned_turn)\n SELECT perceptions.character_id, 'location', events.location_id, events.turn\n FROM perceptions JOIN events ON events.id = perceptions.event_id\n WHERE events.location_id IS NOT NULL;\n INSERT OR IGNORE INTO entity_knowledge (character_id, subject_kind, subject_id, learned_turn)\n SELECT perceptions.character_id, 'item', event_items.item_id, events.turn\n FROM perceptions JOIN events ON events.id = perceptions.event_id JOIN event_items ON event_items.event_id = events.id;\n INSERT OR IGNORE INTO relationships (from_id, to_id, label, summary, familiarity, trust, affinity, tension, updated_turn, created_at)\n SELECT perceptions.character_id, event_involves.character_id, 'acquaintance', '', 0, 0, 0, 0, min(events.turn), min(perceptions.created_at)\n FROM perceptions JOIN events ON events.id = perceptions.event_id JOIN event_involves ON event_involves.event_id = events.id\n WHERE perceptions.character_id <> event_involves.character_id\n GROUP BY perceptions.character_id, event_involves.character_id;\n `,\n },\n {\n version: 4,\n sql: `\n CREATE TABLE factions (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n name_key TEXT NOT NULL,\n summary TEXT NOT NULL DEFAULT '',\n description TEXT NOT NULL DEFAULT '',\n values_json TEXT NOT NULL DEFAULT '[]',\n structure TEXT NOT NULL DEFAULT '',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX factions_name_key ON factions (name_key);\n\n CREATE TABLE faction_aliases (\n faction_id INTEGER NOT NULL REFERENCES factions (id) ON DELETE CASCADE,\n position INTEGER NOT NULL,\n alias TEXT NOT NULL,\n alias_key TEXT NOT NULL,\n PRIMARY KEY (faction_id, position),\n UNIQUE (faction_id, alias_key)\n ) STRICT;\n CREATE INDEX faction_aliases_key ON faction_aliases (alias_key);\n\n CREATE TABLE faction_state (\n faction_id INTEGER PRIMARY KEY REFERENCES factions (id) ON DELETE CASCADE,\n public_state TEXT NOT NULL DEFAULT '',\n inner_state TEXT NOT NULL DEFAULT '',\n version INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE faction_memberships (\n faction_id INTEGER NOT NULL REFERENCES factions (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n role TEXT NOT NULL DEFAULT '',\n rank TEXT NOT NULL DEFAULT '',\n status TEXT NOT NULL CHECK (status IN ('active', 'inactive', 'former')),\n is_public INTEGER NOT NULL DEFAULT 1 CHECK (is_public IN (0, 1)),\n commitment REAL NOT NULL DEFAULT 0 CHECK (commitment BETWEEN 0 AND 1),\n joined_turn INTEGER NOT NULL,\n left_turn INTEGER,\n PRIMARY KEY (faction_id, character_id)\n ) STRICT;\n CREATE INDEX faction_memberships_character ON faction_memberships (character_id, status);\n\n CREATE TABLE faction_relationships (\n id INTEGER PRIMARY KEY,\n from_kind TEXT NOT NULL CHECK (from_kind IN ('character', 'faction')),\n from_id INTEGER NOT NULL,\n to_kind TEXT NOT NULL CHECK (to_kind IN ('character', 'faction')),\n to_id INTEGER NOT NULL,\n label TEXT NOT NULL,\n summary TEXT NOT NULL DEFAULT '',\n familiarity REAL NOT NULL DEFAULT 0 CHECK (familiarity BETWEEN 0 AND 1),\n trust REAL NOT NULL DEFAULT 0 CHECK (trust BETWEEN -1 AND 1),\n affinity REAL NOT NULL DEFAULT 0 CHECK (affinity BETWEEN -1 AND 1),\n tension REAL NOT NULL DEFAULT 0 CHECK (tension BETWEEN 0 AND 1),\n updated_turn INTEGER NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE (from_kind, from_id, to_kind, to_id),\n CHECK (from_kind <> to_kind OR from_id <> to_id)\n ) STRICT;\n CREATE INDEX faction_relationships_to ON faction_relationships (to_kind, to_id);\n\n CREATE TABLE faction_intents (\n id INTEGER PRIMARY KEY,\n faction_id INTEGER NOT NULL REFERENCES factions (id) ON DELETE CASCADE,\n type TEXT NOT NULL CHECK (type IN ('need', 'obligation', 'quest', 'agenda', 'aspiration', 'relationship', 'habit', 'reaction')),\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n status TEXT NOT NULL CHECK (status IN ('active', 'paused', 'completed', 'failed', 'abandoned')),\n horizon TEXT NOT NULL CHECK (horizon IN ('immediate', 'short', 'day', 'long', 'open_ended')),\n priority REAL NOT NULL CHECK (priority BETWEEN 0 AND 1),\n urgency REAL NOT NULL CHECK (urgency BETWEEN 0 AND 1),\n plan TEXT NOT NULL DEFAULT '[]',\n open_threads TEXT NOT NULL DEFAULT '[]',\n constraints TEXT NOT NULL DEFAULT '[]',\n deadline TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX faction_intents_faction ON faction_intents (faction_id, status);\n `,\n },\n {\n version: 5,\n sql: `ALTER TABLE characters ADD COLUMN voice TEXT;`,\n },\n {\n version: 6,\n sql: `\n CREATE TABLE lore (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n title TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('history', 'culture', 'religion', 'politics', 'geography', 'science', 'custom', 'legend', 'other')),\n summary TEXT NOT NULL DEFAULT '',\n body TEXT NOT NULL DEFAULT '',\n starts_at INTEGER,\n ends_at INTEGER,\n sources_json TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE lore_subjects (\n lore_id INTEGER NOT NULL REFERENCES lore (id) ON DELETE CASCADE,\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('character', 'faction', 'location', 'item', 'lore')),\n subject_id INTEGER NOT NULL,\n PRIMARY KEY (lore_id, subject_kind, subject_id)\n ) STRICT;\n CREATE INDEX lore_subjects_subject ON lore_subjects (subject_kind, subject_id);\n CREATE TABLE lore_relations (\n lore_id INTEGER NOT NULL REFERENCES lore (id) ON DELETE CASCADE,\n related_lore_id INTEGER NOT NULL REFERENCES lore (id) ON DELETE CASCADE,\n PRIMARY KEY (lore_id, related_lore_id),\n CHECK (lore_id <> related_lore_id)\n ) STRICT;\n\n ALTER TABLE entity_knowledge RENAME TO old_entity_knowledge;\n CREATE TABLE entity_knowledge (\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('location', 'item', 'exit', 'lore')),\n subject_id INTEGER NOT NULL,\n learned_turn INTEGER NOT NULL,\n last_observed_turn INTEGER,\n PRIMARY KEY (character_id, subject_kind, subject_id)\n ) STRICT;\n INSERT INTO entity_knowledge SELECT * FROM old_entity_knowledge;\n DROP TABLE old_entity_knowledge;\n CREATE INDEX entity_knowledge_subject ON entity_knowledge (subject_kind, subject_id);\n `,\n },\n]\n\nexport const LATEST_VERSION = MIGRATIONS[MIGRATIONS.length - 1]?.version ?? 0\n\n/** Marks the file as a roleplay session database (\"DRSS\"). */\nexport const APPLICATION_ID = 0x44525353\n","import type { SqlDatabase } from '../driver/types.ts'\nimport { SchemaError } from '../errors.ts'\nimport { APPLICATION_ID, LATEST_VERSION, MIGRATIONS } from './schema.ts'\n\nexport interface DatabaseState {\n version: number\n applicationId: number\n /** Whether the file holds any tables at all. */\n empty: boolean\n}\n\nexport function inspect(db: SqlDatabase): DatabaseState {\n const version = db.get<{ user_version: number }>('PRAGMA user_version')?.user_version ?? 0\n const applicationId = db.get<{ application_id: number }>('PRAGMA application_id')?.application_id ?? 0\n const tables = db.get<{ count: number }>(\"SELECT count(*) AS count FROM sqlite_master WHERE type = 'table'\")?.count ?? 0\n return { version, applicationId, empty: tables === 0 }\n}\n\n/**\n * Bring the database up to the latest schema, applying each missing migration\n * in its own transaction.\n * @throws {SchemaError} when the file belongs to something else, or was written by a newer version.\n */\nexport function migrate(db: SqlDatabase): void {\n const state = inspect(db)\n if (state.version === 0 && !state.empty) throw new SchemaError('the file is not a session database')\n if (state.version > 0 && state.applicationId !== APPLICATION_ID) throw new SchemaError('the file is not a session database')\n if (state.version > LATEST_VERSION) {\n throw new SchemaError(`the database has schema version ${state.version}, but this version understands up to ${LATEST_VERSION}`)\n }\n for (const migration of MIGRATIONS.filter(candidate => candidate.version > state.version)) {\n db.transaction(() => {\n db.exec(migration.sql)\n if (migration.version === 1) db.exec(`PRAGMA application_id = ${APPLICATION_ID}`)\n db.exec(`PRAGMA user_version = ${migration.version}`)\n })\n }\n}\n","import type { CharacterId, CharacterState, CharacterStatePatch, NewCharacterState } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, NotFoundError } from '../errors.ts'\nimport type { CharacterStateRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface StateRow {\n character_id: number\n public_state: string\n inner_state: string\n activity: string\n version: number\n updated_at: string\n}\n\nfunction toState(row: StateRow): CharacterState {\n return { characterId: row.character_id, publicState: row.public_state, innerState: row.inner_state, activity: row.activity, version: row.version, updatedAt: row.updated_at }\n}\n\nexport class SqliteCharacterStateRepository implements CharacterStateRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n create(characterId: CharacterId, state: NewCharacterState): CharacterState {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) {\n throw new NotFoundError(`character ${characterId} does not exist`)\n }\n this.db.run(\n 'INSERT INTO character_state (character_id, public_state, inner_state, activity, updated_at) VALUES (?, ?, ?, ?, ?)',\n [characterId, state.publicState, state.innerState, state.activity, this.clock().toISOString()],\n )\n return this.require(characterId)\n }))\n }\n\n get(characterId: CharacterId): CharacterState | undefined {\n const row = this.db.get<StateRow>('SELECT * FROM character_state WHERE character_id = ?', [characterId])\n return row === undefined ? undefined : toState(row)\n }\n\n update(characterId: CharacterId, patch: CharacterStatePatch, options: { expectedVersion?: number } = {}): CharacterState {\n return guard(() => this.db.transaction(() => {\n const current = this.require(characterId)\n if (options.expectedVersion !== undefined && current.version !== options.expectedVersion) {\n throw new ConflictError(`the state of character ${characterId} is at version ${current.version}, not ${options.expectedVersion}`)\n }\n if (Object.keys(patch).length === 0) return current\n this.db.run(\n `UPDATE character_state\n SET public_state = ?, inner_state = ?, activity = ?, version = version + 1, updated_at = ?\n WHERE character_id = ?`,\n [\n patch.publicState ?? current.publicState,\n patch.innerState ?? current.innerState,\n patch.activity ?? current.activity,\n this.clock().toISOString(),\n characterId,\n ],\n )\n return this.require(characterId)\n }))\n }\n\n private require(characterId: CharacterId): CharacterState {\n const state = this.get(characterId)\n if (state === undefined) throw new NotFoundError(`character ${characterId} has no state`)\n return state\n }\n}\n","import type { VisualIdentity, VisualIdentityInput, VisualIdentityPatch, VisualSubjectKind } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { VisualIdentityRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface VisualIdentityRow {\n subject_kind: VisualSubjectKind\n subject_id: number\n global_id: string | null\n description: string\n tags: string\n negative_tags: string\n version: number\n updated_at: string\n}\n\nconst MAX_DESCRIPTION = 2_000\nconst MAX_TAGS = 40\n\nfunction clean(identity: VisualIdentityInput): VisualIdentityInput {\n const description = identity.description.trim()\n const tags = [...new Set(identity.tags.map(tag => tag.trim()).filter(Boolean))]\n const negativeTags = [...new Set(identity.negativeTags.map(tag => tag.trim()).filter(Boolean))]\n const globalId = identity.globalId?.trim()\n if (description === '') throw new InvalidValueError('a visual identity needs a description')\n if (description.length > MAX_DESCRIPTION) throw new InvalidValueError(`a visual identity description has at most ${MAX_DESCRIPTION} characters`)\n if (tags.length > MAX_TAGS || negativeTags.length > MAX_TAGS) throw new InvalidValueError(`a visual identity has at most ${MAX_TAGS} positive and ${MAX_TAGS} negative tags`)\n if (globalId !== undefined && (globalId === '' || globalId.length > 200)) throw new InvalidValueError('a global visual id must be from 1 to 200 characters')\n return { description, tags, negativeTags, ...(globalId === undefined ? {} : { globalId }) }\n}\n\nfunction fromRow(row: VisualIdentityRow): VisualIdentity {\n return {\n subjectKind: row.subject_kind, subjectId: row.subject_id,\n ...(row.global_id === null ? {} : { globalId: row.global_id }),\n description: row.description, tags: parseStringList(row.tags, 'visual_identities.tags'),\n negativeTags: parseStringList(row.negative_tags, 'visual_identities.negative_tags'),\n version: row.version, updatedAt: row.updated_at,\n }\n}\n\nexport class SqliteVisualIdentityRepository implements VisualIdentityRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly clock: Clock,\n private readonly exists: (kind: VisualSubjectKind, id: number) => boolean,\n ) {}\n\n set(subjectKind: VisualSubjectKind, subjectId: number, input: VisualIdentityInput): VisualIdentity {\n if (!this.exists(subjectKind, subjectId)) throw new NotFoundError(`${subjectKind} ${subjectId} does not exist`)\n const identity = clean(input)\n return guard(() => {\n this.db.run(\n `INSERT INTO visual_identities (subject_kind, subject_id, global_id, description, tags, negative_tags, version, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, 1, ?)\n ON CONFLICT (subject_kind, subject_id) DO UPDATE SET\n global_id = excluded.global_id, description = excluded.description, tags = excluded.tags,\n negative_tags = excluded.negative_tags, version = visual_identities.version + 1, updated_at = excluded.updated_at`,\n [subjectKind, subjectId, identity.globalId ?? null, identity.description, toJson(identity.tags), toJson(identity.negativeTags), this.clock().toISOString()],\n )\n return this.require(subjectKind, subjectId)\n })\n }\n\n get(subjectKind: VisualSubjectKind, subjectId: number): VisualIdentity | undefined {\n const row = this.db.get<VisualIdentityRow>('SELECT * FROM visual_identities WHERE subject_kind = ? AND subject_id = ?', [subjectKind, subjectId])\n return row === undefined ? undefined : fromRow(row)\n }\n\n list(subjectKind?: VisualSubjectKind): VisualIdentity[] {\n const rows = subjectKind === undefined\n ? this.db.all<VisualIdentityRow>('SELECT * FROM visual_identities ORDER BY subject_kind, subject_id')\n : this.db.all<VisualIdentityRow>('SELECT * FROM visual_identities WHERE subject_kind = ? ORDER BY subject_id', [subjectKind])\n return rows.map(fromRow)\n }\n\n update(subjectKind: VisualSubjectKind, subjectId: number, patch: VisualIdentityPatch): VisualIdentity {\n const current = this.require(subjectKind, subjectId)\n return this.set(subjectKind, subjectId, {\n description: patch.description ?? current.description,\n tags: patch.tags ?? current.tags,\n negativeTags: patch.negativeTags ?? current.negativeTags,\n ...(patch.globalId === undefined ? current.globalId === undefined ? {} : { globalId: current.globalId } : { globalId: patch.globalId }),\n })\n }\n\n remove(subjectKind: VisualSubjectKind, subjectId: number): boolean {\n return this.db.run('DELETE FROM visual_identities WHERE subject_kind = ? AND subject_id = ?', [subjectKind, subjectId]).changes > 0\n }\n\n private require(subjectKind: VisualSubjectKind, subjectId: number): VisualIdentity {\n const identity = this.get(subjectKind, subjectId)\n if (identity === undefined) throw new NotFoundError(`${subjectKind} ${subjectId} has no visual identity`)\n return identity\n }\n}\n","import type { CharacterId, EntityKnowledge, KnowledgeKind } from 'dsh-roleplay-model'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { KnowledgeRepository } from '../repositories.ts'\n\ninterface Row { character_id: number; subject_kind: KnowledgeKind; subject_id: number; learned_turn: number; last_observed_turn: number | null }\n\nconst fromRow = (row: Row): EntityKnowledge => ({\n characterId: row.character_id, subjectKind: row.subject_kind, subjectId: row.subject_id, learnedTurn: row.learned_turn,\n ...(row.last_observed_turn === null ? {} : { lastObservedTurn: row.last_observed_turn }),\n})\n\nexport class SqliteKnowledgeRepository implements KnowledgeRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n learn(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number, turn: number, observed = false): EntityKnowledge {\n this.requireSubject(characterId, subjectKind, subjectId)\n this.db.run(`INSERT INTO entity_knowledge (character_id, subject_kind, subject_id, learned_turn, last_observed_turn)\n VALUES (?, ?, ?, ?, ?) ON CONFLICT (character_id, subject_kind, subject_id) DO UPDATE SET\n last_observed_turn = CASE WHEN excluded.last_observed_turn IS NULL THEN entity_knowledge.last_observed_turn ELSE excluded.last_observed_turn END`,\n [characterId, subjectKind, subjectId, turn, observed ? turn : null])\n return this.get(characterId, subjectKind, subjectId)!\n }\n\n knows(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number): boolean {\n return this.get(characterId, subjectKind, subjectId) !== undefined\n }\n\n get(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number): EntityKnowledge | undefined {\n const row = this.db.get<Row>('SELECT * FROM entity_knowledge WHERE character_id = ? AND subject_kind = ? AND subject_id = ?', [characterId, subjectKind, subjectId])\n return row === undefined ? undefined : fromRow(row)\n }\n\n list(characterId: CharacterId, subjectKind?: KnowledgeKind): EntityKnowledge[] {\n return this.db.all<Row>(`SELECT * FROM entity_knowledge WHERE character_id = ?${subjectKind === undefined ? '' : ' AND subject_kind = ?'} ORDER BY subject_kind, subject_id`, subjectKind === undefined ? [characterId] : [characterId, subjectKind]).map(fromRow)\n }\n\n forget(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number): boolean {\n return this.db.run('DELETE FROM entity_knowledge WHERE character_id = ? AND subject_kind = ? AND subject_id = ?', [characterId, subjectKind, subjectId]).changes > 0\n }\n\n private requireSubject(characterId: CharacterId, kind: KnowledgeKind, id: number): void {\n if (this.db.get('SELECT id FROM characters WHERE id = ?', [characterId]) === undefined) throw new NotFoundError(`character ${characterId} does not exist`)\n const table = kind === 'location' ? 'locations' : kind === 'item' ? 'items' : kind === 'exit' ? 'exits' : 'lore'\n if (this.db.get(`SELECT id FROM ${table} WHERE id = ?`, [id]) === undefined) throw new NotFoundError(`${kind} ${id} does not exist`)\n }\n}\n","import type {\n Faction, FactionId, FactionIntent, FactionMembership, FactionPatch, FactionRelationship, FactionState, FactionStatePatch,\n Intent, IntentFilter, IntentPatch, MembershipPatch, MembershipStatus, NewFaction, NewFactionState, RelationshipPatch, SocialSubjectKind,\n} from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { FactionIntentRepository, FactionMembershipRepository, FactionRelationshipRepository, FactionRepository, FactionStateRepository } from '../repositories.ts'\nimport { guard, lookupKey, parseStringList, toJson } from './support.ts'\n\ninterface FactionRow { id: number; source_id: string | null; name: string; summary: string; description: string; values_json: string; structure: string; created_at: string }\ninterface AliasRow { faction_id: number; alias: string }\ninterface StateRow { faction_id: number; public_state: string; inner_state: string; version: number; updated_at: string }\ninterface MembershipRow { faction_id: number; character_id: number; role: string; rank: string; status: MembershipStatus; is_public: number; commitment: number; joined_turn: number; left_turn: number | null }\ninterface RelationshipRow { id: number; from_kind: SocialSubjectKind; from_id: number; to_kind: SocialSubjectKind; to_id: number; label: string; summary: string; familiarity: number; trust: number; affinity: number; tension: number; updated_turn: number; created_at: string }\ninterface IntentRow { id: number; faction_id: number; type: Intent['type']; name: string; description: string; status: Intent['status']; horizon: Intent['horizon']; priority: number; urgency: number; plan: string; open_threads: string; constraints: string; deadline: string | null; created_at: string; updated_at: string }\n\nexport class SqliteFactionRepository implements FactionRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(faction: NewFaction): Faction {\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid: id } = this.db.run('INSERT INTO factions (source_id, name, name_key, summary, description, values_json, structure, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [faction.sourceId ?? null, faction.name, lookupKey(faction.name), faction.summary, faction.description, toJson(faction.values), faction.structure, this.clock().toISOString()])\n const stored = new Set<string>()\n for (const alias of faction.aliases) {\n const key = lookupKey(alias)\n if (stored.has(key)) continue\n this.db.run('INSERT INTO faction_aliases (faction_id, position, alias, alias_key) VALUES (?, ?, ?, ?)', [id, stored.size, alias, key])\n stored.add(key)\n }\n return this.get(Number(id))!\n }))\n }\n\n get(id: FactionId): Faction | undefined { return this.read('WHERE id = ?', [id])[0] }\n getBySourceId(sourceId: string): Faction | undefined { return this.read('WHERE source_id = ?', [sourceId])[0] }\n list(): Faction[] { return this.read('', []) }\n findByName(name: string): Faction[] { return this.read('WHERE name_key = ?1 OR id IN (SELECT faction_id FROM faction_aliases WHERE alias_key = ?1)', [lookupKey(name)]) }\n update(id: FactionId, patch: FactionPatch): Faction {\n const current = this.get(id)\n if (current === undefined) throw new NotFoundError(`faction ${id} does not exist`)\n return guard(() => this.db.transaction(() => {\n const name = patch.name?.trim() ?? current.name\n if (name === '') throw new InvalidValueError('a faction needs a name')\n this.db.run('UPDATE factions SET name = ?, name_key = ?, summary = ?, description = ?, values_json = ?, structure = ? WHERE id = ?', [name, lookupKey(name), patch.summary ?? current.summary, patch.description ?? current.description, toJson(patch.values ?? current.values), patch.structure ?? current.structure, id])\n if (patch.aliases !== undefined) {\n this.db.run('DELETE FROM faction_aliases WHERE faction_id = ?', [id])\n const stored = new Set<string>()\n for (const alias of patch.aliases.map(value => value.trim()).filter(Boolean)) {\n const key = lookupKey(alias)\n if (stored.has(key) || key === lookupKey(name)) continue\n this.db.run('INSERT INTO faction_aliases (faction_id, position, alias, alias_key) VALUES (?, ?, ?, ?)', [id, stored.size, alias, key])\n stored.add(key)\n }\n }\n return this.get(id)!\n }))\n }\n\n private read(where: string, params: readonly SqlValue[]): Faction[] {\n const rows = this.db.all<FactionRow>(`SELECT * FROM factions ${where} ORDER BY id`, params)\n const aliases = new Map<number, string[]>()\n for (const row of this.db.all<AliasRow>(`SELECT faction_id, alias FROM faction_aliases WHERE faction_id IN (SELECT id FROM factions ${where}) ORDER BY faction_id, position`, params)) aliases.set(row.faction_id, [...aliases.get(row.faction_id) ?? [], row.alias])\n return rows.map(row => ({ id: row.id, ...(row.source_id === null ? {} : { sourceId: row.source_id }), name: row.name, aliases: aliases.get(row.id) ?? [], summary: row.summary, description: row.description, values: parseStringList(row.values_json, 'factions.values_json'), structure: row.structure, createdAt: row.created_at }))\n }\n}\n\nexport class SqliteFactionStateRepository implements FactionStateRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n create(factionId: FactionId, state: NewFactionState): FactionState {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM factions WHERE id = ?', [factionId]) === undefined) throw new NotFoundError(`faction ${factionId} does not exist`)\n this.db.run('INSERT INTO faction_state (faction_id, public_state, inner_state, updated_at) VALUES (?, ?, ?, ?)', [factionId, state.publicState ?? '', state.innerState ?? '', this.clock().toISOString()])\n return this.get(factionId)!\n }))\n }\n get(factionId: FactionId): FactionState | undefined {\n const row = this.db.get<StateRow>('SELECT * FROM faction_state WHERE faction_id = ?', [factionId])\n return row === undefined ? undefined : { factionId: row.faction_id, publicState: row.public_state, innerState: row.inner_state, version: row.version, updatedAt: row.updated_at }\n }\n update(factionId: FactionId, patch: FactionStatePatch, options: { expectedVersion?: number } = {}): FactionState {\n const current = this.get(factionId)\n if (current === undefined) throw new NotFoundError(`faction ${factionId} has no state`)\n if (options.expectedVersion !== undefined && options.expectedVersion !== current.version) throw new ConflictError(`the state of faction ${factionId} is at version ${current.version}, not ${options.expectedVersion}`)\n if (Object.keys(patch).length === 0) return current\n this.db.run('UPDATE faction_state SET public_state = ?, inner_state = ?, version = version + 1, updated_at = ? WHERE faction_id = ?', [patch.publicState ?? current.publicState, patch.innerState ?? current.innerState, this.clock().toISOString(), factionId])\n return this.get(factionId)!\n }\n}\n\nconst membership = (row: MembershipRow): FactionMembership => ({ factionId: row.faction_id, characterId: row.character_id, role: row.role, rank: row.rank, status: row.status, public: row.is_public === 1, commitment: row.commitment, joinedTurn: row.joined_turn, ...(row.left_turn === null ? {} : { leftTurn: row.left_turn }) })\n\nexport class SqliteFactionMembershipRepository implements FactionMembershipRepository {\n constructor(private readonly db: SqlDatabase) {}\n upsert(factionId: FactionId, characterId: number, patch: MembershipPatch, turn: number): FactionMembership {\n if (patch.commitment !== undefined && (!Number.isFinite(patch.commitment) || patch.commitment < 0 || patch.commitment > 1)) throw new InvalidValueError('commitment must be a number from 0 to 1')\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM factions WHERE id = ?', [factionId]) === undefined) throw new NotFoundError(`faction ${factionId} does not exist`)\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) throw new NotFoundError(`character ${characterId} does not exist`)\n const current = this.get(factionId, characterId)\n if (current === undefined) this.db.run('INSERT INTO faction_memberships (faction_id, character_id, role, rank, status, is_public, commitment, joined_turn, left_turn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [factionId, characterId, patch.role ?? '', patch.rank ?? '', patch.status ?? 'active', patch.public === false ? 0 : 1, patch.commitment ?? 0, turn, patch.leftTurn ?? null])\n else this.db.run('UPDATE faction_memberships SET role = ?, rank = ?, status = ?, is_public = ?, commitment = ?, left_turn = ? WHERE faction_id = ? AND character_id = ?', [patch.role ?? current.role, patch.rank ?? current.rank, patch.status ?? current.status, (patch.public ?? current.public) ? 1 : 0, patch.commitment ?? current.commitment, patch.leftTurn ?? current.leftTurn ?? null, factionId, characterId])\n return this.get(factionId, characterId)!\n }))\n }\n get(factionId: FactionId, characterId: number): FactionMembership | undefined { const row = this.db.get<MembershipRow>('SELECT * FROM faction_memberships WHERE faction_id = ? AND character_id = ?', [factionId, characterId]); return row === undefined ? undefined : membership(row) }\n ofFaction(factionId: FactionId, status?: MembershipStatus): FactionMembership[] { return this.db.all<MembershipRow>(`SELECT * FROM faction_memberships WHERE faction_id = ?${status === undefined ? '' : ' AND status = ?'} ORDER BY character_id`, status === undefined ? [factionId] : [factionId, status]).map(membership) }\n ofCharacter(characterId: number, status?: MembershipStatus): FactionMembership[] { return this.db.all<MembershipRow>(`SELECT * FROM faction_memberships WHERE character_id = ?${status === undefined ? '' : ' AND status = ?'} ORDER BY faction_id`, status === undefined ? [characterId] : [characterId, status]).map(membership) }\n remove(factionId: FactionId, characterId: number): boolean { return this.db.run('DELETE FROM faction_memberships WHERE faction_id = ? AND character_id = ?', [factionId, characterId]).changes > 0 }\n}\n\nconst RANGES = { familiarity: [0, 1], trust: [-1, 1], affinity: [-1, 1], tension: [0, 1] } as const\nconst relationship = (row: RelationshipRow): FactionRelationship => ({ id: row.id, fromKind: row.from_kind, fromId: row.from_id, toKind: row.to_kind, toId: row.to_id, label: row.label, summary: row.summary, familiarity: row.familiarity, trust: row.trust, affinity: row.affinity, tension: row.tension, updatedTurn: row.updated_turn, createdAt: row.created_at })\n\nexport class SqliteFactionRelationshipRepository implements FactionRelationshipRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n upsert(fromKind: SocialSubjectKind, fromId: number, toKind: SocialSubjectKind, toId: number, patch: RelationshipPatch, turn: number): FactionRelationship {\n if (fromKind === toKind && fromId === toId) throw new InvalidValueError('an entity has no relationship with itself')\n for (const [key, [min, max]] of Object.entries(RANGES) as [keyof typeof RANGES, readonly [number, number]][]) { const value = patch[key]; if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) throw new InvalidValueError(`${key} must be a number from ${min} to ${max}`) }\n if (patch.label !== undefined && patch.label.trim() === '') throw new InvalidValueError('a relationship needs a label')\n return guard(() => this.db.transaction(() => {\n this.requireSubject(fromKind, fromId); this.requireSubject(toKind, toId)\n const current = this.get(fromKind, fromId, toKind, toId)\n if (current === undefined) {\n if (patch.label === undefined) throw new InvalidValueError('a new relationship needs a label')\n this.db.run('INSERT INTO faction_relationships (from_kind, from_id, to_kind, to_id, label, summary, familiarity, trust, affinity, tension, updated_turn, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [fromKind, fromId, toKind, toId, patch.label.trim(), (patch.summary ?? '').trim(), patch.familiarity ?? 0, patch.trust ?? 0, patch.affinity ?? 0, patch.tension ?? 0, turn, this.clock().toISOString()])\n } else this.db.run('UPDATE faction_relationships SET label = ?, summary = ?, familiarity = ?, trust = ?, affinity = ?, tension = ?, updated_turn = ? WHERE id = ?', [(patch.label ?? current.label).trim(), (patch.summary ?? current.summary).trim(), patch.familiarity ?? current.familiarity, patch.trust ?? current.trust, patch.affinity ?? current.affinity, patch.tension ?? current.tension, turn, current.id])\n return this.get(fromKind, fromId, toKind, toId)!\n }))\n }\n get(fromKind: SocialSubjectKind, fromId: number, toKind: SocialSubjectKind, toId: number): FactionRelationship | undefined { const row = this.db.get<RelationshipRow>('SELECT * FROM faction_relationships WHERE from_kind = ? AND from_id = ? AND to_kind = ? AND to_id = ?', [fromKind, fromId, toKind, toId]); return row === undefined ? undefined : relationship(row) }\n from(kind: SocialSubjectKind, id: number): FactionRelationship[] { return this.db.all<RelationshipRow>('SELECT * FROM faction_relationships WHERE from_kind = ? AND from_id = ? ORDER BY id', [kind, id]).map(relationship) }\n to(kind: SocialSubjectKind, id: number): FactionRelationship[] { return this.db.all<RelationshipRow>('SELECT * FROM faction_relationships WHERE to_kind = ? AND to_id = ? ORDER BY id', [kind, id]).map(relationship) }\n list(): FactionRelationship[] { return this.db.all<RelationshipRow>('SELECT * FROM faction_relationships ORDER BY id').map(relationship) }\n remove(fromKind: SocialSubjectKind, fromId: number, toKind: SocialSubjectKind, toId: number): boolean { return this.db.run('DELETE FROM faction_relationships WHERE from_kind = ? AND from_id = ? AND to_kind = ? AND to_id = ?', [fromKind, fromId, toKind, toId]).changes > 0 }\n private requireSubject(kind: SocialSubjectKind, id: number): void { if (this.db.get(`SELECT 1 FROM ${kind === 'character' ? 'characters' : 'factions'} WHERE id = ?`, [id]) === undefined) throw new NotFoundError(`${kind} ${id} does not exist`) }\n}\n\nconst factionIntent = (row: IntentRow): FactionIntent => ({ id: row.id, factionId: row.faction_id, type: row.type, name: row.name, description: row.description, status: row.status, horizon: row.horizon, priority: row.priority, urgency: row.urgency, plan: parseStringList(row.plan, 'faction_intents.plan'), openThreads: parseStringList(row.open_threads, 'faction_intents.open_threads'), constraints: parseStringList(row.constraints, 'faction_intents.constraints'), ...(row.deadline === null ? {} : { deadline: row.deadline }), createdAt: row.created_at, updatedAt: row.updated_at })\n\nexport class SqliteFactionIntentRepository implements FactionIntentRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n add(factionId: FactionId, intent: Intent): FactionIntent {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM factions WHERE id = ?', [factionId]) === undefined) throw new NotFoundError(`faction ${factionId} does not exist`)\n const now = this.clock().toISOString()\n const { lastInsertRowid } = this.db.run('INSERT INTO faction_intents (faction_id, type, name, description, status, horizon, priority, urgency, plan, open_threads, constraints, deadline, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [factionId, intent.type, intent.name, intent.description, intent.status, intent.horizon, intent.priority, intent.urgency, toJson(intent.plan), toJson(intent.openThreads), toJson(intent.constraints), intent.deadline ?? null, now, now])\n return this.get(Number(lastInsertRowid))!\n }))\n }\n get(id: number): FactionIntent | undefined { const row = this.db.get<IntentRow>('SELECT * FROM faction_intents WHERE id = ?', [id]); return row === undefined ? undefined : factionIntent(row) }\n list(factionId: FactionId, filter: IntentFilter = {}): FactionIntent[] { const params: SqlValue[] = [factionId]; let where = 'faction_id = ?'; if (filter.status !== undefined) { where += ' AND status = ?'; params.push(filter.status) }; return this.db.all<IntentRow>(`SELECT * FROM faction_intents WHERE ${where} ORDER BY id`, params).map(factionIntent) }\n update(id: number, patch: IntentPatch): FactionIntent {\n const current = this.get(id); if (current === undefined) throw new NotFoundError(`faction intent ${id} does not exist`)\n this.db.run('UPDATE faction_intents SET type = ?, name = ?, description = ?, status = ?, horizon = ?, priority = ?, urgency = ?, plan = ?, open_threads = ?, constraints = ?, deadline = ?, updated_at = ? WHERE id = ?', [patch.type ?? current.type, patch.name ?? current.name, patch.description ?? current.description, patch.status ?? current.status, patch.horizon ?? current.horizon, patch.priority ?? current.priority, patch.urgency ?? current.urgency, toJson(patch.plan ?? current.plan), toJson(patch.openThreads ?? current.openThreads), toJson(patch.constraints ?? current.constraints), patch.deadline === undefined ? current.deadline ?? null : patch.deadline, this.clock().toISOString(), id])\n return this.get(id)!\n }\n remove(id: number): boolean { return this.db.run('DELETE FROM faction_intents WHERE id = ?', [id]).changes > 0 }\n}\n","import type { Lore, LoreId, LoreKind, LorePatch, LoreSubject, NewLore } from 'dsh-roleplay-model'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { LoreRepository } from '../repositories.ts'\n\ninterface Row { id: number; source_id: string | null; title: string; kind: LoreKind; summary: string; body: string; starts_at: number | null; ends_at: number | null; sources_json: string; created_at: string }\ninterface SubjectRow { subject_kind: LoreSubject['kind']; subject_id: number }\n\nexport class SqliteLoreRepository implements LoreRepository {\n constructor(private readonly db: SqlDatabase, private readonly now: () => string) {}\n\n add(entry: NewLore): Lore {\n return this.db.transaction(() => {\n const result = this.db.run('INSERT INTO lore (source_id, title, kind, summary, body, starts_at, ends_at, sources_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [entry.sourceId ?? null, required(entry.title), entry.kind, entry.summary, entry.body, entry.startsAt ?? null, entry.endsAt ?? null, JSON.stringify(entry.sources), this.now()])\n this.replaceLinks(result.lastInsertRowid, entry.subjects, entry.related)\n return this.get(result.lastInsertRowid)!\n })\n }\n\n get(id: LoreId): Lore | undefined {\n const row = this.db.get<Row>('SELECT * FROM lore WHERE id = ?', [id])\n return row === undefined ? undefined : this.fromRow(row)\n }\n\n getBySourceId(sourceId: string): Lore | undefined {\n const row = this.db.get<Row>('SELECT * FROM lore WHERE source_id = ?', [sourceId])\n return row === undefined ? undefined : this.fromRow(row)\n }\n\n list(): Lore[] { return this.db.all<Row>('SELECT * FROM lore ORDER BY title COLLATE NOCASE, id').map(row => this.fromRow(row)) }\n\n update(id: LoreId, patch: LorePatch): Lore {\n const current = this.get(id)\n if (current === undefined) throw new NotFoundError(`lore ${id} does not exist`)\n const next = { ...current, ...patch, startsAt: patch.startsAt === null ? undefined : patch.startsAt ?? current.startsAt, endsAt: patch.endsAt === null ? undefined : patch.endsAt ?? current.endsAt }\n this.db.transaction(() => {\n this.db.run('UPDATE lore SET title = ?, kind = ?, summary = ?, body = ?, starts_at = ?, ends_at = ?, sources_json = ? WHERE id = ?', [required(next.title), next.kind, next.summary, next.body, next.startsAt ?? null, next.endsAt ?? null, JSON.stringify(next.sources), id])\n if (patch.subjects !== undefined || patch.related !== undefined) this.replaceLinks(id, next.subjects, next.related)\n })\n return this.get(id)!\n }\n\n remove(id: LoreId): boolean { return this.db.run('DELETE FROM lore WHERE id = ?', [id]).changes > 0 }\n\n private replaceLinks(id: number, subjects: readonly LoreSubject[], related: readonly number[]): void {\n this.db.run('DELETE FROM lore_subjects WHERE lore_id = ?', [id]); this.db.run('DELETE FROM lore_relations WHERE lore_id = ?', [id])\n for (const subject of subjects) this.db.run('INSERT INTO lore_subjects (lore_id, subject_kind, subject_id) VALUES (?, ?, ?)', [id, subject.kind, subject.id])\n for (const other of related) this.db.run('INSERT INTO lore_relations (lore_id, related_lore_id) VALUES (?, ?)', [id, other])\n }\n\n private fromRow(row: Row): Lore {\n return { id: row.id, ...(row.source_id === null ? {} : { sourceId: row.source_id }), title: row.title, kind: row.kind, summary: row.summary, body: row.body, ...(row.starts_at === null ? {} : { startsAt: row.starts_at }), ...(row.ends_at === null ? {} : { endsAt: row.ends_at }), subjects: this.db.all<SubjectRow>('SELECT subject_kind, subject_id FROM lore_subjects WHERE lore_id = ? ORDER BY subject_kind, subject_id', [row.id]).map(x => ({ kind: x.subject_kind, id: x.subject_id })), related: this.db.all<{ related_lore_id: number }>('SELECT related_lore_id FROM lore_relations WHERE lore_id = ? ORDER BY related_lore_id', [row.id]).map(x => x.related_lore_id), sources: JSON.parse(row.sources_json) as string[], createdAt: row.created_at }\n }\n}\n\nfunction required(value: string): string { const clean = value.trim(); if (clean === '') throw new RangeError('lore title cannot be blank'); return clean }\n","import { existsSync, mkdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { CharacterId, Move, MovePlan, NewSession, StoryEvent, TriggerNote } from 'dsh-roleplay-model'\nimport { lapseNotes, runTriggers, type TriggerRun, type TriggerRunOptions } from './records/triggers.ts'\nimport { deliverNotes, type Delivery } from './records/deferred.ts'\nimport type { TriggerClock } from './records/trigger-rules.ts'\nimport { moveCharacter, planKnownMove, planMove } from './records/movement.ts'\nimport { systemClock, type Clock } from './clock.ts'\nimport { nodeSqliteDriver } from './driver/node-sqlite.ts'\nimport type { OpenOptions, SqlDatabase, SqlDriver } from './driver/types.ts'\nimport { ConflictError, CorruptDataError, NotFoundError, SchemaError } from './errors.ts'\nimport type {\n ClockRepository, VariableRepository, EngagementRepository, TriggerRepository, RoutineRepository, CharacterRepository, CharacterStateRepository, EventRepository, IntentRepository, MemoryRepository, MetadataRepository,\n ConsolidationRepository, ItemRepository, KnowledgeRepository, LocationRepository, PendingCommitRepository, RelationshipRepository, PlacementRepository, RecallIndexRepository, SlotRepository, SummaryRepository, ThreadRepository, VectorSupport, VisualIdentityRepository,\n FactionRepository, FactionStateRepository, FactionMembershipRepository, FactionRelationshipRepository, FactionIntentRepository,\n LoreRepository,\n} from './repositories.ts'\nimport { denseScore, finishRecall, recall, recallCandidates, recallPool, type RecallPool, type MemoryPolicy, type RecallCandidate, type RecallEvidence, type RecallQuery, type Recalled } from './memory/recall.ts'\nimport { applyRecordsEdit, type EditResult, type RecordsEdit } from './records/edit.ts'\nimport { readRecords, type RecordsScope, type RecordsView } from './records/read.ts'\nimport { SqliteEventRepository } from './sqlite/event-repository.ts'\nimport { SqliteMemoryRepository } from './sqlite/memory-repository.ts'\nimport { SqlitePendingCommitRepository, SqliteSummaryRepository, SqliteThreadRepository } from './sqlite/narrative-repositories.ts'\nimport { SqliteRecallIndex } from './sqlite/recall-index.ts'\nimport { SqliteEngagementRepository, SqliteRoutineRepository } from './sqlite/agenda-repositories.ts'\nimport { SqliteTriggerRepository } from './sqlite/trigger-repository.ts'\nimport { SqliteClockRepository } from './sqlite/clock-repository.ts'\nimport { SqliteVariableRepository } from './sqlite/variable-repository.ts'\nimport { SqliteItemRepository, SqliteSlotRepository } from './sqlite/item-repository.ts'\nimport { SqliteConsolidationRepository, SqliteRelationshipRepository } from './sqlite/relationship-repository.ts'\nimport { SqliteLocationRepository, SqlitePlacementRepository } from './sqlite/location-repository.ts'\nimport { vectorExtension } from './sqlite/vector-extension.ts'\nimport { SqliteCharacterRepository } from './sqlite/character-repository.ts'\nimport { SqliteIntentRepository } from './sqlite/intent-repository.ts'\nimport { SqliteMetadataRepository } from './sqlite/metadata-repository.ts'\nimport { inspect, migrate } from './sqlite/migrate.ts'\nimport { APPLICATION_ID, LATEST_VERSION } from './sqlite/schema.ts'\nimport { SqliteCharacterStateRepository } from './sqlite/state-repository.ts'\nimport { SqliteVisualIdentityRepository } from './sqlite/visual-identity-repository.ts'\nimport { SqliteKnowledgeRepository } from './sqlite/knowledge-repository.ts'\nimport { SqliteFactionIntentRepository, SqliteFactionMembershipRepository, SqliteFactionRelationshipRepository, SqliteFactionRepository, SqliteFactionStateRepository } from './sqlite/faction-repositories.ts'\nimport { SqliteLoreRepository } from './sqlite/lore-repository.ts'\n\nexport interface StoreOptions extends OpenOptions {\n /** Defaults to the driver on Node's built-in SQLite. */\n driver?: SqlDriver\n /** Supplies the time stamped on rows; defaults to the system clock. */\n clock?: Clock\n /** Whether to load the sqlite-vec extension for vector search. On by default; a session works without it when it is missing. */\n vectors?: boolean\n}\n\n/** One session: everything stored about it, reached through repositories. */\nexport interface SessionStore {\n readonly metadata: MetadataRepository\n readonly characters: CharacterRepository\n readonly characterStates: CharacterStateRepository\n readonly factions: FactionRepository\n readonly factionStates: FactionStateRepository\n readonly factionMemberships: FactionMembershipRepository\n readonly factionRelationships: FactionRelationshipRepository\n readonly factionIntents: FactionIntentRepository\n readonly lore: LoreRepository\n readonly intents: IntentRepository\n readonly events: EventRepository\n readonly memories: MemoryRepository\n readonly threads: ThreadRepository\n readonly summaries: SummaryRepository\n readonly pendingCommits: PendingCommitRepository\n readonly locations: LocationRepository\n readonly placements: PlacementRepository\n readonly relationships: RelationshipRepository\n readonly knowledge: KnowledgeRepository\n readonly consolidation: ConsolidationRepository\n readonly slots: SlotRepository\n readonly items: ItemRepository\n readonly visualIdentities: VisualIdentityRepository\n /** The story's own time. */\n readonly clock: ClockRepository\n /** What the story keeps track of: feelings, and whatever the world or the story declares. */\n readonly variables: VariableRepository\n /** The recurring day of each character. */\n readonly routines: RoutineRepository\n /** What characters have committed to, by date. */\n readonly engagements: EngagementRepository\n readonly triggers: TriggerRepository\n /** What the session can be searched by: its texts by words, and by meaning once vectors are stored. */\n readonly recallIndex: RecallIndexRepository\n /** Run `fn` atomically across the repositories; see {@link SqlDatabase.transaction}. */\n transaction<T>(fn: () => T): T\n /**\n * What a character is reminded of at this moment: what it took in and believes, chosen by what\n * the situation calls to mind and, with flaky memory, by how much of it is left.\n */\n recall(query: Omit<RecallQuery, 'characters'>, evidence?: RecallEvidence): Recalled[]\n /** The first stage of {@link SessionStore.recall}: retrieve by the cues, the words and the meaning of the moment, fuse, and over-retrieve. */\n recallPool(query: Omit<RecallQuery, 'characters'>, evidence?: Omit<RecallEvidence, 'rerank'>): RecallPool\n /** The last stage: choose the best of a pool, by a reranker's judgement when there is one, and count what is recalled. */\n finishRecall(pool: RecallPool, turn: number, rerank?: ReadonlyMap<string, number>): Recalled[]\n /**\n * What a character is reminded of, using the session's index as well as the cues: texts that match the\n * moment by words, and, when the vector of the moment is given (from the model that made the stored\n * vectors), texts that match it by meaning.\n * @throws {InvalidValueError} when the vector has other dimensions than the stored ones.\n */\n recallStored(query: Omit<RecallQuery, 'characters'>, options?: { queryVector?: readonly number[] }): Recalled[]\n /** What the session's index says about each candidate for a moment: by words, and by meaning when the vector of the moment is given. */\n storedEvidence(query: Omit<RecallQuery, 'characters'>, queryVector?: readonly number[]): Pick<RecallEvidence, 'lexical' | 'dense'>\n /**\n * Look up what happened (not what any character took in) by words and, with a vector, by meaning, best first.\n * The two searches are merged by reciprocal rank, so what ranks well in either comes first.\n */\n searchEvents(search: { text: string; vector?: readonly number[]; limit?: number; fromTurn?: number; toTurn?: number; minImportance?: number; locationId?: number; itemId?: number }): StoryEvent[]\n /** What a character could be reminded of, to be ranked by meaning before {@link recall}. */\n recallCandidates(query: Omit<RecallQuery, 'characters' | 'policy'>): RecallCandidate[]\n /**\n * Change the story's records (state, events and who took them in, beliefs, threads), together or not at all.\n * @throws {InvalidEditError} naming every problem; nothing was written then.\n */\n /** Whether a character can go there, and the way it would take. */\n planMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove>\n /** Plan over only the places and directed exits this character knows. */\n planKnownMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove>\n /** Move a character: its place changes, at the position or feature given. @throws {InvalidMoveError} naming every reason. */\n move(characterId: CharacterId, move: Move): MovePlan\n /** Apply an edit atomically; with `seal`, the events it adds are final at once (otherwise they stay drafts until sealed). */\n edit(edit: RecordsEdit, options?: { seal?: boolean }): EditResult\n /** Read the records back in the form models read them. */\n records(scope?: RecordsScope): RecordsView\n /** Fire the triggers whose conditions just came true, each together with its effects or not at all. */\n runTriggers(options: TriggerRunOptions): TriggerRun\n /** Let go of the beats and cues nobody took up in this many turns. */\n lapseNotes(turn: number, kept: { beats: number; cues: number }): TriggerNote[]\n /** Which of these notes are still to be told, and in what words as the story stands now; the others are withdrawn, with the reason. Nothing is changed. */\n deliverNotes(notes: readonly TriggerNote[], clock: TriggerClock): Delivery\n /** Write a consistent copy of the whole database to `path`, which must not exist. */\n snapshotTo(path: string): void\n close(): void\n}\n\n/** How many hits of each search are weighed when recalling. */\nconst STORED_CANDIDATES = 50\n/** Reciprocal rank fusion: how much the first places count against the later ones. */\nconst RANK_OFFSET = 60\n\nclass SqliteSessionStore implements SessionStore {\n readonly metadata: SqliteMetadataRepository\n readonly characters: CharacterRepository\n readonly characterStates: CharacterStateRepository\n readonly factions: FactionRepository\n readonly factionStates: FactionStateRepository\n readonly factionMemberships: FactionMembershipRepository\n readonly factionRelationships: FactionRelationshipRepository\n readonly factionIntents: FactionIntentRepository\n readonly lore: LoreRepository\n readonly intents: IntentRepository\n readonly events: EventRepository\n readonly memories: MemoryRepository\n readonly threads: ThreadRepository\n readonly summaries: SummaryRepository\n readonly pendingCommits: PendingCommitRepository\n readonly locations: LocationRepository\n readonly placements: PlacementRepository\n readonly relationships: RelationshipRepository\n readonly knowledge: KnowledgeRepository\n readonly consolidation: ConsolidationRepository\n readonly slots: SlotRepository\n readonly items: ItemRepository\n readonly visualIdentities: VisualIdentityRepository\n readonly clock: ClockRepository\n readonly variables: VariableRepository\n readonly routines: RoutineRepository\n readonly engagements: EngagementRepository\n readonly triggers: TriggerRepository\n readonly recallIndex: SqliteRecallIndex\n private readonly eventRepository: SqliteEventRepository\n\n constructor(private readonly db: SqlDatabase, clock: Clock, vectors: VectorSupport) {\n this.metadata = new SqliteMetadataRepository(db, clock)\n this.recallIndex = new SqliteRecallIndex(db, this.metadata, vectors)\n this.characters = new SqliteCharacterRepository(db, clock)\n this.characterStates = new SqliteCharacterStateRepository(db, clock)\n this.factions = new SqliteFactionRepository(db, clock)\n this.factionStates = new SqliteFactionStateRepository(db, clock)\n this.factionMemberships = new SqliteFactionMembershipRepository(db)\n this.factionRelationships = new SqliteFactionRelationshipRepository(db, clock)\n this.factionIntents = new SqliteFactionIntentRepository(db, clock)\n this.lore = new SqliteLoreRepository(db, () => clock().toISOString())\n this.intents = new SqliteIntentRepository(db, clock)\n this.locations = new SqliteLocationRepository(db, clock, id => { this.eventRepository.reindexPlace(id) })\n this.placements = new SqlitePlacementRepository(db, this.locations)\n this.relationships = new SqliteRelationshipRepository(db, clock)\n this.knowledge = new SqliteKnowledgeRepository(db)\n this.consolidation = new SqliteConsolidationRepository(db)\n this.slots = new SqliteSlotRepository(db)\n this.items = new SqliteItemRepository(db, clock)\n this.visualIdentities = new SqliteVisualIdentityRepository(db, clock, (kind, id) => (\n kind === 'character' ? this.characters.get(id) !== undefined : kind === 'location' ? this.locations.get(id) !== undefined : this.items.get(id) !== undefined\n ))\n this.clock = new SqliteClockRepository(db)\n this.variables = new SqliteVariableRepository(db)\n this.routines = new SqliteRoutineRepository(db)\n this.engagements = new SqliteEngagementRepository(db)\n this.triggers = new SqliteTriggerRepository(db)\n this.eventRepository = new SqliteEventRepository(db, clock, this.recallIndex, id => this.locations.get(id)?.name, id => this.items.get(id)?.name)\n this.events = this.eventRepository\n this.memories = new SqliteMemoryRepository(db, clock, this.recallIndex)\n this.threads = new SqliteThreadRepository(db, clock)\n this.summaries = new SqliteSummaryRepository(db, clock)\n this.pendingCommits = new SqlitePendingCommitRepository(db, clock)\n }\n\n transaction<T>(fn: () => T): T {\n return this.db.transaction(fn)\n }\n\n recallCandidates(query: Omit<RecallQuery, 'characters' | 'policy'>): RecallCandidate[] {\n return recallCandidates(this, { ...query, characters: this.characters.list() })\n }\n\n recall(query: Omit<RecallQuery, 'characters'>, evidence?: RecallEvidence): Recalled[] {\n return this.finishRecall(this.recallPool(query, evidence), query.turn, evidence?.rerank)\n }\n\n recallPool(query: Omit<RecallQuery, 'characters'>, evidence?: Omit<RecallEvidence, 'rerank'>): RecallPool {\n return recallPool(this, { ...query, characters: this.characters.list() }, evidence)\n }\n\n finishRecall(pool: RecallPool, turn: number, rerank?: ReadonlyMap<string, number>): Recalled[] {\n const found = finishRecall(pool, rerank)\n this.events.touchPerceptions(found.flatMap(entry => (entry.source.kind === 'perception' ? [entry.source.id] : [])), turn)\n this.memories.touch(found.flatMap(entry => (entry.source.kind === 'memory' ? [entry.source.id] : [])), turn)\n return found\n }\n\n storedEvidence(query: Omit<RecallQuery, 'characters'>, queryVector?: readonly number[]): Pick<RecallEvidence, 'lexical' | 'dense'> {\n const found = (hits: { key: string; score: number }[], map: (score: number) => number = score => score): ReadonlyMap<string, number> =>\n new Map(hits.map(hit => [hit.key, map(hit.score)]))\n const lexical = found(this.recallIndex.lexical({ text: query.situation, characterId: query.characterId, kinds: ['perception', 'memory'], limit: STORED_CANDIDATES }))\n const dense = queryVector === undefined ? undefined : found(this.recallIndex.vector({ vector: queryVector, characterId: query.characterId, limit: STORED_CANDIDATES }), denseScore)\n return { lexical, ...(dense === undefined ? {} : { dense }) }\n }\n\n recallStored(query: Omit<RecallQuery, 'characters'>, options: { queryVector?: readonly number[] } = {}): Recalled[] {\n return this.recall(query, this.storedEvidence(query, options.queryVector))\n }\n\n searchEvents({ text, vector, limit = 10, fromTurn, toTurn, minImportance, locationId, itemId }: { text: string; vector?: readonly number[]; limit?: number; fromTurn?: number; toTurn?: number; minImportance?: number; locationId?: number; itemId?: number }): StoryEvent[] {\n const lexical = this.recallIndex.lexical({ text, kinds: ['event'], limit: STORED_CANDIDATES })\n const dense = vector === undefined ? [] : this.recallIndex.vector({ vector, characterId: 0, limit: STORED_CANDIDATES })\n const scores = new Map<number, number>()\n for (const hits of [lexical, dense]) hits.forEach((hit, rank) => { scores.set(hit.refId, (scores.get(hit.refId) ?? 0) + 1 / (RANK_OFFSET + rank)) })\n return [...scores].sort((a, b) => b[1] - a[1]).flatMap(([id]) => {\n const event = this.events.get(id)\n if (event === undefined) return []\n if ((fromTurn !== undefined && event.turn < fromTurn) || (toTurn !== undefined && event.turn > toTurn) || (minImportance !== undefined && event.importance < minImportance) || (locationId !== undefined && event.locationId !== locationId) || (itemId !== undefined && !event.items.includes(itemId))) return []\n return [event]\n }).slice(0, limit)\n }\n\n planMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove> {\n return planMove(this, characterId, move)\n }\n\n planKnownMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove> {\n return planKnownMove(this, characterId, move)\n }\n\n move(characterId: CharacterId, move: Move): MovePlan {\n return this.transaction(() => moveCharacter(this, characterId, move))\n }\n\n edit(edit: RecordsEdit, options: { seal?: boolean } = {}): EditResult {\n return this.transaction(() => {\n const result = applyRecordsEdit(this, edit)\n if (options.seal === true) this.events.seal(result.eventIds)\n return result\n })\n }\n\n records(scope?: RecordsScope): RecordsView {\n return readRecords(this, scope)\n }\n\n runTriggers(options: TriggerRunOptions): TriggerRun {\n return runTriggers(this, options)\n }\n\n deliverNotes(notes: readonly TriggerNote[], clock: TriggerClock): Delivery {\n return deliverNotes(this, notes, clock)\n }\n\n lapseNotes(turn: number, kept: { beats: number; cues: number }): TriggerNote[] {\n return this.transaction(() => lapseNotes(this, turn, kept))\n }\n\n /** Write a consistent copy of the whole database to `path`, which must not exist (`VACUUM INTO`). */\n snapshotTo(path: string): void {\n this.db.run('VACUUM INTO ?', [path])\n }\n\n close(): void {\n this.db.close()\n }\n}\n\n/** Open the database, with the vector extension when there is one; without it the session still works, minus vector search. */\nfunction connect(location: string, options: StoreOptions): { db: SqlDatabase; vectors: VectorSupport } {\n const { driver = nodeSqliteDriver, clock: _clock, vectors: wanted = true, ...open } = options\n if (!wanted) return { db: driver.open(location, open), vectors: { available: false, error: 'switched off' } }\n const extension = vectorExtension()\n if ('error' in extension) return { db: driver.open(location, open), vectors: { available: false, error: extension.error } }\n try {\n return { db: driver.open(location, { ...open, extensions: [extension.path] }), vectors: { available: true } }\n } catch (error) {\n return { db: driver.open(location, open), vectors: { available: false, error: error instanceof Error ? error.message : String(error) } }\n }\n}\n\n/**\n * Create the database of a new session at `location` (the file must not hold a\n * session yet, and its folder must exist).\n * @throws {ConflictError} when the location already holds a session database.\n */\nexport function createSessionStore(location: string, session: NewSession, options: StoreOptions = {}): SessionStore {\n const { db, vectors } = connect(location, options)\n try {\n if (inspect(db).version > 0) throw new ConflictError(`${location} already holds a session database`)\n migrate(db)\n const store = new SqliteSessionStore(db, options.clock ?? systemClock, vectors)\n store.metadata.create(session)\n store.slots.ensureDefaults()\n store.variables.ensureDefaults()\n return store\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n/**\n * Open the database of an existing session, bringing an older schema up to date.\n * @throws {NotFoundError} when there is no file at `location`.\n * @throws {SchemaError} when the file is not a session database, or is from a newer version.\n */\nexport function openSessionStore(location: string, options: StoreOptions = {}): SessionStore {\n if (location !== ':memory:' && !existsSync(location)) throw new NotFoundError(`no session database at ${location}`)\n const { db, vectors } = connect(location, options)\n try {\n const state = inspect(db)\n if (state.version === 0 || state.applicationId !== APPLICATION_ID) throw new SchemaError(`${location} is not a session database`)\n if (state.version < LATEST_VERSION && location !== ':memory:') backUpBeforeMigrating(db, location, state.version)\n migrate(db)\n return new SqliteSessionStore(db, options.clock ?? systemClock, vectors)\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n/** Folder, beside the database, holding the copies made before a schema upgrade. */\nexport const MIGRATION_BACKUP_FOLDER = 'migration-backups'\n\n/** Where the copy of a database as it was at schema `version` is kept. */\nexport function migrationBackupPath(location: string, version: number): string {\n return join(dirname(location), MIGRATION_BACKUP_FOLDER, `schema-${version}.sqlite`)\n}\n\n/**\n * A released session cannot be rebuilt, so an upgrade starts from a copy that passed the integrity check; one copy per old version is kept.\n * @throws {CorruptDataError} when the database is damaged, before anything is changed.\n */\nfunction backUpBeforeMigrating(db: SqlDatabase, location: string, version: number): void {\n const check = db.get<{ quick_check: string }>('PRAGMA quick_check')?.quick_check\n if (check !== 'ok') throw new CorruptDataError(`${location} failed its integrity check, so it was not upgraded: ${check ?? 'no result'}`)\n const target = migrationBackupPath(location, version)\n if (existsSync(target)) return\n mkdirSync(dirname(target), { recursive: true })\n db.run('VACUUM INTO ?', [target])\n}\n\nexport { LATEST_VERSION as SCHEMA_VERSION }\nexport type { MemoryPolicy }\n","import { randomUUID } from 'node:crypto'\nimport { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { NewSession, SessionMetadata } from 'dsh-roleplay-model'\nimport { ConflictError, NotFoundError } from './errors.ts'\nimport { createSessionStore, openSessionStore, type SessionStore, type StoreOptions } from './store.ts'\n\nexport const SESSION_DATABASE_FILE = 'session.sqlite'\n\nconst SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/\n\n/** A new session; its id is generated unless one is given. */\nexport type SessionInit = Omit<NewSession, 'id'> & { id?: string }\n\nexport function isSessionId(value: string): boolean {\n return SESSION_ID.test(value)\n}\n\n/** The id becomes a folder name, so only a UUID v4 is accepted. */\nfunction checked(id: string): string {\n if (!isSessionId(id)) throw new RangeError(`\"${id}\" is not a session id`)\n return id\n}\n\n/** Folder holding everything about one session. */\nexport function sessionFolder(sessionsDir: string, id: string): string {\n return join(sessionsDir, checked(id))\n}\n\nexport function sessionDatabase(sessionsDir: string, id: string): string {\n return join(sessionFolder(sessionsDir, id), SESSION_DATABASE_FILE)\n}\n\n/**\n * Create `<sessionsDir>/<id>/session.sqlite` for a new session. Nothing is\n * left behind when creating the database fails.\n * @throws {ConflictError} when a session with that id already exists.\n */\nexport function createSession(sessionsDir: string, init: SessionInit, options: StoreOptions = {}): SessionStore {\n const id = checked(init.id ?? randomUUID())\n const folder = sessionFolder(sessionsDir, id)\n mkdirSync(sessionsDir, { recursive: true })\n try {\n mkdirSync(folder)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new ConflictError(`session ${id} already exists`, { cause: error })\n throw error\n }\n try {\n return createSessionStore(sessionDatabase(sessionsDir, id), { ...init, id }, options)\n } catch (error) {\n rmSync(folder, { recursive: true, force: true })\n throw error\n }\n}\n\n/** @throws {NotFoundError} when the session does not exist. */\nexport function openSession(sessionsDir: string, id: string, options: StoreOptions = {}): SessionStore {\n return openSessionStore(sessionDatabase(sessionsDir, id), options)\n}\n\n/** Remove a session's folder and everything in it. */\nexport function deleteSession(sessionsDir: string, id: string): void {\n rmSync(sessionFolder(sessionsDir, id), { recursive: true, force: true })\n}\n\n/** The sessions found under a sessions folder, and those that could not be read. */\nexport interface SessionListing {\n sessions: SessionMetadata[]\n problems: { id: string; message: string }[]\n}\n\n/**\n * Read the metadata of every session under `sessionsDir`. Folders that are not\n * named like a session are ignored; a session that cannot be read is reported\n * and left out. Order is not defined.\n * @param reuse - supplies a connection that is already open, so it is not opened twice.\n */\nexport function listSessions(\n sessionsDir: string,\n options: StoreOptions = {},\n reuse?: (id: string) => SessionStore | undefined,\n): SessionListing {\n const listing: SessionListing = { sessions: [], problems: [] }\n let ids: string[]\n try {\n ids = readdirSync(sessionsDir, { withFileTypes: true }).filter(entry => entry.isDirectory() && isSessionId(entry.name)).map(entry => entry.name)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return listing\n throw error\n }\n for (const id of ids) {\n const open = reuse?.(id)\n try {\n const store = open ?? openSession(sessionsDir, id, options)\n try {\n listing.sessions.push(store.metadata.get())\n } finally {\n if (open === undefined) store.close()\n }\n } catch (error) {\n listing.problems.push({ id, message: error instanceof Error ? error.message : String(error) })\n }\n }\n return listing\n}\n\n/** What a copy of a session is made from: a snapshot of it, or its database as it is. */\nexport type ForkSource = { snapshot: string } | { live: Pick<SessionStore, 'snapshotTo'> }\n\nexport interface ForkOptions {\n name: string\n /** The snapshots the copy keeps, besides its database; each must exist. */\n keep: readonly string[]\n}\n\n/**\n * Make a new session from a state of another: a folder of its own with the database, the settings and the named snapshots, and\n * the identity of the new session in place of the old. Nothing is left behind when it fails.\n * @throws {ConflictError} when the new id exists. @throws {NotFoundError} when the snapshot or a kept snapshot does not exist.\n */\nexport function forkSession(sessionsDir: string, fromId: string, toId: string, source: ForkSource, options: ForkOptions, storeOptions: StoreOptions = {}): void {\n const target = sessionFolder(sessionsDir, toId)\n const from = sessionFolder(sessionsDir, fromId)\n const used = 'snapshot' in source ? [source.snapshot] : []\n for (const name of [...options.keep, ...used]) {\n if (!existsSync(snapshotPath(sessionsDir, fromId, name))) throw new NotFoundError(`session ${fromId} has no snapshot \"${name}\"`)\n }\n try {\n mkdirSync(target)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new ConflictError(`session ${toId} already exists`, { cause: error })\n throw error\n }\n try {\n const file = sessionDatabase(sessionsDir, toId)\n if ('snapshot' in source) copyFileSync(snapshotPath(sessionsDir, fromId, source.snapshot), file)\n else source.live.snapshotTo(file)\n if (existsSync(join(from, 'settings.json'))) copyFileSync(join(from, 'settings.json'), join(target, 'settings.json'))\n if (options.keep.length > 0) mkdirSync(join(target, SNAPSHOT_FOLDER))\n for (const name of options.keep) copyFileSync(snapshotPath(sessionsDir, fromId, name), snapshotPath(sessionsDir, toId, name))\n const store = openSessionStore(file, storeOptions)\n try { store.metadata.rebrand(toId, options.name) } finally { store.close() }\n } catch (error) {\n rmSync(target, { recursive: true, force: true })\n throw error\n }\n}\n\nconst SNAPSHOT_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst SNAPSHOT_FOLDER = 'snapshots'\n\n/** The place of a named snapshot of a session's database. @throws {RangeError} for a name that is not lowercase letters, digits and hyphens. */\nexport function snapshotPath(sessionsDir: string, id: string, name: string): string {\n if (!SNAPSHOT_NAME.test(name)) throw new RangeError(`\"${name}\" is not a snapshot name`)\n return join(sessionFolder(sessionsDir, id), SNAPSHOT_FOLDER, `${name}.sqlite`)\n}\n\n/** Take a snapshot of an open session under a name, replacing one of that name; it is written aside and renamed, so a snapshot is never half written. */\nexport function takeSnapshot(sessionsDir: string, id: string, name: string, store: Pick<SessionStore, 'snapshotTo'>): string {\n const target = snapshotPath(sessionsDir, id, name)\n mkdirSync(join(sessionFolder(sessionsDir, id), SNAPSHOT_FOLDER), { recursive: true })\n const aside = `${target}.writing`\n rmSync(aside, { force: true })\n store.snapshotTo(aside)\n renameSync(aside, target)\n return target\n}\n\n/** The names of a session's snapshots. */\nexport function snapshotNames(sessionsDir: string, id: string): string[] {\n try {\n return readdirSync(join(sessionFolder(sessionsDir, id), SNAPSHOT_FOLDER)).filter(file => file.endsWith('.sqlite')).map(file => file.slice(0, -'.sqlite'.length)).sort()\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n}\n\nexport function removeSnapshot(sessionsDir: string, id: string, name: string): void {\n rmSync(snapshotPath(sessionsDir, id, name), { force: true })\n}\n\n/**\n * Put a snapshot in the place of the session's database. The session must not be open (the service\n * closes it first); the copy is made aside and renamed over the database.\n * @throws {NotFoundError} when there is no such snapshot.\n */\nexport function restoreSnapshot(sessionsDir: string, id: string, name: string, storeOptions: StoreOptions = {}): void {\n const source = snapshotPath(sessionsDir, id, name)\n if (!existsSync(source)) throw new NotFoundError(`session ${id} has no snapshot \"${name}\"`)\n const database = sessionDatabase(sessionsDir, id)\n const aside = `${database}.restoring`\n copyFileSync(source, aside)\n for (const sidecar of ['-wal', '-shm', '-journal']) rmSync(`${database}${sidecar}`, { force: true })\n const previous = identityOf(database, storeOptions)\n renameSync(aside, database)\n if (previous !== undefined) {\n const store = openSessionStore(database, storeOptions)\n try { store.metadata.rebrand(previous.id, previous.name, previous.createdAt) } finally { store.close() }\n }\n}\n\n/** The identity the database has now, which a snapshot taken under another id (a fork's parent) must not take away. */\nfunction identityOf(database: string, storeOptions: StoreOptions): { id: string; name: string; createdAt: string } | undefined {\n if (!existsSync(database)) return undefined\n const store = openSessionStore(database, storeOptions)\n try {\n const { id, name, createdAt } = store.metadata.get()\n return { id, name, createdAt }\n } finally { store.close() }\n}\n","import type { Exit, Location } from 'dsh-roleplay-model'\nimport { lookupKey } from '../sqlite/support.ts'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\n\nexport type LintSeverity = 'error' | 'warning' | 'info'\n\nexport interface LintFinding {\n /** An error leaves the world inconsistent (nobody can get to a place, two characters share a name); a warning is something that should be fitted in; an info is only worth knowing. */\n severity: LintSeverity\n code: string\n subject: { kind: 'character' | 'location' | 'exit' | 'relationship' | 'item'; key: string }\n message: string\n}\n\nexport type LintTarget = Pick<RecordsTarget, 'characters' | 'locations' | 'placements' | 'relationships' | 'consolidation' | 'items'>\n\n/**\n * What is inconsistent or unfinished in the world's graph of places and characters. Things made up in\n * play and not fitted in yet are held to a stricter standard than what the world was written with: a\n * place that no one can reach or leave is an error for them, and a warning for the rest.\n */\nexport function lintWorld(target: LintTarget): LintFinding[] {\n const findings: LintFinding[] = []\n const pending = target.consolidation.pending()\n const newCharacters = new Set(pending.filter(item => item.kind === 'character').map(item => item.subjectId))\n const newPlaces = new Set(pending.filter(item => item.kind === 'location').map(item => item.subjectId))\n const places = target.locations.list()\n const exits = target.locations.allExits()\n const characters = target.characters.list()\n const relationships = target.relationships.list()\n const containers = new Set(places.flatMap(place => (place.parentId === undefined ? [] : [place.parentId])))\n const keyOfPlace = (place: Pick<Location, 'id' | 'sourceId'>): string => locationKey(place)\n const placeById = new Map(places.map(place => [place.id, place]))\n const strict = (isNew: boolean): LintSeverity => (isNew ? 'error' : 'warning')\n\n // Places.\n const outgoing = new Map<number, Exit[]>()\n const touched = new Set<number>()\n for (const exit of exits) {\n outgoing.set(exit.fromId, [...(outgoing.get(exit.fromId) ?? []), exit])\n touched.add(exit.fromId)\n touched.add(exit.toId)\n }\n const walkable = places.filter(place => !containers.has(place.id))\n if (walkable.length > 1) {\n for (const place of walkable) {\n if (!touched.has(place.id)) findings.push({ severity: strict(newPlaces.has(place.id)), code: 'location-no-exit', subject: { kind: 'location', key: keyOfPlace(place) }, message: `${place.name} has no way in or out, so no one can go there or leave it` })\n }\n const player = characters.find(character => character.control === 'player')\n const start = (player === undefined ? undefined : target.placements.get('character', player.id)?.locationId) ?? walkable[0]!.id\n const reached = new Set<number>([start])\n for (const queue = [start]; queue.length > 0;) {\n const at = queue.shift()!\n for (const exit of outgoing.get(at) ?? []) if (!reached.has(exit.toId)) { reached.add(exit.toId); queue.push(exit.toId) }\n }\n for (const place of walkable) {\n if (reached.has(place.id) || !touched.has(place.id)) continue\n findings.push({ severity: 'warning', code: 'location-unreachable', subject: { kind: 'location', key: keyOfPlace(place) }, message: `${place.name} cannot be reached from ${placeById.get(start)?.name ?? 'where the story is'} by any chain of exits` })\n }\n }\n for (const exit of exits) {\n if (exits.some(other => other.fromId === exit.toId && other.toId === exit.fromId)) continue\n const from = placeById.get(exit.fromId)\n const to = placeById.get(exit.toId)\n if (from === undefined || to === undefined) continue\n findings.push({ severity: 'info', code: 'exit-no-way-back', subject: { kind: 'exit', key: `${keyOfPlace(from)}->${keyOfPlace(to)}` }, message: `there is a way from ${from.name} to ${to.name} but none back` })\n }\n const sameName = new Map<string, Location[]>()\n for (const place of places) sameName.set(`${place.parentId ?? 0}:${lookupKey(place.name)}`, [...(sameName.get(`${place.parentId ?? 0}:${lookupKey(place.name)}`) ?? []), place])\n for (const group of sameName.values()) {\n if (group.length > 1) findings.push({ severity: 'error', code: 'duplicate-name', subject: { kind: 'location', key: keyOfPlace(group[1]!) }, message: `${group.length} places in the same place are called ${group[0]!.name}: ${group.map(keyOfPlace).join(', ')}` })\n }\n\n // Characters.\n const byName = new Map<string, typeof characters>()\n for (const character of characters) byName.set(lookupKey(character.name), [...(byName.get(lookupKey(character.name)) ?? []), character])\n for (const group of byName.values()) {\n if (group.length > 1) findings.push({ severity: 'error', code: 'duplicate-name', subject: { kind: 'character', key: characterKey(group[1]!) }, message: `${group.length} characters are called ${group[0]!.name}: ${group.map(characterKey).join(', ')}` })\n }\n for (const character of characters) {\n const key = characterKey(character)\n if (places.length > 0 && target.placements.get('character', character.id) === undefined) {\n findings.push({ severity: strict(newCharacters.has(character.id)), code: 'character-unplaced', subject: { kind: 'character', key }, message: `${character.name} is not in any place` })\n }\n if (newCharacters.has(character.id) && characters.length > 1 && !relationships.some(relation => relation.fromId === character.id || relation.toId === character.id)) {\n findings.push({ severity: 'warning', code: 'character-no-relationships', subject: { kind: 'character', key }, message: `${character.name} was made up and has no relationship with anyone yet` })\n }\n }\n for (const relation of relationships) {\n if (relationships.some(other => other.fromId === relation.toId && other.toId === relation.fromId)) continue\n const from = characters.find(character => character.id === relation.fromId)\n const to = characters.find(character => character.id === relation.toId)\n if (from === undefined || to === undefined) continue\n findings.push({ severity: 'info', code: 'relationship-one-sided', subject: { kind: 'relationship', key: `${characterKey(from)}->${characterKey(to)}` }, message: `${from.name} has a profile of ${to.name} (${relation.label}) but ${to.name} has none of ${from.name}` })\n }\n // Items.\n const newItems = new Set(pending.filter(item => item.kind === 'item').map(item => item.subjectId))\n const things = target.items.list()\n const sameHolder = new Map<string, typeof things>()\n for (const item of things) {\n const holding = target.items.holding(item.id)\n const where = holding === undefined ? 'nowhere' : `${holding.holder.kind}:${'locationId' in holding.holder ? holding.holder.locationId : 'characterId' in holding.holder ? holding.holder.characterId : holding.holder.itemId}`\n const group = `${where}:${lookupKey(item.name)}`\n sameHolder.set(group, [...(sameHolder.get(group) ?? []), item])\n if (item.container?.state === 'locked' && target.items.openers({ kind: 'item', id: item.id }).length === 0) {\n findings.push({ severity: newItems.has(item.id) ? 'warning' : 'info', code: 'lock-without-key', subject: { kind: 'item', key: itemKey(item) }, message: `${item.name} is locked and no item is known to open it` })\n }\n }\n for (const group of sameHolder.values()) {\n const twins = group.filter(item => !item.unique)\n if (twins.length > 1) findings.push({ severity: 'warning', code: 'item-duplicate', subject: { kind: 'item', key: itemKey(twins[1]!) }, message: `${twins.length} separate items called ${twins[0]!.name} are in the same place: ${twins.map(itemKey).join(', ')}; they could be one with a quantity` })\n }\n for (const exit of exits) {\n if (exit.state !== 'locked' || target.items.openers({ kind: 'exit', id: exit.id }).length > 0 || exit.note !== '') continue\n const from = placeById.get(exit.fromId)\n const to = placeById.get(exit.toId)\n if (from !== undefined && to !== undefined) findings.push({ severity: 'info', code: 'lock-without-key', subject: { kind: 'exit', key: `${keyOfPlace(from)}->${keyOfPlace(to)}` }, message: `the way from ${from.name} to ${to.name} is locked and nothing says what opens it` })\n }\n const order = { error: 0, warning: 1, info: 2 } as const\n return findings.sort((a, b) => order[a.severity] - order[b.severity])\n}\n","import type { CharacterId, CharacterIntent, Engagement, StoredRoutineWindow } from 'dsh-roleplay-model'\nimport type { EngagementRepository, IntentRepository, RoutineRepository } from '../repositories.ts'\nimport { DAY, HOUR, MINUTE, addLocalDays, parseInstant, zonedInstant } from './time.ts'\n\n/** One occurrence of a routine window: the stretch of time it holds on a particular day. */\nexport interface Occurrence {\n window: StoredRoutineWindow\n startsAt: number\n endsAt: number\n}\n\n/** An engagement still pending this long after it was due (or over) is overdue. */\nexport const ENGAGEMENT_GRACE = 30 * MINUTE\n\nfunction occurrenceOn(window: StoredRoutineWindow, day: { year: number; month: number; day: number; weekday: number }, zone: string): Occurrence | undefined {\n if (window.days.length > 0 && !window.days.includes(day.weekday)) return undefined\n const startsAt = zonedInstant({ ...day, hour: Math.floor(window.start / 60), minute: window.start % 60 }, zone)\n const wraps = window.end < window.start\n const endDay = wraps ? addLocalDays(startsAt, zone, 1) : day\n const endsAt = zonedInstant({ ...endDay, hour: Math.floor(window.end / 60), minute: window.end % 60 }, zone)\n return { window, startsAt, endsAt }\n}\n\n/** The window that holds at an instant (the first of the list that does), with the stretch of this occurrence of it. */\nexport function occurrenceAt(windows: readonly StoredRoutineWindow[], now: number, zone: string): Occurrence | undefined {\n const days = [addLocalDays(now, zone, 0), addLocalDays(now, zone, -1)]\n for (const window of windows) {\n for (const day of days) {\n const occurrence = occurrenceOn(window, day, zone)\n if (occurrence !== undefined && occurrence.startsAt <= now && now < occurrence.endsAt) return occurrence\n }\n }\n return undefined\n}\n\n/** The window that starts next after an instant, within `horizon`. */\nexport function nextOccurrence(windows: readonly StoredRoutineWindow[], now: number, zone: string, horizon: number): Occurrence | undefined {\n let best: Occurrence | undefined\n for (const offset of [0, 1, 2]) {\n const day = addLocalDays(now, zone, offset)\n for (const window of windows) {\n const occurrence = occurrenceOn(window, day, zone)\n if (occurrence === undefined || occurrence.startsAt <= now || occurrence.startsAt > now + horizon) continue\n if (best === undefined || occurrence.startsAt < best.startsAt) best = occurrence\n }\n }\n return best\n}\n\nexport interface RankedGoal {\n intent: CharacterIntent\n /** The deadline as an instant, when it has one that can be read. */\n deadlineAt?: number\n overdue: boolean\n score: number\n}\n\n/** What a character is after, most pressing first: priority and urgency, and how close or past the deadline is. Goals not active are left out. */\nexport function rankGoals(goals: readonly CharacterIntent[], now: number, zone: string, limit: number): RankedGoal[] {\n return goals.filter(goal => goal.status === 'active').map((intent): RankedGoal => {\n let deadlineAt: number | undefined\n if (intent.deadline !== undefined) {\n try { deadlineAt = parseInstant(intent.deadline, zone) } catch { /* a deadline that is not a date does not count */ }\n }\n const left = deadlineAt === undefined ? undefined : deadlineAt - now\n const bonus = left === undefined ? 0 : left < 0 ? 0.4 : left < 6 * HOUR ? 0.3 : left < DAY ? 0.2 : left < 7 * DAY ? 0.1 : 0\n return { intent, ...(deadlineAt === undefined ? {} : { deadlineAt }), overdue: left !== undefined && left < 0, score: 0.5 * intent.priority + 0.3 * intent.urgency + bonus }\n }).sort((a, b) => b.score - a.score || a.intent.id - b.intent.id).slice(0, limit)\n}\n\nexport interface AgendaEngagement {\n engagement: Engagement\n overdue: boolean\n}\n\nexport interface Agenda {\n /** What the routine has the character doing now. */\n now?: Occurrence\n /** What the routine has it doing next, within the horizon. */\n next?: Occurrence\n /** What it has committed to that is due within the horizon or is overdue, in the order they are due. */\n engagements: AgendaEngagement[]\n goals: RankedGoal[]\n}\n\nexport interface AgendaOptions {\n /** How far ahead to look, in milliseconds. */\n horizon?: number\n goals?: number\n engagements?: number\n}\n\nconst DEFAULTS = { horizon: 24 * HOUR, goals: 3, engagements: 4 } as const\n\n/** What a character is expected to be doing and to have done at an instant: its routine, its commitments and its goals. */\nexport function agendaAt(\n source: { routines: Pick<RoutineRepository, 'list'>; engagements: Pick<EngagementRepository, 'list'>; intents: Pick<IntentRepository, 'list'> },\n characterId: CharacterId,\n now: number,\n zone: string,\n options: AgendaOptions = {},\n): Agenda {\n const horizon = options.horizon ?? DEFAULTS.horizon\n const windows = source.routines.list(characterId)\n const current = occurrenceAt(windows, now, zone)\n const next = nextOccurrence(windows, now, zone, horizon)\n const engagements = source.engagements.list({ status: 'pending', participant: characterId, to: now + horizon })\n .map((engagement): AgendaEngagement => ({ engagement, overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE) }))\n .slice(0, options.engagements ?? DEFAULTS.engagements)\n return {\n ...(current === undefined ? {} : { now: current }),\n ...(next === undefined ? {} : { next }),\n engagements,\n goals: rankGoals(source.intents.list(characterId), now, zone, options.goals ?? DEFAULTS.goals),\n }\n}\n","import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'\nimport { IMPORTANCE_MAX, IMPORTANCE_MIN, MEMORY_KINDS, PERCEPTION_MODES, ACCURACIES } from 'dsh-roleplay-model'\nimport { NotFoundError } from '../errors.ts'\nimport type { MemoryPolicy } from '../memory/recall.ts'\nimport { characterKey, locationKey, parseRecordsEdit, recordsEditSchema } from '../records/edit.ts'\nimport { lintWorld } from '../records/lint.ts'\nimport { describeHolder } from '../records/read.ts'\nimport { agendaAt } from '../records/agenda.ts'\nimport { describeValue, shownVariables } from '../records/variables.ts'\nimport { describeInstant, localIso, minuteText } from '../records/time.ts'\nimport { itemKey } from '../records/items.ts'\nimport type { Session } from '../plugin.ts'\n\n/** The roleplay session an agent works in, as the plugin that runs the agent knows it. */\nexport interface AgentLink {\n session: Pick<Session, 'characters' | 'factions' | 'factionStates' | 'factionMemberships' | 'factionRelationships' | 'factionIntents' | 'lore' | 'events' | 'memories' | 'threads' | 'records' | 'recallRanked' | 'searchEvents' | 'edit' | 'locations' | 'placements' | 'relationships' | 'knowledge' | 'consolidation' | 'planMove' | 'items' | 'slots' | 'variables' | 'intents' | 'routines' | 'engagements' | 'clock'>\n /** The time zone the story's times are written and read in; UTC when not given. */\n timeZone?: string\n /** The turn the agent is playing, which is what the age of a memory is counted from. */\n turn: number\n policy: MemoryPolicy\n /**\n * The vector of a text of the moment, from the model that made the session's stored vectors, so that\n * a search also finds what means the same in other words. `undefined` (or a promise of it) when\n * there is none, and the search then goes by words alone.\n */\n queryVector?: (text: string, signal?: AbortSignal) => Promise<readonly number[] | undefined>\n}\n\n/** The vector of a text for a search, or nothing when the agent has no way to make one. */\nexport async function vectorOf(agent: AgentLink, text: string, signal?: AbortSignal): Promise<{ queryVector: readonly number[] } | Record<string, never>> {\n const vector = await agent.queryVector?.(text, signal)\n return vector === undefined ? {} : { queryVector: vector }\n}\n\n/** Finds the session behind an agent, by the id of the agent's own session; `undefined` when it works in none. */\nexport type AgentResolver = (agentSessionId: string) => AgentLink | undefined\n\n/** The parts of the records `read_records` can be limited to. */\nconst READ_SECTIONS = ['characters', 'factions', 'faction_relationships', 'events', 'beliefs', 'open_threads', 'items', 'relationships', 'knowledge', 'variable_defs', 'variables', 'engagements']\n\nconst MAX_EVENTS = 20\nconst MAX_LISTED_PLACES = 100\nconst MAX_LISTED_ITEMS = 60\n\nconst link = (resolve: AgentResolver, agent: { session: { id: string } } | undefined): AgentLink => {\n const found = agent === undefined ? undefined : resolve(agent.session.id)\n if (found === undefined) throw new NotFoundError('this agent is not working in a roleplay session, so there are no records to use')\n return found\n}\n\nconst pretty = (_args: unknown, value: unknown) => [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }]\nconst summary = (text: string) => (_args: unknown, value: { writes: number }) => [{ type: 'text' as const, text: `${text} (${value.writes} change${value.writes === 1 ? '' : 's'})` }]\nconst strings = { type: 'array', items: { type: 'string' } } as const\nconst integers = { type: 'array', items: { type: 'integer' } } as const\n/** The members of an output object are all present. */\nconst str = { type: 'string', required: true } as const\nconst int = { type: 'integer', required: true } as const\nconst strs = { ...strings, required: true } as const\nconst ints = { ...integers, required: true } as const\n\n/**\n * The model-facing tools over a roleplay session. Reading tools show what the story has\n * recorded; writing tools change it and are registered only when the plugin is configured\n * for them. Both resolve the session from the agent that calls them.\n */\nexport function createTools(resolve: AgentResolver, options: {\n write: boolean\n /** Limits the characters a call may name to these keys, for an agent that works on one story. */\n characters?: readonly string[]\n /** Tools of the agent that makes up characters and places and fits them into the world: it makes them with `edit_world` instead of `edit_records`, and reads what is inconsistent. Never for a global registration. */\n authoring?: boolean\n}): ToolDefinition[] {\n const reads = [\n defineTool({\n name: 'search_lore',\n description: 'Search the canonical background lore of the story. Use this when history, culture, geography, institutions, customs or legends matter to the scene. This is game-master knowledge; character agents receive only lore they explicitly know.',\n parameters: { about: { type: 'string', required: true }, limit: { type: 'integer', description: 'Maximum entries, from 1 to 20.' } },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, title: str, kind: str, summary: str, body: str, sources: strs } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent); const needle = args.about.trim().toLowerCase(); const limit = Math.max(1, Math.min(20, args.limit ?? 8))\n return session.lore.list().filter(entry => `${entry.title} ${entry.summary} ${entry.body} ${entry.sources.join(' ')}`.toLowerCase().includes(needle)).slice(0, limit).map(entry => ({ key: entry.sourceId ?? String(entry.id), title: entry.title, kind: entry.kind, summary: entry.summary, body: entry.body, sources: entry.sources }))\n },\n }),\n defineTool({\n name: 'list_characters',\n description: 'List the characters of the story with the key each is named by, who controls it and a short summary.',\n parameters: {},\n output: {\n schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, name: str, role: str, controlled_by: str, summary: str } } },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n const { session } = link(resolve, exec.agent)\n return session.characters.list().map(character => ({ key: characterKey(character), name: character.name, role: character.role, controlled_by: character.control === 'player' ? 'the player' : 'an agent', summary: character.summary }))\n },\n }),\n defineTool({\n name: 'get_character',\n description: 'Read one character: who it is and its current state (what can be seen of it, what it thinks and feels, what it is doing, and what is tracked of it: its feelings and whatever else the story keeps track of).',\n parameters: { character: { type: 'string', required: true, description: 'The key of the character, as list_characters gives it.' } },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n character: str, name: str, aliases: strs, summary: str, personality: str,\n public_state: str, inner_state: str, activity: str, variables: { type: 'json', required: true },\n location: { type: 'json', required: true }, position: str,\n relationships: { type: 'json', required: true },\n carrying: { type: 'json', required: true },\n },\n },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const view = session.records().characters.find(entry => entry.character === args.character)\n const found = session.characters.list().find(character => characterKey(character) === args.character)\n if (view === undefined || found === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n return { character: view.character, name: view.name, aliases: found.aliases, summary: found.summary, personality: found.personality, public_state: view.public_state, inner_state: view.inner_state, activity: view.activity, variables: shownVariables(session, 'character', found.id, characterKey(found), 'story').map(entry => ({ variable: entry.variable.key, name: entry.variable.name, value: describeValue(entry.variable, entry.value), ...(entry.baseline === undefined ? {} : { baseline: describeValue(entry.variable, entry.baseline) }) })), location: view.location, position: view.position, relationships: session.records().relationships.filter(relation => relation.from === args.character), carrying: session.items.contents({ kind: 'character', id: found.id }).map(({ item, holding }) => ({ key: itemKey(item), name: item.name, quantity: item.quantity, how: holding.holder.kind === 'character' && holding.holder.mode === 'worn' ? `worn on the ${holding.holder.slot}` : 'carried', ...(item.container === undefined ? {} : { state: item.container.state }) })) }\n },\n }),\n defineTool({\n name: 'list_factions',\n description: 'List the persistent organisations of the story. These hold institutional state and strategy; group characters are the actors that appear in scenes.',\n parameters: {},\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n const { session } = link(resolve, exec.agent)\n return session.factions.list().map(faction => ({ key: faction.sourceId ?? String(faction.id), name: faction.name, summary: faction.summary, members: session.factionMemberships.ofFaction(faction.id, 'active').length, active_goals: session.factionIntents.list(faction.id, { status: 'active' }).length }))\n },\n }),\n defineTool({\n name: 'get_faction',\n description: 'Read one faction: its identity, institutional state, active strategy, memberships, and every directional relationship involving it.',\n parameters: { faction: { type: 'string', required: true, description: 'The key of the faction, as list_factions gives it.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const faction = session.factions.list().find(entry => (entry.sourceId ?? String(entry.id)) === args.faction)\n if (faction === undefined) throw new NotFoundError(`there is no faction \"${args.faction}\"; list_factions shows the keys`)\n const records = session.records()\n return { ...records.factions.find(entry => entry.faction === args.faction), relationships: { sees: records.faction_relationships.filter(entry => entry.from_kind === 'faction' && entry.from === args.faction), seen_by: records.faction_relationships.filter(entry => entry.to_kind === 'faction' && entry.to === args.faction) } }\n },\n }),\n defineTool({\n name: 'list_relationships',\n description: 'How characters stand towards each other: for each, the label (what the other is to it), a sentence, and how well it knows, trusts, likes and is strained with the other. Give a character to see how it sees others and how others see it.',\n parameters: { character: { type: 'string', description: 'The key of a character. Leave out for every relationship (the most recently changed first, at most 80).' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const all = session.records().relationships\n if (args.character === undefined) return JSON.parse(JSON.stringify(all)) as never\n if (!session.characters.list().some(character => characterKey(character) === args.character)) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n return JSON.parse(JSON.stringify({ sees: all.filter(relation => relation.from === args.character), seenBy: all.filter(relation => relation.to === args.character) })) as never\n },\n }),\n\n defineTool({\n name: 'list_items',\n description: 'List things, with the key each is named by and where it is. Narrow to what a character has, what is in a place, or what is inside a container; or search by words. At most 60 are listed, notable ones first.',\n parameters: {\n character: { type: 'string', description: 'The key of a character: what it carries and wears.' },\n location: { type: 'string', description: 'The key of a place: what is lying there (not what is inside containers).' },\n container: { type: 'string', description: 'The key of an item: what is inside it, whether it is open or not.' },\n text: { type: 'string', description: 'Only items whose name or description has this.' },\n },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const characters = session.characters.list()\n const keyOf = (id: number): string => { const found = characters.find(character => character.id === id); return found === undefined ? String(id) : characterKey(found) }\n const target = { items: session.items, locations: session.locations, characters: session.characters }\n let pool = session.items.list()\n if (args.character !== undefined) {\n const who = characters.find(character => characterKey(character) === args.character)\n if (who === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n pool = session.items.contents({ kind: 'character', id: who.id }).map(entry => entry.item)\n } else if (args.location !== undefined) {\n const where = session.locations.list().find(candidate => locationKey(candidate) === args.location)\n if (where === undefined) throw new NotFoundError(`there is no place \"${args.location}\"; list_locations shows the keys`)\n pool = session.items.contents({ kind: 'location', id: where.id }).map(entry => entry.item)\n } else if (args.container !== undefined) {\n const box = session.items.list().find(candidate => itemKey(candidate) === args.container)\n if (box === undefined) throw new NotFoundError(`there is no item \"${args.container}\"; list_items shows the keys`)\n pool = session.items.contents({ kind: 'item', id: box.id }).map(entry => entry.item)\n }\n const needle = args.text?.trim().toLowerCase()\n if (needle !== undefined && needle !== '') pool = pool.filter(item => item.name.toLowerCase().includes(needle) || item.description.toLowerCase().includes(needle))\n return JSON.parse(JSON.stringify([...pool].sort((a, b) => Number(b.notable) - Number(a.notable) || a.id - b.id).slice(0, MAX_LISTED_ITEMS).map(item => ({\n key: itemKey(item), name: item.name, quantity: item.quantity, quality: item.quality, state: item.container?.state ?? null, hidden: item.hidden, notable: item.notable, holder: describeHolder(target, item.id, keyOf),\n })))) as never\n },\n }),\n defineTool({\n name: 'get_item',\n description: 'Read one item: what it is, its condition, whose it is, where it is, what is inside it when it is a container, and what opens it. A hidden or closed thing is shown too: this is what the story knows.',\n parameters: { item: { type: 'string', required: true, description: 'The key of the item, as list_items gives it.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const found = session.items.list().find(candidate => itemKey(candidate) === args.item)\n if (found === undefined) throw new NotFoundError(`there is no item \"${args.item}\"; list_items shows the keys`)\n const characters = session.characters.list()\n const keyOf = (id: number): string => { const who = characters.find(character => character.id === id); return who === undefined ? String(id) : characterKey(who) }\n const keys = (ids: readonly number[]): string[] => ids.map(id => { const other = session.items.get(id); return other === undefined ? String(id) : itemKey(other) })\n return JSON.parse(JSON.stringify({\n item: itemKey(found), name: found.name, description: found.description, quantity: found.quantity, unique: found.unique, quality: found.quality, notable: found.notable, hidden: found.hidden,\n wearable: found.wearableSlot ?? null, state: found.container?.state ?? null, owner: found.ownerId === undefined ? null : keyOf(found.ownerId),\n where: describeHolder({ items: session.items, locations: session.locations, characters: session.characters }, found.id, keyOf),\n inside: found.container === undefined ? null : session.items.contents({ kind: 'item', id: found.id }).map(entry => ({ key: itemKey(entry.item), name: entry.item.name, quantity: entry.item.quantity })),\n opened_by: keys(session.items.openers({ kind: 'item', id: found.id })),\n })) as never\n },\n }),\n defineTool({\n name: 'list_slots',\n description: 'The places on the body something can be worn in this world, and how many things fit in each.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { id: str, name: str, capacity: int } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return link(resolve, exec.agent).session.slots.list()\n },\n }),\n defineTool({\n name: 'list_locations',\n description: 'List the places of the story with the key each is named by and the place it is in. Narrow to what is inside one place with `within`; at most 100 are listed.',\n parameters: { within: { type: 'string', description: 'The key of a place: list only the places inside it, at any depth.' } },\n output: {\n schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, name: str, in: { type: 'json', required: true }, exits: int } } },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const all = session.locations.list()\n const keys = new Map(all.map(place => [place.id, locationKey(place)]))\n const within = args.within === undefined ? undefined : all.find(place => locationKey(place) === args.within)\n if (args.within !== undefined && within === undefined) throw new NotFoundError(`there is no place \"${args.within}\"; list_locations shows the keys`)\n const inside = (place: (typeof all)[number]): boolean => {\n for (let up = place.parentId; up !== undefined; up = all.find(candidate => candidate.id === up)?.parentId) if (up === within?.id) return true\n return false\n }\n return all.filter(place => within === undefined || inside(place)).slice(0, MAX_LISTED_PLACES).map(place => ({ key: locationKey(place), name: place.name, in: place.parentId === undefined ? null : keys.get(place.parentId) ?? null, exits: session.locations.exitsFrom(place.id).length }))\n },\n }),\n defineTool({\n name: 'get_location',\n description: 'Read one place: what it is like, the things in it that can be pointed at, the ways out (and whether each is open, locked or blocked), and who is there.',\n parameters: { location: { type: 'string', required: true, description: 'The key of the place, as list_locations gives it.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const place = session.locations.list().find(candidate => locationKey(candidate) === args.location)\n if (place === undefined) throw new NotFoundError(`there is no place \"${args.location}\"; list_locations shows the keys`)\n const key = (id: number): string => { const found = session.locations.get(id); return found === undefined ? String(id) : locationKey(found) }\n const people = session.characters.list()\n return JSON.parse(JSON.stringify({\n location: locationKey(place), name: place.name, description: place.description, in: place.parentId === undefined ? null : key(place.parentId),\n features: place.features,\n exits: session.locations.exitsFrom(place.id).map(exit => ({ to: key(exit.toId), name: session.locations.get(exit.toId)?.name, state: exit.state, description: exit.description, note: exit.note, travel_time_seconds: exit.travelSeconds ?? null })),\n items: session.items.contents({ kind: 'location', id: place.id }).map(({ item, holding }) => ({ key: itemKey(item), name: item.name, quantity: item.quantity, ...(item.hidden ? { hidden: true } : {}), ...(item.container === undefined ? {} : { state: item.container.state }), ...(holding.holder.kind === 'location' && holding.holder.position !== undefined ? { position: holding.holder.position } : {}) })),\n here: session.placements.at(place.id, 'character').map(placement => { const who = people.find(character => character.id === placement.entityId); return { character: who === undefined ? String(placement.entityId) : characterKey(who), position: placement.position, feature: placement.featureKey ?? null } }),\n })) as never\n },\n }),\n\n defineTool({\n name: 'search_events',\n description: 'Look up what objectively happened in the story, in the order it happened. Narrow by character, turns, importance or what it is about.',\n parameters: {\n character: { type: 'string', description: 'Only events this character is involved in.' },\n text: { type: 'string', description: 'Only events about this, found by its words or its meaning; with it, the best matches come first.' },\n location: { type: 'string', description: 'Only events that happened in this place (its key).' },\n item: { type: 'string', description: 'Only events about this item (its key).' },\n from_turn: { type: 'integer' },\n to_turn: { type: 'integer' },\n min_importance: { type: 'integer', description: `From ${IMPORTANCE_MIN} to ${IMPORTANCE_MAX}.` },\n limit: { type: 'integer', description: `At most this many (at most ${MAX_EVENTS}): the most recent, or the best matches when text is given.` },\n },\n output: {\n schema: {\n type: 'array',\n items: { type: 'object', additionalProperties: false, properties: { id: int, turn: int, round: int, text: str, importance: int, tags: strs, involves: strs } },\n },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const agent = link(resolve, exec.agent)\n const { session } = agent\n const characters = session.characters.list()\n const involving = args.character === undefined ? undefined : characters.find(character => characterKey(character) === args.character)\n if (args.character !== undefined && involving === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n const place = args.location === undefined ? undefined : session.locations.list().find(candidate => locationKey(candidate) === args.location)\n if (args.location !== undefined && place === undefined) throw new NotFoundError(`there is no place \"${args.location}\"; list_locations shows the keys`)\n const thing = args.item === undefined ? undefined : session.items.list().find(candidate => itemKey(candidate) === args.item)\n if (args.item !== undefined && thing === undefined) throw new NotFoundError(`there is no item \"${args.item}\"; list_items shows the keys`)\n const needle = args.text?.trim().toLowerCase()\n const filter = {\n ...(place === undefined ? {} : { locationId: place.id }),\n ...(thing === undefined ? {} : { aboutItem: thing.id }),\n ...(involving === undefined ? {} : { involving: involving.id }),\n ...(args.from_turn === undefined ? {} : { fromTurn: args.from_turn }),\n ...(args.to_turn === undefined ? {} : { toTurn: args.to_turn }),\n ...(args.min_importance === undefined ? {} : { minImportance: args.min_importance }),\n }\n const listed = session.events.list(filter)\n const limit = Math.min(Math.max(args.limit ?? MAX_EVENTS, 1), MAX_EVENTS)\n const keyOf = (id: number): string => { const owner = characters.find(character => character.id === id); return owner === undefined ? String(id) : characterKey(owner) }\n const shown = (events: readonly (typeof listed)[number][]) => events.map(event => ({\n id: event.id, turn: event.turn, round: event.round, text: event.text, importance: event.importance, tags: event.tags, involves: event.involves.map(keyOf),\n }))\n if (needle === undefined || needle === '') return shown(listed.slice(-limit))\n // What matches the words or the meaning of the text comes first, best first; a plain substring match still counts.\n const { queryVector } = await vectorOf(agent, needle, exec.signal)\n const ranked = session.searchEvents({\n text: needle, limit: 50,\n ...(queryVector === undefined ? {} : { vector: queryVector }),\n ...(filter.fromTurn === undefined ? {} : { fromTurn: filter.fromTurn }),\n ...(filter.toTurn === undefined ? {} : { toTurn: filter.toTurn }),\n ...(filter.minImportance === undefined ? {} : { minImportance: filter.minImportance }),\n ...(filter.locationId === undefined ? {} : { locationId: filter.locationId }),\n ...(filter.aboutItem === undefined ? {} : { itemId: filter.aboutItem }),\n })\n const allowed = new Set(listed.map(event => event.id))\n const first = ranked.filter(event => allowed.has(event.id))\n const rest = listed.filter(event => !first.some(hit => hit.id === event.id) && (event.text.toLowerCase().includes(needle) || event.tags.some(tag => tag.includes(needle))))\n return shown([...first, ...rest].slice(0, limit))\n },\n }),\n defineTool({\n name: 'recall_memories',\n description: 'What a character remembers of a situation, in the way it remembers it: its own version of events and what it believes, with older and less important things faded or gone when the chat has imperfect memory.',\n parameters: {\n character: { type: 'string', required: true, description: 'The key of the character.' },\n situation: { type: 'string', required: true, description: 'What is happening now, which is what reminds the character of things.' },\n },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { clarity: str, turn: int, text: str } } }, render: pretty },\n isConcurrencySafe: () => false,\n async execute(args, exec) {\n const agent = link(resolve, exec.agent)\n const { session, turn, policy } = agent\n const found = session.characters.list().find(character => characterKey(character) === args.character)\n if (found === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n return (await session.recallRanked({ characterId: found.id, situation: args.situation, turn, policy, ...(session.placements.get('character', found.id) === undefined ? {} : { locationId: session.placements.get('character', found.id)!.locationId }) }, exec.signal, await vectorOf(agent, args.situation, exec.signal))).map(entry => ({ clarity: entry.clarity, turn: entry.turn, text: entry.text }))\n },\n }),\n defineTool({\n name: 'read_records',\n description: 'Read the records as stored: the state of every character, the events of the given rounds (or all) with who took each in and how, the beliefs formed in those turns, and the open threads.',\n parameters: {\n rounds: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { turn: { type: 'integer', required: true }, round: { type: 'integer', required: true } } }, description: 'Only the events and beliefs of these rounds. Leave out for everything.' },\n sections: { type: 'array', items: { type: 'string', enum: READ_SECTIONS }, description: 'Only these parts of the records (the others come back empty); leave out for all. Asking for what you need keeps the answer short.' },\n relationships_since: { type: 'integer', description: 'Of the relationships, only those that changed in this turn or later.' },\n },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session, timeZone } = link(resolve, exec.agent)\n const view = session.records({ ...(args.rounds === undefined ? {} : { rounds: args.rounds }), ...(timeZone === undefined ? {} : { timeZone }), ...(args.sections === undefined ? {} : { only: args.sections as (keyof ReturnType<typeof session.records>)[] }), ...(args.relationships_since === undefined ? {} : { relationshipsSince: args.relationships_since }) })\n return JSON.parse(JSON.stringify(view)) as never\n },\n }),\n defineTool({\n name: 'list_variables',\n description: 'What the story keeps track of: each variable with the key it is changed by, what it is about (every character, item or place, or the whole world), what it measures, its bounds or words, its default, and who can tell its value.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, name: str, description: str, kind: str, subject: str, only: strs, min: { type: 'json', required: true }, max: { type: 'json', required: true }, options: strs, default: { type: 'json', required: true }, visibility: str, baseline: { type: 'boolean', required: true } } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return link(resolve, exec.agent).session.records().variable_defs\n },\n }),\n defineTool({\n name: 'get_agenda',\n description: 'What a character is expected to be doing and to have done: its routine now and next, what it has committed to that is due soon or overdue, what it is after, and its whole day. Times are in the story\\'s time zone.',\n parameters: { character: { type: 'string', required: true, description: 'The key of the character.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session, timeZone } = link(resolve, exec.agent)\n const zone = timeZone ?? 'UTC'\n const found = session.characters.list().find(character => characterKey(character) === args.character)\n const state = session.clock.get()\n if (found === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n if (state === undefined) throw new NotFoundError('the story has no clock yet')\n const places = new Map(session.locations.list().map(place => [place.id, locationKey(place)]))\n const names = new Map(session.characters.list().map(character => [character.id, characterKey(character)]))\n const agenda = agendaAt(session, found.id, state.now, zone, { horizon: 48 * 3_600_000, engagements: 10, goals: 5 })\n const place = (id: number | undefined) => (id === undefined ? null : places.get(id) ?? null)\n const occurrence = (entry: typeof agenda.now) => (entry === undefined ? null : { activity: entry.window.activity, location: place(entry.window.locationId), from: localIso(entry.startsAt, zone), until: localIso(entry.endsAt, zone), interruptible: entry.window.interruptible })\n return JSON.parse(JSON.stringify({\n now: describeInstant(state.now, zone),\n routine_now: occurrence(agenda.now),\n routine_next: occurrence(agenda.next),\n engagements: agenda.engagements.map(entry => ({ id: entry.engagement.id, title: entry.engagement.title, at: localIso(entry.engagement.at, zone), location: place(entry.engagement.locationId), with: entry.engagement.participants.map(id => names.get(id) ?? String(id)), overdue: entry.overdue })),\n goals: agenda.goals.map(entry => ({ id: entry.intent.id, name: entry.intent.name, type: entry.intent.type, priority: entry.intent.priority, urgency: entry.intent.urgency, deadline: entry.deadlineAt === undefined ? null : localIso(entry.deadlineAt, zone), overdue: entry.overdue, plan: entry.intent.plan })),\n day: session.routines.list(found.id).map(window => ({ days: window.days.length === 0 ? 'every day' : window.days.join(','), from: minuteText(window.start), to: minuteText(window.end), activity: window.activity, location: place(window.locationId), interruptible: window.interruptible })),\n })) as never\n },\n }),\n defineTool({\n name: 'list_threads',\n description: 'List what is still open in the story: promises made, mysteries raised and goals not settled yet.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { id: int, text: str, opened_turn: int } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return link(resolve, exec.agent).session.records().open_threads\n },\n }),\n ]\n const authoringReads: ToolDefinition[] = options.authoring !== true ? [] : [\n defineTool({\n name: 'world_lint',\n description: 'What is inconsistent or unfinished in the world\\'s places and characters: places no one can reach or leave, characters in no place, names used twice, characters made up and not yet connected to anyone, ways with no way back. An error leaves the world inconsistent and has to be fixed; a warning should be fitted in; an info is only worth knowing.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { severity: str, code: str, subject: { type: 'json', required: true }, message: str } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return JSON.parse(JSON.stringify(lintWorld(link(resolve, exec.agent).session))) as never\n },\n }),\n defineTool({\n name: 'list_consolidation',\n description: 'What was made up in play and has not been fitted into the world yet: characters and places, with the turn they were made in and why.',\n parameters: {},\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n const { session } = link(resolve, exec.agent)\n return JSON.parse(JSON.stringify(session.consolidation.pending().map((item) => {\n const subject = item.kind === 'character' ? session.characters.get(item.subjectId) : session.locations.get(item.subjectId)\n return { id: item.id, kind: item.kind, key: subject === undefined ? String(item.subjectId) : item.kind === 'character' ? characterKey(subject as never) : locationKey(subject as never), name: subject?.name ?? '', made_in_turn: item.createdTurn, why: item.note }\n }))) as never\n },\n }),\n ]\n reads.push(...authoringReads)\n if (!options.write) return reads\n\n const done = { type: 'object', additionalProperties: false, properties: { writes: int, event_ids: ints, belief_ids: ints } } as const\n const written = (result: { writes: number; eventIds: number[]; beliefIds: number[] }) => ({ writes: result.writes, event_ids: result.eventIds, belief_ids: result.beliefIds })\n const perceivedBy = {\n type: 'array',\n description: 'Who took the event in: only characters who could actually have perceived it, each with how and, when it differs from the event, what they took in.',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n character: { type: 'string', required: true },\n mode: { type: 'string', enum: PERCEPTION_MODES },\n content: { type: 'string' },\n gist: { type: 'string' },\n accuracy: { type: 'string', enum: ACCURACIES },\n },\n },\n } as const\n\n const editSchema = recordsEditSchema({ ...(options.characters === undefined ? {} : { characters: options.characters }), changes: true, ...(options.authoring === true ? { authoring: true } : {}) })\n const writes: ToolDefinition[] = [\n {\n name: options.authoring === true ? 'edit_world' : 'edit_records',\n description: options.authoring === true\n ? 'Make up characters and places and fit them into the world, in one call, together or not at all: new characters (with their state and where they are), new places with their features and ways, new ways between places, relationship profiles between characters (one per direction), changes to places and ways, and corrections. If anything in it is refused, nothing is written and the reasons are returned: correct them and call again.'\n : 'Change the story\\'s records in one call, together or not at all: character states, new events (with where they happened and who took them in), corrections and retractions of draft events, revisions of what characters took in, changes to places and the ways between them, how characters stand towards each other, beliefs, and story threads. If anything in it is refused, nothing is written and the reasons are returned: correct them and call again.',\n parameters: editSchema as unknown as Record<string, unknown>,\n output: {\n schema: { type: 'object', properties: { writes: { type: 'integer' }, event_ids: { type: 'array', items: { type: 'integer' } }, belief_ids: { type: 'array', items: { type: 'integer' } }, character_keys: { type: 'array', items: { type: 'string' } }, place_keys: { type: 'array', items: { type: 'string' } }, item_keys: { type: 'array', items: { type: 'string' } }, variable_keys: { type: 'array', items: { type: 'string' } }, trigger_keys: { type: 'array', items: { type: 'string' } } }, required: ['writes', 'event_ids', 'belief_ids', 'character_keys', 'place_keys', 'item_keys', 'variable_keys', 'trigger_keys'], additionalProperties: false },\n render: (_args, value) => summary(options.authoring === true ? 'World changed' : 'Records changed')(_args, value as { writes: number }),\n },\n async execute(args, exec) {\n const { session, timeZone } = link(resolve, exec.agent)\n const result = session.edit({ ...parseRecordsEdit(args), ...(timeZone === undefined ? {} : { timeZone }) })\n return { writes: result.writes, event_ids: result.eventIds, belief_ids: result.beliefIds, character_keys: result.characterKeys ?? [], place_keys: result.placeKeys ?? [], item_keys: result.itemKeys ?? [], variable_keys: result.variableKeys ?? [], trigger_keys: result.triggerKeys ?? [] }\n },\n },\n ...(options.authoring !== true ? [] : [defineTool({\n name: 'resolve_consolidation',\n description: 'Say that something made up in play has been fitted into the world, and how: what you connected it to, or why nothing more is needed. Only after you have done it.',\n parameters: {\n id: { type: 'integer', required: true, description: 'The id list_consolidation gives.' },\n resolution: { type: 'string', required: true, description: 'What was done, in a sentence.' },\n },\n output: { schema: done, render: summary('Fitted in') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n if (args.resolution.trim() === '') throw new NotFoundError('say what was done to fit it in')\n session.consolidation.resolve(args.id, turn, args.resolution)\n return { writes: 1, event_ids: [], belief_ids: [] }\n },\n })]),\n defineTool({\n name: 'update_character_state',\n description: 'Change the current state of a character. Give only what changed: public_state is what anyone present can see (a present-tense description, not a log), inner_state is private, activity is what it is doing now.',\n parameters: {\n character: { type: 'string', required: true },\n public_state: { type: 'string' },\n inner_state: { type: 'string' },\n activity: { type: 'string' },\n },\n output: { schema: done, render: summary('State updated') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n const { character, public_state, inner_state, activity } = args\n return written(session.edit({\n turn,\n states: [{ character, ...(public_state === undefined ? {} : { publicState: public_state }), ...(inner_state === undefined ? {} : { innerState: inner_state }), ...(activity === undefined ? {} : { activity }) }],\n }))\n },\n }),\n defineTool({\n name: 'move_character',\n description: 'Move a character to another place. It must be possible: there has to be a way over open exits from where it is, unless ignore_exits says the story itself carries it (carried off, teleported, falls). The reasons come back if it is not.',\n parameters: {\n character: { type: 'string', required: true },\n to: { type: 'string', required: true, description: 'The key of the place, as list_locations gives it.' },\n position: { type: 'string', description: 'Where in the place, in words: \"at the bar\", \"by the door\".' },\n feature: { type: 'string', description: 'The key of a feature of the place it is at.' },\n ignore_exits: { type: 'boolean' },\n },\n output: { schema: done, render: summary('Moved') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, moves: [{ character: args.character, to: args.to, ...(args.position === undefined ? {} : { position: args.position }), ...(args.feature === undefined ? {} : { feature: args.feature }), ...(args.ignore_exits === true ? { ignoreExits: true } : {}) }] }))\n },\n }),\n defineTool({\n name: 'record_event',\n description: 'Record something that objectively happened, as a short factual past-tense statement, and who took it in.',\n parameters: {\n text: { type: 'string', required: true },\n importance: { type: 'integer', required: true, description: `From ${IMPORTANCE_MIN} (a passing detail) to ${IMPORTANCE_MAX} (turns the story).` },\n round: { type: 'integer', description: 'The round of the turn it happened in; 1 by default.' },\n tags: strings,\n involves: { ...strings, description: 'The keys of the characters the event is about.' },\n perceived_by: perceivedBy,\n },\n output: { schema: done, render: summary('Event recorded') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n // Written directly, not by a keeper that checks it afterwards: the event is final at once.\n return written(session.edit({\n turn,\n events: [{\n turn, round: args.round ?? 1, text: args.text, importance: args.importance,\n ...(args.tags === undefined ? {} : { tags: args.tags }),\n ...(args.involves === undefined ? {} : { involves: args.involves }),\n perceivedBy: (args.perceived_by ?? []).map(entry => ({ character: entry.character, mode: (entry.mode ?? 'witnessed') as (typeof PERCEPTION_MODES)[number], ...(entry.content === undefined ? {} : { content: entry.content }), ...(entry.gist === undefined ? {} : { gist: entry.gist }), ...(entry.accuracy === undefined ? {} : { accuracy: entry.accuracy as (typeof ACCURACIES)[number] }) })),\n }],\n }, { seal: true }))\n },\n }),\n defineTool({\n name: 'remember',\n description: 'Record something a character has come to believe or know, from that character\\'s own point of view.',\n parameters: {\n character: { type: 'string', required: true },\n kind: { type: 'string', required: true, enum: MEMORY_KINDS },\n text: { type: 'string', required: true },\n about: { ...strings, description: 'The keys of the characters it is about.' },\n importance: { type: 'integer', required: true },\n },\n output: { schema: done, render: summary('Remembered') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, beliefs: [{ character: args.character, kind: args.kind as (typeof MEMORY_KINDS)[number], text: args.text, importance: args.importance, ...(args.about === undefined ? {} : { about: args.about }) }] }))\n },\n }),\n defineTool({\n name: 'open_thread',\n description: 'Open a story thread: a promise made, a mystery raised or a goal set that is not settled yet.',\n parameters: { text: { type: 'string', required: true, description: 'One sentence.' } },\n output: { schema: done, render: summary('Thread opened') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, threadsOpened: [args.text] }))\n },\n }),\n defineTool({\n name: 'resolve_thread',\n description: 'Mark an open story thread as settled.',\n parameters: { id: { type: 'integer', required: true, description: 'The id list_threads gives.' } },\n output: { schema: done, render: summary('Thread resolved') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, threadsResolved: [args.id] }))\n },\n }),\n ]\n return [...reads, ...writes]\n}\n","import { resolve } from 'node:path'\nimport { Service, type Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-tools'\nimport z from '@deepseek-ai/schemastery'\nimport { createSession, deleteSession, forkSession, type ForkOptions, type ForkSource, listSessions, openSession, removeSnapshot, restoreSnapshot, sessionDatabase, snapshotNames, takeSnapshot, type SessionInit, type SessionListing } from './sessions.ts'\nimport type { SessionStore, StoreOptions } from './store.ts'\nimport type { RecallQuery, Recalled } from './memory/recall.ts'\nimport type { SemanticRanker } from './memory/ranker.ts'\nimport { poolCandidates } from './memory/recall.ts'\nimport { createTools, type AgentResolver } from './tools/index.ts'\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n roleplayState: RoleplayState\n }\n}\n\nexport interface Config {\n /** `delete` keeps each session in a single file that can be copied; `wal` allows readers while writing. */\n journalMode: 'delete' | 'wal'\n /**\n * Whether the model-facing tools that change the records are registered too. The reading\n * tools are always there; leave writing off where another agent is responsible for the records.\n */\n writeTools: boolean\n}\n\nexport const Config: z<Config> = z.object({\n journalMode: z.union(['delete', 'wal'] as const).default('delete'),\n writeTools: z.boolean().default(false),\n})\n\n/** A session's repositories. Connections belong to the service, so there is nothing to close. */\nexport type Session = Omit<SessionStore, 'close' | 'snapshotTo'> & {\n /**\n * {@link SessionStore.recall}, with the over-retrieved pool reranked when a ranker is registered with\n * `roleplayState.rankMemories`. The one call for anything that reminds a character of something.\n */\n recallRanked(query: Omit<RecallQuery, 'characters'>, signal?: AbortSignal, options?: { queryVector?: readonly number[] }): Promise<Recalled[]>\n}\n\n/**\n * Roleplay session state for other plugins. It creates and opens sessions\n * under a sessions folder, shares one connection per session, and closes them\n * all when the plugin unloads.\n */\nexport class RoleplayState extends Service {\n private readonly sessions = new Map<string, { store: SessionStore; session: Session }>()\n private readonly options: StoreOptions\n private readonly resolvers = new Set<AgentResolver>()\n private readonly rankers: SemanticRanker[] = []\n\n constructor(ctx: Context, config: Partial<Config> = {}) {\n super(ctx, 'roleplayState')\n this.options = { journalMode: config.journalMode ?? 'delete' }\n ctx.effect(() => () => { this.closeAll() }, 'roleplay-state: connections')\n const resolve: AgentResolver = (agentSessionId) => {\n for (const resolver of this.resolvers) {\n const found = resolver(agentSessionId)\n if (found !== undefined) return found\n }\n return undefined\n }\n ctx.inject(['tools'], (scope) => {\n for (const tool of createTools(resolve, { write: config.writeTools ?? false })) scope.tools.register(tool)\n })\n }\n\n /**\n * Let what characters remember be ranked by meaning, with an embedding model or a reranker\n * from another plugin. The latest one registered is used, by every recall: the tools, and the\n * plugins that run characters through `session.recallRanked`. Where it fails, recall carries on\n * with the cues alone and says so in the log.\n * @returns what removes it again.\n */\n rankMemories(ranker: SemanticRanker): () => void {\n this.rankers.push(ranker)\n return () => { this.rankers.splice(this.rankers.indexOf(ranker), 1) }\n }\n\n /**\n * Tell the tools which roleplay session an agent works in. The plugin that runs agents\n * calls this with a function from the id of an agent's session to its roleplay session,\n * the turn it is playing and how its characters remember.\n * @returns what removes the binding again.\n */\n bind(resolver: AgentResolver): () => void {\n this.resolvers.add(resolver)\n return () => { this.resolvers.delete(resolver) }\n }\n\n /**\n * Create a session and open it. Its id is `init.id` or a generated UUID, and is in `metadata.get().id`.\n * @throws {ConflictError} when a session with that id exists.\n */\n createSession(sessionsDir: string, init: SessionInit): Session {\n const store = createSession(sessionsDir, init, this.options)\n return this.track(resolve(sessionDatabase(sessionsDir, store.metadata.get().id)), store)\n }\n\n /** @throws {NotFoundError} when the session does not exist. */\n openSession(sessionsDir: string, id: string): Session {\n const key = resolve(sessionDatabase(sessionsDir, id))\n return this.sessions.get(key)?.session ?? this.track(key, openSession(sessionsDir, id, this.options))\n }\n\n /** The metadata of every session under the folder; sessions that cannot be read are reported, not thrown. */\n listSessions(sessionsDir: string): SessionListing {\n return listSessions(sessionsDir, this.options, id => this.sessions.get(resolve(sessionDatabase(sessionsDir, id)))?.store)\n }\n\n /** Release a session's connection; opening it again reconnects. */\n closeSession(sessionsDir: string, id: string): void {\n const key = resolve(sessionDatabase(sessionsDir, id))\n this.sessions.get(key)?.store.close()\n this.sessions.delete(key)\n }\n\n /** Keep a consistent copy of a session's database under a name (a lowercase name of letters, digits and hyphens), replacing one of that name. */\n snapshot(sessionsDir: string, id: string, name: string): void {\n const key = resolve(sessionDatabase(sessionsDir, id))\n const open = this.sessions.get(key)?.store\n if (open !== undefined) { takeSnapshot(sessionsDir, id, name, open); return }\n const store = openSession(sessionsDir, id, this.options)\n try { takeSnapshot(sessionsDir, id, name, store) } finally { store.close() }\n }\n\n /** The names of the snapshots a session has. */\n snapshots(sessionsDir: string, id: string): string[] {\n return snapshotNames(sessionsDir, id)\n }\n\n /** Delete a snapshot, if there is one. */\n removeSnapshot(sessionsDir: string, id: string, name: string): void {\n removeSnapshot(sessionsDir, id, name)\n }\n\n /**\n * Put the database of a session back as it was in a snapshot. The connection is released first, so anything that\n * holds the session from before has to ask for it again: nothing may be using it.\n * @throws {NotFoundError} when there is no such snapshot.\n */\n restore(sessionsDir: string, id: string, name: string): void {\n this.closeSession(sessionsDir, id)\n restoreSnapshot(sessionsDir, id, name, this.options)\n }\n\n /**\n * Make a new session from a snapshot of another, or from its database as it is (nothing may be writing to it): the new one has\n * a folder of its own with the database, the settings and the snapshots named in `keep`, and its own id and name.\n * @throws {ConflictError} when the new id exists. @throws {NotFoundError} when a snapshot does not exist.\n */\n fork(sessionsDir: string, fromId: string, toId: string, from: { snapshot: string } | { live: true }, options: ForkOptions): void {\n if ('snapshot' in from) { forkSession(sessionsDir, fromId, toId, from, options, this.options); return }\n const open = this.sessions.get(resolve(sessionDatabase(sessionsDir, fromId)))?.store\n const store = open ?? openSession(sessionsDir, fromId, this.options)\n try { forkSession(sessionsDir, fromId, toId, { live: store } satisfies ForkSource, options, this.options) } finally { if (open === undefined) store.close() }\n }\n\n /** Close a session and remove its folder, including everything else kept in it. */\n deleteSession(sessionsDir: string, id: string): void {\n this.closeSession(sessionsDir, id)\n deleteSession(sessionsDir, id)\n }\n\n private track(key: string, store: SessionStore): Session {\n const session: Session = {\n metadata: store.metadata,\n characters: store.characters,\n characterStates: store.characterStates,\n factions: store.factions,\n factionStates: store.factionStates,\n factionMemberships: store.factionMemberships,\n factionRelationships: store.factionRelationships,\n factionIntents: store.factionIntents,\n lore: store.lore,\n intents: store.intents,\n events: store.events,\n memories: store.memories,\n threads: store.threads,\n summaries: store.summaries,\n pendingCommits: store.pendingCommits,\n locations: store.locations,\n placements: store.placements,\n relationships: store.relationships,\n knowledge: store.knowledge,\n consolidation: store.consolidation,\n slots: store.slots,\n items: store.items,\n visualIdentities: store.visualIdentities,\n clock: store.clock,\n variables: store.variables,\n routines: store.routines,\n engagements: store.engagements,\n triggers: store.triggers,\n planMove: (characterId, move) => store.planMove(characterId, move),\n planKnownMove: (characterId, move) => store.planKnownMove(characterId, move),\n move: (characterId, move) => store.move(characterId, move),\n recallIndex: store.recallIndex,\n transaction: fn => store.transaction(fn),\n recall: (query, evidence) => store.recall(query, evidence),\n recallStored: (query, options) => store.recallStored(query, options),\n searchEvents: search => store.searchEvents(search),\n recallCandidates: query => store.recallCandidates(query),\n storedEvidence: (query, queryVector) => store.storedEvidence(query, queryVector),\n recallPool: (query, evidence) => store.recallPool(query, evidence),\n finishRecall: (pool, turn, rerank) => store.finishRecall(pool, turn, rerank),\n recallRanked: async (query, signal, options = {}) => {\n const pool = store.recallPool(query, store.storedEvidence(query, options.queryVector))\n const ranker = this.rankers.at(-1)\n if (ranker === undefined) return store.finishRecall(pool, query.turn)\n try {\n const judged = await ranker({ situation: query.situation, candidates: poolCandidates(pool), ...(signal === undefined ? {} : { signal }) })\n return store.finishRecall(pool, query.turn, judged)\n } catch (error) {\n if (signal?.aborted === true) throw error\n this.ctx.logger.warn(`roleplay-state: reranking memories failed, using retrieval alone: ${error instanceof Error ? error.message : String(error)}`)\n return store.finishRecall(pool, query.turn)\n }\n },\n edit: (edit, options) => store.edit(edit, options),\n runTriggers: options => store.runTriggers(options),\n lapseNotes: (turn, kept) => store.lapseNotes(turn, kept),\n deliverNotes: (notes, clock) => store.deliverNotes(notes, clock),\n records: scope => store.records(scope),\n }\n this.sessions.set(key, { store, session })\n return session\n }\n\n private closeAll(): void {\n for (const { store } of this.sessions.values()) store.close()\n this.sessions.clear()\n }\n}\n\nexport const name = '@dsh-agentic-roleplay/state'\n\nexport function apply(ctx: Context, config: Config): void {\n new RoleplayState(ctx, config)\n}\n","import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'\nimport type { CharacterId } from 'dsh-roleplay-model'\nimport { vectorOf, type AgentLink } from './index.ts'\nimport { characterKey, locationKey } from '../records/edit-types.ts'\nimport { itemKey } from '../records/items.ts'\nimport { mentioned } from '../memory/recall.ts'\n\n/**\n * The tools of one character's own agent. They are built for that character and registered\n * on that agent alone, so what they return is only what that character took in and believes:\n * agents running side by side for different characters each get their own, and none can\n * reach another's memory.\n */\n/** Where the character is, as a recall cue: what happened where it stands comes back more readily. */\nconst placeOf = (session: AgentLink['session'], characterId: CharacterId): { locationId?: number } => {\n const placement = session.placements.get('character', characterId)\n return placement === undefined ? {} : { locationId: placement.locationId }\n}\n\nexport function createCharacterTools(link: () => AgentLink, characterId: CharacterId): ToolDefinition[] {\n return [\n defineTool({\n name: 'recall_my_memories',\n description: 'Ask yourself what you remember about something: a person, an object, a place or an earlier moment. You get your own version of it, what you took in yourself and what you believe, and what has faded comes back as hazy or not at all. Use it only when you need a memory that the situation does not already give you.',\n parameters: {\n about: { type: 'string', required: true, description: 'What to remember: a name, an object, a topic or a short description of the moment.' },\n person: { type: 'string', description: 'Only what concerns this person (a name or alias you know): everything you remember of them.' },\n },\n output: {\n schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { clarity: { type: 'string', required: true }, turn: { type: 'integer', required: true }, text: { type: 'string', required: true } } } },\n render: (_args, value) => [{ type: 'text', text: value.length === 0 ? 'You do not remember anything about that, and there is nothing more to find: go on with what you know.' : value.map(entry => `- (${entry.clarity === 'clear' ? '' : entry.clarity === 'faded' ? 'the details are fuzzy' : 'you barely remember'}) ${entry.text}`.replace('- () ', '- ')).join('\\n') }],\n },\n isConcurrencySafe: () => false,\n async execute(args, exec) {\n const agent = link()\n const { session, turn, policy } = agent\n const who = args.person === undefined || args.person.trim() === '' ? [] : [...mentioned(args.person, session.characters.list())].filter(id => id !== characterId)\n if (args.person !== undefined && args.person.trim() !== '' && who.length === 0) return []\n const situation = who.length === 0 ? args.about : `${args.about} ${args.person}`\n return (await session.recallRanked({ characterId, situation, turn, policy, ...(who.length === 0 ? {} : { about: who }), ...placeOf(session, characterId) }, exec.signal, await vectorOf(agent, situation, exec.signal))).map(entry => ({ clarity: entry.clarity, turn: entry.turn, text: entry.text }))\n },\n }),\n defineTool({\n name: 'recall_my_known_entities',\n description: 'Recall the people, places, things and routes you know exist. This says only that you know them, not where they are now or their current state.',\n parameters: { about: { type: 'string', description: 'Optional name or word to narrow the result.' } },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { kind: { type: 'string', required: true }, key: { type: 'string', required: true }, name: { type: 'string', required: true } } } }, render: (_args, value) => [{ type: 'text', text: value.length === 0 ? 'You know of nothing matching that.' : value.map(entry => `- ${entry.kind}: ${entry.name}`).join('\\n') }] },\n isConcurrencySafe: () => true,\n async execute(args) {\n const { session } = link()\n const found = [\n ...session.relationships.from(characterId).flatMap(relation => { const character = session.characters.get(relation.toId); return character === undefined ? [] : [{ kind: 'character', key: characterKey(character), name: character.name }] }),\n ...session.factionRelationships.from('character', characterId).filter(relation => relation.toKind === 'faction').flatMap(relation => { const faction = session.factions.get(relation.toId); return faction === undefined ? [] : [{ kind: 'faction', key: faction.sourceId ?? String(faction.id), name: faction.name }] }),\n ...session.knowledge.list(characterId, 'location').flatMap(entry => { const place = session.locations.get(entry.subjectId); return place === undefined ? [] : [{ kind: 'location', key: locationKey(place), name: place.name }] }),\n ...session.knowledge.list(characterId, 'item').flatMap(entry => { const item = session.items.get(entry.subjectId); return item === undefined ? [] : [{ kind: 'item', key: itemKey(item), name: item.name }] }),\n ...session.knowledge.list(characterId, 'exit').flatMap(entry => { const exit = session.locations.allExits().find(candidate => candidate.id === entry.subjectId); const from = exit === undefined ? undefined : session.locations.get(exit.fromId); const to = exit === undefined ? undefined : session.locations.get(exit.toId); return from === undefined || to === undefined ? [] : [{ kind: 'route', key: `${locationKey(from)} -> ${locationKey(to)}`, name: `${from.name} to ${to.name}` }] }),\n ]\n const needle = args.about?.trim().toLowerCase()\n return needle === undefined || needle === '' ? found : found.filter(entry => `${entry.key} ${entry.name}`.toLowerCase().includes(needle))\n },\n }),\n defineTool({\n name: 'recall_my_lore',\n description: 'Recall established lore that you know: history, customs, legends, places and other background knowledge. Unknown lore is never returned.',\n parameters: { about: { type: 'string', required: true, description: 'A name, subject or phrase to look for in what you know.' } },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: { type: 'string', required: true }, title: { type: 'string', required: true }, kind: { type: 'string', required: true }, text: { type: 'string', required: true } } } }, render: (_args, value) => [{ type: 'text', text: value.length === 0 ? 'You do not know any lore matching that.' : value.map(entry => `- ${entry.title} [${entry.kind}] (${entry.key}): ${entry.text}`).join('\\n') }] },\n isConcurrencySafe: () => true,\n async execute(args) {\n const needle = args.about.trim().toLowerCase()\n return link().session.knowledge.list(characterId, 'lore').flatMap(known => {\n const lore = link().session.lore.get(known.subjectId)\n if (lore === undefined || !`${lore.title} ${lore.summary} ${lore.body}`.toLowerCase().includes(needle)) return []\n return [{ key: lore.sourceId ?? String(lore.id), title: lore.title, kind: lore.kind, text: lore.body || lore.summary }]\n })\n },\n }),\n ]\n}\n"],"mappings":";;;;;;;;;AAOA,MAAa,kBAAkB,CAAC,YAAY,KAAK;AACjD,MAAa,kBAAkB;CAAC;CAAa;CAAc;AAAY;AACvE,MAAa,kBAAkB,CAAC,UAAU,OAAO;;;ACTjD,MAAa,eAAe;CAAC;CAAQ;CAAc;CAAS;CAAU;CAAc;CAAgB;CAAS;AAAU;AACvH,MAAa,kBAAkB;CAAC;CAAU;CAAU;CAAa;CAAU;AAAW;AACtF,MAAa,kBAAkB;CAAC;CAAa;CAAS;CAAO;CAAQ;AAAY;;;;ACKjF,MAAa,mBAAmB;CAAC;CAAQ;CAAU;AAAQ;AAY3D,MAAa,UAAU;AAEvB,MAAa,gBAAiC;CAC5C;EAAE,IAAI;EAAQ,MAAM;EAAQ,UAAU;CAAE;CACxC;EAAE,IAAI;EAAQ,MAAM;EAAQ,UAAU;CAAE;CACxC;EAAE,IAAI;EAAQ,MAAM;EAAQ,UAAU;CAAE;CACxC;EAAE,IAAI;EAAS,MAAM;EAAS,UAAU;CAAE;CAC1C;EAAE,IAAI;EAAQ,MAAM;EAAQ,UAAU;CAAE;CACxC;EAAE,IAAI;EAAS,MAAM;EAAS,UAAU;CAAE;CAC1C;EAAE,IAAI;EAAS,MAAM;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O,UAAU,CAAC;KAAE,MAAM;KAAQ,MAAM,MAAM,WAAW,IAAI,4CAA4C,MAAM,KAAI,UAAS,KAAK,MAAM,MAAM,IAAI,MAAM,KAAK,KAAK,MAAM,IAAI,KAAK,MAAM,MAAM,CAAC,CAAC,KAAK,IAAI;IAAE,CAAC;GAAE;GAC1e,yBAAyB;GACzB,MAAM,QAAQ,MAAM;IAClB,MAAM,SAAS,KAAK,MAAM,KAAK,CAAC,CAAC,YAAY;IAC7C,OAAO,KAAK,CAAC,CAAC,QAAQ,UAAU,KAAK,aAAa,MAAM,CAAC,CAAC,SAAQ,UAAS;KACzE,MAAM,OAAO,KAAK,CAAC,CAAC,QAAQ,KAAK,IAAI,MAAM,SAAS;KACpD,IAAI,SAAS,KAAA,KAAa,CAAC,GAAG,KAAK,MAAM,GAAG,KAAK,QAAQ,GAAG,KAAK,OAAO,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG,OAAO,CAAC;KAChH,OAAO,CAAC;MAAE,KAAK,KAAK,YAAY,OAAO,KAAK,EAAE;MAAG,OAAO,KAAK;MAAO,MAAM,KAAK;MAAM,MAAM,KAAK,QAAQ,KAAK;KAAQ,CAAC;IACxH,CAAC;GACH;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"index.js","names":["within","pad","present","list","name","isObject","MAX_TEXT","isObject","resolve","DAY","toItem","RANGES","checked","SESSION_ID","fromRow"],"sources":["../../dsh-roleplay-model/src/character.ts","../../dsh-roleplay-model/src/intent.ts","../../dsh-roleplay-model/src/item.ts","../../dsh-roleplay-model/src/location.ts","../../dsh-roleplay-model/src/session.ts","../../dsh-roleplay-model/src/memory.ts","../../dsh-roleplay-model/src/relationship.ts","../../dsh-roleplay-model/src/knowledge.ts","../../dsh-roleplay-model/src/faction.ts","../../dsh-roleplay-model/src/clock.ts","../../dsh-roleplay-model/src/agenda.ts","../../dsh-roleplay-model/src/variable.ts","../../dsh-roleplay-model/src/trigger.ts","../../dsh-roleplay-model/src/dice.ts","../../dsh-roleplay-model/src/visual.ts","../../dsh-roleplay-model/src/lore.ts","../../dsh-roleplay-model/src/plot.ts","../../dsh-roleplay-model/src/messages-zh.ts","../../dsh-roleplay-model/src/messages.ts","../src/clock.ts","../src/driver/node-sqlite.ts","../src/errors.ts","../src/sqlite/support.ts","../src/records/edit-types.ts","../src/sqlite/agenda-repositories.ts","../src/records/calendar.ts","../src/records/time.ts","../src/records/agenda-edit.ts","../src/records/items.ts","../src/records/movement.ts","../src/records/template.ts","../src/sqlite/variable-repository.ts","../src/records/variables.ts","../src/records/trigger-rules.ts","../src/records/wire.ts","../src/records/edit.ts","../src/records/triggers.ts","../src/records/deferred.ts","../src/memory/recall.ts","../src/records/read.ts","../src/sqlite/event-repository.ts","../src/sqlite/memory-repository.ts","../src/sqlite/narrative-repositories.ts","../src/sqlite/recall-index.ts","../src/sqlite/trigger-repository.ts","../src/sqlite/dice-repository.ts","../src/sqlite/clock-repository.ts","../src/sqlite/item-repository.ts","../src/sqlite/relationship-repository.ts","../src/sqlite/location-repository.ts","../src/sqlite/vector-extension.ts","../src/sqlite/character-repository.ts","../src/sqlite/intent-repository.ts","../src/sqlite/metadata-repository.ts","../src/sqlite/schema.ts","../src/sqlite/migrate.ts","../src/sqlite/state-repository.ts","../src/sqlite/visual-identity-repository.ts","../src/sqlite/knowledge-repository.ts","../src/sqlite/faction-repositories.ts","../src/sqlite/lore-repository.ts","../src/store.ts","../src/sessions.ts","../src/records/dice.ts","../src/tools/dice.ts","../src/records/lint.ts","../src/records/agenda.ts","../src/tools/index.ts","../src/plugin.ts","../src/tools/character.ts"],"sourcesContent":["import type { RoutineDefinition } from './agenda.ts'\nimport type { VariableValue } from './variable.ts'\nimport type { RelationshipDefinition } from './relationship.ts'\nimport type { CharacterStart } from './state.ts'\nimport type { VisualIdentityInput } from './visual.ts'\nimport type { KnowledgeDefinition } from './knowledge.ts'\n\nexport const CHARACTER_ROLES = ['playable', 'npc'] as const\nexport const CHARACTER_TIERS = ['principal', 'supporting', 'background'] as const\nexport const CHARACTER_KINDS = ['person', 'group'] as const\n\n/** Whether the player may choose the character; a world can offer several. */\nexport type CharacterRole = typeof CHARACTER_ROLES[number]\n\n/**\n * How much simulation a character gets: principals act on their own,\n * supporting characters act when the scene involves them, background\n * characters only react as the world changes.\n */\nexport type CharacterTier = typeof CHARACTER_TIERS[number]\n\n/** A single person, or a crowd or organisation treated as one participant. */\nexport type CharacterKind = typeof CHARACTER_KINDS[number]\n\nexport interface CharacterSpeech {\n style: string\n examples: string[]\n}\n\n/** A character as authored in a world. */\nexport interface CharacterDefinition {\n /** Provisional, unique within the world; only for links inside the exported files. */\n id: string\n name: string\n /** Nicknames and other names the character answers to. */\n aliases: string[]\n age?: string\n gender?: string\n /** May differ from the gender, for example \"she/her\". */\n pronouns?: string\n kind: CharacterKind\n tier: CharacterTier\n role: CharacterRole\n /** One or two sentences, for lists and previews. */\n summary: string\n personality: string\n background: string\n appearance: string\n /** Stable visual facts; current expression, clothing, activity and surroundings do not belong here. */\n visualIdentity?: VisualIdentityInput\n speech: CharacterSpeech\n /** Provider voice id used for spoken utterances. */\n voice?: string\n start: CharacterStart\n /** How this character stands towards others of the world, by their ids. */\n relationships?: RelationshipDefinition[]\n /** Places, things and ways this character knows exist when the story starts. */\n knowledge?: KnowledgeDefinition\n /** The recurring day of the character: what it is doing and where, by the clock. */\n routine?: RoutineDefinition[]\n /** What it starts with of what the world tracks (a value for each of the variables named), by variable key. */\n variables?: Record<string, VariableValue>\n}\n","export const INTENT_TYPES = ['need', 'obligation', 'quest', 'agenda', 'aspiration', 'relationship', 'habit', 'reaction'] as const\nexport const INTENT_STATUSES = ['active', 'paused', 'completed', 'failed', 'abandoned'] as const\nexport const INTENT_HORIZONS = ['immediate', 'short', 'day', 'long', 'open_ended'] as const\n\nexport type IntentType = typeof INTENT_TYPES[number]\nexport type IntentStatus = typeof INTENT_STATUSES[number]\nexport type IntentHorizon = typeof INTENT_HORIZONS[number]\n\n/** A driving thread behind what a character does. */\nexport interface Intent {\n type: IntentType\n name: string\n description: string\n status: IntentStatus\n horizon: IntentHorizon\n /** 0 to 1. */\n priority: number\n /** 0 to 1. */\n urgency: number\n plan: string[]\n openThreads: string[]\n constraints: string[]\n /** ISO 8601 date-time. */\n deadline?: string\n}\n","import type { CharacterId } from './session.ts'\nimport type { LocationId } from './location.ts'\nimport type { VisualIdentityInput } from './visual.ts'\n\nexport type ItemId = number\n\n/** Whether a container can be got into. */\nexport const CONTAINER_STATES = ['open', 'closed', 'locked'] as const\nexport type ContainerState = (typeof CONTAINER_STATES)[number]\n\n/** A place on the body something can be worn. Worlds can have their own; these are what a world starts with. */\nexport interface Slot {\n /** Short and lowercase: how items and tools name it. */\n id: string\n name: string\n /** How many things can be worn there at once. */\n capacity: number\n}\n\nexport const SLOT_ID = /^[a-z][a-z0-9_-]{0,39}$/\n\nexport const DEFAULT_SLOTS: readonly Slot[] = [\n { id: 'head', name: 'head', capacity: 1 },\n { id: 'face', name: 'face', capacity: 1 },\n { id: 'neck', name: 'neck', capacity: 1 },\n { id: 'torso', name: 'torso', capacity: 2 },\n { id: 'back', name: 'back', capacity: 1 },\n { id: 'waist', name: 'waist', capacity: 1 },\n { id: 'hands', name: 'hands', capacity: 1 },\n { id: 'wrists', name: 'wrists', capacity: 2 },\n { id: 'fingers', name: 'fingers', capacity: 4 },\n { id: 'legs', name: 'legs', capacity: 1 },\n { id: 'feet', name: 'feet', capacity: 1 },\n]\n\n/** What can hold other things: a chest, a satchel, a drawer. */\nexport interface ContainerSpec {\n state: ContainerState\n}\n\n/**\n * A thing that can be moved, held, worn, opened or used: one kind for everything physical. What it\n * can do is what it has: a slot it is worn in, a container it holds things in, a quantity when there\n * are several alike. Scenery that cannot be moved (a desk, a window) is a feature of its place instead.\n */\nexport interface Item {\n id: ItemId\n /** The id in the world's files; absent for something made up in play. */\n sourceId?: string\n name: string\n description: string\n /** How many there are, for things that come in numbers (coins, arrows). */\n quantity: number\n /** Only one exists in the story: it is never split or merged. */\n unique: boolean\n /** Its condition, in words: \"worn\", \"freshly oiled\". */\n quality: string\n /** Matters to the story: told first and never left out of a short list. */\n notable: boolean\n /** Not seen by anyone until it is found. */\n hidden: boolean\n /** The slot it is worn in, when it can be worn. */\n wearableSlot?: string\n container?: ContainerSpec\n /** Whose it is, which is not the same as who has it. */\n ownerId?: CharacterId\n createdAt: string\n}\n\nexport type NewItem = Omit<Item, 'id' | 'createdAt'>\n/** What may change about a thing. `ownerId: null` says it belongs to no one. */\nexport type ItemPatch = Partial<Pick<Item, 'name' | 'description' | 'quantity' | 'quality' | 'notable' | 'hidden'>> & { ownerId?: CharacterId | null; container?: ContainerSpec }\n\n/** What holds an item: a place, a character (in its hands, or worn) or another item (inside it). */\nexport type Holder =\n | { kind: 'location'; locationId: LocationId; position?: string; featureKey?: string }\n | { kind: 'character'; characterId: CharacterId; mode: 'held' }\n | { kind: 'character'; characterId: CharacterId; mode: 'worn'; slot: string; position?: string }\n | { kind: 'item'; itemId: ItemId; position?: string }\n\nexport interface Holding {\n itemId: ItemId\n holder: Holder\n}\n\n/** What an item is, as the world's files write it, before it is put in a session. */\nexport interface ItemDefinition {\n id: string\n name: string\n description: string\n visualIdentity?: VisualIdentityInput\n quantity: number\n unique: boolean\n quality: string\n notable: boolean\n hidden: boolean\n wearable?: string\n container?: { state: ContainerState; openedBy: string[] }\n owner?: string\n /** What it starts with of what the world tracks, by variable key. */\n variables?: Record<string, import('./variable.ts').VariableValue>\n /** Where it starts: one of these. */\n start:\n | { kind: 'location'; location: string; position?: string; feature?: string }\n | { kind: 'held'; character: string }\n | { kind: 'worn'; character: string; slot?: string; position?: string }\n | { kind: 'inside'; item: string; position?: string }\n /** For an exit: which of the item's ways it opens is written on the exit; here only what opens this item, if it is a container. */\n}\n\n/** The things the world says open its exits, by place and the id of the place it leads to. */\nexport interface ExitOpener {\n from: string\n to: string\n items: string[]\n}\n","import type { CharacterId } from './session.ts'\nimport type { VisualIdentityInput } from './visual.ts'\n\nexport type LocationId = number\nexport type ExitId = number\n\n/** A named thing in a place that a story can point at: a desk, a window, a notice board. */\nexport interface LocationFeature {\n /** Unique within its location; how authors and tools refer to it. */\n key: string\n name: string\n description: string\n}\n\n/** At most this many features describe one place, so that a place never overwhelms a prompt. */\nexport const MAX_LOCATION_FEATURES = 30\n\nexport interface Location {\n id: LocationId\n /** The id of the place in the world's files; absent for a place made up in play. */\n sourceId?: string\n name: string\n description: string\n /** The place this one is in (a room in a building, a building in a district). Containment only: it does not say how to get from one to the other. */\n parentId?: LocationId\n features: LocationFeature[]\n createdAt: string\n}\n\nexport type NewLocation = Omit<Location, 'id' | 'createdAt'>\n\n/** What may change about a place once it exists. `parentId: null` takes it out of the place that contains it. */\nexport type LocationPatch = Partial<Pick<Location, 'name' | 'description' | 'features'>> & { parentId?: LocationId | null }\n\n/** Whether people can go through an exit now. */\nexport const EXIT_STATES = ['open', 'locked', 'blocked'] as const\nexport type ExitState = (typeof EXIT_STATES)[number]\n\n/** A way from one place to another, one direction at a time; a door usually has one each way. */\nexport interface Exit {\n id: ExitId\n fromId: LocationId\n toId: LocationId\n /** What it looks like from the place it leaves: \"a narrow stair down to the cellar\". */\n description: string\n /** How long going through takes, when it is known. Authored data; nothing here runs a clock. */\n travelSeconds?: number\n /** Open to use; locked until something unlocks it; blocked until the way is cleared. */\n state: ExitState\n /** Why it is locked or blocked, or what opens it. */\n note: string\n}\n\nexport type NewExit = Omit<Exit, 'id' | 'state' | 'note'> & { state?: ExitState; note?: string }\nexport type ExitPatch = Partial<Omit<Pick<Exit, 'description' | 'travelSeconds' | 'state' | 'note'>, 'travelSeconds'> & { travelSeconds: number | null }>\n\n/** The kinds of thing that can stand in a place. Characters now; items and containers are placed the same way. */\nexport const PLACEABLE_KINDS = ['character'] as const\nexport type PlaceableKind = (typeof PLACEABLE_KINDS)[number]\n\nexport interface Placement {\n kind: PlaceableKind\n entityId: CharacterId\n locationId: LocationId\n /** Where in the place, in words: \"at the bar\", \"by the door\". */\n position: string\n /** The feature of the place it is at or by, when it is one. */\n featureKey?: string\n}\n\nexport interface NewPlacement {\n locationId: LocationId\n position?: string\n featureKey?: string\n}\n\n/** A request to go somewhere. */\nexport interface Move {\n to: LocationId\n position?: string\n featureKey?: string\n /** Skip the exits: the story itself carries the character (carried off, teleported, falls). */\n ignoreExits?: boolean\n}\n\n/** How a move would go: the places passed through, in order, ending at the destination. */\nexport interface MovePlan {\n from?: LocationId\n to: LocationId\n via: LocationId[]\n /** The summed travel time when every exit on the way has one. */\n travelSeconds?: number\n}\n\n/** One way out of a place as the world's files write it. */\nexport interface ExitDefinition {\n /** The id of the place it leads to. */\n to: string\n description: string\n /** Whether there is no way back; otherwise the way back is made too. */\n oneWay: boolean\n backDescription?: string\n travelSeconds?: number\n state: ExitState\n note: string\n /** The ids of the items that open it when it is locked. */\n openedBy?: string[]\n}\n\n/** A place as the world's files write it, before it is put in a session. */\nexport interface LocationDefinition {\n id: string\n name: string\n description: string\n visualIdentity?: VisualIdentityInput\n /** The id of the place it is in. */\n parent?: string\n features: LocationFeature[]\n exits: ExitDefinition[]\n /** What it starts with of what the world tracks, by variable key. */\n variables?: Record<string, import('./variable.ts').VariableValue>\n}\n","import type { CharacterDefinition } from './character.ts'\nimport type { JsonValue } from './json.ts'\nimport type { CharacterStart } from './state.ts'\nimport type { Intent } from './intent.ts'\n\nexport const CHARACTER_CONTROLS = ['player', 'agent'] as const\n\nexport type CharacterId = number\nexport type IntentId = number\n\n/** Who decides what a character does in a session. */\nexport type CharacterControl = typeof CHARACTER_CONTROLS[number]\n\n/**\n * Where a session's world came from. The session keeps no copy of the world,\n * so this is only a reference; further provenance can go in `extra` without a\n * schema change.\n */\nexport interface WorldReference {\n /** The world's stable id, kept in its `world.json`; not a database id. */\n id: string\n name: string\n version?: string\n /** Identifies the exact world content the session was started from. */\n fingerprint?: string\n source?: string\n extra?: Record<string, JsonValue>\n}\n\nexport interface NewSession {\n /** Also the name of the session's folder. */\n id: string\n /** What the player calls the session; usually starts as the world's name. */\n name: string\n world: WorldReference\n}\n\nexport interface SessionMetadata extends NewSession {\n createdAt: string\n /** When the last turn was played; absent for a session that has not been played yet. */\n lastPlayedAt?: string\n /** Turns played so far. */\n turns: number\n}\n\n/** A character in a session: the definition without its start state, under a session-local id. */\nexport interface Character extends Omit<CharacterDefinition, 'id' | 'start'> {\n id: CharacterId\n /** The character's provisional id in the world it came from; absent when created during play. */\n sourceId?: string\n control: CharacterControl\n createdAt: string\n}\n\nexport type NewCharacter = Omit<Character, 'id' | 'createdAt'>\n\n/** What of a character can be edited: who it is, not who controls it. A field left out stays; `null` takes an optional one away. */\nexport interface CharacterPatch {\n name?: string\n aliases?: string[]\n age?: string | null\n gender?: string | null\n pronouns?: string | null\n kind?: Character['kind']\n tier?: Character['tier']\n role?: Character['role']\n summary?: string\n personality?: string\n background?: string\n appearance?: string\n speech?: Character['speech']\n voice?: string | null\n}\n\nexport interface CharacterFilter {\n role?: Character['role']\n tier?: Character['tier']\n kind?: Character['kind']\n control?: CharacterControl\n}\n\n/** A character's current state; it starts as the world's `start` block and changes during play. */\nexport interface CharacterState extends Omit<CharacterStart, 'intents' | 'emotion'> {\n characterId: CharacterId\n /** Increases with every change, for detecting conflicting updates. */\n version: number\n updatedAt: string\n}\n\nexport type NewCharacterState = Omit<CharacterStart, 'intents' | 'emotion'>\n\n/** Fields left out stay as they are. */\nexport interface CharacterStatePatch {\n publicState?: string\n innerState?: string\n activity?: string\n}\n\nexport interface CharacterIntent extends Intent {\n id: IntentId\n characterId: CharacterId\n createdAt: string\n updatedAt: string\n}\n\n/** Fields left out stay as they are; `null` removes the deadline. */\nexport type IntentPatch = Partial<Omit<Intent, 'deadline'>> & { deadline?: string | null }\n\nexport interface IntentFilter {\n status?: Intent['status']\n}\n","import type { CharacterId } from './session.ts'\nimport type { JsonValue } from './json.ts'\nimport type { ItemId } from './item.ts'\nimport type { LocationId } from './location.ts'\n\n/** How a character came to take in an event. */\nexport const PERCEPTION_MODES = ['witnessed', 'heard', 'told', 'inferred'] as const\nexport type PerceptionMode = (typeof PERCEPTION_MODES)[number]\n\n/** How well what a character took in matches what happened; recorded for checking, never shown to the character. */\nexport const ACCURACIES = ['accurate', 'partial', 'mistaken'] as const\nexport type Accuracy = (typeof ACCURACIES)[number]\n\nexport const MEMORY_KINDS = ['belief', 'relationship', 'knowledge'] as const\nexport type MemoryKind = (typeof MEMORY_KINDS)[number]\n\n/** How sure a character is of what it believes, from least to most. */\nexport const MEMORY_CONFIDENCES = ['doubtful', 'likely', 'sure'] as const\nexport type MemoryConfidence = (typeof MEMORY_CONFIDENCES)[number]\nexport const DEFAULT_CONFIDENCE: MemoryConfidence = 'likely'\n\n/** Whether a perception speaks for a belief or against it. */\nexport const EVIDENCE_RELATIONS = ['supports', 'contradicts'] as const\nexport type EvidenceRelation = (typeof EVIDENCE_RELATIONS)[number]\n\nexport const THREAD_STATUSES = ['open', 'resolved'] as const\nexport type ThreadStatus = (typeof THREAD_STATUSES)[number]\n\n/** A digest covers a stretch of recent turns closely; a chapter covers older turns briefly. */\nexport const SUMMARY_LEVELS = ['digest', 'chapter'] as const\nexport type SummaryLevel = (typeof SUMMARY_LEVELS)[number]\n\nexport const IMPORTANCE_MIN = 1\nexport const IMPORTANCE_MAX = 5\n\nexport type EventId = number\nexport type PerceptionId = number\nexport type MemoryId = number\nexport type ThreadId = number\nexport type SummaryId = number\n\n/** Something that objectively happened in the story: the ground truth the rest is derived from. */\nexport interface StoryEvent {\n id: EventId\n turn: number\n round: number\n text: string\n /** From 1 (passing) to 5 (turns the story). */\n importance: number\n tags: string[]\n /** The characters the event is about: who acted, and who it was done to. */\n involves: CharacterId[]\n /** The things it is about: what was taken, opened, found. */\n items: ItemId[]\n /** Where it happened, when that is known. */\n locationId?: LocationId\n /**\n * Events are ground truth and cannot change once sealed, which happens when the records of the rounds they\n * belong to are complete. Until then they are a draft that its writer may still correct.\n */\n sealed: boolean\n createdAt: string\n}\n\nexport type NewStoryEvent = Omit<StoryEvent, 'id' | 'createdAt' | 'sealed' | 'items'> & { items?: ItemId[] }\n\nexport interface StoryEventPatch {\n text?: string\n importance?: number\n tags?: string[]\n involves?: CharacterId[]\n locationId?: LocationId\n items?: ItemId[]\n}\n\nexport interface StoryEventFilter {\n /** Only events that happened in this place. */\n locationId?: LocationId\n turn?: number\n round?: number\n fromTurn?: number\n toTurn?: number\n involving?: CharacterId\n /** Only events about this item. */\n aboutItem?: ItemId\n minImportance?: number\n}\n\n/** What one character took in of an event: its own version, which may be partial or wrong. */\nexport interface Perception {\n id: PerceptionId\n eventId: EventId\n characterId: CharacterId\n mode: PerceptionMode\n /** What the character took in, in full. */\n content: string\n /** The essence of it in a few words, which is what is left of it as it fades. */\n gist: string\n accuracy: Accuracy\n recalls: number\n lastRecalledTurn?: number\n createdAt: string\n}\n\n/** What may change about a perception: a character's version of an event is revised as it learns more or remembers it differently. */\nexport type PerceptionPatch = Partial<Pick<Perception, 'mode' | 'content' | 'gist' | 'accuracy'>>\n\nexport interface NewPerception {\n characterId: CharacterId\n mode: PerceptionMode\n content: string\n gist: string\n accuracy: Accuracy\n}\n\nexport interface PerceivedEvent {\n perception: Perception\n event: StoryEvent\n}\n\n/** What a character has come to believe or know, beyond single events. */\nexport interface CharacterMemory {\n id: MemoryId\n characterId: CharacterId\n kind: MemoryKind\n text: string\n /** The characters it is about. */\n about: CharacterId[]\n importance: number\n /** How sure the character is of it. */\n confidence: MemoryConfidence\n /** The turn it was formed in. */\n turn: number\n recalls: number\n lastRecalledTurn?: number\n createdAt: string\n}\n\nexport type NewCharacterMemory = Omit<CharacterMemory, 'id' | 'createdAt' | 'recalls' | 'lastRecalledTurn' | 'confidence'> & { confidence?: MemoryConfidence }\n\nexport interface CharacterMemoryPatch {\n text?: string\n about?: CharacterId[]\n importance?: number\n confidence?: MemoryConfidence\n}\n\n/** What a character took in that a belief rests on, or that speaks against it. */\nexport interface MemoryEvidence {\n memoryId: MemoryId\n perceptionId: PerceptionId\n relation: EvidenceRelation\n /** The turn the link was made. */\n turn: number\n}\n\n/** Something in the story that is not settled yet: a promise, a mystery, a goal. */\nexport interface StoryThread {\n id: ThreadId\n text: string\n status: ThreadStatus\n openedTurn: number\n resolvedTurn?: number\n}\n\n/** A written account of a stretch of turns, built from the events in it. */\nexport interface Summary {\n id: SummaryId\n level: SummaryLevel\n fromTurn: number\n toTurn: number\n text: string\n createdAt: string\n}\n\nexport type NewSummary = Omit<Summary, 'id' | 'createdAt'>\n\n/** One recorded round whose events and memories have not been written yet. */\nexport interface PendingCommit {\n turn: number\n round: number\n payload: JsonValue\n createdAt: string\n}\n\n/** What a stored text belongs to: what a character took in, what it believes, or what happened (not any character's). */\nexport const RECALL_ITEM_KINDS = ['perception', 'memory', 'event'] as const\nexport type RecallItemKind = (typeof RECALL_ITEM_KINDS)[number]\n\n/** One thing found by a search, by the key the recall uses for it: `p:<id>`, `m:<id>`, `e:<id>`. */\nexport interface RecallHit {\n key: string\n kind: RecallItemKind\n /** The id of the perception, memory or event. */\n refId: number\n /** From 0 (not related) to 1 (the best match of the search); for a lexical search relative to the best hit, for a vector search the cosine similarity. */\n score: number\n}\n\n/** What the vectors of a session were made by. They are only comparable with each other. */\nexport interface EmbeddingIndexInfo {\n model: string\n dimensions: number\n /** How many texts have a vector. */\n embedded: number\n /** How many texts still wait for one. */\n pending: number\n}\n\n/** A text that has no vector yet. */\nexport interface PendingEmbedding {\n /** The id to give back with its vector. */\n id: number\n kind: RecallItemKind\n text: string\n}\n","import type { CharacterId } from './session.ts'\n\nexport type RelationshipId = number\n\n/** How a character stands towards another: a short profile, not a single edge. Each direction is its own profile. */\nexport interface Relationship {\n id: RelationshipId\n /** Whose view it is. */\n fromId: CharacterId\n toId: CharacterId\n /** What the other is to this character, in a word or two: \"sister\", \"rival\", \"landlord\". */\n label: string\n /** The relationship in a sentence or two: how it came about, what it is like now. */\n summary: string\n /** How well it knows the other, from 0 (a stranger) to 1 (intimately). */\n familiarity: number\n /** From -1 (distrusts) to 1 (trusts completely). */\n trust: number\n /** From -1 (dislikes) to 1 (is fond of). */\n affinity: number\n /** How strained it is right now, from 0 to 1. */\n tension: number\n /** The turn it last changed. */\n updatedTurn: number\n createdAt: string\n}\n\nexport interface NewRelationship {\n fromId: CharacterId\n toId: CharacterId\n label: string\n summary?: string\n familiarity?: number\n trust?: number\n affinity?: number\n tension?: number\n}\n\nexport type RelationshipPatch = Partial<Pick<Relationship, 'label' | 'summary' | 'familiarity' | 'trust' | 'affinity' | 'tension'>>\n\n/** A relationship as the world's files write it: from the character whose file it is in, to another by its id in the world. */\nexport interface RelationshipDefinition {\n to: string\n label: string\n summary: string\n familiarity: number\n trust: number\n affinity: number\n tension: number\n}\n\n/** What was made up in play and still has to be fitted into the rest of the world. */\nexport const CONSOLIDATION_KINDS = ['character', 'location', 'item'] as const\nexport type ConsolidationKind = (typeof CONSOLIDATION_KINDS)[number]\n\nexport type ConsolidationItemId = number\n\nexport interface ConsolidationItem {\n id: ConsolidationItemId\n kind: ConsolidationKind\n /** The id of the character or place. */\n subjectId: number\n /** Why it was made, in the words of whoever asked for it. */\n note: string\n createdTurn: number\n resolvedTurn?: number\n /** What was done to fit it in, when it is resolved. */\n resolution?: string\n}\n","import type { CharacterId } from './session.ts'\n\nexport const KNOWLEDGE_KINDS = ['location', 'item', 'exit', 'lore'] as const\nexport type KnowledgeKind = typeof KNOWLEDGE_KINDS[number]\n\n/** That a character knows a place, thing or way exists. Current facts about it come from perception and memory. */\nexport interface EntityKnowledge {\n characterId: CharacterId\n subjectKind: KnowledgeKind\n subjectId: number\n learnedTurn: number\n lastObservedTurn?: number\n}\n\n/** What a character file says the character knows when the story starts. */\nexport interface KnowledgeDefinition {\n locations: string[]\n items: string[]\n exits: { from: string; to: string }[]\n lore?: string[]\n}\n","import type { Intent } from './intent.ts'\nimport type { RelationshipPatch } from './relationship.ts'\n\nexport type FactionId = number\n\nexport interface Faction {\n id: FactionId\n sourceId?: string\n name: string\n aliases: string[]\n summary: string\n description: string\n values: string[]\n structure: string\n createdAt: string\n}\n\nexport type NewFaction = Omit<Faction, 'id' | 'createdAt'>\nexport type FactionPatch = Partial<Pick<Faction, 'name' | 'aliases' | 'summary' | 'description' | 'values' | 'structure'>>\n\nexport interface FactionState {\n factionId: FactionId\n publicState: string\n innerState: string\n version: number\n updatedAt: string\n}\n\nexport interface NewFactionState {\n publicState?: string\n innerState?: string\n}\n\nexport type FactionStatePatch = Partial<NewFactionState>\n\nexport const MEMBERSHIP_STATUSES = ['active', 'inactive', 'former'] as const\nexport type MembershipStatus = typeof MEMBERSHIP_STATUSES[number]\n\nexport interface FactionMembership {\n factionId: FactionId\n characterId: number\n role: string\n rank: string\n status: MembershipStatus\n public: boolean\n commitment: number\n joinedTurn: number\n leftTurn?: number\n}\n\nexport type MembershipPatch = Partial<Pick<FactionMembership, 'role' | 'rank' | 'status' | 'public' | 'commitment' | 'leftTurn'>>\n\nexport type SocialSubjectKind = 'character' | 'faction'\n\nexport interface FactionRelationship {\n id: number\n fromKind: SocialSubjectKind\n fromId: number\n toKind: SocialSubjectKind\n toId: number\n label: string\n summary: string\n familiarity: number\n trust: number\n affinity: number\n tension: number\n updatedTurn: number\n createdAt: string\n}\n\nexport interface FactionIntent extends Intent {\n id: number\n factionId: FactionId\n createdAt: string\n updatedAt: string\n}\n\nexport interface FactionRelationshipDefinition extends RelationshipPatch {\n to: { kind: SocialSubjectKind; id: string }\n label: string\n}\n\nexport interface FactionMembershipDefinition {\n character: string\n role: string\n rank: string\n status: MembershipStatus\n public: boolean\n commitment: number\n}\n\nexport interface FactionDefinition {\n id: string\n name: string\n aliases: string[]\n summary: string\n description: string\n values: string[]\n structure: string\n start: {\n publicState: string\n innerState: string\n goals: Intent[]\n }\n members: FactionMembershipDefinition[]\n relationships: FactionRelationshipDefinition[]\n}\n","/**\n * How the story's time passes: `simulated` moves only when the story does (the game master says how\n * long things take and may skip ahead), `real` follows the wall clock.\n */\nexport const CLOCK_MODES = ['simulated', 'real'] as const\nexport type ClockMode = (typeof CLOCK_MODES)[number]\n\n/** The story's clock: the instant it is in the story, in milliseconds since the Unix epoch (UTC). */\nexport interface ClockState {\n mode: ClockMode\n now: number\n}\n\n/** Why the story's time moved. */\nexport const TIME_CHANGE_KINDS = ['start', 'elapsed', 'real', 'skip', 'resync'] as const\nexport type TimeChangeKind = (typeof TIME_CHANGE_KINDS)[number]\n\n/** One step of the story's time. `round` is 0 for what happens outside a round. */\nexport interface TimeChange {\n id: number\n turn: number\n round: number\n kind: TimeChangeKind\n from: number\n to: number\n reason: string\n}\n\nexport interface TimeChangeFilter {\n turn?: number\n round?: number\n fromTurn?: number\n toTurn?: number\n kind?: TimeChangeKind\n}\n","import type { CharacterId } from './session.ts'\nimport type { LocationId } from './location.ts'\n\n/** A recurring stretch of the day in which a character is occupied with something, in a place. */\nexport interface RoutineWindow {\n /** The days of the week it applies on, 0 for Sunday; every day when empty. A window past midnight belongs to the day it starts on. */\n days: number[]\n /**\n * Other days it applies on or does not (`dec`, `12-24`, `season:winter`, `nth:mon:1`, `holiday:<id>`, a `!` before one for a day it does not apply\n * on): it applies on a day that is among `days` and that these allow. Every day when empty or left out.\n */\n on?: string[]\n /** The minute of the day it starts, 0 to 1439. */\n start: number\n /** The minute it ends (exclusive); before `start` it ends the next day. Equal to `start` is not a window. */\n end: number\n activity: string\n locationId?: LocationId\n featureKey?: string\n /** Where in the place, in words. */\n position?: string\n /** Whether the character will drop it to join something that comes up; a shift at work may not be. */\n interruptible: boolean\n}\n\nexport interface StoredRoutineWindow extends RoutineWindow {\n on: string[]\n id: number\n characterId: CharacterId\n}\n\n/** A routine window as a world's files write it. */\nexport interface RoutineDefinition {\n /** Three-letter days (`mon` to `sun`); every day when left out. */\n days: string[]\n /** Other days it applies on or does not, as for {@link RoutineWindow.on}. */\n on?: string[]\n /** `HH:MM`. */\n from: string\n to: string\n activity: string\n /** The id of a place in the world. */\n location?: string\n feature?: string\n position?: string\n interruptible: boolean\n}\n\nexport const WEEKDAY_NAMES = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] as const\n\nexport type EngagementId = number\n\nexport const ENGAGEMENT_STATUSES = ['pending', 'kept', 'missed', 'cancelled'] as const\nexport type EngagementStatus = (typeof ENGAGEMENT_STATUSES)[number]\n\n/** Something dated that characters have committed to: a meeting, an errand, an event they are to attend. */\nexport interface Engagement {\n id: EngagementId\n title: string\n /** When it is due, in UTC milliseconds. */\n at: number\n /** When it is over, when that is not simply soon after `at`. */\n until?: number\n locationId?: LocationId\n participants: CharacterId[]\n status: EngagementStatus\n note: string\n createdTurn: number\n updatedTurn: number\n}\n\nexport interface NewEngagement {\n title: string\n at: number\n until?: number\n locationId?: LocationId\n participants: CharacterId[]\n note?: string\n turn: number\n}\n\nexport interface EngagementPatch {\n title?: string\n at?: number\n until?: number\n locationId?: LocationId\n participants?: CharacterId[]\n status?: EngagementStatus\n note?: string\n turn: number\n}\n\nexport interface EngagementFilter {\n status?: EngagementStatus\n participant?: CharacterId\n /** Only those due at or after this instant. */\n from?: number\n /** Only those due before this instant. */\n to?: number\n}\n","/** What a variable holds: a number within bounds, a yes or no, or one of a list of words. */\nexport const VARIABLE_KINDS = ['number', 'flag', 'choice'] as const\nexport type VariableKind = (typeof VARIABLE_KINDS)[number]\n\n/** What a variable is about: each character, item or place has its own value; `world` has one value for the whole story. */\nexport const VARIABLE_SUBJECTS = ['character', 'item', 'location', 'world'] as const\nexport type VariableSubject = (typeof VARIABLE_SUBJECTS)[number]\n\n/**\n * Who can tell what the value is. `public`: anyone present (what shows). `private`: the character it belongs to, and the\n * game master (what it feels or knows of itself). `hidden`: only the game master and the record keeper.\n */\nexport const VARIABLE_VISIBILITIES = ['public', 'private', 'hidden'] as const\nexport type VariableVisibility = (typeof VARIABLE_VISIBILITIES)[number]\n\nexport type VariableValue = number | boolean | string\n\n/** The word for a number up to a bound: values up to `upTo` (and above the previous band) are called `label`. */\nexport interface VariableBand {\n upTo: number\n label: string\n}\n\n/** A kind of thing the story keeps track of, declared by a world, by the story, or built in. */\nexport interface VariableDefinition {\n /** Lowercase letters, digits and underscores, starting with a letter. */\n key: string\n name: string\n /** What it measures or means, for the models that read and change it. */\n description: string\n kind: VariableKind\n subject: VariableSubject\n /** The subjects it applies to, by their keys; every subject of its kind when empty. */\n only: string[]\n /** The bounds of a number. */\n min?: number\n max?: number\n /** Whether a number is a whole number. */\n integer: boolean\n /** The words a choice is one of. */\n options: string[]\n /** What it is for a subject that has no value of its own yet. */\n default: VariableValue\n /** Whether each value has a baseline beside the current one: the slow-moving temperament the current value is measured from (feelings). */\n baseline: boolean\n visibility: VariableVisibility\n /** Words for ranges of a number, lowest first; the last one covers whatever is above. */\n bands: VariableBand[]\n /** Whether it is always told, even at its default; otherwise only once it differs from it. */\n always: boolean\n /** Built in: it cannot be removed, and what it is cannot be changed. */\n builtin: boolean\n}\n\n/** A variable as the world's files write it: what is left out takes its default. */\nexport type VariableDefinitionInput = Pick<VariableDefinition, 'key' | 'name' | 'kind' | 'subject'> & Partial<Omit<VariableDefinition, 'key' | 'name' | 'kind' | 'subject' | 'builtin'>>\n\nexport interface StoredVariable {\n variable: string\n subject: VariableSubject\n /** 0 for the world. */\n subjectId: number\n value: VariableValue\n baseline?: VariableValue\n updatedTurn: number\n}\n\nexport const VARIABLE_KEY = /^[a-z][a-z0-9_]{0,39}$/\n/** At most this many variables in a story, so that what is tracked stays something a model can hold. */\nexport const MAX_VARIABLES = 60\n\n/** The feelings every character has: built in, from -1 to 1, with a temperament beside the current value. */\nexport const EMOTION_VARIABLES: readonly VariableDefinition[] = [\n { key: 'valence', name: 'Valence', description: 'How pleasant its mood is: -1 very unpleasant, 0 neutral, 1 very pleasant.', labels: [{ upTo: -0.6, label: 'miserable' }, { upTo: -0.25, label: 'unhappy' }, { upTo: 0.25, label: 'even' }, { upTo: 0.6, label: 'pleased' }, { upTo: 1, label: 'delighted' }] },\n { key: 'arousal', name: 'Arousal', description: 'How worked up it is: -1 drowsy, 0 ordinary, 1 frantic.', labels: [{ upTo: -0.6, label: 'drowsy' }, { upTo: -0.25, label: 'calm' }, { upTo: 0.25, label: 'alert' }, { upTo: 0.6, label: 'keyed up' }, { upTo: 1, label: 'frantic' }] },\n { key: 'dominance', name: 'Dominance', description: 'How much in control it feels: -1 helpless, 0 even, 1 commanding.', labels: [{ upTo: -0.6, label: 'helpless' }, { upTo: -0.25, label: 'uneasy' }, { upTo: 0.25, label: 'steady' }, { upTo: 0.6, label: 'confident' }, { upTo: 1, label: 'commanding' }] },\n].map(({ labels, ...rest }): VariableDefinition => ({\n ...rest, kind: 'number', subject: 'character', only: [], min: -1, max: 1, integer: false, options: [], default: 0, baseline: true, visibility: 'private',\n bands: labels.map(band => ({ upTo: band.upTo, label: band.label })), always: false, builtin: true,\n}))\n","import type { VariableValue } from './variable.ts'\n\nexport type TriggerId = number\n\nexport const COMPARISONS = ['eq', 'ne', 'lt', 'le', 'gt', 'ge'] as const\nexport type Comparison = (typeof COMPARISONS)[number]\n\n/**\n * When something happens, decided in code from what the story has recorded; only `judged` is a model's reading of the story, kept as a verdict that the code reads.\n * Keys name characters, places, items and variables as the world's files and the tools do. Times are local to\n * the story's zone: `YYYY-MM-DDTHH:MM`, and `HH:MM` for a time of day.\n */\nexport type TriggerCondition =\n /** True from `from` on, until `to`; or while the time of day is in `window` (past midnight when it ends before it starts), on `days` (`mon` to `sun`) when given and on the days `on` allows (months, dates, seasons, holidays of the world's calendar). */\n | { type: 'time'; from?: string; to?: string; window?: { from: string; to: string }; days?: string[]; on?: string[] }\n /** A character is in a place, at a feature of it when given. */\n | { type: 'place'; character: string; location: string; feature?: string }\n /** A variable compares to a value; `subject` is the key of the character, item or place it is about, none for a world variable. */\n | { type: 'variable'; variable: string; subject?: string; op: Comparison; value: VariableValue }\n /** An item is held by a character, or lies in a place (also inside something there). */\n | { type: 'item'; item: string; heldBy?: string; at?: string }\n /** An event with this tag was recorded. */\n | { type: 'event'; tag: string }\n /** Another trigger has fired. */\n | { type: 'fired'; trigger: string }\n /** A statement about the story that a model judges true or false after each turn, for what no record can say (\"the mayor has lost the town's trust\"); false until judged. */\n | { type: 'judged'; text: string }\n | { type: 'all'; conditions: TriggerCondition[] }\n | { type: 'any'; conditions: TriggerCondition[] }\n | { type: 'not'; condition: TriggerCondition }\n\n/** Who a cue is for, or who knows of something coming: everyone, named characters, or whoever is in a place at that moment. */\nexport type TriggerAudience = 'everyone' | { characters: string[] } | { place: string }\n\n/**\n * What is known before a trigger fires, and by whom: a scheduled event that is no secret (an exam, a ball, a deadline).\n * Without it a trigger is a secret until it fires.\n */\nexport interface TriggerAnnouncement {\n audience: TriggerAudience\n /** What is known beforehand: the public side of it, never what the effects do. */\n text: string\n /** When it becomes known, a local time; known from the start when left out. */\n from?: string\n /** When it is to happen, a local time, as told with the announcement; the time the condition waits for when it is a plain one, if left out. */\n at?: string\n}\n\n/** In a cue, the key of the character it is said to: in a `while` condition and in the words of the cue. */\nexport const SELF = '@self'\n\n/** What happens when a trigger fires. */\nexport type TriggerEffect =\n /** A checked change of the story's records, in the format of an edit (events, variable changes, exit and item changes, moves, goals, engagements). */\n | { type: 'edit'; edit: Record<string, unknown> }\n /**\n * Something the game master is told to weave into the story, until it says it did or a few turns pass. It is written when it is told, not when\n * the trigger fired: `text` may name things the story has by `{kind:key}` and so is said as the story stands then (see `TEMPLATE_KINDS`), and\n * `while` is a condition that must still hold then, or the beat is withdrawn instead.\n */\n | { type: 'beat'; text: string; while?: TriggerCondition }\n /** Something the audience notices, said to each of them the next time they act; written, and withdrawn, as a beat is, for each of them (`SELF` is the one it is said to). */\n | { type: 'cue'; audience: TriggerAudience; text: string; while?: TriggerCondition }\n\nexport const TRIGGER_STATUSES = ['dormant', 'fired', 'failed', 'expired'] as const\nexport type TriggerStatus = (typeof TRIGGER_STATUSES)[number]\n\n/** A trigger as a world's files, or the world author, write it. */\nexport interface TriggerDefinition {\n key: string\n name: string\n condition: TriggerCondition\n effects: TriggerEffect[]\n /** Whether it can fire again after it fired and its condition went false and true again. */\n repeat: boolean\n /** With `repeat`, the least story time between two firings, in seconds. */\n cooldownSeconds?: number\n /** The chance, 0 to 1, that a rising condition fires; a failed roll uses that rise up. */\n chance?: number\n /** The higher goes first when several are due at once. */\n priority: number\n /** After this local time it never fires. */\n expires?: string\n /** Known beforehand by whom, and what; without it, nobody knows until it fires. */\n announce?: TriggerAnnouncement\n}\n\nexport interface Trigger extends TriggerDefinition {\n id: TriggerId\n status: TriggerStatus\n fireCount: number\n lastFiredMs?: number\n /** What the condition was when it was last looked at, to see it rise. */\n lastResult: boolean\n /** Why it failed, when it did. */\n problem?: string\n origin: 'world' | 'story'\n createdTurn: number\n}\n\nexport const TRIGGER_NOTE_KINDS = ['beat', 'cue'] as const\nexport type TriggerNoteKind = (typeof TRIGGER_NOTE_KINDS)[number]\n\n/** What a fired trigger leaves to be told: a beat for the game master, a cue for characters. */\nexport interface TriggerNote {\n id: number\n triggerId: TriggerId\n kind: TriggerNoteKind\n text: string\n /** The characters a cue is for. */\n characterIds: number[]\n turn: number\n status: 'pending' | 'done' | 'lapsed'\n}\n\nexport interface NewTriggerNote {\n triggerId: TriggerId\n kind: TriggerNoteKind\n text: string\n characterIds?: number[]\n turn: number\n}\n\n/** At most this many triggers in a story. */\nexport const MAX_TRIGGERS = 200\n","export type DiceCheckId = number\nexport type DiceRollId = number\n\n/** What a band of a check makes of an attempt; the same three results a round's outcome has. */\nexport const DICE_RESULTS = ['succeeded', 'partial', 'failed'] as const\nexport type DiceResult = (typeof DICE_RESULTS)[number]\n\n/** How a roll is read: by its total, or by how many of the dice came up high enough. */\nexport const DICE_READINGS = ['total', 'successes'] as const\nexport type DiceReading = (typeof DICE_READINGS)[number]\n\n/**\n * What the value is compared with: `absolute` reads the value itself, `over` the amount by which it beats the target\n * (a difficulty to meet or exceed), `under` the amount by which it stays below the target (a skill to roll under).\n */\nexport const DICE_COMPARISONS = ['absolute', 'over', 'under'] as const\nexport type DiceComparison = (typeof DICE_COMPARISONS)[number]\n\n/** One range of values and what it means; a range left open at an end runs on for ever. */\nexport interface DiceBand {\n min?: number\n max?: number\n /** What it is called in play (\"critical failure\", \"success at a cost\"). */\n label: string\n result: DiceResult\n /** A result that is more than the plain one: a critical. */\n critical?: boolean\n}\n\n/** A way of settling an attempt, as a world defines it; the dice and the reading of what they show are the world's, not the model's. */\nexport interface DiceCheckDefinition {\n key: string\n name: string\n /** When the game master uses this check, in the author's words. */\n use: string\n /** Dice notation: `1d20`, `2d6`, `4d6kh3`, `d100`. */\n dice: string\n reading?: DiceReading\n /** With the reading `successes`: a die counts when it shows at least this. */\n hit?: number\n compare?: DiceComparison\n /** The key of a variable of the acting character that is added to the total. */\n modifier?: string\n bands: DiceBand[]\n}\n\nexport interface DiceCheck extends DiceCheckDefinition {\n id: DiceCheckId\n}\n\n/** What the dice and the reading of them gave, once a roll is made. */\nexport interface DiceReadout {\n label: string\n result: DiceResult\n critical: boolean\n}\n\nexport interface NewDiceRoll {\n turn: number\n /** The check that was rolled, none for a plain roll. */\n check?: string\n expression: string\n /** Every die rolled, in order. */\n faces: number[]\n /** The dice that count, after any are dropped or only the best are kept. */\n kept: number[]\n /** What is added to the dice: constants of the expression, the character's modifier, a bonus. */\n modifier: number\n target?: number\n /** What the dice and the modifier add up to, or the number of dice that hit. */\n total: number\n /** What the bands were compared with: the total, or its distance from the target. */\n value: number\n readout?: DiceReadout\n reason: string\n /** The character the roll was for, by key. */\n character?: string\n /** Who asked for it. */\n by: 'agent' | 'player'\n}\n\nexport interface DiceRoll extends NewDiceRoll {\n id: DiceRollId\n at: string\n}\n\n/** Rolls and checks are limited so that a story cannot grow without bound. */\nexport const MAX_DICE_CHECKS = 40\nexport const MAX_DICE_BANDS = 20\nexport const MAX_DICE_PER_ROLL = 100\nexport const MAX_DICE_SIDES = 1000\nexport const MAX_DICE_TERMS = 8\n","export const VISUAL_SUBJECT_KINDS = ['character', 'location', 'item'] as const\nexport type VisualSubjectKind = typeof VISUAL_SUBJECT_KINDS[number]\n\n/** Stable, provider-neutral visual facts that every image of an entity should preserve. */\nexport interface VisualIdentityInput {\n description: string\n tags: string[]\n negativeTags: string[]\n /** A globally unique identity when the entity has one; world-local ids remain valid without it. */\n globalId?: string\n}\n\n/** A visual identity attached to one entity of a session. */\nexport interface VisualIdentity extends VisualIdentityInput {\n subjectKind: VisualSubjectKind\n subjectId: number\n /** Increases when the canonical identity changes, so an image can name what it was made from. */\n version: number\n updatedAt: string\n}\n\nexport type VisualIdentityPatch = Partial<VisualIdentityInput>\n","export type LoreId = number\n\nexport const LORE_KINDS = ['history', 'culture', 'religion', 'politics', 'geography', 'science', 'custom', 'legend', 'other'] as const\nexport type LoreKind = typeof LORE_KINDS[number]\n\nexport const LORE_SUBJECT_KINDS = ['character', 'faction', 'location', 'item', 'lore'] as const\nexport type LoreSubjectKind = typeof LORE_SUBJECT_KINDS[number]\n\nexport interface LoreSubject {\n kind: LoreSubjectKind\n id: number\n}\n\nexport interface Lore {\n id: LoreId\n sourceId?: string\n title: string\n kind: LoreKind\n summary: string\n body: string\n startsAt?: number\n endsAt?: number\n subjects: LoreSubject[]\n related: LoreId[]\n sources: string[]\n createdAt: string\n}\n\nexport type NewLore = Omit<Lore, 'id' | 'createdAt'>\nexport type LorePatch = Partial<Pick<Lore, 'title' | 'kind' | 'summary' | 'body' | 'subjects' | 'related' | 'sources'>> & { startsAt?: number | null; endsAt?: number | null }\n\nexport interface LoreSubjectDefinition {\n kind: LoreSubjectKind\n id: string\n}\n\n/** One independently addressable piece of canonical world lore. */\nexport interface LoreDefinition {\n id: string\n title: string\n kind: LoreKind\n summary: string\n body: string\n startsAt?: number\n endsAt?: number\n subjects: LoreSubjectDefinition[]\n related: string[]\n sources: string[]\n}\n","export const PLOT_STATUSES = ['dormant', 'available', 'engaged', 'cooling', 'resolved', 'abandoned'] as const\nexport type PlotStatus = (typeof PLOT_STATUSES)[number]\n\nexport const PLOT_NUDGE_MODES = ['opportunity', 'reminder', 'character', 'consequence', 'escalation', 'breathing_room'] as const\nexport type PlotNudgeMode = (typeof PLOT_NUDGE_MODES)[number]\n\nexport interface PlotDevelopment {\n id: string\n text: string\n mode: PlotNudgeMode\n prerequisites: string[]\n guidance: string\n avoid: string[]\n}\n\nexport interface PlotDefinition {\n id: string\n name: string\n premise: string\n themes: string[]\n hooks: PlotDevelopment[]\n developments: PlotDevelopment[]\n stakes: string[]\n resolutions: string[]\n participants: string[]\n start: PlotStatus\n pacing: {\n quietTurns: number\n cooldownTurns: number\n cooldownDays: number\n }\n}\n\nexport interface PlotProgress {\n plot: PlotDefinition\n status: PlotStatus\n introduced: string[]\n rejected: string[]\n lastNudgeTurn: number\n lastNudgeAt?: number\n}\n","/** The Chinese of the texts built in code, by the English that stands in the code. A `{name}` is filled in and must stand in both. */\nconst ZH: Readonly<Record<string, string>> = {\n // words a text is built from\n ', ': ',', '; ': ';', ': ': ':', '.': '。', ' and ': '和',\n 'doubtful': '存疑', 'likely': '较有把握', 'sure': '确信',\n 'open': '畅通', 'locked': '已上锁', 'blocked': '被堵住',\n 'night': '夜里', 'morning': '上午', 'afternoon': '下午', 'evening': '傍晚',\n 'spring': '春季', 'summer': '夏季', 'autumn': '秋季', 'winter': '冬季',\n 'today is {holidays}': '今天是{holidays}',\n 'Summary': '概述', 'Personality': '性格', 'Background': '背景', 'Appearance': '外貌', 'How you speak': '说话方式',\n\n // the character's own description\n 'You are {name}.': '你是{name}。',\n 'You are also called {names}.': '你也被称作{names}。',\n 'age: {value}': '年龄:{value}', 'gender: {value}': '性别:{value}', 'pronouns: {value}': '代词:{value}',\n\n // the dice the game master rolls\n '- {key} ({name}): {use}': '- {key}({name}):{use}',\n 'Rolls {dice}.': '掷 {dice}。',\n 'Give a target: the difficulty, the number to meet or beat; set it by how hard the attempt is.': '需给出 target:难度,即要达到或超过的数字;按这次尝试的难易来定。',\n 'Give a target: the number to stay under; set it by how hard the attempt is.': '需给出 target:要低于的数字;按这次尝试的难易来定。',\n 'It adds the character\\'s {variable}.': '它会加上该角色的 {variable}。',\n 'Counts the dice that show {hit} or more.': '统计显示 {hit} 或更高的骰子数。',\n 'the player\\'s roll': '玩家的掷骰',\n 'The player rolled {dice} ({reason}) and got {total}: dice {faces}. This is a fact, decided by the dice: take it into account when you judge the attempt and decide what happens.': '玩家掷了 {dice}({reason}),得到 {total}:骰面 {faces}。这是由骰子决定的事实:在你判断这次尝试、决定发生什么时把它考虑进去。',\n 'The checks of this story:': '本故事的检定:',\n 'No checks are defined: use roll_dice only.': '没有定义检定:只用 roll_dice。',\n\n // the scene a character is told\n 'Situation:': '当前情形:',\n 'Now: {time}.': '现在是:{time}。',\n 'Where you are:': '你所在之处:',\n 'Present:': '在场的人:',\n ' (you)': '(你)',\n 'What you know is coming:': '你知道即将发生的事:',\n 'Just now you notice:': '此刻你注意到:',\n 'How you are (what you can tell of yourself):': '你的状态(你自己能感觉到的):',\n 'What you can tell of the others here:': '你能看出在场其他人的情况:',\n 'What you have on you:': '你身上带着:',\n 'Things here: ': '这里有:', 'Ways out: ': '出路:', 'Lying about: ': '散落在周围的:',\n 'hidden': '隐蔽', ' holding {things}': ',里面有{things}', '; and {count} more': ';另有{count}项', 'at {feature}': '在{feature}',\n '; and {count} more you can recall if needed': ';另有{count}项,需要时你可以回想起来',\n 'What you know exists (this does not tell you where it is now or what state it is in):': '你知道存在的事物(这并不说明它现在在哪里、处于什么状态):',\n 'People: ': '人物:', 'Factions: ': '组织:', 'Places: ': '地点:', 'Routes: ': '路径:', 'Things: ': '物品:',\n\n // a character's day\n 'Your day and what you are after (plans, not orders: keep them, put them off or drop them as the moment and your character suggest):': '你的日程与你想达成的事(只是计划,不是命令:依当下情形和你的性格,可以照做、推迟或放弃):',\n 'Your day, now: {activity}{place}, until {until}{note}.': '你此刻的日程:{activity}{place},持续到{until}{note}。',\n 'Your day, next: {activity}{place}, from {from}.': '你接下来的日程:{activity}{place},{from}开始。',\n ' at {place}': ',在{place}',\n ' (not something you would drop lightly)': '(你不会轻易放下)',\n ', with {names}': ',与{names}一起',\n 'You were to: {title}{place}{with}, at {at}, which has passed and is still open.': '你本应:{title}{place}{with},时间是{at},已经过了,事情仍未了结。',\n 'You are due to: {title}{place}{with}, at {at}.': '你约定要:{title}{place}{with},时间是{at}。',\n 'What you are after:': '你想达成的事:',\n ', by {deadline}, which has passed': ',限期{deadline},已过',\n ', by {deadline}': ',限期{deadline}',\n ' Next: {plan}.': ' 下一步:{plan}。',\n\n // how a character stands with people and organisations\n 'How you stand with people who bear on this moment (your own view, not objective fact):': '你与和此刻相关的人的关系(是你自己的看法,不是客观事实):',\n ' (here)': '(在场)', ' (not here)': '(不在场)',\n 'knows them well': '很了解对方', 'barely knows them': '几乎不了解对方', 'trusts them': '信任对方', 'distrusts them': '不信任对方',\n 'is fond of them': '喜欢对方', 'dislikes them': '不喜欢对方', 'things are strained between them': '彼此关系紧张',\n 'Your affiliations (their goals are pressures and commitments, not commands):': '你的所属组织(其目标是压力和承诺,不是命令):',\n 'member': '成员',\n ' Goals: {goals}.': ' 目标:{goals}。',\n '- {name}: {position}; {status}; commitment {commitment}.': '- {name}:{position};{status};投入程度 {commitment}。',\n ' Your view: {attitude}.': ' 你的看法:{attitude}。',\n\n // memory\n 'What you remember that bears on this (only what you took in yourself; do not claim to remember more, and be unsure of what is fuzzy):': '你记得的、与此相关的事(只限你自己亲身经历的;不要声称记得更多,模糊的地方要保持不确定):',\n 'What you remember that bears on this: nothing comes to mind.': '你记得的、与此相关的事:想不起任何事。',\n 'some time ago': '一段时间以前', 'just now': '刚才',\n '1 day ago': '1天前', '{amount} days ago': '{amount}天前',\n '1 hour ago': '1小时前', '{amount} hours ago': '{amount}小时前',\n '1 minute ago': '1分钟前', '{amount} minutes ago': '{amount}分钟前',\n 'the details are fuzzy': '细节已经模糊', 'you barely remember': '你几乎记不清了',\n 'you are sure of it': '你对此确信无疑', 'you doubt it': '你对此存疑',\n 'something you have seen since speaks against it': '此后你所见所闻有与之相悖的地方',\n 'it comes to mind with the rest': '它和其余的事一起浮现在脑海',\n 'Earlier in this scene, before this moment:': '这一幕此刻之前发生的事:',\n 'What just happened, and what you are reacting to:': '刚才发生的事,以及你在回应的是什么:',\n '- {name} intended: {intent} ({result}) {summary}': '- {name}打算:{intent}({result}){summary}',\n '- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}': '- {name}说了“{utterance}”,并打算:{intent}({result}){summary}',\n 'Your earlier intent did not work out: {intent}\\nYou are trying again, knowing the above. Decide again what you do now.': '你先前的打算没有成功:{intent}\\n你带着上面这些再试一次。重新决定你现在做什么。',\n\n // reflection\n 'Character: {name}{summary}': '角色:{name}{summary}',\n 'What they believe now:': '他们现在的看法:',\n '(nothing yet)': '(暂时没有)',\n 'What they have taken in since:': '他们此后经历的事:',\n 'Sort their memory.': '请整理他们的记忆。',\n 'not acceptable: {problems}': '不可接受:{problems}',\n '{kind}, importance {importance}, {confidence}{about}{dispute}': '{kind},重要性 {importance},{confidence}{about}{dispute}',\n ', about {names}': ',关于{names}',\n ', something taken in since speaks against it': ',此后经历的事与之相悖',\n 'add: at most {max} new beliefs in one pass; merge or choose': 'add:一次最多 {max} 条新看法;请合并或取舍',\n 'at most {max} changes in one pass': '一次最多 {max} 处修改',\n '{where}: there is no thing it took in numbered {id}': '{where}:没有编号为 {id} 的经历',\n '{where}: confidence is one of {options}': '{where}:confidence 须为 {options} 之一',\n '{where}: unknown kind \"{kind}\"': '{where}:未知的 kind “{kind}”',\n '{where}: say what it believes': '{where}:请写出它相信什么',\n '{where}: at most {max} characters; say it shorter': '{where}:最多 {max} 个字符;请写得更短',\n '{where}: importance runs from {min} to {max}': '{where}:importance 取值为 {min} 到 {max}',\n '{where}: there is no belief numbered {id}': '{where}:没有编号为 {id} 的看法',\n '{where}: one passing moment is not yet a belief; rest it on things from at least two different turns, or on one event that turned the story': '{where}:一个转瞬即逝的瞬间还不是看法;请以至少两个不同回合的经历为依据,或以一件扭转了故事的事件为依据',\n '{where}: to be sure of something it must rest on things from at least two different turns': '{where}:要对某事确信,必须以至少两个不同回合的经历为依据',\n '{where}: \"{name}\" is not a character; name them as they are named': '{where}:“{name}”不是角色;请使用他们的名字',\n '{where}: belief {id} is already changed in this pass': '{where}:看法 {id} 在这一轮中已经修改过',\n '{where}: say what it took in since that bears on it': '{where}:请写出此后与之相关的经历',\n '{where}: thing {id} came before the belief was formed; cite what came after': '{where}:经历 {id} 发生在看法形成之前;请引用之后发生的事',\n '{where}: say what changes': '{where}:请写出有何改变',\n '{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is': '{where}:文字不能为空,且最多 {max} 个字符;想保持信念原样就不要写这一项',\n '{where}: the confidence, the importance and the numbers are fields of their own, not part of the text': '{where}:把握程度、重要性和编号是各自独立的字段,不属于文字',\n '{where}: name what speaks against the belief in contradicted_by': '{where}:在 contradicted_by 里写出与该信念相悖的内容的编号',\n '{where}: a belief that something contradicts must be doubted: lower its confidence': '{where}:被事实相悖的看法必须存疑:请降低其 confidence',\n '{where}: to doubt a belief, name what contradicts it in contradicted_by': '{where}:要对看法存疑,请在 contradicted_by 中写明与之相悖的经历',\n '{where}: merge into a belief that stays': '{where}:请合并到保留的看法中',\n\n // the game master's scene notice\n 'Time: {time}.': '时间:{time}。',\n \"The story's time moves only as you say: each round takes what you give it (elapsed_seconds in resolve_round, or the default), and advance_time skips ahead.\": '故事的时间只按你说的推进:每一轮耗时由你给定(resolve_round 的 elapsed_seconds,或取默认值),advance_time 可以跳过一段时间。',\n 'The player was away for {duration} of real time and the story went on meanwhile: characters have been about their own business, so do not assume anyone is where or as the player left them unless the records say so.': '玩家离开了{duration}的真实时间,其间故事仍在继续:角色们各忙各的事,除非记录另有说明,不要假定任何人还在玩家离开时的位置或状态。',\n \"The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.\": '故事时间跟随真实时钟:无法跳过,每一轮耗时就是它实际花费的时间。',\n 'By their routines since you last looked: {moves}.': '按各自的日程,自你上次查看以来:{moves}。',\n '{name} went to {place} ({activity})': '{name}去了{place}({activity})',\n \"With the player's character, and their days: {days}. The characters decide for themselves whether to keep to their day; the moment may keep them.\": '与玩家角色在一起的人及其日程:{days}。是否照日程行事由角色自己决定;当下的情形也可能拖住他们。',\n ', at {place}': ',在{place}',\n '\"{title}\" ({with}{place}) was due {when} and is still open': '“{title}”({with}{place})原定{when},仍未了结',\n '\"{title}\" ({with}{place}) is due {when}': '“{title}”({with}{place})定于{when}',\n 'Commitments due soon or overdue: {entries}.': '即将到期或已逾期的约定:{entries}。',\n 'named in the move': '被这一步行动点到',\n 'in the scene': '在场',\n 'own goal: {goal}': '自身目标:{goal}',\n 'faction pressure: {goal}': '组织压力:{goal}',\n 'high tension toward the player': '对玩家高度紧张',\n 'distrusts the player': '不信任玩家',\n 'cares about the player': '在意玩家',\n 'dislikes the player': '不喜欢玩家',\n 'Likely characters to activate, in priority order (advice only; activate only whoever the moment actually reaches):': '可能需要启动的角色,按优先级排列(仅供参考;只启动当下真正牵涉到的人):',\n 'socially implicated': '社交上被牵涉',\n \"The player's character is in {place}\": '玩家角色在{place}',\n 'Characters here:': '在这里的角色:',\n 'Characters elsewhere (they perceive nothing here unless the moment reaches them):': '在别处的角色(除非当下波及他们,否则感知不到这里的事):',\n '{member} - in {place} ({key})': '{member} - 在{place}({key})',\n 'Characters with no place (not part of this scene; they cannot be asked to act):': '没有所在地点的角色(不属于这一幕;不能让他们行动):',\n 'the player\\'s character, \"{key}\"': '玩家角色,“{key}”',\n 'acts through \"{key}\"': '通过“{key}”行动',\n 'Currently: {state}': '目前:{state}',\n 'Scene before turn {turn}:': '第 {turn} 回合之前的场景:',\n 'What characters have on them:': '角色们身上带着:',\n 'The world acted since the last turn, by itself:': '自上一回合以来,世界自行发生的事:',\n 'Known beforehand, still to come (who knows of it; it will happen by itself when its time comes):': '事先已知、尚未发生的事(谁知道;时候到了会自行发生):',\n '[known to {who}]': '[知情者:{who}]',\n 'Weave these into the story when it fits, then say you did with addressed in narrate (each stays for a few turns and is then let go):': '合适时把这些织入故事,然后在 narrate 的 addressed 中说明已处理(每条会保留几个回合,之后放弃):',\n 'What the story keeps track of (change it with variable_changes in an outcome when what happened calls for it):': '故事追踪的内容(发生的事需要时,在结果中用 variable_changes 修改):',\n 'Still open in the story:': '故事中仍未了结的事:',\n 'Earlier events that bear on what the player just did (from the records of the story):': '与玩家刚才的行动相关的早先事件(来自故事记录):',\n 'turn {turn}': '第 {turn} 回合',\n 'You were to {title}, at {when}': '你本应{title},时间是{when}',\n 'You were to {title} at {place}, at {when}': '你本应在{place}:{title},时间是{when}',\n ' ({note})': '({note})',\n 'It is {now} now and the time has passed.': '现在是{now},时间已经过了。',\n 'It is {now} now.': '现在是{now}。',\n 'It was with: {who}.': '同你一起的有:{who}。',\n 'You are not with the player\\'s character, and nothing of this happens in front of anyone: decide what you do about it.': '你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。',\n 'The time you had for \"{goal}\" has passed ({when}; it is {now} now)': '你为“{goal}”预留的时间已过({when};现在是{now})',\n 'You are not with the player\\'s character and nothing of this happens in front of anyone: decide what you do about it.': '你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。',\n '{names} noticed: {text}': '{names}注意到:{text}',\n '{name} went to {place}.': '{name}去了{place}。',\n '## MCP resource servers\\n\\nUse {tools} with the server argument naming an MCP server.': '## MCP 资源服务器\\n\\n使用 {tools},server 参数填 MCP 服务器的名称。',\n '## MCP resource servers\\n\\nUse {tools} with one of these names as the server argument: {servers}.': '## MCP 资源服务器\\n\\n使用 {tools},server 参数填下列名称之一:{servers}。',\n}\nexport { ZH }\n","import { ZH } from './messages-zh.ts'\n\n/** The languages the texts a model reads are written in. English is the source: a text is its own key. */\nexport const LANGUAGES = ['en', 'zh'] as const\nexport type Language = (typeof LANGUAGES)[number]\n\n/** The language a setting such as `zh-CN` or `en` stands for; English when it is none that is known. */\nexport function languageOf(code: string | undefined): Language {\n return (code ?? '').trim().toLowerCase().startsWith('zh') ? 'zh' : 'en'\n}\n\nexport type MessageValues = Readonly<Record<string, string | number>>\n\n/** Says a text in the language of the story: `tr('{name} is in {place}.', { name, place })`. */\nexport type Translate = (text: string, values?: MessageValues) => string\n\nconst fill = (template: string, values: MessageValues | undefined): string => (values === undefined ? template : template.replace(/\\{(\\w+)\\}/g, (whole, name: string) => (name in values ? String(values[name]) : whole)))\n\nconst CATALOGUES: Readonly<Record<Exclude<Language, 'en'>, Readonly<Record<string, string>>>> = { zh: ZH }\n\n/**\n * The texts the engine builds for a model (briefs, reports, refusals) in a language. The text written in the code is the English one and the key of\n * the others; a text a language lacks is told in English, and a test keeps that from happening.\n */\nexport function translator(language: Language): Translate {\n const catalogue = language === 'en' ? undefined : CATALOGUES[language]\n return (text, values) => fill(catalogue?.[text] ?? text, values)\n}\n\n/** The texts with a translation, for the test that every text has one. */\nexport const translated = (language: Exclude<Language, 'en'>): readonly string[] => Object.keys(CATALOGUES[language])\nexport const translation = (language: Exclude<Language, 'en'>, text: string): string | undefined => CATALOGUES[language][text]\n","export type Clock = () => Date\n\nexport const systemClock: Clock = () => new Date()\n","import { DatabaseSync, type StatementSync } from 'node:sqlite'\nimport type { OpenOptions, RunResult, SqlDatabase, SqlDriver, SqlValue } from './types.ts'\n\nclass NodeSqliteDatabase implements SqlDatabase {\n private readonly statements = new Map<string, StatementSync>()\n private depth = 0\n\n constructor(private readonly db: DatabaseSync) {}\n\n exec(sql: string): void {\n this.db.exec(sql)\n }\n\n run(sql: string, params: readonly SqlValue[] = []): RunResult {\n const result = this.statement(sql).run(...params)\n return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) }\n }\n\n get<Row>(sql: string, params: readonly SqlValue[] = []): Row | undefined {\n return this.statement(sql).get(...params) as Row | undefined\n }\n\n all<Row>(sql: string, params: readonly SqlValue[] = []): Row[] {\n return this.statement(sql).all(...params) as Row[]\n }\n\n transaction<T>(fn: () => T): T {\n const outermost = this.depth === 0\n const savepoint = `nested_${this.depth}`\n this.db.exec(outermost ? 'BEGIN IMMEDIATE' : `SAVEPOINT ${savepoint}`)\n this.depth++\n let result: T\n try {\n result = fn()\n // A promise would settle after the transaction has ended.\n if (result instanceof Promise) throw new TypeError('a transaction callback must be synchronous')\n } catch (error) {\n this.depth--\n this.db.exec(outermost ? 'ROLLBACK' : `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}`)\n throw error\n }\n this.depth--\n this.db.exec(outermost ? 'COMMIT' : `RELEASE ${savepoint}`)\n return result\n }\n\n close(): void {\n this.statements.clear()\n this.db.close()\n }\n\n private statement(sql: string): StatementSync {\n let statement = this.statements.get(sql)\n if (statement === undefined) {\n statement = this.db.prepare(sql)\n this.statements.set(sql, statement)\n }\n return statement\n }\n}\n\n/** The driver built on Node's bundled SQLite (`node:sqlite`); it needs no native dependency. */\nexport const nodeSqliteDriver: SqlDriver = {\n open(location: string, options: OpenOptions = {}): SqlDatabase {\n const busyTimeout = options.busyTimeoutMs ?? 5000\n if (!Number.isInteger(busyTimeout) || busyTimeout < 0) throw new RangeError('busyTimeoutMs must be a non-negative integer')\n const extensions = options.extensions ?? []\n const db = new DatabaseSync(location, { allowExtension: extensions.length > 0 })\n try {\n for (const path of extensions) db.loadExtension(path)\n db.exec('PRAGMA foreign_keys = ON')\n db.exec(`PRAGMA busy_timeout = ${busyTimeout}`)\n if (location !== ':memory:') db.exec(`PRAGMA journal_mode = ${options.journalMode === 'wal' ? 'WAL' : 'DELETE'}`)\n } catch (error) {\n db.close()\n throw error\n }\n return new NodeSqliteDatabase(db)\n },\n}\n","export class StateError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = new.target.name\n }\n}\n\n/** The requested row does not exist. */\nexport class NotFoundError extends StateError {}\n\n/** The change clashes with existing data, such as a repeated id or a stale version. */\nexport class ConflictError extends StateError {}\n\n/** A value is outside what the schema allows. */\nexport class InvalidValueError extends StateError {}\n\n/** The file is not a session database, or was written by a newer version. */\nexport class SchemaError extends StateError {}\n\n/** Stored data cannot be read back as a canonical model. */\nexport class CorruptDataError extends StateError {}\n\n/** An edit of the story's records cannot be applied; it names every problem, and nothing was written. */\nexport class InvalidEditError extends StateError {\n constructor(readonly problems: readonly string[]) {\n super(`the edit is not acceptable: ${problems.join('; ')}`)\n }\n}\n\n/** A character cannot go where it was sent; it names every reason, and nothing changed. */\nexport class InvalidMoveError extends StateError {\n constructor(readonly problems: readonly string[]) {\n super(`the move is not possible: ${problems.join('; ')}`)\n }\n}\n","import { ConflictError, CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\n\n/** Keys for case-insensitive lookup; they fold compatibility forms, which SQLite's own NOCASE does not. */\nexport function lookupKey(text: string): string {\n return text.normalize('NFKC').trim().toLowerCase()\n}\n\n/** Run a statement, turning constraint failures into the errors callers know. */\nexport function guard<T>(fn: () => T): T {\n try {\n return fn()\n } catch (error) {\n const message = error instanceof Error ? error.message : ''\n if (message.includes('UNIQUE constraint failed')) throw new ConflictError(message, { cause: error })\n if (message.includes('FOREIGN KEY constraint failed')) throw new NotFoundError('a referenced row does not exist', { cause: error })\n if (message.includes('CHECK constraint failed')) throw new InvalidValueError(message, { cause: error })\n throw error\n }\n}\n\nexport function toJson(value: unknown): string {\n return JSON.stringify(value)\n}\n\nexport function parseStringList(text: string, column: string): string[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(entry => typeof entry === 'string')) return value as string[]\n } catch {\n // reported below\n }\n throw new CorruptDataError(`${column} does not hold a list of strings`)\n}\n\nexport function parseNumberList(text: string, column: string): number[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(entry => typeof entry === 'number')) return value as number[]\n } catch {\n // reported below\n }\n throw new CorruptDataError(`${column} does not hold a list of numbers`)\n}\n","import type {\n VariableDefinitionInput, TriggerDefinition,\n Accuracy, Character, CharacterKind, CharacterStatePatch, CharacterTier, ContainerState, EngagementStatus, ExitState, IntentHorizon, IntentStatus, IntentType, KnowledgeKind, Location, MemoryConfidence, MemoryKind, PerceptionMode, Slot,\n} from 'dsh-roleplay-model'\nimport type {\n CharacterRepository, CharacterStateRepository, ConsolidationRepository, EngagementRepository, EventRepository, IntentRepository, ItemRepository, LocationRepository, MemoryRepository,\n KnowledgeRepository, MetadataRepository, PlacementRepository, RelationshipRepository, RoutineRepository, SlotRepository, ThreadRepository, TriggerRepository, VariableRepository,\n FactionRepository, FactionStateRepository, FactionMembershipRepository, FactionRelationshipRepository, FactionIntentRepository,\n} from '../repositories.ts'\nimport type { ItemChangeSpec } from './items.ts'\nimport type { VariableChangeSpec } from './variables.ts'\n\n/** The name by which models and other plugins refer to a place: its id in the world, or its number when it was made up in play. */\n\nexport const locationKey = (location: Pick<Location, 'id' | 'sourceId'>): string => location.sourceId ?? String(location.id)\n\n/** The name by which models and other plugins refer to a character: its id in the world, or its number when it has none. */\nexport const characterKey = (character: Pick<Character, 'id' | 'sourceId'>): string => character.sourceId ?? String(character.id)\n\n/** What an edit of the story's records can touch. */\nexport interface RecordsTarget {\n characters: CharacterRepository\n characterStates: CharacterStateRepository\n events: EventRepository\n memories: MemoryRepository\n threads: ThreadRepository\n locations: LocationRepository\n placements: PlacementRepository\n relationships: RelationshipRepository\n factions: FactionRepository\n factionStates: FactionStateRepository\n factionMemberships: FactionMembershipRepository\n factionRelationships: FactionRelationshipRepository\n factionIntents: FactionIntentRepository\n knowledge: KnowledgeRepository\n consolidation: ConsolidationRepository\n items: ItemRepository\n slots: SlotRepository\n intents: IntentRepository\n variables: VariableRepository\n routines: RoutineRepository\n engagements: EngagementRepository\n triggers: TriggerRepository\n /** What the story keeps about itself; the calendar of its world is read from here. */\n metadata: Pick<MetadataRepository, 'getValue'>\n transaction<T>(fn: () => T): T\n}\n\nexport interface PerceivedBy {\n character: string\n mode: PerceptionMode\n /** What the character took in, when it is not exactly the event. */\n content?: string\n gist?: string\n accuracy?: Accuracy\n}\n\nexport interface StatePatch extends Pick<CharacterStatePatch, 'publicState' | 'innerState' | 'activity'> {\n character: string\n}\n\nexport interface NewEvent {\n /** The key of the place it happened in. */\n location?: string\n /** The keys of the items it is about. */\n items?: string[]\n turn: number\n round: number\n text: string\n importance: number\n tags?: string[]\n involves?: string[]\n perceivedBy?: PerceivedBy[]\n}\n\nexport interface EventEdit {\n id: number\n location?: string\n text?: string\n importance?: number\n tags?: string[]\n involves?: string[]\n /** Replaces who took the event in. */\n perceivedBy?: PerceivedBy[]\n}\n\n/** A character's version of an event, revised: it learned more, or remembers it differently. Works on sealed events too. */\nexport interface PerceptionEdit {\n id: number\n mode?: PerceptionMode\n content?: string\n gist?: string\n accuracy?: Accuracy\n}\n\n/** One more character took in an event, possibly long after: it was told, or worked it out. Works on sealed events too. */\nexport interface PerceptionAddition extends PerceivedBy {\n event: number\n}\n\nexport interface NewExit {\n /** The key of the place it leads to. */\n to: string\n description?: string\n /** Also make the way back, with `backDescription`; on by default. */\n oneWay?: boolean\n backDescription?: string\n travelSeconds?: number\n state?: ExitState\n note?: string\n}\n\n/** A place made up in play (or arriving with a plugin): a hidden passage, a room the story opens. */\nexport interface NewPlace {\n key: string\n name: string\n description?: string\n /** The key of the place it is in. */\n parent?: string\n features?: { key: string; name: string; description?: string }[]\n exits?: NewExit[]\n /** Why it was made, for whoever fits it into the world later. */\n note?: string\n}\n\n/** A character the story makes up: someone who arrives, is introduced, or turns out to be needed. Always played by an agent. */\nexport interface NewCharacterSpec {\n key: string\n name: string\n aliases?: string[]\n age?: string\n gender?: string\n pronouns?: string\n kind?: CharacterKind\n tier?: CharacterTier\n summary: string\n personality?: string\n background?: string\n appearance?: string\n speech?: { style: string; examples?: string[] }\n state?: { publicState?: string; innerState?: string; activity?: string }\n place?: { location: string; position?: string; feature?: string }\n /** Why it was made, for whoever fits it into the world later. */\n note?: string\n}\n\n/** A character's profile of another, made or changed; what is not given stays as it was. */\nexport interface RelationshipSet {\n from: string\n to: string\n label?: string\n summary?: string\n familiarity?: number\n trust?: number\n affinity?: number\n tension?: number\n}\n\nexport interface RelationshipRetraction {\n from: string\n to: string\n}\n\n/** A place, item or directed exit a character learns exists. */\nexport interface KnowledgeSet {\n character: string\n kind: KnowledgeKind\n /** The location or item key. */\n subject?: string\n /** For an exit, its directed endpoints. */\n from?: string\n to?: string\n observed?: boolean\n}\n\nexport interface FactionStateSet { faction: string; publicState?: string; innerState?: string }\nexport interface FactionMembershipSet { faction: string; character: string; role?: string; rank?: string; status?: 'active' | 'inactive' | 'former'; public?: boolean; commitment?: number; leftTurn?: number }\nexport interface FactionRelationshipSet extends Omit<RelationshipSet, 'from' | 'to'> { fromKind: 'character' | 'faction'; from: string; toKind: 'character' | 'faction'; to: string }\nexport interface NewFactionIntentSpec extends Omit<NewIntentSpec, 'character'> { faction: string }\n\nexport type KnowledgeRetraction = Omit<KnowledgeSet, 'observed'>\n\n/** A new way between two places that already exist (or are made in the same edit). */\nexport interface NewExitBetween {\n from: string\n to: string\n description?: string\n /** Also make the way back, with `backDescription`; on by default. */\n oneWay?: boolean\n backDescription?: string\n travelSeconds?: number\n state?: ExitState\n note?: string\n}\n\n/** A thing the story makes up (or that arrives with a plugin): an object that matters, handed over or found. It starts in exactly one of `at`, `heldBy`, `wornBy` or `inside`. */\nexport interface NewItemSpec {\n key: string\n name: string\n description?: string\n quantity?: number\n unique?: boolean\n quality?: string\n notable?: boolean\n hidden?: boolean\n /** The slot it is worn in. */\n wearable?: string\n container?: { state?: ContainerState; openedBy?: string[] }\n owner?: string\n at?: { location: string; position?: string; feature?: string }\n heldBy?: string\n wornBy?: string\n wornPosition?: string\n inside?: string\n insidePosition?: string\n /** Why it was made, for whoever fits it into the world later. */\n note?: string\n}\n\n/** What a character does with an item; the engine decides it, this is for plugins and tools. */\nexport interface ItemChange extends ItemChangeSpec {\n character: string\n}\n\nexport interface ItemEditSpec {\n item: string\n description?: string\n quality?: string\n quantity?: number\n notable?: boolean\n hidden?: boolean\n /** The state of a container, when it is changed by the story rather than by a character's action. */\n state?: ContainerState\n owner?: string\n /** Replaces the items that open it (a container or the way named by `exit`). */\n openedBy?: string[]\n}\n\nexport interface PlaceEdit {\n place: string\n name?: string\n description?: string\n /** Replaces the list of features. */\n features?: { key: string; name: string; description?: string }[]\n}\n\n/** A door is unlocked, a passage collapses: the way between two places changes, both ways unless told otherwise. */\nexport interface ExitChange {\n from: string\n to: string\n state?: ExitState\n description?: string\n note?: string\n travelSeconds?: number\n oneWay?: boolean\n}\n\nexport interface CharacterMove {\n character: string\n to: string\n position?: string\n feature?: string\n ignoreExits?: boolean\n}\n\nexport interface NewBelief {\n character: string\n kind: MemoryKind\n text: string\n about?: string[]\n importance: number\n /** How sure the character is; likely when not said. */\n confidence?: MemoryConfidence\n /** The numbers of perceptions of the character's own that it rests on, and that speak against it. */\n evidenceFor?: number[]\n evidenceAgainst?: number[]\n}\n\nexport interface BeliefEdit {\n id: number\n text?: string\n about?: string[]\n importance?: number\n confidence?: MemoryConfidence\n evidenceFor?: number[]\n evidenceAgainst?: number[]\n}\n\n/**\n * A change to the story's records, applied together or not at all: the unit in which the\n * record keeper, the model-facing tools and other plugins write what happened.\n */\n/** A new goal of a character, which the story gave it: a promise made, a task taken on. */\nexport interface NewIntentSpec {\n character: string\n type: IntentType\n name: string\n description?: string\n horizon: IntentHorizon\n priority: number\n urgency: number\n plan?: string[]\n constraints?: string[]\n /** A date and time, in the time zone of the story unless it carries an offset. */\n deadline?: string\n}\n\nexport interface IntentEditSpec {\n id: number\n status?: IntentStatus\n description?: string\n horizon?: IntentHorizon\n priority?: number\n urgency?: number\n plan?: string[]\n openThreads?: string[]\n deadline?: string\n}\n\n/** Something characters have committed to, at a time. */\nexport interface NewEngagementSpec {\n title: string\n /** When it is due: a date and time, in the time zone of the story unless it carries an offset. */\n at: string\n until?: string\n /** The key of the place. */\n location?: string\n participants: string[]\n note?: string\n}\n\nexport interface EngagementEditSpec {\n id: number\n status?: EngagementStatus\n title?: string\n at?: string\n until?: string\n location?: string\n participants?: string[]\n note?: string\n}\n\nexport interface RoutineWindowSpec {\n /** `mon` to `sun`; every day when left out. */\n days?: string[]\n /** Other days it applies on or not: `dec`, `12-24`, `season:winter`, `nth:mon:1`, `holiday:<id>`, `!` before one for a day it does not apply on. */\n on?: string[]\n /** `HH:MM`. */\n from: string\n to: string\n activity: string\n location?: string\n feature?: string\n position?: string\n interruptible?: boolean\n}\n\n/** Sets the recurring day of a character, replacing what it had. */\nexport interface RoutineSet {\n character: string\n windows: RoutineWindowSpec[]\n}\n\nexport interface RecordsEdit {\n /** The turn new beliefs and threads belong to. */\n turn: number\n /** The time zone the dates of the edit are written in; UTC when not given. */\n timeZone?: string\n /** Changes to what the story tracks: a feeling, a debt, a flag. */\n variableChanges?: VariableChangeSpec[]\n /** Variables the story declares, only by the agent whose work that is. */\n variables?: VariableDefinitionInput[]\n intentsAdded?: NewIntentSpec[]\n intentEdits?: IntentEditSpec[]\n engagements?: NewEngagementSpec[]\n engagementEdits?: EngagementEditSpec[]\n routines?: RoutineSet[]\n /** Things the world does when their conditions come true, only by the agent whose work that is. */\n triggers?: TriggerDefinition[]\n states?: StatePatch[]\n events?: NewEvent[]\n eventEdits?: EventEdit[]\n eventRetractions?: number[]\n perceptionEdits?: PerceptionEdit[]\n perceptionsAdded?: PerceptionAddition[]\n characters?: NewCharacterSpec[]\n items?: NewItemSpec[]\n slots?: Slot[]\n itemChanges?: ItemChange[]\n itemEdits?: ItemEditSpec[]\n places?: NewPlace[]\n exits?: NewExitBetween[]\n relationships?: RelationshipSet[]\n relationshipRetractions?: RelationshipRetraction[]\n knowledge?: KnowledgeSet[]\n knowledgeRetractions?: KnowledgeRetraction[]\n factionStates?: FactionStateSet[]\n factionMemberships?: FactionMembershipSet[]\n factionRelationships?: FactionRelationshipSet[]\n factionIntentsAdded?: NewFactionIntentSpec[]\n placeEdits?: PlaceEdit[]\n exitChanges?: ExitChange[]\n moves?: CharacterMove[]\n beliefs?: NewBelief[]\n beliefEdits?: BeliefEdit[]\n beliefRetractions?: number[]\n threadsOpened?: string[]\n threadsResolved?: number[]\n}\n\nexport interface EditResult {\n /** The ids of the events and beliefs the edit added, in order. */\n eventIds: number[]\n /** The keys of the characters and places the edit made up. */\n characterKeys?: string[]\n placeKeys?: string[]\n triggerKeys?: string[]\n itemKeys?: string[]\n /** The keys of the variables the edit declared. */\n variableKeys?: string[]\n beliefIds: number[]\n /** How many rows were added, changed or removed. */\n writes: number\n}\n","import type { CharacterId, Engagement, EngagementFilter, EngagementId, EngagementPatch, EngagementStatus, NewEngagement, RoutineWindow, StoredRoutineWindow } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { EngagementRepository, RoutineRepository } from '../repositories.ts'\nimport { guard, parseNumberList, parseStringList, toJson } from './support.ts'\n\n/** At most this many windows for one character, so that a day stays something a model can hold. */\nexport const MAX_ROUTINE_WINDOWS = 24\nconst MAX_TITLE = 200\n\ninterface WindowRow {\n id: number\n character_id: number\n days: string\n filters: string\n start_minute: number\n end_minute: number\n activity: string\n location_id: number | null\n feature_key: string | null\n position: string\n interruptible: number\n}\n\nconst toWindow = (row: WindowRow): StoredRoutineWindow => ({\n id: row.id,\n characterId: row.character_id,\n days: parseNumberList(row.days, 'routine_windows.days'),\n on: parseStringList(row.filters, 'routine_windows.filters'),\n start: row.start_minute,\n end: row.end_minute,\n activity: row.activity,\n ...(row.location_id === null ? {} : { locationId: row.location_id }),\n ...(row.feature_key === null ? {} : { featureKey: row.feature_key }),\n ...(row.position === '' ? {} : { position: row.position }),\n interruptible: row.interruptible === 1,\n})\n\nconst isMinute = (value: number): boolean => Number.isInteger(value) && value >= 0 && value < 1440\n\nexport class SqliteRoutineRepository implements RoutineRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n list(characterId: CharacterId): StoredRoutineWindow[] {\n return this.db.all<WindowRow>('SELECT * FROM routine_windows WHERE character_id = ? ORDER BY ordinal', [characterId]).map(toWindow)\n }\n\n all(): StoredRoutineWindow[] {\n return this.db.all<WindowRow>('SELECT * FROM routine_windows ORDER BY character_id, ordinal').map(toWindow)\n }\n\n replace(characterId: CharacterId, windows: readonly RoutineWindow[]): StoredRoutineWindow[] {\n if (windows.length > MAX_ROUTINE_WINDOWS) throw new InvalidValueError(`a character has at most ${MAX_ROUTINE_WINDOWS} windows in its day`)\n windows.forEach((window, index) => {\n const at = `window ${index + 1}`\n if (!isMinute(window.start) || !isMinute(window.end)) throw new InvalidValueError(`${at}: a minute of the day is from 0 to 1439`)\n if (window.start === window.end) throw new InvalidValueError(`${at}: it starts and ends at the same minute`)\n if (window.days.some(day => !Number.isInteger(day) || day < 0 || day > 6)) throw new InvalidValueError(`${at}: a day of the week is from 0 (Sunday) to 6`)\n if (window.activity.trim() === '') throw new InvalidValueError(`${at}: say what the character is doing`)\n })\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) throw new NotFoundError(`character ${characterId} does not exist`)\n this.db.run('DELETE FROM routine_windows WHERE character_id = ?', [characterId])\n windows.forEach((window, index) => {\n this.db.run(\n 'INSERT INTO routine_windows (character_id, ordinal, days, filters, start_minute, end_minute, activity, location_id, feature_key, position, interruptible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [characterId, index, toJson([...new Set(window.days)].sort()), toJson([...new Set(window.on ?? [])]), window.start, window.end, window.activity.trim(), window.locationId ?? null, window.featureKey ?? null, window.position ?? '', window.interruptible ? 1 : 0],\n )\n })\n return this.list(characterId)\n }))\n }\n}\n\ninterface EngagementRow {\n id: number\n title: string\n at_ms: number\n until_ms: number | null\n location_id: number | null\n status: EngagementStatus\n note: string\n created_turn: number\n updated_turn: number\n}\n\nexport class SqliteEngagementRepository implements EngagementRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n add(engagement: NewEngagement): Engagement {\n this.check(engagement.title, engagement.at, engagement.until, engagement.participants)\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO engagements (title, at_ms, until_ms, location_id, status, note, created_turn, updated_turn) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',\n [engagement.title.trim(), engagement.at, engagement.until ?? null, engagement.locationId ?? null, 'pending', engagement.note ?? '', engagement.turn, engagement.turn],\n )\n const id = Number(lastInsertRowid)\n this.setParticipants(id, engagement.participants)\n return this.require(id)\n }))\n }\n\n get(id: EngagementId): Engagement | undefined {\n const row = this.db.get<EngagementRow>('SELECT * FROM engagements WHERE id = ?', [id])\n return row === undefined ? undefined : this.toEngagement(row)\n }\n\n list(filter: EngagementFilter = {}): Engagement[] {\n const where: string[] = []\n const params: SqlValue[] = []\n const add = (clause: string, value: SqlValue): void => { where.push(clause); params.push(value) }\n if (filter.status !== undefined) add('status = ?', filter.status)\n if (filter.participant !== undefined) add('id IN (SELECT engagement_id FROM engagement_participants WHERE character_id = ?)', filter.participant)\n if (filter.from !== undefined) add('at_ms >= ?', filter.from)\n if (filter.to !== undefined) add('at_ms < ?', filter.to)\n return this.db.all<EngagementRow>(`SELECT * FROM engagements ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`} ORDER BY at_ms, id`, params).map(row => this.toEngagement(row))\n }\n\n update(id: EngagementId, patch: EngagementPatch): Engagement {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const at = patch.at ?? current.at\n const until = patch.until ?? current.until\n const participants = patch.participants ?? current.participants\n this.check(patch.title ?? current.title, at, until, participants)\n this.db.run('UPDATE engagements SET title = ?, at_ms = ?, until_ms = ?, location_id = ?, status = ?, note = ?, updated_turn = ? WHERE id = ?', [\n (patch.title ?? current.title).trim(), at, until ?? null, patch.locationId ?? current.locationId ?? null, patch.status ?? current.status, patch.note ?? current.note, patch.turn, id,\n ])\n if (patch.participants !== undefined) this.setParticipants(id, patch.participants)\n return this.require(id)\n }))\n }\n\n remove(id: EngagementId): boolean {\n return this.db.run('DELETE FROM engagements WHERE id = ?', [id]).changes > 0\n }\n\n private check(title: string, at: number, until: number | undefined, participants: readonly CharacterId[]): void {\n if (title.trim() === '' || title.trim().length > MAX_TITLE) throw new InvalidValueError(`an engagement needs a title of at most ${MAX_TITLE} characters`)\n if (!Number.isSafeInteger(at)) throw new InvalidValueError('an engagement needs the instant it is due')\n if (until !== undefined && (!Number.isSafeInteger(until) || until < at)) throw new InvalidValueError('an engagement cannot end before it is due')\n if (participants.length === 0) throw new InvalidValueError('an engagement needs at least one character who has committed to it')\n }\n\n private setParticipants(id: EngagementId, participants: readonly CharacterId[]): void {\n this.db.run('DELETE FROM engagement_participants WHERE engagement_id = ?', [id])\n for (const characterId of new Set(participants)) this.db.run('INSERT INTO engagement_participants (engagement_id, character_id) VALUES (?, ?)', [id, characterId])\n }\n\n private toEngagement(row: EngagementRow): Engagement {\n return {\n id: row.id, title: row.title, at: row.at_ms,\n ...(row.until_ms === null ? {} : { until: row.until_ms }),\n ...(row.location_id === null ? {} : { locationId: row.location_id }),\n participants: this.db.all<{ character_id: number }>('SELECT character_id FROM engagement_participants WHERE engagement_id = ? ORDER BY character_id', [row.id]).map(entry => entry.character_id),\n status: row.status, note: row.note, createdTurn: row.created_turn, updatedTurn: row.updated_turn,\n }\n }\n\n private require(id: EngagementId): Engagement {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`engagement ${id} does not exist`)\n return found\n }\n}\n","import { WEEKDAY_NAMES } from 'dsh-roleplay-model'\n\n/**\n * Which days a thing applies on, beyond the days of the week: whole months, a date every year or once, a stretch of dates, the day of the month,\n * the first or last Monday of a month, a season, and the holidays a world names. A day is told by tokens (`dec`, `12-24`, `1912-09-21..1912-09-22`,\n * `dom:1`, `nth:mon:1`, `season:winter`, `holiday:founders-day`, `fri`); a token with `!` before it is a day it does not apply on. A list holds on a\n * day when it names no day to apply on or one of them is today, and none of the days to leave out is.\n */\nexport const MONTH_NAMES = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] as const\nexport const SEASONS = ['spring', 'summer', 'autumn', 'winter'] as const\nexport type Season = (typeof SEASONS)[number]\nexport type Hemisphere = 'north' | 'south'\n\n/** A day by the wall clock of the story: the month is 1 to 12 and the weekday 0 (Sunday) to 6. */\nexport interface CalendarDay {\n year: number\n month: number\n day: number\n weekday: number\n}\n\nexport interface Holiday {\n id: string\n name: string\n /** The days it falls on, as tokens other than `holiday:`. */\n on: string[]\n}\n\nexport interface Calendar {\n hemisphere: Hemisphere\n holidays: Holiday[]\n}\n\nexport const NO_CALENDAR: Calendar = { hemisphere: 'north', holidays: [] }\n\nconst MAX_TOKEN = 60\n\ntype Parsed =\n | { kind: 'weekday'; weekday: number }\n | { kind: 'month'; month: number }\n | { kind: 'date'; year?: number; month: number; day: number }\n | { kind: 'span'; from: { year?: number; month: number; day: number }; to: { year?: number; month: number; day: number } }\n | { kind: 'dom'; day: number | 'last' }\n | { kind: 'nth'; weekday: number; n: number | 'last' }\n | { kind: 'season'; season: Season }\n | { kind: 'holiday'; id: string }\n\nconst daysIn = (year: number, month: number): number => new Date(Date.UTC(year, month, 0)).getUTCDate()\nconst DATE = /^(?:(\\d{4})-)?(\\d{2})-(\\d{2})$/\n\nfunction dateOf(text: string): { year?: number; month: number; day: number } | undefined {\n const found = DATE.exec(text)\n if (found === null) return undefined\n const [, year, month, day] = found\n const m = Number(month)\n const d = Number(day)\n if (m < 1 || m > 12 || d < 1 || d > daysIn(year === undefined ? 2024 : Number(year), m)) return undefined\n return { ...(year === undefined ? {} : { year: Number(year) }), month: m, day: d }\n}\n\n/** What a token says, or why it says nothing. */\nexport function parseDayToken(raw: string): { token: Parsed; negated: boolean } | { problem: string } {\n const negated = raw.startsWith('!')\n const text = (negated ? raw.slice(1) : raw).trim().toLowerCase()\n const fail = (problem: string): { problem: string } => ({ problem: `\"${raw}\": ${problem}` })\n if (text === '' || text.length > MAX_TOKEN) return fail('a day is told in a few words')\n const weekday = WEEKDAY_NAMES.indexOf(text as (typeof WEEKDAY_NAMES)[number])\n if (weekday >= 0) return { token: { kind: 'weekday', weekday }, negated }\n const month = MONTH_NAMES.indexOf(text as (typeof MONTH_NAMES)[number])\n if (month >= 0) return { token: { kind: 'month', month: month + 1 }, negated }\n const one = dateOf(text)\n if (one !== undefined) return { token: { kind: 'date', ...one }, negated }\n if (text.includes('..')) {\n const [from, to, ...rest] = text.split('..')\n const start = from === undefined ? undefined : dateOf(from)\n const end = to === undefined ? undefined : dateOf(to)\n if (rest.length > 0 || start === undefined || end === undefined || (start.year === undefined) !== (end.year === undefined)) return fail('a stretch is two dates of the same kind: `12-20..01-05` every year, or `1912-09-21..1912-09-22` once')\n return { token: { kind: 'span', from: start, to: end }, negated }\n }\n const [head, a, b] = text.split(':')\n if (head === 'dom' && a !== undefined && b === undefined) {\n if (a === 'last') return { token: { kind: 'dom', day: 'last' }, negated }\n const day = Number(a)\n return Number.isInteger(day) && day >= 1 && day <= 31 ? { token: { kind: 'dom', day }, negated } : fail('the day of the month is 1 to 31, or `dom:last`')\n }\n if (head === 'nth' && a !== undefined && b !== undefined) {\n const day = WEEKDAY_NAMES.indexOf(a as (typeof WEEKDAY_NAMES)[number])\n const n = b === 'last' ? 'last' as const : Number(b)\n return day >= 0 && (n === 'last' || (Number.isInteger(n) && n >= 1 && n <= 5)) ? { token: { kind: 'nth', weekday: day, n }, negated } : fail('`nth:mon:1` is the first Monday of a month, `nth:fri:last` the last Friday')\n }\n if (head === 'season' && a !== undefined && b === undefined) {\n const season = SEASONS.find(candidate => candidate === a)\n return season === undefined ? fail(`a season is one of ${SEASONS.join(', ')}`) : { token: { kind: 'season', season }, negated }\n }\n if (head === 'holiday' && a !== undefined && b === undefined && a !== '') return { token: { kind: 'holiday', id: a }, negated }\n return fail('not a day: use a weekday (`mon`), a month (`dec`), a date (`12-24`, `1912-09-21`), a stretch (`12-20..01-05`), `dom:1`, `nth:mon:1`, `season:winter` or `holiday:<id>`')\n}\n\n/** What is wrong with a list of day tokens, each with where it is. `holidays` are those the world names, when `holiday:` may be used. */\nexport function dayTokenProblems(tokens: readonly string[], path: string, holidays?: ReadonlySet<string> | 'any'): string[] {\n return tokens.flatMap((raw): string[] => {\n const parsed = parseDayToken(raw)\n if ('problem' in parsed) return [`${path}: ${parsed.problem}`]\n if (parsed.token.kind === 'holiday') {\n if (holidays === undefined) return [`${path}: \"${raw}\": a holiday cannot be named here`]\n if (holidays !== 'any' && !holidays.has(parsed.token.id)) return [`${path}: \"${raw}\": the world names no holiday \"${parsed.token.id}\"`]\n }\n return []\n })\n}\n\n/** The season a day is in, by the months of its hemisphere (winter is December to February in the north, June to August in the south). */\nexport function seasonOf(day: Pick<CalendarDay, 'month'>, hemisphere: Hemisphere = 'north'): Season {\n const north: Season = day.month === 12 || day.month <= 2 ? 'winter' : day.month <= 5 ? 'spring' : day.month <= 8 ? 'summer' : 'autumn'\n if (hemisphere === 'north') return north\n return north === 'winter' ? 'summer' : north === 'summer' ? 'winter' : north === 'spring' ? 'autumn' : 'spring'\n}\n\nconst key = (month: number, day: number): number => month * 100 + day\n\nfunction within(day: CalendarDay, from: { year?: number; month: number; day: number }, to: { year?: number; month: number; day: number }): boolean {\n if (from.year !== undefined && to.year !== undefined) {\n const at = day.year * 10000 + key(day.month, day.day)\n return at >= from.year * 10000 + key(from.month, from.day) && at <= to.year * 10000 + key(to.month, to.day)\n }\n const at = key(day.month, day.day)\n const start = key(from.month, from.day)\n const end = key(to.month, to.day)\n return start <= end ? at >= start && at <= end : at >= start || at <= end\n}\n\nfunction matches(token: Parsed, day: CalendarDay, calendar: Calendar): boolean {\n switch (token.kind) {\n case 'weekday': return day.weekday === token.weekday\n case 'month': return day.month === token.month\n case 'date': return day.month === token.month && day.day === token.day && (token.year === undefined || day.year === token.year)\n case 'span': return within(day, token.from, token.to)\n case 'dom': return token.day === 'last' ? day.day === daysIn(day.year, day.month) : day.day === token.day\n case 'nth': return day.weekday === token.weekday && (token.n === 'last' ? day.day + 7 > daysIn(day.year, day.month) : Math.ceil(day.day / 7) === token.n)\n case 'season': return seasonOf(day, calendar.hemisphere) === token.season\n case 'holiday': return holidaysOn(calendar, day).some(holiday => holiday.id === token.id)\n }\n}\n\n/** Whether a list of day tokens holds on a day; tokens that say nothing sensible count as not matching. An empty list holds on every day. */\nexport function dayMatches(tokens: readonly string[], day: CalendarDay, calendar: Calendar = NO_CALENDAR): boolean {\n const parsed = tokens.flatMap((raw) => { const found = parseDayToken(raw); return 'problem' in found ? [] : [found] })\n const wanted = parsed.filter(entry => !entry.negated)\n const unwanted = parsed.filter(entry => entry.negated)\n return (wanted.length === 0 || wanted.some(entry => matches(entry.token, day, calendar))) && !unwanted.some(entry => matches(entry.token, day, calendar))\n}\n\n/** The holidays that fall on a day. A holiday is told by days that are no holidays themselves, so that none can lead back to itself. */\nexport function holidaysOn(calendar: Calendar, day: CalendarDay): Holiday[] {\n return calendar.holidays.filter(holiday => holiday.on.length > 0 && dayMatches(holiday.on, day, { ...calendar, holidays: [] }))\n}\n\nconst CALENDAR_KEY = 'calendar'\n\n/** The calendar a story was started with, from its metadata; none when the world has none. */\nexport function readCalendar(metadata: { getValue(key: string): unknown }): Calendar {\n const stored = metadata.getValue(CALENDAR_KEY)\n if (typeof stored !== 'object' || stored === null || Array.isArray(stored)) return NO_CALENDAR\n const { hemisphere, holidays } = stored as { hemisphere?: unknown; holidays?: unknown }\n return {\n hemisphere: hemisphere === 'south' ? 'south' : 'north',\n holidays: Array.isArray(holidays) ? holidays.flatMap((entry): Holiday[] => {\n const { id, name, on } = (entry ?? {}) as { id?: unknown; name?: unknown; on?: unknown }\n return typeof id === 'string' && typeof name === 'string' && Array.isArray(on) ? [{ id, name, on: on.filter((token): token is string => typeof token === 'string') }] : []\n }) : [],\n }\n}\n\nexport const writeCalendar = (metadata: { setValue(key: string, value: never): void }, calendar: Calendar): void => { metadata.setValue(CALENDAR_KEY, calendar as never) }\n","/** Instants are UTC milliseconds; a time zone only decides how they read. */\n\nexport const SECOND = 1000\nexport const MINUTE = 60 * SECOND\nexport const HOUR = 60 * MINUTE\nexport const DAY = 24 * HOUR\n\nconst formatters = new Map<string, Intl.DateTimeFormat>()\n\nfunction formatterFor(zone: string): Intl.DateTimeFormat {\n let formatter = formatters.get(zone)\n if (formatter === undefined) {\n formatter = new Intl.DateTimeFormat('en-GB', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', weekday: 'short' })\n formatters.set(zone, formatter)\n }\n return formatter\n}\n\n/** Whether a name is a time zone this runtime knows (an IANA name such as `Europe/London`, or `UTC`). */\nexport function isTimeZone(zone: string): boolean {\n if (zone.trim() === '' || zone !== zone.trim()) return false\n try {\n formatterFor(zone)\n return true\n } catch {\n return false\n }\n}\n\n/** The time zone of this computer. */\nexport const systemTimeZone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone\n\nexport interface LocalTime {\n year: number\n /** 1 to 12. */\n month: number\n day: number\n hour: number\n minute: number\n second: number\n /** 0 for Sunday to 6 for Saturday. */\n weekday: number\n minuteOfDay: number\n}\n\nconst WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] as const\nconst MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] as const\n\n/** What the wall clock of a zone reads at an instant. */\nexport function localTime(instant: number, zone: string): LocalTime {\n const parts = Object.fromEntries(formatterFor(zone).formatToParts(new Date(instant)).map(part => [part.type, part.value]))\n const hour = Number(parts['hour'])\n const minute = Number(parts['minute'])\n return {\n year: Number(parts['year']), month: Number(parts['month']), day: Number(parts['day']), hour, minute, second: Number(parts['second']),\n weekday: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(String(parts['weekday'])),\n minuteOfDay: hour * 60 + minute,\n }\n}\n\nfunction utcOf(fields: { year: number; month: number; day: number; hour?: number; minute?: number; second?: number }): number {\n const date = new Date(0)\n date.setUTCFullYear(fields.year, fields.month - 1, fields.day)\n date.setUTCHours(fields.hour ?? 0, fields.minute ?? 0, fields.second ?? 0, 0)\n return date.getTime()\n}\n\n/** The instant at which the wall clock of a zone reads this; a time that does not exist (the clocks jumped over it) is moved on by the length of the jump. */\nexport function zonedInstant(fields: { year: number; month: number; day: number; hour?: number; minute?: number; second?: number }, zone: string): number {\n const asUtc = utcOf(fields)\n const offsetAt = (instant: number): number => {\n const local = localTime(instant, zone)\n return utcOf(local) - Math.floor(instant / SECOND) * SECOND\n }\n const first = asUtc - offsetAt(asUtc)\n const second = asUtc - offsetAt(first)\n return second\n}\n\nconst LOCAL = /^(-?\\d{1,6})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?$/\n\n/**\n * An instant from text: an ISO 8601 date and time with an offset or `Z` is taken as written; without one\n * it is the wall clock of `zone`. A date alone is that day at midnight.\n * @throws {RangeError} when it is not a date and time.\n */\nexport function parseInstant(text: string, zone: string): number {\n const trimmed = text.trim()\n const local = LOCAL.exec(trimmed)\n if (local !== null) {\n const [, year, month, day, hour, minute, second] = local\n const fields = { year: Number(year), month: Number(month), day: Number(day), hour: Number(hour ?? 0), minute: Number(minute ?? 0), second: Number(second ?? 0) }\n const check = new Date(utcOf(fields))\n if (check.getUTCMonth() !== fields.month - 1 || check.getUTCDate() !== fields.day || fields.hour > 23 || fields.minute > 59 || fields.second > 59) throw new RangeError(`\"${text}\" is not a date and time`)\n return zonedInstant(fields, zone)\n }\n if (/^-?\\d{4,6}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})$/.test(trimmed)) {\n const instant = Date.parse(trimmed.replace(' ', 'T'))\n if (!Number.isNaN(instant)) return instant\n }\n throw new RangeError(`\"${text}\" is not a date and time: write it as 1912-10-04T19:30 (or with an offset, 1912-10-04T19:30+01:00)`)\n}\n\nconst WEEKDAYS_ZH = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'] as const\n\n/** `Tuesday 4 October 1912, 21:40`, or `1912年10月4日 星期二 21:40`. */\nexport function describeInstant(instant: number, zone: string, language: 'en' | 'zh' = 'en'): string {\n const local = localTime(instant, zone)\n if (language === 'zh') return `${local.year}年${local.month}月${local.day}日 ${WEEKDAYS_ZH[local.weekday]} ${pad(local.hour)}:${pad(local.minute)}`\n return `${WEEKDAYS[local.weekday]} ${local.day} ${MONTHS[local.month - 1]} ${local.year}, ${pad(local.hour)}:${pad(local.minute)}`\n}\n\n/** `1912-10-04T21:40:00` as the wall clock of a zone reads, the form a file or a person can write back. */\nexport function localIso(instant: number, zone: string): string {\n const local = localTime(instant, zone)\n return `${String(local.year).padStart(4, '0')}-${pad(local.month)}-${pad(local.day)}T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}`\n}\n\nconst pad = (value: number): string => String(value).padStart(2, '0')\n\nexport const DAY_PARTS = ['night', 'morning', 'afternoon', 'evening'] as const\nexport type DayPart = (typeof DAY_PARTS)[number]\n\n/** Night is from 22:00 to 05:00, morning to 12:00, afternoon to 17:00, evening after. */\nexport function dayPart(minuteOfDay: number): DayPart {\n const hour = Math.floor(minuteOfDay / 60)\n return hour < 5 || hour >= 22 ? 'night' : hour < 12 ? 'morning' : hour < 17 ? 'afternoon' : 'evening'\n}\n\n/** In words and rounded to what matters: `45 seconds`, `3 hours 12 minutes`, `2 days 3 hours`; or `45秒`, `3小时12分钟`, `2天3小时`. */\nexport function describeDuration(milliseconds: number, language: 'en' | 'zh' = 'en'): string {\n const total = Math.max(0, Math.round(milliseconds / SECOND))\n if (language === 'zh') {\n if (total < 60) return `${total}秒`\n const parts: string[] = []\n let left = total\n for (const [name, size] of [['天', 86_400], ['小时', 3600], ['分钟', 60]] as const) {\n const count = Math.floor(left / size)\n left -= count * size\n if (count > 0) parts.push(`${count}${name}`)\n if (parts.length === 2) break\n }\n return parts.join('')\n }\n if (total < 60) return `${total} second${total === 1 ? '' : 's'}`\n const units: [string, number][] = [['day', 86_400], ['hour', 3600], ['minute', 60]]\n const parts: string[] = []\n let left = total\n for (const [name, size] of units) {\n const count = Math.floor(left / size)\n left -= count * size\n if (count > 0) parts.push(`${count} ${name}${count === 1 ? '' : 's'}`)\n if (parts.length === 2) break\n }\n return parts.join(' ')\n}\n\n/** The minute of the day for `HH:MM` (24-hour), or nothing when it is not one. */\nexport function parseTimeOfDay(text: string): number | undefined {\n const match = /^(\\d{1,2}):(\\d{2})$/.exec(text.trim())\n if (match === null) return undefined\n const hour = Number(match[1])\n const minute = Number(match[2])\n return hour < 24 && minute < 60 ? hour * 60 + minute : undefined\n}\n\n/**\n * The instant the wall clock of a zone next reads `HH:MM` after `now`; with `daysLater`, that time on the day\n * that many days after today (it must still be after `now`).\n * @throws {RangeError} when the time is not `HH:MM` or is not after `now`.\n */\nexport function nextTimeOfDay(now: number, zone: string, time: string, daysLater?: number): number {\n const minuteOfDay = parseTimeOfDay(time)\n if (minuteOfDay === undefined) throw new RangeError(`\"${time}\" is not a time of day: write it as 07:30 (24-hour)`)\n const today = localTime(now, zone)\n const at = (extraDays: number): number => {\n const day = new Date(utcOf({ year: today.year, month: today.month, day: today.day }) + extraDays * DAY)\n return zonedInstant({ year: day.getUTCFullYear(), month: day.getUTCMonth() + 1, day: day.getUTCDate(), hour: Math.floor(minuteOfDay / 60), minute: minuteOfDay % 60 }, zone)\n }\n if (daysLater !== undefined) {\n const target = at(daysLater)\n if (target <= now) throw new RangeError(`${time} ${daysLater === 0 ? 'today' : `${daysLater} day${daysLater === 1 ? '' : 's'} later`} is not after now (${describeInstant(now, zone)})`)\n return target\n }\n const sameDay = at(0)\n return sameDay > now ? sameDay : at(1)\n}\n\n/** Whether a minute of the day is inside a window; `start` to `end` is half open and wraps past midnight, and equal ends make an empty window. */\nexport function inWindow(minuteOfDay: number, start: number, end: number): boolean {\n for (const value of [minuteOfDay, start, end]) if (!Number.isInteger(value) || value < 0 || value >= 1440) throw new RangeError('a minute of the day is from 0 to 1439')\n return start <= end ? minuteOfDay >= start && minuteOfDay < end : minuteOfDay >= start || minuteOfDay < end\n}\n\n/**\n * What to catch up on after being away: only the newest `maxMs` of the gap, in at most `maxSteps` equal\n * steps, so that a long absence costs a bounded amount of work.\n */\nexport function catchUpPlan(cursor: number, now: number, limits: { maxMs?: number; maxSteps?: number } = {}): { from: number; to: number; skipped: number; steps: { from: number; to: number }[] } {\n const maxMs = limits.maxMs ?? 6 * HOUR\n const maxSteps = limits.maxSteps ?? 360\n if (!Number.isInteger(maxMs) || maxMs <= 0 || !Number.isInteger(maxSteps) || maxSteps <= 0) throw new RangeError('the limits of a catch-up are positive whole numbers')\n const to = Math.max(cursor, now)\n const from = Math.max(cursor, to - maxMs)\n const span = to - from\n const count = Math.min(maxSteps, Math.ceil(span / MINUTE))\n return { from, to, skipped: from - cursor, steps: Array.from({ length: count }, (_, index) => ({ from: from + Math.floor(span * index / count), to: from + Math.floor(span * (index + 1) / count) })) }\n}\n\n/** `21:40`: the clock of a zone at an instant. */\nexport function clockTime(instant: number, zone: string): string {\n const local = localTime(instant, zone)\n return `${pad(local.hour)}:${pad(local.minute)}`\n}\n\n/** The local calendar day `days` after the one the instant falls on, as year, month and day. */\nexport function addLocalDays(instant: number, zone: string, days: number): { year: number; month: number; day: number; weekday: number } {\n const today = localTime(instant, zone)\n const moved = new Date(utcOf({ year: today.year, month: today.month, day: today.day }) + days * DAY)\n return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate(), weekday: moved.getUTCDay() }\n}\n\n/** `07:30` for a minute of the day. */\nexport const minuteText = (minute: number): string => `${pad(Math.floor(minute / 60))}:${pad(minute % 60)}`\n","import { ENGAGEMENT_STATUSES, INTENT_HORIZONS, INTENT_STATUSES, INTENT_TYPES, WEEKDAY_NAMES, type CharacterId, type Intent, type IntentPatch, type Location, type RoutineWindow } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport { MAX_ROUTINE_WINDOWS } from '../sqlite/agenda-repositories.ts'\nimport type { RecordsEdit, RecordsTarget } from './edit-types.ts'\nimport { dayTokenProblems, readCalendar } from './calendar.ts'\nimport { isTimeZone, parseInstant, parseTimeOfDay } from './time.ts'\n\nconst MAX_PLAN_STEPS = 8\nconst MAX_LIST_ENTRY = 240\nconst present = (value: string | undefined): boolean => value !== undefined && value.trim() !== ''\nconst list = <T>(value: readonly T[] | undefined): readonly T[] => value ?? []\n\n/** What the agenda part of an edit comes to, once every part of it is known to be acceptable. */\nexport interface PreparedAgenda {\n intents: { character: CharacterId; intent: Intent }[]\n intentEdits: { id: number; patch: IntentPatch }[]\n engagements: { title: string; at: number; until?: number; location?: string; participants: CharacterId[]; note?: string }[]\n engagementEdits: { id: number; patch: { status?: (typeof ENGAGEMENT_STATUSES)[number]; title?: string; at?: number; until?: number; location?: string; participants?: CharacterId[]; note?: string } }[]\n routines: { character: CharacterId; windows: (Omit<RoutineWindow, 'locationId'> & { location?: string })[] }[]\n}\n\ninterface Context {\n idOf: (key: string, where: string) => CharacterId | undefined\n placeKnown: (key: string, where: string) => void\n /** The existing places by key, to check the features of a place. */\n places: ReadonlyMap<string, Location>\n problems: string[]\n}\n\n/** Checks the goals, engagements and routines of an edit, and says what they would write. Problems are added to the context's. */\nexport function prepareAgenda(target: RecordsTarget, edit: RecordsEdit, context: Context): PreparedAgenda {\n const { idOf, placeKnown, problems } = context\n const zone = edit.timeZone ?? 'UTC'\n if (!isTimeZone(zone)) problems.push(`time_zone: \"${zone}\" is not a time zone`)\n const instant = (text: string | undefined, where: string): number | undefined => {\n if (text === undefined) return undefined\n try {\n return parseInstant(text, isTimeZone(zone) ? zone : 'UTC')\n } catch (error) {\n problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`)\n return undefined\n }\n }\n const unit = (value: number | undefined, where: string): void => {\n if (value !== undefined && (!Number.isFinite(value) || value < 0 || value > 1)) problems.push(`${where} must be a number from 0 to 1`)\n }\n const steps = (given: readonly string[] | undefined, where: string): string[] | undefined => {\n if (given === undefined) return undefined\n if (given.length > MAX_PLAN_STEPS) problems.push(`${where}: at most ${MAX_PLAN_STEPS} entries`)\n if (given.some(step => !present(step) || step.length > MAX_LIST_ENTRY)) problems.push(`${where}: each entry is a sentence of at most ${MAX_LIST_ENTRY} characters`)\n return given.map(step => step.trim())\n }\n\n const intents = list(edit.intentsAdded).flatMap((spec, index) => {\n const where = `intents_added[${index}]`\n const character = idOf(spec.character, where)\n if (!INTENT_TYPES.includes(spec.type)) problems.push(`${where}: unknown type \"${String(spec.type)}\" (${INTENT_TYPES.join(', ')})`)\n if (!INTENT_HORIZONS.includes(spec.horizon)) problems.push(`${where}: unknown horizon \"${String(spec.horizon)}\" (${INTENT_HORIZONS.join(', ')})`)\n if (!present(spec.name) || spec.name.length > 120) problems.push(`${where}: give the goal a name of at most 120 characters`)\n unit(spec.priority, `${where}.priority`)\n unit(spec.urgency, `${where}.urgency`)\n const plan = steps(spec.plan, `${where}.plan`)\n const constraints = steps(spec.constraints, `${where}.constraints`)\n const deadline = spec.deadline === undefined ? undefined : instant(spec.deadline, `${where}.deadline`)\n if (character === undefined) return []\n return [{ character, intent: {\n type: spec.type, name: spec.name.trim(), description: spec.description?.trim() ?? '', status: 'active' as const, horizon: spec.horizon, priority: spec.priority, urgency: spec.urgency,\n plan: plan ?? [], openThreads: [], constraints: constraints ?? [], ...(deadline === undefined ? {} : { deadline: new Date(deadline).toISOString() }),\n } }]\n })\n\n const intentEdits = list(edit.intentEdits).map((change, index) => {\n const where = `intent_edits[${index}]`\n if (target.intents.get(change.id) === undefined) problems.push(`${where}: there is no goal ${change.id} (read_records shows the ids)`)\n if (change.status !== undefined && !INTENT_STATUSES.includes(change.status)) problems.push(`${where}: unknown status \"${String(change.status)}\" (${INTENT_STATUSES.join(', ')})`)\n if (change.horizon !== undefined && !INTENT_HORIZONS.includes(change.horizon)) problems.push(`${where}: unknown horizon \"${String(change.horizon)}\"`)\n unit(change.priority, `${where}.priority`)\n unit(change.urgency, `${where}.urgency`)\n const plan = steps(change.plan, `${where}.plan`)\n const openThreads = steps(change.openThreads, `${where}.open_threads`)\n const deadline = change.deadline === undefined ? undefined : instant(change.deadline, `${where}.deadline`)\n const patch: IntentPatch = {\n ...(change.status === undefined ? {} : { status: change.status }), ...(change.horizon === undefined ? {} : { horizon: change.horizon }),\n ...(change.description === undefined ? {} : { description: change.description.trim() }),\n ...(change.priority === undefined ? {} : { priority: change.priority }), ...(change.urgency === undefined ? {} : { urgency: change.urgency }),\n ...(plan === undefined ? {} : { plan }), ...(openThreads === undefined ? {} : { openThreads }),\n ...(deadline === undefined ? {} : { deadline: new Date(deadline).toISOString() }),\n }\n if (Object.keys(patch).length === 0) problems.push(`${where}: nothing to change`)\n return { id: change.id, patch }\n })\n\n const engagements = list(edit.engagements).flatMap((spec, index) => {\n const where = `engagements[${index}]`\n if (!present(spec.title) || spec.title.length > 200) problems.push(`${where}: give it a title of at most 200 characters`)\n const at = instant(spec.at, `${where}.at`)\n const until = spec.until === undefined ? undefined : instant(spec.until, `${where}.until`)\n if (at !== undefined && until !== undefined && until < at) problems.push(`${where}: it cannot end before it is due`)\n if (spec.location !== undefined) placeKnown(spec.location, `${where}.location`)\n const participants = list(spec.participants).flatMap(key => idOf(key, `${where}.participants`) ?? [])\n if (list(spec.participants).length === 0) problems.push(`${where}: say who has committed to it (participants)`)\n return at === undefined ? [] : [{ title: spec.title.trim(), at, ...(until === undefined ? {} : { until }), ...(spec.location === undefined ? {} : { location: spec.location }), participants, ...(spec.note === undefined ? {} : { note: spec.note.trim() }) }]\n })\n\n const engagementEdits = list(edit.engagementEdits).map((change, index) => {\n const where = `engagement_edits[${index}]`\n const current = target.engagements.get(change.id)\n if (current === undefined) problems.push(`${where}: there is no engagement ${change.id} (read_records shows the ids)`)\n if (change.status !== undefined && !ENGAGEMENT_STATUSES.includes(change.status)) problems.push(`${where}: unknown status \"${String(change.status)}\" (${ENGAGEMENT_STATUSES.join(', ')})`)\n if (change.title !== undefined && !present(change.title)) problems.push(`${where}: the title cannot be empty`)\n const at = change.at === undefined ? undefined : instant(change.at, `${where}.at`)\n const until = change.until === undefined ? undefined : instant(change.until, `${where}.until`)\n if ((at ?? current?.at) !== undefined && until !== undefined && until < (at ?? current!.at)) problems.push(`${where}: it cannot end before it is due`)\n if (change.location !== undefined) placeKnown(change.location, `${where}.location`)\n const participants = change.participants === undefined ? undefined : change.participants.flatMap(key => idOf(key, `${where}.participants`) ?? [])\n if (change.participants !== undefined && change.participants.length === 0) problems.push(`${where}: it needs at least one participant`)\n const patch = {\n ...(change.status === undefined ? {} : { status: change.status }), ...(change.title === undefined ? {} : { title: change.title.trim() }),\n ...(at === undefined ? {} : { at }), ...(until === undefined ? {} : { until }), ...(change.location === undefined ? {} : { location: change.location }),\n ...(participants === undefined ? {} : { participants }), ...(change.note === undefined ? {} : { note: change.note.trim() }),\n }\n if (Object.keys(patch).length === 0) problems.push(`${where}: nothing to change`)\n return { id: change.id, patch }\n })\n\n const routines = list(edit.routines).flatMap((set, index) => {\n const where = `routines[${index}]`\n const character = idOf(set.character, where)\n if (list(set.windows).length > MAX_ROUTINE_WINDOWS) problems.push(`${where}: at most ${MAX_ROUTINE_WINDOWS} windows in a day`)\n const windows = list(set.windows).flatMap((window, at) => {\n const here = `${where}.windows[${at}]`\n const start = parseTimeOfDay(window.from)\n const end = parseTimeOfDay(window.to)\n if (start === undefined) problems.push(`${here}.from: \"${window.from}\" is not a time of day (HH:MM)`)\n if (end === undefined) problems.push(`${here}.to: \"${window.to}\" is not a time of day (HH:MM)`)\n if (start !== undefined && start === end) problems.push(`${here}: it starts and ends at the same time`)\n if (!present(window.activity)) problems.push(`${here}: say what the character is doing`)\n const days = list(window.days).flatMap((day) => {\n const found = WEEKDAY_NAMES.indexOf(day as (typeof WEEKDAY_NAMES)[number])\n if (found < 0) problems.push(`${here}.days: \"${day}\" is not a day (${WEEKDAY_NAMES.join(', ')})`)\n return found < 0 ? [] : [found]\n })\n const holidays = new Set(readCalendar(target.metadata).holidays.map(holiday => holiday.id))\n problems.push(...dayTokenProblems(list(window.on), `${here}.on`, holidays))\n if (window.location !== undefined) {\n placeKnown(window.location, `${here}.location`)\n const place = context.places.get(window.location)\n if (window.feature !== undefined && place !== undefined && !place.features.some(feature => feature.key === window.feature)) problems.push(`${here}: ${place.name} has no feature \"${window.feature}\"`)\n } else if (window.feature !== undefined) problems.push(`${here}: a feature needs a location`)\n if (start === undefined || end === undefined) return []\n return [{\n days, on: [...list(window.on)], start, end, activity: window.activity.trim(), interruptible: window.interruptible ?? true,\n ...(window.location === undefined ? {} : { location: window.location }), ...(window.feature === undefined ? {} : { featureKey: window.feature }),\n ...(window.position === undefined || window.position.trim() === '' ? {} : { position: window.position.trim() }),\n }]\n })\n return character === undefined ? [] : [{ character, windows }]\n })\n\n return { intents, intentEdits, engagements, engagementEdits, routines }\n}\n\n/** Writes what {@link prepareAgenda} found acceptable; returns how many rows were written. */\nexport function writeAgenda(target: RecordsTarget, prepared: PreparedAgenda, turn: number, placeId: (key: string) => number): number {\n let writes = 0\n for (const { character, intent } of prepared.intents) { target.intents.add(character, intent); writes += 1 }\n for (const { id, patch } of prepared.intentEdits) { target.intents.update(id, patch); writes += 1 }\n for (const spec of prepared.engagements) {\n target.engagements.add({ title: spec.title, at: spec.at, ...(spec.until === undefined ? {} : { until: spec.until }), ...(spec.location === undefined ? {} : { locationId: placeId(spec.location) }), participants: spec.participants, ...(spec.note === undefined ? {} : { note: spec.note }), turn })\n writes += 1\n }\n for (const { id, patch } of prepared.engagementEdits) {\n const { location, ...rest } = patch\n try {\n target.engagements.update(id, { ...rest, ...(location === undefined ? {} : { locationId: placeId(location) }), turn })\n } catch (error) {\n throw error instanceof Error ? new InvalidEditError([`engagement_edits: ${error.message}`]) : error\n }\n writes += 1\n }\n for (const set of prepared.routines) {\n target.routines.replace(set.character, set.windows.map(({ location, ...window }) => ({ ...window, ...(location === undefined ? {} : { locationId: placeId(location) }) })))\n writes += 1\n }\n return writes\n}\n","import type { CharacterId, ExitState, Holder, Item, ItemId, LocationId } from 'dsh-roleplay-model'\nimport { InvalidMoveError } from '../errors.ts'\nimport type { CharacterRepository, ItemRepository, LocationRepository, PlacementRepository } from '../repositories.ts'\nimport { characterKey, locationKey } from './edit-types.ts'\n\n/** The name by which models and tools refer to an item: its id in the world, or its number when it was made up in play. */\nexport const itemKey = (item: Pick<Item, 'id' | 'sourceId'>): string => item.sourceId ?? String(item.id)\n\nexport const ITEM_ACTIONS = ['take', 'drop', 'give', 'put', 'wear', 'remove', 'open', 'close', 'lock', 'unlock', 'reveal'] as const\nexport type ItemAction = (typeof ITEM_ACTIONS)[number]\n\n/** What a character does with an item, by keys. */\nexport interface ItemChangeSpec {\n item: string\n action: ItemAction\n /** For give: the character it goes to. For put: the container it goes into. */\n to?: string\n /** For wear: the slot, when it has to be named. */\n slot?: string\n /** How many, of something that comes in numbers; all of it when left out. */\n quantity?: number\n /** For drop and put: where in the place or container. */\n position?: string\n /** For drop: the feature of the place it is left at. */\n feature?: string\n /** For lock and unlock: the item used. */\n with?: string\n /** For lock and unlock of a way instead of an item: the key of the place the way leads to. */\n exit?: string\n /** For open, lock and unlock: the story breaks it open or shut instead (picked, smashed). */\n forced?: boolean\n}\n\nexport interface ItemContext {\n items: ItemRepository\n locations: Pick<LocationRepository, 'get' | 'getExit' | 'list' | 'updateExit'>\n placements: Pick<PlacementRepository, 'get'>\n characters: Pick<CharacterRepository, 'get' | 'list'>\n}\n\n/** What changes if the action is done. */\nexport type ItemPlan =\n | { action: 'move'; spec: ItemChangeSpec; item: Item; quantity: number; holder: Holder; summary: string }\n | { action: 'container'; spec: ItemChangeSpec; item: Item; state: 'open' | 'closed' | 'locked'; summary: string }\n | { action: 'exit'; spec: ItemChangeSpec; from: LocationId; to: LocationId; state: ExitState; summary: string }\n | { action: 'reveal'; spec: ItemChangeSpec; item: Item; summary: string }\n\n/** What was done, for the record of the round. */\nexport interface ItemEffect {\n item: { key: string; name: string }\n action: ItemAction\n /** In words: \"now carried by Bob\", \"now in the chest\". */\n summary: string\n}\n\ntype Reach = { kind: 'held' } | { kind: 'here' } | { kind: 'other'; by: string } | { kind: 'blocked'; why: string } | { kind: 'elsewhere' }\n\n/** How a character can get at an item: carrying it, with it in the place it is in, or not at all and why. */\nfunction reach(ctx: ItemContext, actor: CharacterId, item: Item, options: { allowHidden?: boolean; selfClosed?: boolean } = {}): Reach {\n const place = ctx.placements.get('character', actor)?.locationId\n if (item.hidden && options.allowHidden !== true) return { kind: 'blocked', why: `${item.name} cannot be seen` }\n let current: Item = item\n for (let hop = 0; hop < 32; hop++) {\n const holding = ctx.items.holding(current.id)\n if (holding === undefined) return { kind: 'elsewhere' }\n const { holder } = holding\n if (holder.kind === 'item') {\n const container = ctx.items.get(holder.itemId)\n if (container === undefined) return { kind: 'elsewhere' }\n if (container.hidden && options.allowHidden !== true) return { kind: 'blocked', why: `${item.name} cannot be seen` }\n if (container.container?.state !== 'open') return { kind: 'blocked', why: `${item.name} is inside ${container.name}, which is ${container.container?.state ?? 'closed'}` }\n current = container\n continue\n }\n if (holder.kind === 'character') {\n if (holder.characterId === actor) return { kind: 'held' }\n return { kind: 'other', by: ctx.characters.get(holder.characterId)?.name ?? String(holder.characterId) }\n }\n return holder.locationId === place ? { kind: 'here' } : { kind: 'elsewhere' }\n }\n return { kind: 'elsewhere' }\n}\n\nconst resolveItem = (ctx: ItemContext, key: string): Item | undefined => ctx.items.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? ctx.items.get(Number(key)) : undefined)\nconst resolveCharacter = (ctx: ItemContext, key: string) => ctx.characters.list().find(character => characterKey(character) === key)\nconst resolvePlace = (ctx: ItemContext, key: string) => ctx.locations.list().find(place => locationKey(place) === key)\n\n/**\n * Whether a character can do what the spec says with an item right now, and what it would come to. The\n * rules are the ones the story would expect, decided in code: it can only act on what it can get at (carried,\n * or here and in plain sight, in open containers only), it cannot take what someone else holds, a lock needs\n * the key it fits, a slot holds only so many.\n * @returns the plan, or every reason it cannot be done.\n */\nexport function planItemChange(ctx: ItemContext, actorId: CharacterId, spec: ItemChangeSpec): { ok: true; plan: ItemPlan } | { ok: false; problems: string[] } {\n const fail = (...problems: string[]): { ok: false; problems: string[] } => ({ ok: false, problems })\n const actor = ctx.characters.get(actorId)\n if (actor === undefined) return fail(`there is no character ${actorId}`)\n if (!ITEM_ACTIONS.includes(spec.action)) return fail(`unknown action \"${String(spec.action)}\" (the actions are: ${ITEM_ACTIONS.join(', ')})`)\n const place = ctx.placements.get('character', actorId)?.locationId\n\n if ((spec.action === 'lock' || spec.action === 'unlock' || spec.action === 'open') && spec.exit !== undefined) {\n if (spec.action === 'open') return fail('a way is open or locked, not opened: use unlock for a locked way')\n const to = resolvePlace(ctx, spec.exit)\n if (to === undefined) return fail(`there is no place \"${spec.exit}\"`)\n if (place === undefined) return fail(`${actor.name} is not in any place`)\n const exit = ctx.locations.getExit(place, to.id)\n if (exit === undefined) return fail(`there is no way from here to ${to.name}`)\n if (exit.state === 'blocked') return fail(`the way to ${to.name} is blocked, not locked: clearing it is a matter of the story, not a key`)\n const wanted = spec.action === 'lock' ? 'locked' : 'open'\n if (exit.state === wanted) return fail(`the way to ${to.name} is already ${wanted}`)\n const keyProblem = keyFor(ctx, actorId, spec, ctx.items.openers({ kind: 'exit', id: exit.id }), `the way to ${to.name}`)\n return keyProblem === undefined ? { ok: true, plan: { action: 'exit', spec, from: place, to: to.id, state: wanted, summary: `the way to ${to.name} is now ${wanted}` } } : fail(keyProblem)\n }\n\n const item = resolveItem(ctx, spec.item)\n if (item === undefined) return fail(`there is no item \"${spec.item}\" (list_items shows the keys)`)\n const quantity = spec.quantity ?? item.quantity\n const countProblems = (): string[] => {\n if (!Number.isInteger(quantity) || quantity < 1) return ['the quantity must be a whole number from 1']\n if (quantity > item.quantity) return [`there ${item.quantity === 1 ? 'is only 1' : `are only ${item.quantity}`} ${item.name}, not ${quantity}`]\n if (quantity < item.quantity && item.unique) return [`${item.name} is one thing and cannot be split`]\n return []\n }\n const reachable = reach(ctx, actorId, item, { allowHidden: spec.action === 'reveal' })\n const blocked = (): string[] => {\n if (reachable.kind === 'blocked') return [reachable.why]\n if (reachable.kind === 'elsewhere') return [`${item.name} is not here, and ${actor.name} does not have it`]\n return []\n }\n const moving = (holder: Holder, summary: string): { ok: true; plan: ItemPlan } => ({ ok: true, plan: { action: 'move', spec, item, quantity, holder, summary } })\n\n switch (spec.action) {\n case 'take': {\n const problems = [...blocked(), ...countProblems()]\n const direct = ctx.items.holding(item.id)?.holder\n if (reachable.kind === 'held' && direct?.kind === 'character') problems.push(`${actor.name} already has ${item.name}`)\n if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}, who has to give it`)\n return problems.length > 0 ? fail(...problems) : moving({ kind: 'character', characterId: actorId, mode: 'held' }, `now carried by ${actor.name}`)\n }\n case 'drop': {\n const problems = [...blocked(), ...countProblems()]\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind === 'character' && holding.holder.mode === 'worn') problems.push(`${item.name} is worn: remove it first`)\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n if (place === undefined) problems.push(`${actor.name} is not in any place, so there is nowhere to leave it`)\n if (problems.length > 0 || place === undefined) return fail(...problems)\n const where = ctx.locations.get(place)\n if (spec.feature !== undefined && !where?.features.some(feature => feature.key === spec.feature)) return fail(`${where?.name ?? 'this place'} has no feature \"${spec.feature}\"`)\n return moving({ kind: 'location', locationId: place, ...(spec.position === undefined ? {} : { position: spec.position }), ...(spec.feature === undefined ? {} : { featureKey: spec.feature }) }, `now left in ${where?.name ?? 'the place'}`)\n }\n case 'give': {\n const problems = [...blocked(), ...countProblems()]\n const to = spec.to === undefined ? undefined : resolveCharacter(ctx, spec.to)\n if (spec.to === undefined) problems.push('say who it is given to')\n else if (to === undefined) problems.push(`there is no character \"${spec.to}\"`)\n else if (to.id === actorId) problems.push(`${actor.name} cannot give something to itself`)\n else if (place === undefined || ctx.placements.get('character', to.id)?.locationId !== place) problems.push(`${to.name} is not here`)\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind === 'character' && holding.holder.mode === 'worn') problems.push(`${item.name} is worn: remove it first`)\n return problems.length > 0 || to === undefined ? fail(...problems) : moving({ kind: 'character', characterId: to.id, mode: 'held' }, `now carried by ${to.name}`)\n }\n case 'put': {\n const problems = [...blocked(), ...countProblems()]\n const container = spec.to === undefined ? undefined : resolveItem(ctx, spec.to)\n if (spec.to === undefined) problems.push('say which container it goes into')\n else if (container === undefined) problems.push(`there is no item \"${spec.to}\"`)\n else if (container.container === undefined) problems.push(`${container.name} cannot hold things`)\n else if (container.id === item.id || ctx.items.ancestors(container.id).includes(item.id)) problems.push(`${item.name} cannot be put inside itself`)\n else {\n const reachContainer = reach(ctx, actorId, container)\n if (reachContainer.kind === 'blocked') problems.push(reachContainer.why)\n else if (reachContainer.kind === 'elsewhere' || reachContainer.kind === 'other') problems.push(`${container.name} is not within reach`)\n else if (container.container?.state !== 'open') problems.push(`${container.name} is ${container.container?.state}: open it first`)\n }\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n return problems.length > 0 || container === undefined ? fail(...problems) : moving({ kind: 'item', itemId: container.id, ...(spec.position === undefined ? {} : { position: spec.position }) }, `now in ${container.name}`)\n }\n case 'wear': {\n const problems = [...blocked()]\n if (item.wearableSlot === undefined) problems.push(`${item.name} cannot be worn`)\n else if (spec.slot !== undefined && spec.slot !== item.wearableSlot) problems.push(`${item.name} is worn on the ${item.wearableSlot}, not the ${spec.slot}`)\n if (reachable.kind !== 'held' && problems.length === 0) problems.push(`${actor.name} is not carrying ${item.name}`)\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind === 'character' && holding.holder.mode === 'worn') problems.push(`${item.name} is already worn`)\n if (problems.length > 0 || item.wearableSlot === undefined) return fail(...problems)\n const slot = item.wearableSlot\n return moving({ kind: 'character', characterId: actorId, mode: 'worn', slot, ...(spec.position === undefined ? {} : { position: spec.position }) }, `now worn by ${actor.name} on the ${slot}`)\n }\n case 'remove': {\n const holding = ctx.items.holding(item.id)\n if (holding?.holder.kind !== 'character' || holding.holder.characterId !== actorId || holding.holder.mode !== 'worn') return fail(`${actor.name} is not wearing ${item.name}`)\n return moving({ kind: 'character', characterId: actorId, mode: 'held' }, `now carried by ${actor.name}`)\n }\n case 'open':\n case 'close': {\n const problems = [...blocked()]\n if (item.container === undefined) problems.push(`${item.name} cannot be opened or closed`)\n else if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}`)\n const state = item.container?.state\n if (spec.action === 'open') {\n if (state === 'open') problems.push(`${item.name} is already open`)\n if (state === 'locked' && spec.forced !== true) {\n const keyProblem = keyFor(ctx, actorId, spec, ctx.items.openers({ kind: 'item', id: item.id }), item.name)\n problems.push(keyProblem === undefined ? `${item.name} is locked: unlock it first` : `${item.name} is locked: ${keyProblem}`)\n }\n } else if (state !== 'open') problems.push(`${item.name} is already ${state}`)\n return problems.length > 0 ? fail(...problems) : { ok: true, plan: { action: 'container', spec, item, state: spec.action === 'open' ? 'open' : 'closed', summary: `${item.name} is now ${spec.action === 'open' ? 'open' : 'closed'}` } }\n }\n case 'lock':\n case 'unlock': {\n const problems = [...blocked()]\n const state = item.container?.state\n if (item.container === undefined) problems.push(`${item.name} has no lock`)\n else if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}`)\n if (spec.action === 'lock') {\n if (state === 'locked') problems.push(`${item.name} is already locked`)\n if (state === 'open') problems.push(`${item.name} is open: close it first`)\n } else if (state !== 'locked') problems.push(`${item.name} is not locked`)\n if (problems.length === 0) {\n const keyProblem = spec.forced === true && spec.action === 'unlock' ? undefined : keyFor(ctx, actorId, spec, ctx.items.openers({ kind: 'item', id: item.id }), item.name)\n if (keyProblem !== undefined) problems.push(keyProblem)\n }\n return problems.length > 0 ? fail(...problems) : { ok: true, plan: { action: 'container', spec, item, state: spec.action === 'lock' ? 'locked' : 'closed', summary: `${item.name} is now ${spec.action === 'lock' ? 'locked' : 'unlocked'}` } }\n }\n case 'reveal': {\n if (!item.hidden) return fail(`${item.name} is not hidden`)\n const problems = blocked()\n if (reachable.kind === 'other') problems.push(`${item.name} is held by ${reachable.by}`)\n return problems.length > 0 ? fail(...problems) : { ok: true, plan: { action: 'reveal', spec, item, summary: `${item.name} is found` } }\n }\n }\n}\n\n/** Why a lock cannot be worked, or nothing when it can: the key must be held and be one that fits. */\nfunction keyFor(ctx: ItemContext, actor: CharacterId, spec: ItemChangeSpec, fits: readonly ItemId[], what: string): string | undefined {\n if (spec.forced === true) return undefined\n if (fits.length === 0) return `nothing is known to fit the lock of ${what}: if the story breaks it, say forced`\n if (spec.with === undefined) return `say which key is used on ${what}`\n const key = resolveItem(ctx, spec.with)\n if (key === undefined) return `there is no item \"${spec.with}\"`\n if (!fits.includes(key.id)) return `${key.name} does not fit the lock of ${what}`\n const reachKey = reach(ctx, actor, key)\n return reachKey.kind === 'held' ? undefined : `${key.name} is not in hand`\n}\n\n/** A copy of an item with another quantity, for splitting off part of a pile. */\nconst sameKind = (a: Item, b: Item): boolean => !a.unique && !b.unique && a.name === b.name && a.quality === b.quality && a.wearableSlot === b.wearableSlot && a.container === undefined && b.container === undefined && a.ownerId === b.ownerId\n\n/** Do what a plan says. Part of a pile is split off, and joins a pile of the same kind where it lands. */\nexport function applyItemPlan(ctx: ItemContext, plan: ItemPlan): ItemEffect {\n const describe = (item: Pick<Item, 'id' | 'sourceId' | 'name'>, action: ItemAction, summary: string): ItemEffect => ({ item: { key: itemKey(item), name: item.name }, action, summary })\n switch (plan.action) {\n case 'reveal':\n ctx.items.update(plan.item.id, { hidden: false })\n return describe(plan.item, 'reveal', plan.summary)\n case 'container':\n ctx.items.update(plan.item.id, { container: { state: plan.state } })\n return describe(plan.item, plan.spec.action, plan.summary)\n case 'exit': {\n for (const [from, to] of [[plan.from, plan.to], [plan.to, plan.from]] as const) {\n const exit = ctx.locations.getExit(from, to)\n if (exit !== undefined) ctx.locations.updateExit(exit.id, { state: plan.state })\n }\n return { item: { key: locationKey(ctx.locations.get(plan.to)!), name: ctx.locations.get(plan.to)!.name }, action: plan.spec.action, summary: plan.summary }\n }\n case 'move': {\n const { item, quantity, holder } = plan\n const joins = holder.kind !== 'character' || holder.mode === 'held'\n const twin = joins ? ctx.items.contents(holderKey(holder)).find(({ item: other }) => other.id !== item.id && sameKind(item, other))?.item : undefined\n if (quantity >= item.quantity) {\n if (twin === undefined) {\n ctx.items.place(item.id, holder)\n return describe(item, plan.spec.action, plan.summary)\n }\n ctx.items.update(twin.id, { quantity: twin.quantity + item.quantity })\n ctx.items.remove(item.id)\n return describe(twin, plan.spec.action, plan.summary)\n }\n ctx.items.update(item.id, { quantity: item.quantity - quantity })\n if (twin !== undefined) {\n ctx.items.update(twin.id, { quantity: twin.quantity + quantity })\n return describe(twin, plan.spec.action, plan.summary)\n }\n const { id: _id, sourceId: _sourceId, createdAt: _createdAt, ...rest } = item\n return describe(ctx.items.add({ ...rest, quantity }, holder), plan.spec.action, plan.summary)\n }\n }\n}\n\nfunction holderKey(holder: Holder): { kind: 'location' | 'character' | 'item'; id: number } {\n return holder.kind === 'location' ? { kind: 'location', id: holder.locationId } : holder.kind === 'character' ? { kind: 'character', id: holder.characterId } : { kind: 'item', id: holder.itemId }\n}\n\n/**\n * Do what a character does with an item.\n * @throws {InvalidMoveError} naming every reason when it cannot, changing nothing.\n */\nexport function changeItem(ctx: ItemContext, actorId: CharacterId, spec: ItemChangeSpec): ItemEffect {\n const planned = planItemChange(ctx, actorId, spec)\n if (!planned.ok) throw new InvalidMoveError(planned.problems)\n return applyItemPlan(ctx, planned.plan)\n}\n","import type { Exit, LocationId, Move, MovePlan } from 'dsh-roleplay-model'\nimport { InvalidMoveError } from '../errors.ts'\nimport type { KnowledgeRepository, LocationRepository, PlacementRepository } from '../repositories.ts'\n\nexport interface MoveContext {\n locations: Pick<LocationRepository, 'get' | 'allExits'>\n placements: Pick<PlacementRepository, 'get' | 'place'>\n}\n\nexport interface KnownMoveContext extends MoveContext {\n knowledge: Pick<KnowledgeRepository, 'knows'>\n}\n\nconst name = (context: MoveContext, id: LocationId): string => context.locations.get(id)?.name ?? String(id)\n\n/** The shortest way over exits that satisfy `usable`, as the exits taken in order, or `undefined` when there is none. */\nfunction shortestWay(exits: readonly Exit[], from: LocationId, to: LocationId, usable: (exit: Exit) => boolean): Exit[] | undefined {\n const reached = new Map<LocationId, Exit[]>([[from, []]])\n const queue: LocationId[] = [from]\n for (let next = queue.shift(); next !== undefined; next = queue.shift()) {\n if (next === to) return reached.get(next)\n for (const exit of exits) {\n if (exit.fromId !== next || reached.has(exit.toId) || !usable(exit)) continue\n reached.set(exit.toId, [...reached.get(next)!, exit])\n queue.push(exit.toId)\n }\n }\n return undefined\n}\n\n/**\n * Whether a character can go where a move says, and the way it would take. Moving to where it\n * already is only changes its position. Otherwise there must be a way over open exits, unless the\n * move ignores them.\n * @returns the plan, or the reasons it cannot be done.\n */\nexport function planMove(context: MoveContext, characterId: number, move: Move): { ok: true; plan: MovePlan } | { ok: false; problems: string[] } {\n const problems: string[] = []\n const destination = context.locations.get(move.to)\n if (destination === undefined) return { ok: false, problems: [`there is no place ${move.to}`] }\n if (move.featureKey !== undefined && !destination.features.some(feature => feature.key === move.featureKey)) {\n problems.push(`${destination.name} has no feature \"${move.featureKey}\" (it has: ${destination.features.map(feature => feature.key).join(', ') || 'none'})`)\n }\n const from = context.placements.get('character', characterId)?.locationId\n if (from === move.to) return problems.length > 0 ? { ok: false, problems } : { ok: true, plan: { from, to: move.to, via: [] } }\n if (from === undefined || move.ignoreExits === true) return problems.length > 0 ? { ok: false, problems } : { ok: true, plan: { ...(from === undefined ? {} : { from }), to: move.to, via: [move.to] } }\n\n const exits = context.locations.allExits()\n const way = shortestWay(exits, from, move.to, exit => exit.state === 'open')\n if (way === undefined) {\n const blocked = shortestWay(exits, from, move.to, () => true)\n if (blocked === undefined) problems.push(`there is no way from ${name(context, from)} to ${destination.name}`)\n else {\n const stopper = blocked.find(exit => exit.state !== 'open')!\n problems.push(`the way from ${name(context, from)} to ${destination.name} is ${stopper.state} at ${name(context, stopper.fromId)} -> ${name(context, stopper.toId)}${stopper.note === '' ? '' : `: ${stopper.note}`}`)\n }\n }\n if (problems.length > 0 || way === undefined) return { ok: false, problems }\n const times = way.map(exit => exit.travelSeconds)\n return { ok: true, plan: { from, to: move.to, via: way.map(exit => exit.toId), ...(times.every(time => time !== undefined) ? { travelSeconds: times.reduce<number>((sum, time) => sum + time!, 0) } : {}) } }\n}\n\n/** Plan only through places and directed ways this character knows; forced movement remains the authoritative planner's job. */\nexport function planKnownMove(context: KnownMoveContext, characterId: number, move: Move): ReturnType<typeof planMove> {\n if (move.ignoreExits !== true && !context.knowledge.knows(characterId, 'location', move.to)) return { ok: false, problems: [`the character does not know place ${move.to}`] }\n if (move.ignoreExits === true) return planMove(context, characterId, move)\n return planMove({\n placements: context.placements,\n locations: { get: id => context.locations.get(id), allExits: () => context.locations.allExits().filter(exit => context.knowledge.knows(characterId, 'exit', exit.id)) },\n }, characterId, move)\n}\n\n/**\n * Move a character: where it stands changes to the destination, at the position or feature given.\n * @throws {InvalidMoveError} naming every reason when it cannot.\n */\nexport function moveCharacter(context: MoveContext, characterId: number, move: Move): MovePlan {\n const result = planMove(context, characterId, move)\n if (!result.ok) throw new InvalidMoveError(result.problems)\n if (result.plan.from === move.to && move.position === undefined && move.featureKey === undefined) return result.plan\n context.placements.place('character', characterId, { locationId: move.to, ...(move.position === undefined ? {} : { position: move.position }), ...(move.featureKey === undefined ? {} : { featureKey: move.featureKey }) })\n return result.plan\n}\n","/**\n * What the words of a cue or a beat may name by `{kind:key}`, filled in from the story when they are told. The key is how the world's files\n * name the thing (`@self` in a cue is the character it is said to), and a name follows the story: a renamed character is renamed in the words.\n */\nexport const TEMPLATE_KINDS = {\n /** The name of a character. */\n character: { args: 1, about: 'a character' },\n /** The name of a place. */\n place: { args: 1, about: 'a place' },\n /** The name of an item. */\n item: { args: 1, about: 'an item' },\n /** The name of the place a character is in now. */\n where: { args: 1, about: 'a character' },\n /** Who holds an item now, or the place it lies in. */\n holder: { args: 1, about: 'an item' },\n /** What a variable is now, in words: `{value:key}` for a world variable, `{value:key:subject}` for the character, item or place it is about. */\n value: { args: 2, about: 'a variable' },\n /** The time of day in the story, as `19:30`. */\n time: { args: 0, about: '' },\n} as const\n\nexport type TemplateKind = keyof typeof TEMPLATE_KINDS\n\nexport interface Placeholder {\n raw: string\n kind: TemplateKind\n args: string[]\n}\n\nconst PATTERN = /\\{([a-z]+)(?::([^{}]*))?\\}/g\n\n/** The placeholders in some words, and what is wrong with any that is not one. Anything that does not look like `{word}` or `{word:key}` is plain text. */\nexport function placeholdersOf(text: string): { found: Placeholder[]; problems: string[] } {\n const found: Placeholder[] = []\n const problems: string[] = []\n for (const match of text.matchAll(PATTERN)) {\n const [raw, word, rest] = match as unknown as [string, string, string | undefined]\n if (!(word in TEMPLATE_KINDS)) { problems.push(`${raw}: there is no \"${word}\"; the words may name ${Object.keys(TEMPLATE_KINDS).join(', ')}`); continue }\n const kind = word as TemplateKind\n const args = rest === undefined ? [] : rest.split(':').map(part => part.trim())\n const { args: wanted } = TEMPLATE_KINDS[kind]\n const ok = kind === 'value' ? args.length >= 1 && args.length <= 2 : args.length === wanted\n if (!ok || args.some(part => part === '')) { problems.push(`${raw}: ${kind === 'time' ? '{time} takes nothing' : kind === 'value' ? '{value:variable} or {value:variable:subject}' : `{${kind}:key} takes the key of ${TEMPLATE_KINDS[kind].about}`}`); continue }\n found.push({ raw, kind, args })\n }\n return { found, problems }\n}\n","import { EMOTION_VARIABLES, MAX_VARIABLES, VARIABLE_KEY, VARIABLE_KINDS, VARIABLE_SUBJECTS, VARIABLE_VISIBILITIES, type StoredVariable, type VariableBand, type VariableDefinition, type VariableDefinitionInput, type VariableSubject, type VariableValue } from 'dsh-roleplay-model'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { VariableRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface DefRow {\n key: string\n ordinal: number\n name: string\n description: string\n kind: VariableDefinition['kind']\n subject: VariableSubject\n only_keys: string\n min_value: number | null\n max_value: number | null\n is_integer: number\n options: string\n default_value: string\n has_baseline: number\n visibility: VariableDefinition['visibility']\n bands: string\n always_shown: number\n builtin: number\n}\n\ninterface ValueRow {\n variable: string\n subject: VariableSubject\n subject_id: number\n value: string\n baseline: string | null\n updated_turn: number\n}\n\nconst MAX_BANDS = 8\nconst MAX_OPTIONS = 12\nconst MAX_ONLY = 50\n\nfunction parseValue(text: string, column: string): VariableValue {\n try {\n const value: unknown = JSON.parse(text)\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string') return value\n } catch {\n // reported below\n }\n throw new CorruptDataError(`${column} does not hold a number, a yes or no, or text`)\n}\n\nfunction parseBands(text: string): VariableBand[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(band => typeof band === 'object' && band !== null && typeof (band as VariableBand).upTo === 'number' && typeof (band as VariableBand).label === 'string')) return value as VariableBand[]\n } catch {\n // reported below\n }\n throw new CorruptDataError('variable_defs.bands does not hold a list of bands')\n}\n\nconst toDef = (row: DefRow): VariableDefinition => ({\n key: row.key, name: row.name, description: row.description, kind: row.kind, subject: row.subject, only: parseStringList(row.only_keys, 'variable_defs.only_keys'),\n ...(row.min_value === null ? {} : { min: row.min_value }), ...(row.max_value === null ? {} : { max: row.max_value }),\n integer: row.is_integer === 1, options: parseStringList(row.options, 'variable_defs.options'), default: parseValue(row.default_value, 'variable_defs.default_value'),\n baseline: row.has_baseline === 1, visibility: row.visibility, bands: parseBands(row.bands), always: row.always_shown === 1, builtin: row.builtin === 1,\n})\n\nconst toStored = (row: ValueRow): StoredVariable => ({\n variable: row.variable, subject: row.subject, subjectId: row.subject_id, value: parseValue(row.value, 'variable_values.value'),\n ...(row.baseline === null ? {} : { baseline: parseValue(row.baseline, 'variable_values.baseline') }), updatedTurn: row.updated_turn,\n})\n\n/** Why a value is not one the variable can have, or nothing when it is. */\nexport function valueIssue(def: Pick<VariableDefinition, 'key' | 'kind' | 'min' | 'max' | 'integer' | 'options'>, value: unknown): string | undefined {\n if (def.kind === 'flag') return typeof value === 'boolean' ? undefined : `${def.key} is a yes or no`\n if (def.kind === 'choice') return typeof value === 'string' && def.options.includes(value) ? undefined : `${def.key} is one of: ${def.options.join(', ')}`\n if (typeof value !== 'number' || !Number.isFinite(value)) return `${def.key} is a number`\n if (def.integer && !Number.isInteger(value)) return `${def.key} is a whole number`\n if ((def.min !== undefined && value < def.min) || (def.max !== undefined && value > def.max)) return `${def.key} is a number ${def.min === undefined ? '' : `from ${def.min} `}${def.max === undefined ? '' : `up to ${def.max}`}`.trim()\n return undefined\n}\n\nconst SUBJECT_TABLES: Record<Exclude<VariableSubject, 'world'>, string> = { character: 'characters', item: 'items', location: 'locations' }\n\nexport class SqliteVariableRepository implements VariableRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n ensureDefaults(): void {\n for (const def of EMOTION_VARIABLES) if (this.def(def.key) === undefined) this.write(def)\n }\n\n defs(): VariableDefinition[] {\n return this.db.all<DefRow>('SELECT * FROM variable_defs ORDER BY ordinal').map(toDef)\n }\n\n def(key: string): VariableDefinition | undefined {\n const row = this.db.get<DefRow>('SELECT * FROM variable_defs WHERE key = ?', [key])\n return row === undefined ? undefined : toDef(row)\n }\n\n define(input: VariableDefinitionInput): VariableDefinition {\n const existing = this.def(input.key)\n if (existing?.builtin === true) {\n const kept: VariableDefinition = { ...existing, name: input.name, description: input.description ?? existing.description, only: input.only ?? existing.only, visibility: input.visibility ?? existing.visibility, bands: input.bands ?? existing.bands, always: input.always ?? existing.always }\n return this.write(this.checked(kept))\n }\n if (existing === undefined && this.defs().length >= MAX_VARIABLES) throw new InvalidValueError(`a story tracks at most ${MAX_VARIABLES} variables`)\n return this.write(this.checked({\n key: input.key, name: input.name, description: input.description ?? '', kind: input.kind, subject: input.subject, only: input.only ?? [],\n ...(input.min === undefined ? {} : { min: input.min }), ...(input.max === undefined ? {} : { max: input.max }),\n integer: input.integer ?? false, options: input.options ?? [], default: input.default ?? (input.kind === 'flag' ? false : input.kind === 'choice' ? input.options?.[0] ?? '' : (input.min ?? 0)),\n baseline: input.baseline ?? false, visibility: input.visibility ?? 'public', bands: input.bands ?? [], always: input.always ?? false, builtin: false,\n }))\n }\n\n remove(key: string): boolean {\n const found = this.def(key)\n if (found?.builtin === true) throw new ConflictError(`${key} is built in and cannot be removed`)\n return this.db.run('DELETE FROM variable_defs WHERE key = ?', [key]).changes > 0\n }\n\n get(variable: string, subject: VariableSubject, subjectId: number): StoredVariable | undefined {\n const row = this.db.get<ValueRow>('SELECT * FROM variable_values WHERE variable = ? AND subject = ? AND subject_id = ?', [variable, subject, subjectId])\n return row === undefined ? undefined : toStored(row)\n }\n\n value(variable: string, subject: VariableSubject, subjectId: number): VariableValue {\n const stored = this.get(variable, subject, subjectId)\n if (stored !== undefined) return stored.value\n const def = this.def(variable)\n if (def === undefined) throw new NotFoundError(`there is no variable \"${variable}\"`)\n return def.default\n }\n\n set(variable: string, subject: VariableSubject, subjectId: number, change: { value?: VariableValue; baseline?: VariableValue }, turn: number): StoredVariable {\n return guard(() => this.db.transaction(() => {\n const def = this.def(variable)\n if (def === undefined) throw new NotFoundError(`there is no variable \"${variable}\"`)\n if (!this.applies(def, subject, subjectId)) throw new InvalidValueError(`${def.name} does not apply to this ${subject}`)\n for (const [what, given] of [['value', change.value], ['baseline', change.baseline]] as const) {\n if (given === undefined) continue\n if (what === 'baseline' && !def.baseline) throw new InvalidValueError(`${def.name} has no baseline`)\n const issue = valueIssue(def, given)\n if (issue !== undefined) throw new InvalidValueError(issue)\n }\n const current = this.get(variable, subject, subjectId)\n const baseline = !def.baseline ? undefined : change.baseline ?? current?.baseline ?? change.value ?? def.default\n const value = change.value ?? current?.value ?? baseline ?? def.default\n this.db.run(\n `INSERT INTO variable_values (variable, subject, subject_id, value, baseline, updated_turn) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (variable, subject, subject_id) DO UPDATE SET value = excluded.value, baseline = excluded.baseline, updated_turn = excluded.updated_turn`,\n [variable, subject, subjectId, toJson(value), baseline === undefined ? null : toJson(baseline), turn],\n )\n return this.get(variable, subject, subjectId)!\n }))\n }\n\n list(subject: VariableSubject, subjectId: number): StoredVariable[] {\n return this.db.all<ValueRow>('SELECT * FROM variable_values WHERE subject = ? AND subject_id = ? ORDER BY variable', [subject, subjectId]).map(toStored)\n }\n\n all(): StoredVariable[] {\n return this.db.all<ValueRow>('SELECT * FROM variable_values ORDER BY updated_turn DESC, variable').map(toStored)\n }\n\n applies(def: VariableDefinition, subject: VariableSubject, subjectId: number): boolean {\n if (def.subject !== subject) return false\n if (def.only.length === 0 || subject === 'world') return true\n const row = this.db.get<{ source_id: string | null }>(`SELECT source_id FROM ${SUBJECT_TABLES[subject]} WHERE id = ?`, [subjectId])\n if (row === undefined) return false\n return def.only.includes(row.source_id ?? String(subjectId))\n }\n\n private checked(def: VariableDefinition): VariableDefinition {\n const bad = (message: string): never => { throw new InvalidValueError(`${def.key}: ${message}`) }\n if (!VARIABLE_KEY.test(def.key)) bad('the key is lowercase letters, digits and underscores, starting with a letter, at most 40 characters')\n if (def.name.trim() === '' || def.name.length > 80) bad('give it a name of at most 80 characters')\n if (def.description.length > 400) bad('the description is at most 400 characters')\n if (!VARIABLE_KINDS.includes(def.kind)) bad(`unknown kind \"${String(def.kind)}\"`)\n if (!VARIABLE_SUBJECTS.includes(def.subject)) bad(`unknown subject \"${String(def.subject)}\"`)\n if (!VARIABLE_VISIBILITIES.includes(def.visibility)) bad(`unknown visibility \"${String(def.visibility)}\"`)\n if (def.visibility === 'private' && def.subject !== 'character') bad('only what belongs to a character can be private')\n if (def.only.length > MAX_ONLY || def.only.some(key => key.trim() === '')) bad(`it applies to at most ${MAX_ONLY} named subjects`)\n if (def.subject === 'world' && def.only.length > 0) bad('there is only one world')\n if (def.kind === 'number') {\n if ((def.min !== undefined && !Number.isFinite(def.min)) || (def.max !== undefined && !Number.isFinite(def.max)) || (def.min !== undefined && def.max !== undefined && def.min > def.max)) bad('its bounds are not acceptable')\n if (def.options.length > 0) bad('a number has no options')\n } else {\n if (def.min !== undefined || def.max !== undefined || def.integer || def.bands.length > 0) bad('only a number has bounds, whole numbers or bands')\n if (def.baseline && def.kind === 'flag') bad('a yes or no has no baseline')\n }\n if (def.kind === 'choice' && (def.options.length < 2 || def.options.length > MAX_OPTIONS || new Set(def.options).size !== def.options.length || def.options.some(option => option.trim() === ''))) bad(`a choice has from 2 to ${MAX_OPTIONS} different options`)\n if (def.kind !== 'choice' && def.options.length > 0) bad('only a choice has options')\n const issue = valueIssue(def, def.default)\n if (issue !== undefined) bad(`the default is not acceptable: ${issue}`)\n if (def.bands.length > MAX_BANDS || def.bands.some((band, index) => !Number.isFinite(band.upTo) || band.label.trim() === '' || (index > 0 && band.upTo <= def.bands[index - 1]!.upTo))) bad(`bands are from 1 to ${MAX_BANDS} words for rising bounds`)\n return def\n }\n\n private write(def: VariableDefinition): VariableDefinition {\n return guard(() => this.db.transaction(() => {\n const ordinal = this.db.get<{ ordinal: number }>('SELECT ordinal FROM variable_defs WHERE key = ?', [def.key])?.ordinal ?? (this.db.get<{ next: number | null }>('SELECT MAX(ordinal) + 1 AS next FROM variable_defs')?.next ?? 0)\n this.db.run(\n `INSERT INTO variable_defs (key, ordinal, name, description, kind, subject, only_keys, min_value, max_value, is_integer, options, default_value, has_baseline, visibility, bands, always_shown, builtin)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (key) DO UPDATE SET name = excluded.name, description = excluded.description, kind = excluded.kind, subject = excluded.subject, only_keys = excluded.only_keys,\n min_value = excluded.min_value, max_value = excluded.max_value, is_integer = excluded.is_integer, options = excluded.options, default_value = excluded.default_value,\n has_baseline = excluded.has_baseline, visibility = excluded.visibility, bands = excluded.bands, always_shown = excluded.always_shown`,\n [def.key, ordinal, def.name.trim(), def.description.trim(), def.kind, def.subject, toJson(def.only), def.min ?? null, def.max ?? null, def.integer ? 1 : 0, toJson(def.options), toJson(def.default), def.baseline ? 1 : 0, def.visibility, toJson(def.bands), def.always ? 1 : 0, def.builtin ? 1 : 0],\n )\n return this.def(def.key)!\n }))\n }\n}\n","import type { VariableDefinition, VariableSubject, VariableValue } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport type { CharacterRepository, ItemRepository, LocationRepository, VariableRepository } from '../repositories.ts'\nimport { valueIssue } from '../sqlite/variable-repository.ts'\nimport { characterKey, locationKey } from './edit-types.ts'\nimport { itemKey } from './items.ts'\n\nexport interface VariableContext {\n variables: VariableRepository\n characters: Pick<CharacterRepository, 'list'>\n items: Pick<ItemRepository, 'list'>\n locations: Pick<LocationRepository, 'list'>\n}\n\n/** A change to what the story tracks, as the game master and the keeper write it. Exactly one of `to`, `by` and `baseline`. */\nexport interface VariableChangeSpec {\n variable: string\n /** The key of the character, item or place; `world` for a variable of the whole story. */\n subject: string\n /** The value it becomes. */\n to?: VariableValue\n /** How much a number goes up (or down, when negative); it stops at its bounds. */\n by?: number\n /** For a variable with a baseline: the new baseline (temperament). */\n baseline?: VariableValue\n}\n\nexport interface VariableEffect {\n variable: VariableDefinition\n subjectName: string\n from: VariableValue\n to: VariableValue\n}\n\nexport type VariablePlan = { ok: true; effect: VariableEffect; subjectId: number; change: { value?: VariableValue; baseline?: VariableValue } } | { ok: false; problems: string[] }\n\n/** The subject a key names, for a kind of subject. */\nexport function subjectOf(context: VariableContext, kind: VariableSubject, key: string): { id: number; name: string } | undefined {\n if (kind === 'world') return key === 'world' ? { id: 0, name: 'the world' } : undefined\n if (kind === 'character') {\n const found = context.characters.list().find(character => characterKey(character) === key)\n return found === undefined ? undefined : { id: found.id, name: found.name }\n }\n if (kind === 'item') {\n const found = context.items.list().find(item => itemKey(item) === key)\n return found === undefined ? undefined : { id: found.id, name: found.name }\n }\n const found = context.locations.list().find(place => locationKey(place) === key)\n return found === undefined ? undefined : { id: found.id, name: found.name }\n}\n\n/** A number as it is told: short, without trailing zeros. */\nconst shortNumber = (value: number): string => String(Math.round(value * 100) / 100)\n\n/** A value in words: a number by its band when the variable has bands (and the number), yes or no, or the word. */\nexport function describeValue(def: Pick<VariableDefinition, 'kind' | 'bands'>, value: VariableValue): string {\n if (typeof value === 'boolean') return value ? 'yes' : 'no'\n if (typeof value === 'string') return value\n const band = def.bands.find(candidate => value <= candidate.upTo) ?? def.bands.at(-1)\n return band === undefined ? shortNumber(value) : `${band.label} (${shortNumber(value)})`\n}\n\n/** A variable written by its name or in other letter case (\"Valence\" for `valence`), when exactly one variable has that name or key. */\nfunction namedVariable(variables: Pick<VariableRepository, 'defs'>, written: string): VariableDefinition | undefined {\n const wanted = written.trim().normalize('NFKC').toLowerCase()\n const found = wanted === '' ? [] : variables.defs().filter(def => def.key.normalize('NFKC').toLowerCase() === wanted || def.name.normalize('NFKC').toLowerCase() === wanted)\n return found.length === 1 ? found[0] : undefined\n}\n\n/** Whether a change can be made, and what it would come to. Nothing is changed. */\nexport function planVariableChange(context: VariableContext, spec: VariableChangeSpec): VariablePlan {\n const def = context.variables.def(spec.variable) ?? namedVariable(context.variables, spec.variable)\n if (def === undefined) return { ok: false, problems: [`there is no variable \"${spec.variable}\" (list_variables shows them)`] }\n const given = [spec.to, spec.by, spec.baseline].filter(value => value !== undefined).length\n if (given !== 1) return { ok: false, problems: [`${def.key}: give exactly one of to, by and baseline`] }\n const subject = subjectOf(context, def.subject, spec.subject)\n if (subject === undefined) return { ok: false, problems: [`${def.key}: there is no ${def.subject === 'world' ? 'world: use \"world\"' : `${def.subject} \"${spec.subject}\"`}`] }\n if (!context.variables.applies(def, def.subject, subject.id)) return { ok: false, problems: [`${def.key} does not apply to ${subject.name} (it applies to: ${def.only.join(', ')})`] }\n const from = context.variables.value(def.key, def.subject, subject.id)\n if (spec.baseline !== undefined) {\n const issue = def.baseline ? valueIssue(def, spec.baseline) : `${def.key} has no baseline`\n return issue === undefined ? { ok: true, subjectId: subject.id, change: { baseline: spec.baseline }, effect: { variable: def, subjectName: subject.name, from, to: from } } : { ok: false, problems: [`${def.key}: ${issue}`] }\n }\n let to: VariableValue\n if (spec.by !== undefined) {\n if (def.kind !== 'number' || typeof from !== 'number') return { ok: false, problems: [`${def.key}: only a number goes up or down by an amount; use to`] }\n if (!Number.isFinite(spec.by)) return { ok: false, problems: [`${def.key}: by is a number`] }\n const moved = from + spec.by\n const bounded = Math.min(def.max ?? moved, Math.max(def.min ?? moved, moved))\n to = def.integer ? Math.round(bounded) : bounded\n } else {\n to = spec.to!\n const issue = valueIssue(def, to)\n if (issue !== undefined) return { ok: false, problems: [`${def.key}: ${issue}`] }\n }\n return { ok: true, subjectId: subject.id, change: { value: to }, effect: { variable: def, subjectName: subject.name, from, to } }\n}\n\n/**\n * Change a variable now.\n * @throws {InvalidEditError} naming every reason it cannot be done.\n */\nexport function changeVariable(context: VariableContext, spec: VariableChangeSpec, turn: number): VariableEffect {\n const planned = planVariableChange(context, spec)\n if (!planned.ok) throw new InvalidEditError(planned.problems)\n context.variables.set(planned.effect.variable.key, planned.effect.variable.subject, planned.subjectId, planned.change, turn)\n return planned.effect\n}\n\n/** Who is reading values: the game master and the keeper see everything, a character sees what is public and what is private to it, anyone else only what is public. */\nexport type VariableAudience = 'story' | 'self' | 'others'\n\nexport interface ShownVariable {\n variable: VariableDefinition\n value: VariableValue\n baseline?: VariableValue\n}\n\n/** At most this many variables are told for one subject. */\nexport const MAX_SHOWN = 8\n\n/** The variables of a subject that are worth telling, in the order they were declared: those whose value is not the default, and those always told. */\nexport function shownVariables(context: VariableContext, kind: VariableSubject, subjectId: number, subjectKey: string, audience: VariableAudience): ShownVariable[] {\n const stored = new Map(context.variables.list(kind, subjectId).map(entry => [entry.variable, entry]))\n return context.variables.defs().flatMap((def): ShownVariable[] => {\n if (def.subject !== kind || !(def.only.length === 0 || def.only.includes(subjectKey))) return []\n if (audience === 'others' ? def.visibility !== 'public' : audience === 'self' ? def.visibility === 'hidden' : false) return []\n const entry = stored.get(def.key)\n const value = entry?.value ?? def.default\n if (value === def.default && !def.always) return []\n return [{ variable: def, value, ...(entry?.baseline === undefined ? {} : { baseline: entry.baseline }) }]\n }).slice(0, MAX_SHOWN)\n}\n","import { COMPARISONS, SELF, WEEKDAY_NAMES, type Comparison, type Trigger, type TriggerAnnouncement, type TriggerAudience, type TriggerCondition, type TriggerDefinition, type TriggerEffect, type VariableValue } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\nimport { addLocalDays, inWindow, localTime, parseInstant, parseTimeOfDay } from './time.ts'\nimport { dayMatches, dayTokenProblems, readCalendar } from './calendar.ts'\nimport { placeholdersOf } from './template.ts'\nimport { subjectOf } from './variables.ts'\n\nexport type Wire = Record<string, unknown>\nconst isObject = (value: unknown): value is Wire => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** How deep a condition may nest and how many parts it may have: a trigger is a rule, not a program. */\nconst MAX_DEPTH = 4\nconst MAX_NODES = 24\nconst MAX_EFFECTS = 6\nconst MAX_TEXT = 1000\nconst MAX_JUDGED = 300\n\nconst text = (entry: Wire, key: string): string | undefined => (typeof entry[key] === 'string' && entry[key].trim() !== '' ? entry[key].trim() : undefined)\n\nfunction parseCondition(value: unknown, path: string, problems: string[], count: { nodes: number }, depth = 0): TriggerCondition | undefined {\n count.nodes += 1\n if (count.nodes > MAX_NODES) { if (count.nodes === MAX_NODES + 1) problems.push(`${path}: a condition has at most ${MAX_NODES} parts`); return undefined }\n if (depth > MAX_DEPTH) { problems.push(`${path}: conditions nest at most ${MAX_DEPTH} deep`); return undefined }\n if (!isObject(value)) { problems.push(`${path}: a condition is an object`); return undefined }\n const need = (key: string): string | undefined => {\n const found = text(value, key)\n if (found === undefined) problems.push(`${path}.${key}: required text`)\n return found\n }\n switch (value['type']) {\n case 'time': {\n const from = text(value, 'from')\n const to = text(value, 'to')\n const window = isObject(value['window']) ? { from: text(value['window'], 'from') ?? '', to: text(value['window'], 'to') ?? '' } : undefined\n const days = Array.isArray(value['days']) ? value['days'].filter((day): day is string => typeof day === 'string') : undefined\n const on = Array.isArray(value['on']) ? value['on'].filter((day): day is string => typeof day === 'string') : undefined\n if (value['on'] !== undefined && on?.length !== (value['on'] as unknown[] | undefined)?.length) problems.push(`${path}.on: a list of days (months, dates, seasons, holidays)`)\n if (on !== undefined) problems.push(...dayTokenProblems(on, `${path}.on`, 'any'))\n if (from === undefined && to === undefined && window === undefined && days === undefined && on === undefined) { problems.push(`${path}: a time condition needs from, to, window, days or on`); return undefined }\n if (window !== undefined && (parseTimeOfDay(window.from) === undefined || parseTimeOfDay(window.to) === undefined || window.from === window.to)) problems.push(`${path}.window: from and to are different times of day, HH:MM`)\n for (const day of days ?? []) if (!(WEEKDAY_NAMES as readonly string[]).includes(day)) problems.push(`${path}.days: \"${day}\" is not mon to sun`)\n if (value['days'] !== undefined && days?.length !== (value['days'] as unknown[] | undefined)?.length) problems.push(`${path}.days: a list of mon to sun`)\n return { type: 'time', ...(from === undefined ? {} : { from }), ...(to === undefined ? {} : { to }), ...(window === undefined ? {} : { window }), ...(days === undefined ? {} : { days }), ...(on === undefined ? {} : { on }) }\n }\n case 'place': {\n const character = need('character'); const location = need('location'); const feature = text(value, 'feature')\n return character === undefined || location === undefined ? undefined : { type: 'place', character, location, ...(feature === undefined ? {} : { feature }) }\n }\n case 'variable': {\n const variable = need('variable'); const subject = text(value, 'subject')\n const op = value['op'] as Comparison\n const found = value['value']\n if (!COMPARISONS.includes(op)) problems.push(`${path}.op: one of ${COMPARISONS.join(', ')}`)\n if (typeof found !== 'number' && typeof found !== 'string' && typeof found !== 'boolean') problems.push(`${path}.value: a number, text or yes/no`)\n return variable === undefined || !COMPARISONS.includes(op) || (typeof found !== 'number' && typeof found !== 'string' && typeof found !== 'boolean')\n ? undefined : { type: 'variable', variable, ...(subject === undefined ? {} : { subject }), op, value: found }\n }\n case 'item': {\n const item = need('item'); const heldBy = text(value, 'held_by'); const at = text(value, 'at')\n if ((heldBy === undefined) === (at === undefined)) { problems.push(`${path}: give exactly one of held_by and at`); return undefined }\n return item === undefined ? undefined : { type: 'item', item, ...(heldBy === undefined ? {} : { heldBy }), ...(at === undefined ? {} : { at }) }\n }\n case 'event': { const tag = need('tag'); return tag === undefined ? undefined : { type: 'event', tag: tag.toLowerCase() } }\n case 'fired': { const trigger = need('trigger'); return trigger === undefined ? undefined : { type: 'fired', trigger } }\n case 'judged': {\n const statement = need('text')\n if (statement !== undefined && statement.length > MAX_JUDGED) { problems.push(`${path}.text: at most ${MAX_JUDGED} characters`); return undefined }\n return statement === undefined ? undefined : { type: 'judged', text: statement }\n }\n case 'all':\n case 'any': {\n if (!Array.isArray(value['conditions']) || value['conditions'].length === 0) { problems.push(`${path}.conditions: a list with at least one condition`); return undefined }\n const parts = value['conditions'].map((part, index) => parseCondition(part, `${path}.conditions[${index}]`, problems, count, depth + 1))\n return parts.every(part => part !== undefined) ? { type: value['type'], conditions: parts as TriggerCondition[] } : undefined\n }\n case 'not': {\n const inner = parseCondition(value['condition'], `${path}.condition`, problems, count, depth + 1)\n return inner === undefined ? undefined : { type: 'not', condition: inner }\n }\n default:\n problems.push(`${path}.type: one of time, place, variable, item, event, fired, judged, all, any, not`)\n return undefined\n }\n}\n\nfunction parseAudience(value: unknown, path: string, problems: string[]): TriggerAudience | undefined {\n if (value === 'everyone') return 'everyone'\n if (isObject(value) && Array.isArray(value['characters']) && value['characters'].length > 0 && value['characters'].every(entry => typeof entry === 'string' && entry.trim() !== '')) return { characters: value['characters'] as string[] }\n if (isObject(value) && typeof value['place'] === 'string' && value['place'].trim() !== '') return { place: value['place'].trim() }\n problems.push(`${path}: \"everyone\", {\"characters\": [the characters]} or {\"place\": the place}`)\n return undefined\n}\n\nconst localTimeProblem = (value: string): boolean => { try { parseInstant(value, 'UTC'); return false } catch { return true } }\n\nfunction parseAnnouncement(value: unknown, path: string, problems: string[]): TriggerAnnouncement | undefined {\n if (!isObject(value)) { problems.push(`${path}: an announcement is an object: who knows, and what is known`); return undefined }\n const audience = parseAudience(value['audience'], `${path}.audience`, problems)\n const words = text(value, 'text')\n if (words === undefined || words.length > 500) problems.push(`${path}.text: required text of at most 500 characters`)\n const from = text(value, 'from')\n const at = text(value, 'at')\n for (const [field, found] of [['from', from], ['at', at]] as const) if (found !== undefined && localTimeProblem(found)) problems.push(`${path}.${field}: a local date and time, 1912-10-04T19:30`)\n return audience === undefined || words === undefined ? undefined : { audience, text: words, ...(from === undefined ? {} : { from }), ...(at === undefined ? {} : { at }) }\n}\n\n/** Checks that an edit effect is shaped as an edit; it throws {@link InvalidEditError} when not. */\nexport type EditChecker = (edit: Wire) => void\n\n/** Whether words or a condition name the character a cue is said to. */\nfunction usesSelf(words: string, condition: TriggerCondition | undefined): boolean {\n const inWords = placeholdersOf(words).found.some(placeholder => placeholder.args.includes(SELF))\n return inWords || (condition !== undefined && mentionsSelf(condition))\n}\n\nfunction mentionsSelf(condition: TriggerCondition): boolean {\n switch (condition.type) {\n case 'place': return condition.character === SELF\n case 'variable': return condition.subject === SELF\n case 'item': return condition.item === SELF || condition.heldBy === SELF\n case 'all': case 'any': return condition.conditions.some(mentionsSelf)\n case 'not': return mentionsSelf(condition.condition)\n default: return false\n }\n}\n\nfunction parseEffect(value: unknown, path: string, problems: string[], checkEdit: EditChecker): TriggerEffect | undefined {\n if (!isObject(value)) { problems.push(`${path}: an effect is an object`); return undefined }\n if (value['type'] === 'edit') {\n if (!isObject(value['edit'])) { problems.push(`${path}.edit: an edit, as the record keeper writes one`); return undefined }\n try { checkEdit({ turn: 0, ...value['edit'] }) } catch (error) { problems.push(`${path}.edit: ${error instanceof InvalidEditError ? error.problems.join('; ') : String(error)}`); return undefined }\n if (value['while'] !== undefined) { problems.push(`${path}.while: only a beat or a cue can wait on a condition when it is told`); return undefined }\n return { type: 'edit', edit: value['edit'] }\n }\n if (value['type'] !== 'beat' && value['type'] !== 'cue') { problems.push(`${path}.type: one of edit, beat, cue`); return undefined }\n const words = text(value, 'text')\n if (words === undefined || words.length > MAX_TEXT) { problems.push(`${path}.text: required text of at most ${MAX_TEXT} characters`); return undefined }\n const template = placeholdersOf(words)\n for (const problem of template.problems) problems.push(`${path}.text: ${problem}`)\n const waiting = value['while'] === undefined ? undefined : parseCondition(value['while'], `${path}.while`, problems, { nodes: 0 })\n if (value['while'] !== undefined && waiting === undefined) return undefined\n if (waiting !== undefined && judgedStatements(waiting).length > 0) problems.push(`${path}.while: a statement a model judges (judged) cannot be waited on when something is told; use what the story records`)\n if (value['type'] === 'beat') {\n if (usesSelf(words, waiting)) problems.push(`${path}: only a cue is said to someone, so only a cue can name ${SELF}`)\n return template.problems.length > 0 ? undefined : { type: 'beat', text: words, ...(waiting === undefined ? {} : { while: waiting }) }\n }\n if (value['type'] === 'cue') {\n const audience = value['audience'] !== undefined ? parseAudience(value['audience'], `${path}.audience`, problems) : parseAudience({ characters: value['characters'] }, `${path}.characters`, problems)\n return audience === undefined || template.problems.length > 0 ? undefined : { type: 'cue', audience, text: words, ...(waiting === undefined ? {} : { while: waiting }) }\n }\n problems.push(`${path}.type: one of edit, beat, cue`)\n return undefined\n}\n\n/**\n * Read a trigger from the JSON a world's files and the world author write (snake_case).\n * @returns the definition, or every problem with where it is.\n */\nexport function parseTriggerDefinition(value: unknown, path: string, checkEdit: EditChecker): { definition: TriggerDefinition } | { problems: string[] } {\n const problems: string[] = []\n if (!isObject(value)) return { problems: [`${path}: a trigger is an object`] }\n const key = text(value, 'key'); const name = text(value, 'name')\n if (key === undefined) problems.push(`${path}.key: required text`)\n if (name === undefined) problems.push(`${path}.name: required text`)\n const condition = parseCondition(value['when'], `${path}.when`, problems, { nodes: 0 })\n const rawEffects = value['effects']\n if (!Array.isArray(rawEffects) || rawEffects.length === 0 || rawEffects.length > MAX_EFFECTS) problems.push(`${path}.effects: a list of one to ${MAX_EFFECTS} effects`)\n const effects = Array.isArray(rawEffects) ? rawEffects.slice(0, MAX_EFFECTS).map((effect, index) => parseEffect(effect, `${path}.effects[${index}]`, problems, checkEdit)) : []\n const number = (field: string): number | undefined => (typeof value[field] === 'number' ? value[field] : undefined)\n if (value['repeat'] !== undefined && typeof value['repeat'] !== 'boolean') problems.push(`${path}.repeat: yes or no`)\n for (const field of ['cooldown_seconds', 'chance', 'priority']) if (value[field] !== undefined && typeof value[field] !== 'number') problems.push(`${path}.${field}: a number`)\n const chance = number('chance'); const cooldown = number('cooldown_seconds')\n if (chance !== undefined && (chance < 0 || chance > 1)) problems.push(`${path}.chance: from 0 to 1`)\n if (cooldown !== undefined && (!Number.isSafeInteger(cooldown) || cooldown < 0)) problems.push(`${path}.cooldown_seconds: a whole number of seconds`)\n const expires = text(value, 'expires')\n const announce = value['announce'] === undefined ? undefined : parseAnnouncement(value['announce'], `${path}.announce`, problems)\n if (expires !== undefined) { try { parseInstant(expires, 'UTC') } catch { problems.push(`${path}.expires: a local date and time, 1912-10-04T19:30`) } }\n if (problems.length > 0 || key === undefined || name === undefined || condition === undefined) return { problems }\n return {\n definition: {\n key, name, condition, effects: effects as TriggerEffect[], repeat: value['repeat'] === true, priority: number('priority') ?? 0,\n ...(cooldown === undefined ? {} : { cooldownSeconds: cooldown }), ...(chance === undefined ? {} : { chance }), ...(expires === undefined ? {} : { expires }), ...(announce === undefined ? {} : { announce }),\n },\n }\n}\n\ntype Reading = Pick<RecordsTarget, 'characters' | 'locations' | 'items' | 'variables' | 'triggers' | 'metadata'>\n\nfunction conditionProblems(target: Reading, condition: TriggerCondition, path: string, known: ReadonlySet<string>, self = false): string[] {\n const character = (key: string): string[] => ((self && key === SELF) || target.characters.list().some(entry => characterKey(entry) === key) ? [] : [`${path}: there is no character \"${key}\"`])\n const place = (key: string): string[] => (target.locations.list().some(entry => locationKey(entry) === key) ? [] : [`${path}: there is no place \"${key}\"`])\n switch (condition.type) {\n case 'time': return dayTokenProblems(condition.on ?? [], `${path}.on`, new Set(readCalendar(target.metadata).holidays.map(holiday => holiday.id)))\n case 'place': return [...character(condition.character), ...place(condition.location)]\n case 'variable': {\n const def = target.variables.def(condition.variable)\n if (def === undefined) return [`${path}: there is no variable \"${condition.variable}\"`]\n if (def.subject === 'world' ? condition.subject !== undefined : condition.subject === undefined) return [`${path}: ${def.subject === 'world' ? 'a world variable has no subject' : `give the ${def.subject} it is about as subject`}`]\n const subject = condition.subject === undefined || (self && condition.subject === SELF) ? undefined : subjectOf(target, def.subject, condition.subject)\n return [\n ...(condition.subject !== undefined && subject === undefined && !(self && condition.subject === SELF) ? [`${path}: there is no ${def.subject} \"${condition.subject}\"`] : []),\n ...(def.kind !== 'number' && condition.op !== 'eq' && condition.op !== 'ne' ? [`${path}: ${def.kind} variables compare with eq or ne only`] : []),\n ]\n }\n case 'item': return [\n ...((self && condition.item === SELF) || target.items.list().some(entry => itemKey(entry) === condition.item) ? [] : [`${path}: there is no item \"${condition.item}\"`]),\n ...(condition.heldBy === undefined ? [] : character(condition.heldBy)), ...(condition.at === undefined ? [] : place(condition.at)),\n ]\n case 'event': return []\n case 'fired': return known.has(condition.trigger) ? [] : [`${path}: there is no trigger \"${condition.trigger}\"`]\n case 'judged': return []\n case 'all': case 'any': return condition.conditions.flatMap((part, index) => conditionProblems(target, part, `${path}.conditions[${index}]`, known, self))\n case 'not': return conditionProblems(target, condition.condition, `${path}.condition`, known, self)\n }\n}\n\n/** What the words of a cue or beat name by `{kind:key}` that the story does not have. */\nfunction wordsProblems(target: Reading, words: string, path: string, self: boolean): string[] {\n return placeholdersOf(words).found.flatMap((placeholder): string[] => {\n const key = placeholder.args[0]!\n const selfKey = self && key === SELF\n const missing = (what: string): string[] => [`${path}: ${placeholder.raw}: there is no ${what} \"${key}\"`]\n switch (placeholder.kind) {\n case 'character': case 'where': return selfKey || target.characters.list().some(entry => characterKey(entry) === key) ? [] : missing('character')\n case 'place': return target.locations.list().some(entry => locationKey(entry) === key) ? [] : missing('place')\n case 'item': case 'holder': return target.items.list().some(entry => itemKey(entry) === key) ? [] : missing('item')\n case 'value': {\n const def = target.variables.def(key)\n if (def === undefined) return missing('variable')\n const subject = placeholder.args[1]\n if (def.subject === 'world') return subject === undefined ? [] : [`${path}: ${placeholder.raw}: a world variable has no subject`]\n if (subject === undefined) return [`${path}: ${placeholder.raw}: give the ${def.subject} it is about`]\n return (self && subject === SELF) || subjectOf(target, def.subject, subject) !== undefined ? [] : [`${path}: ${placeholder.raw}: there is no ${def.subject} \"${subject}\"`]\n }\n case 'time': return []\n }\n })\n}\n\n/**\n * What in a trigger names something the story does not have: a character, place, item or variable in a condition, the characters of a cue,\n * a trigger it waits for. (What an edit effect touches is checked when it is applied.)\n */\nexport function triggerReferenceProblems(target: Reading, definition: TriggerDefinition, otherKeys: Iterable<string> = []): string[] {\n const known = new Set([...target.triggers.list().map(trigger => trigger.key), ...otherKeys])\n const audience = (who: TriggerAudience, path: string): string[] => {\n if (who === 'everyone') return []\n if ('place' in who) return target.locations.list().some(entry => locationKey(entry) === who.place) ? [] : [`${path}: there is no place \"${who.place}\"`]\n return who.characters.flatMap(key => (target.characters.list().some(entry => characterKey(entry) === key) ? [] : [`${path}: there is no character \"${key}\"`]))\n }\n const cues = definition.effects.flatMap((effect, index) => (effect.type !== 'cue' ? [] : audience(effect.audience, `effects[${index}]`)))\n const said = definition.effects.flatMap((effect, index) => (effect.type === 'edit' ? [] : [\n ...(effect.while === undefined ? [] : conditionProblems(target, effect.while, `effects[${index}].while`, known, effect.type === 'cue')),\n ...wordsProblems(target, effect.text, `effects[${index}].text`, effect.type === 'cue'),\n ]))\n const announced = definition.announce === undefined ? [] : audience(definition.announce.audience, 'announce')\n return [...conditionProblems(target, definition.condition, 'when', known), ...cues, ...said, ...announced].map(problem => `${definition.key}: ${problem}`)\n}\n\nconst COMPARE: Record<Comparison, (a: number, b: number) => boolean> = { eq: (a, b) => a === b, ne: (a, b) => a !== b, lt: (a, b) => a < b, le: (a, b) => a <= b, gt: (a, b) => a > b, ge: (a, b) => a >= b }\n\nfunction compare(op: Comparison, have: VariableValue, want: VariableValue): boolean {\n if (typeof have === 'number' && typeof want === 'number') return COMPARE[op](have, want)\n return op === 'ne' ? have !== want : op === 'eq' ? have === want : false\n}\n\nexport interface TriggerClock {\n now: number\n zone: string\n /** Whether a model has judged a statement true; a statement nobody judged is false. */\n judged?: (statement: string) => boolean\n}\n\n/** The statements of the `judged` parts of a condition, in order, each once. */\nexport function judgedStatements(condition: TriggerCondition): string[] {\n switch (condition.type) {\n case 'judged': return [condition.text]\n case 'all': case 'any': return [...new Set(condition.conditions.flatMap(judgedStatements))]\n case 'not': return judgedStatements(condition.condition)\n default: return []\n }\n}\n\nfunction holds(target: RecordsTarget, condition: TriggerCondition, clock: TriggerClock): boolean {\n switch (condition.type) {\n case 'time': {\n const { now, zone } = clock\n if (condition.from !== undefined && now < parseInstant(condition.from, zone)) return false\n if (condition.to !== undefined && now >= parseInstant(condition.to, zone)) return false\n const local = localTime(now, zone)\n const calendar = readCalendar(target.metadata)\n /** The day a time belongs to: the morning part of a window past midnight belongs to the day before. */\n const dayAt = (shift: number) => addLocalDays(now, zone, shift)\n const onDay = (shift: number): boolean => {\n const day = dayAt(shift)\n return (condition.days === undefined || condition.days.length === 0 || condition.days.includes(WEEKDAY_NAMES[day.weekday] ?? '')) && (condition.on === undefined || dayMatches(condition.on, day, calendar))\n }\n if (condition.window !== undefined) {\n const start = parseTimeOfDay(condition.window.from) ?? 0\n const end = parseTimeOfDay(condition.window.to) ?? 0\n if (!inWindow(local.minuteOfDay, start, end)) return false\n return onDay(start > end && local.minuteOfDay < end ? -1 : 0)\n }\n return onDay(0)\n }\n case 'place': {\n const who = target.characters.list().find(entry => characterKey(entry) === condition.character)\n const where = target.locations.list().find(entry => locationKey(entry) === condition.location)\n const placement = who === undefined ? undefined : target.placements.get('character', who.id)\n return placement !== undefined && where !== undefined && placement.locationId === where.id && (condition.feature === undefined || placement.featureKey === condition.feature)\n }\n case 'variable': {\n const def = target.variables.def(condition.variable)\n if (def === undefined) return false\n const subject = def.subject === 'world' ? { id: 0 } : condition.subject === undefined ? undefined : subjectOf(target, def.subject, condition.subject)\n return subject !== undefined && compare(condition.op, target.variables.value(condition.variable, def.subject, subject.id), condition.value)\n }\n case 'item': {\n const item = target.items.list().find(entry => itemKey(entry) === condition.item)\n if (item === undefined) return false\n const where = target.items.where(item.id)\n if (condition.heldBy !== undefined) return where.characterId !== undefined && where.characterId === target.characters.list().find(entry => characterKey(entry) === condition.heldBy)?.id\n return where.locationId !== undefined && where.locationId === target.locations.list().find(entry => locationKey(entry) === condition.at)?.id\n }\n case 'event': return target.events.list().some(event => event.tags.includes(condition.tag))\n case 'fired': return (target.triggers.getByKey(condition.trigger)?.fireCount ?? 0) > 0\n case 'judged': return clock.judged?.(condition.text) ?? false\n case 'all': return condition.conditions.every(part => holds(target, part, clock))\n case 'any': return condition.conditions.some(part => holds(target, part, clock))\n case 'not': return !holds(target, condition.condition, clock)\n }\n}\n\n/** Whether a condition holds now, judged only from what the story has recorded. */\nexport const conditionHolds = holds\n\n/** A number from 0 to 1 that depends only on what it is given: a roll that comes out the same when the story is replayed. */\nexport function seededRoll(seed: string): number {\n let hash = 2166136261\n for (const char of seed) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619)\n return ((hash >>> 0) % 1_000_000) / 1_000_000\n}\n\n\n/** When a trigger waits for a plain time, that time: what an announcement says it is to happen at, unless it says so itself. */\nfunction waitedFor(condition: TriggerCondition): string | undefined {\n if (condition.type === 'time') return condition.from\n if (condition.type === 'all') return condition.conditions.map(waitedFor).find(found => found !== undefined)\n return undefined\n}\n\n/** A character is among those an audience names, now. */\nexport function inAudience(target: Pick<RecordsTarget, 'characters' | 'locations' | 'placements'>, audience: TriggerAudience, characterId: number): boolean {\n if (audience === 'everyone') return true\n if ('characters' in audience) return audience.characters.some(key => target.characters.list().find(entry => characterKey(entry) === key)?.id === characterId)\n const place = target.locations.list().find(entry => locationKey(entry) === audience.place)\n return place !== undefined && target.placements.get('character', characterId)?.locationId === place.id\n}\n\n/** The characters an audience is now, those who can be asked to act (the player's own character is told by the game master). */\nexport function audienceIds(target: Pick<RecordsTarget, 'characters' | 'locations' | 'placements'>, audience: TriggerAudience): number[] {\n return target.characters.list().filter(entry => entry.control === 'agent' && inAudience(target, audience, entry.id)).map(entry => entry.id)\n}\n\nexport interface Announcement {\n trigger: Trigger\n text: string\n audience: TriggerAudience\n /** When it is to happen, as an instant, when that is known. */\n at?: number\n}\n\n/** What is known of what is coming: triggers that have not fired and announce themselves, from the time they say, soonest first. */\nexport function announcements(target: Pick<RecordsTarget, 'triggers'>, clock: TriggerClock): Announcement[] {\n return target.triggers.list({ status: 'dormant' }).flatMap((trigger): Announcement[] => {\n const { announce } = trigger\n if (announce === undefined || (announce.from !== undefined && clock.now < parseInstant(announce.from, clock.zone))) return []\n const when = announce.at ?? waitedFor(trigger.condition)\n return [{ trigger, text: announce.text, audience: announce.audience, ...(when === undefined ? {} : { at: parseInstant(when, clock.zone) }) }]\n }).sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity) || a.trigger.id - b.trigger.id)\n}\n","import type { JsonSchemaNode, ObjectJsonSchema } from '@deepseek-ai/dsh-tools'\nimport {\n ACCURACIES, CHARACTER_KINDS, CHARACTER_TIERS, CONTAINER_STATES, ENGAGEMENT_STATUSES, EXIT_STATES, IMPORTANCE_MAX, IMPORTANCE_MIN, INTENT_HORIZONS, INTENT_STATUSES, INTENT_TYPES, KNOWLEDGE_KINDS, MEMORY_CONFIDENCES, MEMORY_KINDS, PERCEPTION_MODES, WEEKDAY_NAMES,\n VARIABLE_KINDS, VARIABLE_SUBJECTS, VARIABLE_VISIBILITIES,\n type VariableDefinitionInput, type VariableKind, type VariableSubject, type VariableValue, type VariableVisibility,\n type TriggerDefinition, type Accuracy, type CharacterKind, type CharacterTier, type ContainerState, type EngagementStatus, type ExitState, type IntentHorizon, type IntentStatus, type IntentType, type KnowledgeKind, type MemoryConfidence, type MemoryKind, type PerceptionMode, type Slot,\n} from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport type {\n BeliefEdit, CharacterMove, EngagementEditSpec, EventEdit, ExitChange, IntentEditSpec, ItemChange, NewEngagementSpec, NewIntentSpec, RoutineSet, RoutineWindowSpec, ItemEditSpec, NewBelief, NewCharacterSpec, NewEvent, NewExit, NewExitBetween, NewItemSpec, NewPlace,\n FactionMembershipSet, FactionRelationshipSet, FactionStateSet, KnowledgeRetraction, KnowledgeSet, NewFactionIntentSpec, PerceivedBy, PerceptionAddition, PerceptionEdit, PlaceEdit, RecordsEdit, RelationshipRetraction, RelationshipSet, StatePatch,\n} from './edit-types.ts'\nimport { ITEM_ACTIONS, type ItemAction } from './items.ts'\nimport type { VariableChangeSpec } from './variables.ts'\nimport { parseTriggerDefinition } from './trigger-rules.ts'\n\n/** An edit effect is an edit, but its events may be seen by `\"everyone\"`, which an ordinary edit cannot say. */\nconst checkEdit = (edit: Wire): void => {\n const events = Array.isArray(edit['events']) ? edit['events'].map(event => (isObject(event) && event['perceived_by'] === 'everyone' ? { ...event, perceived_by: [] } : event)) : edit['events']\n parseRecordsEdit({ ...edit, ...(events === undefined ? {} : { events }) })\n}\n\n/** Read a trigger as a world's files write it. @returns the definition, or every problem with where it is. */\nexport const readTriggerDefinition = (value: unknown, path: string): ReturnType<typeof parseTriggerDefinition> => parseTriggerDefinition(value, path, checkEdit)\n\ntype Wire = Record<string, unknown>\nconst isObject = (value: unknown): value is Wire => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Read an edit from the JSON models write (snake_case), the one wire format of the\n * keeper's output and of the write tools.\n * @throws {InvalidEditError} when it is not shaped as an edit.\n */\nexport function parseRecordsEdit(value: unknown): RecordsEdit {\n const problems: string[] = []\n if (!isObject(value)) throw new InvalidEditError(['the edit must be an object'])\n const array = (key: string): Wire[] => {\n const entries = value[key]\n if (entries === undefined || entries === null) return []\n if (!Array.isArray(entries)) { problems.push(`${key} must be a list`); return [] }\n return entries.flatMap((entry, index) => {\n if (isObject(entry)) return [entry]\n problems.push(`${key}[${index}] must be an object`)\n return []\n })\n }\n const numbers = (key: string): number[] => {\n const entries = value[key]\n if (entries === undefined || entries === null) return []\n if (!Array.isArray(entries) || entries.some(entry => typeof entry !== 'number')) { problems.push(`${key} must be a list of numbers`); return [] }\n return entries as number[]\n }\n const strings = (entry: Wire, key: string): string[] | undefined => {\n const found = entry[key]\n if (found === undefined || found === null) return undefined\n if (!Array.isArray(found) || found.some(item => typeof item !== 'string')) { problems.push(`${key} must be a list of text`); return undefined }\n return found as string[]\n }\n const numbersOf = (entry: Wire, key: string): number[] | undefined => {\n const found = entry[key]\n if (found === undefined || found === null) return undefined\n if (!Array.isArray(found) || found.some(item => typeof item !== 'number')) { problems.push(`${key} must be a list of numbers`); return undefined }\n return found as number[]\n }\n const text = (entry: Wire, key: string): string | undefined => (typeof entry[key] === 'string' ? entry[key] : undefined)\n /** A key, slot or position the model may leave blank instead of leaving out: blank is nothing given, not a name that does not exist. */\n const named = (entry: Wire, key: string): string | undefined => { const value = text(entry, key)?.trim(); return value === undefined || value === '' ? undefined : value }\n const num = (entry: Wire, key: string): number | undefined => (typeof entry[key] === 'number' ? entry[key] : undefined)\n const perceived = (entry: Wire): PerceivedBy[] | undefined => {\n const found = entry['perceived_by']\n if (found === undefined || found === null) return undefined\n if (!Array.isArray(found)) { problems.push('perceived_by must be a list'); return undefined }\n return found.filter(isObject).map(item => ({\n character: text(item, 'character') ?? '', mode: (text(item, 'mode') ?? '') as PerceptionMode,\n ...(text(item, 'content') === undefined ? {} : { content: text(item, 'content')! }),\n ...(text(item, 'gist') === undefined ? {} : { gist: text(item, 'gist')! }),\n ...(text(item, 'accuracy') === undefined ? {} : { accuracy: text(item, 'accuracy') as Accuracy }),\n }))\n }\n const scalar = (entry: Wire, key: string): VariableValue | undefined => { const found = entry[key]; return typeof found === 'number' || typeof found === 'string' || typeof found === 'boolean' ? found : undefined }\n const bool = (entry: Wire, key: string): boolean | undefined => (typeof entry[key] === 'boolean' ? entry[key] : undefined)\n const featuresOf = (entry: Wire): { key: string; name: string; description?: string }[] | undefined => {\n const found = entry['features']\n if (found === undefined || found === null) return undefined\n if (!Array.isArray(found)) { problems.push('features must be a list'); return undefined }\n return found.filter(isObject).map(item => ({ key: text(item, 'key') ?? '', name: text(item, 'name') ?? '', ...(text(item, 'description') === undefined ? {} : { description: text(item, 'description')! }) }))\n }\n const defined = <T>(entry: object): T => Object.fromEntries(Object.entries(entry).filter(([, field]) => field !== undefined)) as T\n\n const turn = num(value, 'turn')\n const edit: RecordsEdit = {\n turn: turn ?? 0,\n states: array('states').map((entry): StatePatch => defined<StatePatch>({\n character: text(entry, 'character') ?? '', publicState: text(entry, 'public_state'), innerState: text(entry, 'inner_state'), activity: text(entry, 'activity'),\n })),\n events: array('events').map((entry): NewEvent => defined<NewEvent>({\n turn: num(entry, 'turn') ?? 0, round: num(entry, 'round') ?? 0, text: text(entry, 'text') ?? '', importance: num(entry, 'importance') ?? 0,\n tags: strings(entry, 'tags'), involves: strings(entry, 'involves'), perceivedBy: perceived(entry), location: text(entry, 'location'), items: strings(entry, 'items'),\n })),\n eventEdits: array('event_edits').map((entry): EventEdit => defined<EventEdit>({\n id: num(entry, 'id') ?? 0, text: text(entry, 'text'), importance: num(entry, 'importance'), tags: strings(entry, 'tags'), involves: strings(entry, 'involves'), perceivedBy: perceived(entry), location: text(entry, 'location'),\n })),\n eventRetractions: numbers('event_retractions'),\n perceptionEdits: array('perception_edits').map((entry): PerceptionEdit => defined<PerceptionEdit>({\n id: num(entry, 'id') ?? 0, mode: text(entry, 'mode') as PerceptionMode | undefined, content: text(entry, 'content'), gist: text(entry, 'gist'), accuracy: text(entry, 'accuracy') as Accuracy | undefined,\n })),\n perceptionsAdded: array('perceptions_added').map((entry): PerceptionAddition => defined<PerceptionAddition>({\n event: num(entry, 'event') ?? 0, character: text(entry, 'character') ?? '', mode: (text(entry, 'mode') ?? '') as PerceptionMode,\n content: text(entry, 'content'), gist: text(entry, 'gist'), accuracy: text(entry, 'accuracy') as Accuracy | undefined,\n })),\n characters: array('characters').map((entry): NewCharacterSpec => defined<NewCharacterSpec>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', aliases: strings(entry, 'aliases'), age: text(entry, 'age'), gender: text(entry, 'gender'), pronouns: text(entry, 'pronouns'),\n kind: text(entry, 'kind') as CharacterKind | undefined, tier: text(entry, 'tier') as CharacterTier | undefined, summary: text(entry, 'summary') ?? '',\n personality: text(entry, 'personality'), background: text(entry, 'background'), appearance: text(entry, 'appearance'), note: text(entry, 'note'),\n speech: isObject(entry['speech']) ? defined<NonNullable<NewCharacterSpec['speech']>>({ style: text(entry['speech'], 'style') ?? '', examples: strings(entry['speech'], 'examples') }) : undefined,\n state: isObject(entry['state']) ? defined<NonNullable<NewCharacterSpec['state']>>({ publicState: text(entry['state'], 'public_state'), innerState: text(entry['state'], 'inner_state'), activity: text(entry['state'], 'activity') }) : undefined,\n place: isObject(entry['place']) ? defined<NonNullable<NewCharacterSpec['place']>>({ location: text(entry['place'], 'location') ?? '', position: text(entry['place'], 'position'), feature: text(entry['place'], 'feature') }) : undefined,\n })),\n items: array('items').map((entry): NewItemSpec => defined<NewItemSpec>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', description: text(entry, 'description'), quantity: num(entry, 'quantity'), unique: bool(entry, 'unique'),\n quality: text(entry, 'quality'), notable: bool(entry, 'notable'), hidden: bool(entry, 'hidden'), wearable: named(entry, 'wearable'), owner: named(entry, 'owner'), note: text(entry, 'note'),\n container: isObject(entry['container']) ? defined<NonNullable<NewItemSpec['container']>>({ state: text(entry['container'], 'state') as ContainerState | undefined, openedBy: strings(entry['container'], 'opened_by') }) : undefined,\n at: isObject(entry['at']) && named(entry['at'], 'location') !== undefined ? defined<NonNullable<NewItemSpec['at']>>({ location: named(entry['at'], 'location') ?? '', position: named(entry['at'], 'position'), feature: named(entry['at'], 'feature') }) : undefined,\n heldBy: named(entry, 'held_by'), wornBy: named(entry, 'worn_by'), wornPosition: named(entry, 'worn_position'), inside: named(entry, 'inside'), insidePosition: named(entry, 'inside_position'),\n })),\n slots: array('slots').map((entry): Slot => ({ id: text(entry, 'id') ?? '', name: text(entry, 'name') ?? '', capacity: num(entry, 'capacity') ?? 0 })),\n itemChanges: array('item_changes').map((entry): ItemChange => defined<ItemChange>({\n character: text(entry, 'character') ?? '', item: text(entry, 'item') ?? '', action: (text(entry, 'action') ?? '') as ItemAction, to: text(entry, 'to'), slot: text(entry, 'slot'),\n quantity: num(entry, 'quantity'), position: text(entry, 'position'), feature: text(entry, 'feature'), with: text(entry, 'with'), exit: text(entry, 'exit'), forced: bool(entry, 'forced'),\n })),\n itemEdits: array('item_edits').map((entry): ItemEditSpec => defined<ItemEditSpec>({\n item: text(entry, 'item') ?? '', description: text(entry, 'description'), quality: text(entry, 'quality'), quantity: num(entry, 'quantity'), notable: bool(entry, 'notable'),\n hidden: bool(entry, 'hidden'), state: text(entry, 'state') as ContainerState | undefined, owner: text(entry, 'owner'), openedBy: strings(entry, 'opened_by'),\n })),\n places: array('places').map((entry): NewPlace => defined<NewPlace>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', description: text(entry, 'description'), parent: text(entry, 'parent'), features: featuresOf(entry), note: text(entry, 'note'),\n exits: Array.isArray(entry['exits']) ? entry['exits'].filter(isObject).map((item): NewExit => defined<NewExit>({\n to: text(item, 'to') ?? '', description: text(item, 'description'), oneWay: bool(item, 'one_way'), backDescription: text(item, 'back_description'),\n travelSeconds: num(item, 'travel_time_seconds'), state: text(item, 'state') as ExitState | undefined, note: text(item, 'note'),\n })) : undefined,\n })),\n exits: array('exits').map((entry): NewExitBetween => defined<NewExitBetween>({\n from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '', description: text(entry, 'description'), oneWay: bool(entry, 'one_way'), backDescription: text(entry, 'back_description'),\n travelSeconds: num(entry, 'travel_time_seconds'), state: text(entry, 'state') as ExitState | undefined, note: text(entry, 'note'),\n })),\n relationships: array('relationships').map((entry): RelationshipSet => defined<RelationshipSet>({\n from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '', label: text(entry, 'label'), summary: text(entry, 'summary'),\n familiarity: num(entry, 'familiarity'), trust: num(entry, 'trust'), affinity: num(entry, 'affinity'), tension: num(entry, 'tension'),\n })),\n relationshipRetractions: array('relationship_retractions').map((entry): RelationshipRetraction => ({ from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '' })),\n knowledge: array('knowledge').map((entry): KnowledgeSet => defined<KnowledgeSet>({ character: text(entry, 'character') ?? '', kind: (text(entry, 'kind') ?? '') as KnowledgeKind, subject: text(entry, 'subject'), from: text(entry, 'from'), to: text(entry, 'to'), observed: bool(entry, 'observed') })),\n knowledgeRetractions: array('knowledge_retractions').map((entry): KnowledgeRetraction => defined<KnowledgeRetraction>({ character: text(entry, 'character') ?? '', kind: (text(entry, 'kind') ?? '') as KnowledgeKind, subject: text(entry, 'subject'), from: text(entry, 'from'), to: text(entry, 'to') })),\n factionStates: array('faction_states').map((entry): FactionStateSet => defined<FactionStateSet>({ faction: text(entry, 'faction') ?? '', publicState: text(entry, 'public_state'), innerState: text(entry, 'inner_state') })),\n factionMemberships: array('faction_memberships').map((entry): FactionMembershipSet => defined<FactionMembershipSet>({ faction: text(entry, 'faction') ?? '', character: text(entry, 'character') ?? '', role: text(entry, 'role'), rank: text(entry, 'rank'), status: text(entry, 'status') as FactionMembershipSet['status'], public: bool(entry, 'public'), commitment: num(entry, 'commitment'), leftTurn: num(entry, 'left_turn') })),\n factionRelationships: array('faction_relationships').map((entry): FactionRelationshipSet => defined<FactionRelationshipSet>({ fromKind: (text(entry, 'from_kind') ?? '') as FactionRelationshipSet['fromKind'], from: text(entry, 'from') ?? '', toKind: (text(entry, 'to_kind') ?? '') as FactionRelationshipSet['toKind'], to: text(entry, 'to') ?? '', label: text(entry, 'label'), summary: text(entry, 'summary'), familiarity: num(entry, 'familiarity'), trust: num(entry, 'trust'), affinity: num(entry, 'affinity'), tension: num(entry, 'tension') })),\n factionIntentsAdded: array('faction_intents_added').map((entry): NewFactionIntentSpec => defined<NewFactionIntentSpec>({ faction: text(entry, 'faction') ?? '', type: (text(entry, 'type') ?? '') as IntentType, name: text(entry, 'name') ?? '', description: text(entry, 'description'), horizon: (text(entry, 'horizon') ?? '') as IntentHorizon, priority: num(entry, 'priority') ?? Number.NaN, urgency: num(entry, 'urgency') ?? Number.NaN, plan: strings(entry, 'plan'), constraints: strings(entry, 'constraints'), deadline: text(entry, 'deadline') })),\n placeEdits: array('place_edits').map((entry): PlaceEdit => defined<PlaceEdit>({ place: text(entry, 'place') ?? '', name: text(entry, 'name'), description: text(entry, 'description'), features: featuresOf(entry) })),\n exitChanges: array('exit_changes').map((entry): ExitChange => defined<ExitChange>({\n from: text(entry, 'from') ?? '', to: text(entry, 'to') ?? '', state: text(entry, 'state') as ExitState | undefined, description: text(entry, 'description'), note: text(entry, 'note'),\n travelSeconds: num(entry, 'travel_time_seconds'), oneWay: bool(entry, 'one_way'),\n })),\n moves: array('moves').map((entry): CharacterMove => defined<CharacterMove>({\n character: text(entry, 'character') ?? '', to: text(entry, 'to') ?? '', position: text(entry, 'position'), feature: text(entry, 'feature'), ignoreExits: bool(entry, 'ignore_exits'),\n })),\n beliefs: array('beliefs').map((entry): NewBelief => defined<NewBelief>({\n character: text(entry, 'character') ?? '', kind: (text(entry, 'kind') ?? '') as MemoryKind, text: text(entry, 'text') ?? '', about: strings(entry, 'about'), importance: num(entry, 'importance') ?? 0,\n confidence: text(entry, 'confidence') as MemoryConfidence | undefined, evidenceFor: numbersOf(entry, 'evidence_for'), evidenceAgainst: numbersOf(entry, 'evidence_against'),\n })),\n beliefEdits: array('belief_edits').map((entry): BeliefEdit => defined<BeliefEdit>({ id: num(entry, 'id') ?? 0, text: text(entry, 'text'), about: strings(entry, 'about'), importance: num(entry, 'importance'), confidence: text(entry, 'confidence') as MemoryConfidence | undefined, evidenceFor: numbersOf(entry, 'evidence_for'), evidenceAgainst: numbersOf(entry, 'evidence_against') })),\n beliefRetractions: numbers('belief_retractions'),\n threadsOpened: Array.isArray(value['threads_opened']) ? (value['threads_opened'] as unknown[]).filter((entry): entry is string => typeof entry === 'string') : [],\n threadsResolved: numbers('threads_resolved'),\n variableChanges: array('variable_changes').map((entry): VariableChangeSpec => defined<VariableChangeSpec>({\n variable: text(entry, 'variable') ?? '', subject: text(entry, 'subject') ?? '', to: scalar(entry, 'to'), by: num(entry, 'by'), baseline: scalar(entry, 'baseline'),\n })),\n variables: array('variables').map((entry): VariableDefinitionInput => defined<VariableDefinitionInput>({\n key: text(entry, 'key') ?? '', name: text(entry, 'name') ?? '', description: text(entry, 'description'), kind: (text(entry, 'kind') ?? '') as VariableKind, subject: (text(entry, 'subject') ?? '') as VariableSubject,\n only: strings(entry, 'only'), min: num(entry, 'min'), max: num(entry, 'max'), integer: bool(entry, 'integer'), options: strings(entry, 'options'), default: scalar(entry, 'default'),\n baseline: bool(entry, 'baseline'), visibility: text(entry, 'visibility') as VariableVisibility | undefined, always: bool(entry, 'always'),\n bands: Array.isArray(entry['bands']) ? entry['bands'].filter(isObject).map(band => ({ upTo: num(band, 'up_to') ?? Number.NaN, label: text(band, 'label') ?? '' })) : undefined,\n })),\n intentsAdded: array('intents_added').map((entry): NewIntentSpec => defined<NewIntentSpec>({\n character: text(entry, 'character') ?? '', type: (text(entry, 'type') ?? '') as IntentType, name: text(entry, 'name') ?? '', description: text(entry, 'description'),\n horizon: (text(entry, 'horizon') ?? '') as IntentHorizon, priority: num(entry, 'priority') ?? Number.NaN, urgency: num(entry, 'urgency') ?? Number.NaN,\n plan: strings(entry, 'plan'), constraints: strings(entry, 'constraints'), deadline: text(entry, 'deadline'),\n })),\n intentEdits: array('intent_edits').map((entry): IntentEditSpec => defined<IntentEditSpec>({\n id: num(entry, 'id') ?? 0, status: text(entry, 'status') as IntentStatus | undefined, description: text(entry, 'description'), horizon: text(entry, 'horizon') as IntentHorizon | undefined,\n priority: num(entry, 'priority'), urgency: num(entry, 'urgency'), plan: strings(entry, 'plan'), openThreads: strings(entry, 'open_threads'), deadline: text(entry, 'deadline'),\n })),\n engagements: array('engagements').map((entry): NewEngagementSpec => defined<NewEngagementSpec>({\n title: text(entry, 'title') ?? '', at: text(entry, 'at') ?? '', until: text(entry, 'until'), location: text(entry, 'location'), participants: strings(entry, 'participants') ?? [], note: text(entry, 'note'),\n })),\n engagementEdits: array('engagement_edits').map((entry): EngagementEditSpec => defined<EngagementEditSpec>({\n id: num(entry, 'id') ?? 0, status: text(entry, 'status') as EngagementStatus | undefined, title: text(entry, 'title'), at: text(entry, 'at'), until: text(entry, 'until'),\n location: text(entry, 'location'), participants: strings(entry, 'participants'), note: text(entry, 'note'),\n })),\n triggers: array('triggers').flatMap((entry, index): TriggerDefinition[] => {\n const parsed = parseTriggerDefinition(entry, `triggers[${index}]`, checkEdit)\n if ('problems' in parsed) { problems.push(...parsed.problems); return [] }\n return [parsed.definition]\n }),\n routines: array('routines').map((entry): RoutineSet => ({\n character: text(entry, 'character') ?? '',\n windows: Array.isArray(entry['windows']) ? entry['windows'].filter(isObject).map((window): RoutineWindowSpec => defined<RoutineWindowSpec>({\n days: strings(window, 'days'), on: strings(window, 'on'), from: text(window, 'from') ?? '', to: text(window, 'to') ?? '', activity: text(window, 'activity') ?? '',\n location: text(window, 'location'), feature: text(window, 'feature'), position: text(window, 'position'), interruptible: bool(window, 'interruptible'),\n })) : [],\n })),\n }\n if (problems.length > 0) throw new InvalidEditError(problems)\n return edit\n}\n\nconst scalarValue: JsonSchemaNode = { oneOf: [{ type: 'number' }, { type: 'boolean' }, { type: 'string' }], description: 'A number, true or false, or one of the words of a choice.' }\n\nconst CONFIDENCE: JsonSchemaNode = { type: 'string', enum: [...MEMORY_CONFIDENCES], description: 'How sure the character is: doubtful, likely (the default) or sure. Sure only for what it has seen more than once or cannot doubt.' }\nconst EVIDENCE_FOR: JsonSchemaNode = { type: 'array', items: { type: 'integer' }, description: 'The numbers of perceptions of the character (from read_records) that this rests on.' }\nconst EVIDENCE_AGAINST: JsonSchemaNode = { type: 'array', items: { type: 'integer' }, description: 'The numbers of perceptions of the character that speak against this; lower the confidence then.' }\nconst IMPORTANCE: JsonSchemaNode = { type: 'integer', enum: [1, 2, 3, 4, 5], description: `From ${IMPORTANCE_MIN} (a passing detail) to ${IMPORTANCE_MAX} (turns the story).` }\n\n/**\n * The JSON schema of the wire format, for a model's structured output or a tool's parameters.\n * With `characters`, a character can only be named by one of those keys.\n */\nexport function recordsEditSchema(options: { characters?: readonly string[]; changes?: boolean; /** Offer the making of characters, places and ways: only for the agent whose work that is. */ authoring?: boolean } = {}): ObjectJsonSchema {\n const character: JsonSchemaNode = options.characters === undefined || options.characters.length === 0\n ? { type: 'string', description: 'The key of a character.' }\n : { type: 'string', enum: [...options.characters], description: 'The key of a character.' }\n const keys: JsonSchemaNode = { type: 'array', items: character }\n const perceivedBy: JsonSchemaNode = {\n type: 'array',\n description: 'Who took the event in: only characters who could actually have perceived it. A character always perceives what it does or says itself.',\n items: {\n type: 'object',\n properties: {\n character,\n mode: { type: 'string', enum: [...PERCEPTION_MODES], description: 'How: saw it, heard it, was told, or worked it out.' },\n content: { type: 'string', description: 'What this character took in, in its own terms. Leave out when it took in exactly the event.' },\n gist: { type: 'string', description: 'The essence of it in a few words.' },\n accuracy: { type: 'string', enum: [...ACCURACIES], description: 'How well that matches what happened. Never shown to the character. Defaults to accurate.' },\n },\n required: ['character', 'mode'],\n additionalProperties: false,\n },\n }\n const placeKey: JsonSchemaNode = { type: 'string', description: 'The key of a place, as list_locations gives it, or one of the places made in this same edit.' }\n const featureList: JsonSchemaNode = {\n type: 'array',\n description: 'Named things in the place that a story can point at: a desk, a window, a notice board.',\n items: { type: 'object', properties: { key: { type: 'string' }, name: { type: 'string' }, description: { type: 'string' } }, required: ['key', 'name'], additionalProperties: false },\n }\n const properties: ObjectJsonSchema['properties'] = {\n turn: { type: 'integer', description: 'The turn these records belong to.' },\n states: {\n type: 'array',\n description: 'The new state of the characters whose state changed. Give only the fields that changed.',\n items: {\n type: 'object',\n properties: {\n character,\n public_state: { type: 'string', description: 'What anyone present can now see of the character: a short present-tense description, never a log of events.' },\n inner_state: { type: 'string', description: 'What the character now thinks and feels; private.' },\n activity: { type: 'string', description: 'What the character is concretely doing now.' },\n },\n required: ['character'],\n additionalProperties: false,\n },\n },\n events: {\n type: 'array',\n description: 'What objectively happened: short, factual, past-tense statements.',\n items: {\n type: 'object',\n properties: {\n turn: { type: 'integer' },\n round: { type: 'integer' },\n text: { type: 'string' },\n importance: IMPORTANCE,\n tags: { type: 'array', items: { type: 'string' }, description: 'Lowercase words a later search could use: objects, places, topics.' },\n involves: { ...keys, description: 'The characters the event is about: who acted and who it was done to.' },\n perceived_by: perceivedBy,\n location: { ...placeKey, description: 'Where it happened: the key of the place.' },\n items: { type: 'array', items: { type: 'string' }, description: 'The keys of the items it is about: what was taken, opened, handed over, found.' },\n },\n required: ['turn', 'round', 'text', 'importance', 'tags', 'involves', 'perceived_by'],\n additionalProperties: false,\n },\n },\n beliefs: {\n type: 'array',\n description: 'What a character has come to believe or know beyond a single event, from its own point of view.',\n items: {\n type: 'object',\n properties: {\n character,\n kind: { type: 'string', enum: [...MEMORY_KINDS] },\n text: { type: 'string' },\n about: keys,\n importance: IMPORTANCE,\n confidence: CONFIDENCE,\n evidence_for: EVIDENCE_FOR,\n evidence_against: EVIDENCE_AGAINST,\n },\n required: ['character', 'kind', 'text', 'importance'],\n additionalProperties: false,\n },\n },\n relationships: {\n type: 'array',\n description: 'How a character stands towards another: a small profile, one per direction. Give only what changed; a new one needs a label. Record a change when something happened that really changes it, not for every pleasantry.',\n items: {\n type: 'object',\n properties: {\n from: character,\n to: character,\n label: { type: 'string', description: 'What the other is to this character, in a word or two: sister, rival, landlord.' },\n summary: { type: 'string', description: 'The relationship in a sentence or two: how it came about, what it is like now.' },\n familiarity: { type: 'number', description: 'How well it knows the other: 0 a stranger, 1 intimately.' },\n trust: { type: 'number', description: 'From -1 (distrusts) to 1 (trusts completely).' },\n affinity: { type: 'number', description: 'From -1 (dislikes) to 1 (is fond of).' },\n tension: { type: 'number', description: 'How strained it is now: 0 none, 1 about to break.' },\n },\n required: ['from', 'to'],\n additionalProperties: false,\n },\n },\n relationship_retractions: {\n type: 'array',\n description: 'Profiles that no longer describe anything: the two never actually met, or it was made by mistake.',\n items: { type: 'object', properties: { from: character, to: character }, required: ['from', 'to'], additionalProperties: false },\n },\n knowledge: {\n type: 'array',\n description: 'Entities a character learns exist. For a location or item give subject; for a directed exit give from and to. This grants identity only, never current state or whereabouts.',\n items: {\n type: 'object',\n properties: { character, kind: { type: 'string', enum: [...KNOWLEDGE_KINDS] }, subject: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' }, observed: { type: 'boolean' } },\n required: ['character', 'kind'], additionalProperties: false,\n },\n },\n knowledge_retractions: {\n type: 'array',\n description: 'Entity awareness recorded by mistake. Ordinary stale information belongs in beliefs and does not remove awareness.',\n items: { type: 'object', properties: { character, kind: { type: 'string', enum: [...KNOWLEDGE_KINDS] }, subject: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' } }, required: ['character', 'kind'], additionalProperties: false },\n },\n faction_states: {\n type: 'array', description: 'Changes in an organisation itself. Give only fields that changed.',\n items: { type: 'object', properties: { faction: { type: 'string' }, public_state: { type: 'string' }, inner_state: { type: 'string' } }, required: ['faction'], additionalProperties: false },\n },\n faction_memberships: {\n type: 'array', description: 'Membership learned or changed. A character may belong to several factions; public says whether outsiders can ordinarily know it.',\n items: { type: 'object', properties: { faction: { type: 'string' }, character, role: { type: 'string' }, rank: { type: 'string' }, status: { type: 'string', enum: ['active', 'inactive', 'former'] }, public: { type: 'boolean' }, commitment: { type: 'number' }, left_turn: { type: 'integer' } }, required: ['faction', 'character'], additionalProperties: false },\n },\n faction_relationships: {\n type: 'array', description: 'A directional profile involving a faction. This is also the awareness edge: without it, the from-side does not know the target exists.',\n items: { type: 'object', properties: { from_kind: { type: 'string', enum: ['character', 'faction'] }, from: { type: 'string' }, to_kind: { type: 'string', enum: ['character', 'faction'] }, to: { type: 'string' }, label: { type: 'string' }, summary: { type: 'string' }, familiarity: { type: 'number' }, trust: { type: 'number' }, affinity: { type: 'number' }, tension: { type: 'number' } }, required: ['from_kind', 'from', 'to_kind', 'to'], additionalProperties: false },\n },\n faction_intents_added: {\n type: 'array', description: 'A durable strategic goal newly adopted by a faction. This pressures its members but does not directly act for them.',\n items: { type: 'object', properties: { faction: { type: 'string' }, type: { type: 'string', enum: [...INTENT_TYPES] }, name: { type: 'string' }, description: { type: 'string' }, horizon: { type: 'string', enum: [...INTENT_HORIZONS] }, priority: { type: 'number' }, urgency: { type: 'number' }, plan: { type: 'array', items: { type: 'string' } }, constraints: { type: 'array', items: { type: 'string' } }, deadline: { type: 'string' } }, required: ['faction', 'type', 'name', 'horizon', 'priority', 'urgency'], additionalProperties: false },\n },\n item_changes: {\n type: 'array',\n description: 'What characters do with items. Not for what the game master already decided; those are written already.',\n items: {\n type: 'object',\n properties: {\n character,\n item: { type: 'string', description: 'The key of the item, as list_items gives it.' },\n action: { type: 'string', enum: [...ITEM_ACTIONS] },\n to: { type: 'string', description: 'For give: the character; for put: the container item.' },\n slot: { type: 'string' },\n quantity: { type: 'integer' },\n position: { type: 'string' },\n feature: { type: 'string' },\n with: { type: 'string', description: 'For lock and unlock: the key item used.' },\n exit: { type: 'string', description: 'For lock and unlock of a way instead of an item: the key of the place it leads to.' },\n forced: { type: 'boolean' },\n },\n required: ['character', 'item', 'action'],\n additionalProperties: false,\n },\n },\n item_edits: {\n type: 'array',\n description: 'Changes to an item that no character did: its condition, a lock the story breaks, who it belongs to, what opens it. Give only what changes.',\n items: {\n type: 'object',\n properties: {\n item: { type: 'string' },\n description: { type: 'string' },\n quality: { type: 'string' },\n quantity: { type: 'integer' },\n notable: { type: 'boolean' },\n hidden: { type: 'boolean' },\n state: { type: 'string', enum: [...CONTAINER_STATES] },\n owner: character,\n opened_by: { type: 'array', items: { type: 'string' }, description: 'Replaces the items that open it.' },\n },\n required: ['item'],\n additionalProperties: false,\n },\n },\n place_edits: {\n type: 'array',\n description: 'Changes to a known place: it burned down, a feature appeared. Give only what changes; features replaces the list.',\n items: { type: 'object', properties: { place: placeKey, name: { type: 'string' }, description: { type: 'string' }, features: featureList }, required: ['place'], additionalProperties: false },\n },\n exit_changes: {\n type: 'array',\n description: 'The way between two places changed: a door unlocked, a passage collapsed. Applies to both directions unless one_way.',\n items: {\n type: 'object',\n properties: { from: placeKey, to: placeKey, state: { type: 'string', enum: [...EXIT_STATES] }, description: { type: 'string' }, note: { type: 'string' }, travel_time_seconds: { type: 'integer' }, one_way: { type: 'boolean' } },\n required: ['from', 'to'],\n additionalProperties: false,\n },\n },\n moves: {\n type: 'array',\n description: 'Where characters go. Not for what the game master already decided; those moves are written already.',\n items: {\n type: 'object',\n properties: { character, to: placeKey, position: { type: 'string' }, feature: { type: 'string' }, ignore_exits: { type: 'boolean' } },\n required: ['character', 'to'],\n additionalProperties: false,\n },\n },\n variable_changes: {\n type: 'array',\n description: 'What the story tracks changed: a feeling, a debt, a reputation, a flag (list_variables shows what is tracked and what each is about). Give exactly one of to (the new value), by (an amount a number goes up or down; it stops at its bounds) or baseline (the new temperament of a variable that has one). Only what the rounds clearly establish.',\n items: {\n type: 'object',\n properties: {\n variable: { type: 'string', description: 'The key of the variable.' },\n subject: { type: 'string', description: 'The key of the character, item or place it is about; world for a variable of the whole story.' },\n to: scalarValue,\n by: { type: 'number' },\n baseline: scalarValue,\n },\n required: ['variable', 'subject'],\n additionalProperties: false,\n },\n },\n intents_added: {\n type: 'array',\n description: 'A goal the story gave a character: a promise it made, a task it took on, a scheme it set in motion. Only what the rounds clearly establish; never one that is already listed for it.',\n items: {\n type: 'object',\n properties: {\n character,\n type: { type: 'string', enum: [...INTENT_TYPES] },\n name: { type: 'string', description: 'A few words.' },\n description: { type: 'string' },\n horizon: { type: 'string', enum: [...INTENT_HORIZONS] },\n priority: { type: 'number', description: 'How much it matters to the character, 0 to 1.' },\n urgency: { type: 'number', description: 'How soon it has to be dealt with, 0 to 1.' },\n plan: { type: 'array', items: { type: 'string' }, description: 'The next steps, a sentence each.' },\n constraints: { type: 'array', items: { type: 'string' } },\n deadline: { type: 'string', description: 'When it has to be done by: a date and time, 1912-09-22T18:00, in the time zone of the story.' },\n },\n required: ['character', 'type', 'name', 'horizon', 'priority', 'urgency'],\n additionalProperties: false,\n },\n },\n intent_edits: {\n type: 'array',\n description: 'A goal of a character that moved on (the ids are in read_records): done, failed, given up, more or less pressing, a step taken. Give only what changes; plan replaces the steps.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n status: { type: 'string', enum: [...INTENT_STATUSES] },\n description: { type: 'string' },\n horizon: { type: 'string', enum: [...INTENT_HORIZONS] },\n priority: { type: 'number' },\n urgency: { type: 'number' },\n plan: { type: 'array', items: { type: 'string' } },\n open_threads: { type: 'array', items: { type: 'string' } },\n deadline: { type: 'string' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n engagements: {\n type: 'array',\n description: 'Something characters committed to at a time: a meeting arranged, an errand promised, an event they are to attend. Only when the rounds clearly establish a time (or a time of day that can be worked out from the story\\'s clock).',\n items: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'A few words: \"Meet Clara at the bar\".' },\n at: { type: 'string', description: 'When it is due: a date and time, 1912-09-22T21:00, in the time zone of the story.' },\n until: { type: 'string', description: 'When it is over, when that matters.' },\n location: placeKey,\n participants: { ...keys, description: 'Who has committed to it: each character that is to be there.' },\n note: { type: 'string' },\n },\n required: ['title', 'at', 'participants'],\n additionalProperties: false,\n },\n },\n engagement_edits: {\n type: 'array',\n description: 'An engagement that moved on (the ids are in read_records): it was kept, missed, cancelled, or put off. Give only what changes.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n status: { type: 'string', enum: [...ENGAGEMENT_STATUSES] },\n title: { type: 'string' },\n at: { type: 'string' },\n until: { type: 'string' },\n location: placeKey,\n participants: keys,\n note: { type: 'string' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n threads_opened: { type: 'array', items: { type: 'string' }, description: 'Promises made, mysteries raised, goals set that are not settled yet: one sentence each.' },\n threads_resolved: { type: 'array', items: { type: 'integer' }, description: 'The ids of open threads that are now settled.' },\n }\n if (options.authoring === true) {\n Object.assign(properties, {\n variables: {\n type: 'array',\n description: 'A thing the story now tracks, declared only when what it established matters from here on and nothing tracked fits (a debt, a character\\'s health, a reputation, whether a door is known). Declared once; then changed with variable_changes (in the same call too).',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'Lowercase letters, digits and underscores, starting with a letter.' },\n name: { type: 'string' },\n description: { type: 'string', description: 'What it measures or means, for those who read and change it.' },\n kind: { type: 'string', enum: [...VARIABLE_KINDS] },\n subject: { type: 'string', enum: [...VARIABLE_SUBJECTS], description: 'What each value is about: every character, item or place has its own; world has one for the whole story.' },\n only: { type: 'array', items: { type: 'string' }, description: 'Keys of the subjects it applies to; leave out for all of its kind.' },\n min: { type: 'number' },\n max: { type: 'number' },\n integer: { type: 'boolean' },\n options: { type: 'array', items: { type: 'string' }, description: 'For a choice: from 2 to 12 words.' },\n default: scalarValue,\n baseline: { type: 'boolean', description: 'Whether each value has a temperament beside the current value (feelings do).' },\n visibility: { type: 'string', enum: [...VARIABLE_VISIBILITIES], description: 'public: anyone present can tell; private: only the character it belongs to (and the game master); hidden: only the game master.' },\n bands: { type: 'array', items: { type: 'object', properties: { up_to: { type: 'number' }, label: { type: 'string' } }, required: ['up_to', 'label'], additionalProperties: false }, description: 'Words for ranges of a number, lowest first: values up to up_to are called label.' },\n always: { type: 'boolean', description: 'Tell it always, not only once it differs from its default.' },\n },\n required: ['key', 'name', 'kind', 'subject'],\n additionalProperties: false,\n },\n },\n triggers: {\n type: 'array',\n description: 'Things the world does by itself when something comes true, made only when the story has set up a moment that is bound to come (a deadline, a promised arrival, a trap, a storm) and nothing existing covers it. At most two at a time. Each fires once, when its condition turns true.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'Lowercase letters, digits, hyphens and underscores.' },\n name: { type: 'string', description: 'A short label for the author; never shown to any character.' },\n when: {\n type: 'object',\n description: 'The condition, decided in code from what the story has recorded. One of: {type:\"time\", from:\"1912-10-05T21:00\", to?, window?:{from:\"22:00\",to:\"06:00\"}, days?:[\"fri\"]} (story-local times); {type:\"place\", character, location, feature?}; {type:\"variable\", variable, subject? (the key of the character, item or place; none for a world variable), op: eq|ne|lt|le|gt|ge, value}; {type:\"item\", item, held_by? | at?}; {type:\"event\", tag}; {type:\"fired\", trigger}; and {type:\"all\"|\"any\", conditions:[...]} or {type:\"not\", condition}, nested at most 4 deep.',\n properties: { type: { type: 'string', enum: ['time', 'place', 'variable', 'item', 'event', 'fired', 'all', 'any', 'not'] } },\n required: ['type'],\n additionalProperties: true,\n },\n effects: {\n type: 'array',\n description: 'What happens, one to six: {type:\"edit\", edit:{...}} a change of the records in the same format as edit_records (events with a location are seen by those there, variable_changes, exit_changes, item_changes, moves, intents_added, engagements); {type:\"beat\", text, while?} something the game master is told to weave into the story; {type:\"cue\", characters:[keys] (or audience: \"everyone\" | {place:key}), text, while?} something those characters notice; a beat or cue is written when it is told, which may be turns after the trigger fired: its text may name things as {character:key}, {place:key}, {item:key}, {where:character} (the place a character is in), {holder:item} (who has it or where it lies), {value:variable} or {value:variable:subject}, {time}, and is told as the story stands then, and `while` is a condition (as above, nothing judged) that must still hold then or it is withdrawn; in a cue \\\"@self\\\" stands for the character it is said to (for example while:{type:\\\"place\\\", character:\\\"@self\\\", location:\\\"cellar\\\"}); in the events of an edit, perceived_by may be \"everyone\".',\n items: { type: 'object', properties: { type: { type: 'string', enum: ['edit', 'beat', 'cue'] } }, required: ['type'], additionalProperties: true },\n },\n repeat: { type: 'boolean', description: 'Fire again after the condition went false and true again. Default no.' },\n cooldown_seconds: { type: 'integer', description: 'With repeat: the least story time between two firings.' },\n chance: { type: 'number', description: 'From 0 to 1: the chance that it fires when the condition turns true.' },\n priority: { type: 'integer', description: 'The higher goes first when several are due at once.' },\n expires: { type: 'string', description: 'After this story-local time it never fires.' },\n announce: {\n type: 'object',\n description: 'Only for something that is no secret, scheduled and known beforehand (an exam, a ball, a deadline): who knows of it and what they know. Without it nobody knows until it fires. audience is \"everyone\", {characters:[keys]} or {place:key} (whoever is there); text is the public side only, never what the effects do; from is when it becomes known (story-local time; known at once when left out); at is when it happens, when the condition does not say so by a plain time.',\n properties: { audience: { type: 'object', description: '\"everyone\", or {characters:[keys]}, or {place:key}.', additionalProperties: true }, text: { type: 'string' }, from: { type: 'string' }, at: { type: 'string' } },\n required: ['audience', 'text'],\n additionalProperties: false,\n },\n },\n required: ['key', 'name', 'when', 'effects'],\n additionalProperties: false,\n },\n },\n routines: {\n type: 'array',\n description: 'The recurring day of a character who matters off stage and has none: windows of the day with what it is doing and where, in the order they apply (the first that fits applies). Replaces what it had.',\n items: {\n type: 'object',\n properties: {\n character,\n windows: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n days: { type: 'array', items: { type: 'string', enum: [...WEEKDAY_NAMES] }, description: 'Leave out for every day.' },\n on: { type: 'array', items: { type: 'string' }, description: 'Other days it applies on, as well as days: months (dec), dates (12-24, 1912-09-21), stretches (12-20..01-05), dom:1, nth:mon:1 (first Monday), season:winter, holiday:<id>; a ! before one is a day it does not apply on (!holiday:festival). Leave out for every day.' },\n from: { type: 'string', description: 'HH:MM, 24-hour.' },\n to: { type: 'string', description: 'HH:MM; a time before from ends the next day (22:00 to 06:00).' },\n activity: { type: 'string', description: 'What it is doing: \"minds the shop\", \"sleeps\".' },\n location: placeKey,\n feature: { type: 'string' },\n position: { type: 'string' },\n interruptible: { type: 'boolean', description: 'Whether it would drop this for something that comes up; true by default.' },\n },\n required: ['from', 'to', 'activity'],\n additionalProperties: false,\n },\n },\n },\n required: ['character', 'windows'],\n additionalProperties: false,\n },\n },\n slots: {\n type: 'array',\n description: 'Places on the body something can be worn, when the world needs one it does not have (a tail, a quiver on the back). The usual ones exist.',\n items: { type: 'object', properties: { id: { type: 'string', description: 'Short and lowercase.' }, name: { type: 'string' }, capacity: { type: 'integer', description: 'How many things can be worn there at once.' } }, required: ['id', 'name', 'capacity'], additionalProperties: false },\n },\n items: {\n type: 'array',\n description: 'Things the story makes up, only when it genuinely needs them: an object handed over, found or drawn. Each starts in exactly one of at (lying in a place), held_by (carried by a character), worn_by (worn by a character) or inside (in a container item). Leave out every field you have nothing to say about; never send an empty string.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'A short lowercase key that does not exist yet.' },\n name: { type: 'string' },\n description: { type: 'string' },\n quantity: { type: 'integer', description: 'How many, for things that come in numbers.' },\n unique: { type: 'boolean' },\n quality: { type: 'string', description: 'Its condition in words.' },\n notable: { type: 'boolean', description: 'Matters to the story.' },\n hidden: { type: 'boolean' },\n wearable: { type: 'string', description: 'The slot it is worn in.' },\n container: { type: 'object', properties: { state: { type: 'string', enum: [...CONTAINER_STATES] }, opened_by: { type: 'array', items: { type: 'string' } } }, additionalProperties: false },\n owner: character,\n at: { type: 'object', description: 'It lies in this place: {\"location\": the place\\'s key, \"feature\": a feature of the place such as its counter, \"position\": in words}.', properties: { location: placeKey, position: { type: 'string' }, feature: { type: 'string' } }, required: ['location'], additionalProperties: false },\n held_by: character,\n worn_by: character,\n worn_position: { type: 'string' },\n inside: { type: 'string', description: 'The key of the container item it is in.' },\n inside_position: { type: 'string' },\n note: { type: 'string', description: 'Why it was made, for whoever fits it into the world later.' },\n },\n required: ['key', 'name'],\n additionalProperties: false,\n },\n },\n places: {\n type: 'array',\n description: 'Places the story makes up or opens: a hidden passage, a room that was behind a door. Only for places that are not already known.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'A short lowercase key that does not exist yet.' },\n name: { type: 'string' },\n description: { type: 'string' },\n parent: placeKey,\n features: featureList,\n exits: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n to: placeKey,\n description: { type: 'string', description: 'What the way looks like from this place.' },\n one_way: { type: 'boolean', description: 'Leave out for a way that works both ways.' },\n back_description: { type: 'string' },\n travel_time_seconds: { type: 'integer' },\n state: { type: 'string', enum: [...EXIT_STATES] },\n note: { type: 'string' },\n },\n required: ['to'],\n additionalProperties: false,\n },\n },\n note: { type: 'string', description: 'Why it was made, for whoever fits it into the world later.' },\n },\n required: ['key', 'name'],\n additionalProperties: false,\n },\n },\n exits: {\n type: 'array',\n description: 'New ways between places that exist (or are made in this edit). Both directions unless one_way.',\n items: {\n type: 'object',\n properties: { from: placeKey, to: placeKey, description: { type: 'string' }, one_way: { type: 'boolean' }, back_description: { type: 'string' }, travel_time_seconds: { type: 'integer' }, state: { type: 'string', enum: [...EXIT_STATES] }, note: { type: 'string' } },\n required: ['from', 'to'],\n additionalProperties: false,\n },\n },\n characters: {\n type: 'array',\n description: 'People the story makes up, only when it genuinely needs them. Played by an agent from what is given here.',\n items: {\n type: 'object',\n properties: {\n key: { type: 'string', description: 'A short lowercase key that does not exist yet.' },\n name: { type: 'string' },\n aliases: { type: 'array', items: { type: 'string' } },\n age: { type: 'string' },\n gender: { type: 'string' },\n pronouns: { type: 'string' },\n kind: { type: 'string', enum: [...CHARACTER_KINDS], description: 'person, or group for a crowd or organisation treated as one.' },\n tier: { type: 'string', enum: [...CHARACTER_TIERS], description: 'supporting by default; background for someone who only reacts.' },\n summary: { type: 'string', description: 'One or two sentences: who they are.' },\n personality: { type: 'string' },\n background: { type: 'string' },\n appearance: { type: 'string' },\n speech: { type: 'object', properties: { style: { type: 'string' }, examples: { type: 'array', items: { type: 'string' } } }, required: ['style'], additionalProperties: false },\n state: { type: 'object', properties: { public_state: { type: 'string' }, inner_state: { type: 'string' }, activity: { type: 'string' } }, additionalProperties: false },\n place: { type: 'object', properties: { location: placeKey, position: { type: 'string' }, feature: { type: 'string' } }, required: ['location'], additionalProperties: false },\n note: { type: 'string', description: 'Why they were made, for whoever fits them into the world later.' },\n },\n required: ['key', 'name', 'summary'],\n additionalProperties: false,\n },\n },\n })\n }\n if (options.changes === true) {\n Object.assign(properties, {\n event_edits: {\n type: 'array',\n description: 'Corrections to draft events of this run (a sealed event cannot change). Give only what changes; perceived_by replaces the whole list.',\n items: {\n type: 'object',\n properties: { id: { type: 'integer' }, text: { type: 'string' }, importance: IMPORTANCE, tags: { type: 'array', items: { type: 'string' } }, involves: keys, perceived_by: perceivedBy, location: placeKey },\n required: ['id'],\n additionalProperties: false,\n },\n },\n event_retractions: { type: 'array', items: { type: 'integer' }, description: 'Ids of recorded events that did not happen or duplicate another.' },\n perception_edits: {\n type: 'array',\n description: 'Revisions of what a character took in of an event (the ids are in read_records): it learned more, or remembers it differently. Allowed on any event.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n mode: { type: 'string', enum: [...PERCEPTION_MODES] },\n content: { type: 'string' },\n gist: { type: 'string' },\n accuracy: { type: 'string', enum: [...ACCURACIES] },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n perceptions_added: {\n type: 'array',\n description: 'A character that took in an earlier event only now (it was told, or worked it out). Allowed on any event.',\n items: {\n type: 'object',\n properties: {\n event: { type: 'integer' },\n character,\n mode: { type: 'string', enum: [...PERCEPTION_MODES] },\n content: { type: 'string' },\n gist: { type: 'string' },\n accuracy: { type: 'string', enum: [...ACCURACIES] },\n },\n required: ['event', 'character', 'mode'],\n additionalProperties: false,\n },\n },\n belief_edits: {\n type: 'array',\n items: { type: 'object', properties: { id: { type: 'integer' }, text: { type: 'string' }, about: keys, importance: IMPORTANCE, confidence: CONFIDENCE, evidence_for: EVIDENCE_FOR, evidence_against: EVIDENCE_AGAINST }, required: ['id'], additionalProperties: false },\n },\n belief_retractions: { type: 'array', items: { type: 'integer' } },\n })\n }\n return { type: 'object', properties, required: ['turn'], additionalProperties: false }\n}\n","import {\n ACCURACIES, CHARACTER_KINDS, CHARACTER_TIERS, CONTAINER_STATES, EXIT_STATES, IMPORTANCE_MAX, IMPORTANCE_MIN, INTENT_HORIZONS, INTENT_TYPES, KNOWLEDGE_KINDS, MAX_LOCATION_FEATURES, MEMBERSHIP_STATUSES, MEMORY_CONFIDENCES, MEMORY_KINDS, PERCEPTION_MODES, SLOT_ID,\n type CharacterId, type CharacterStatePatch, type Holder, type Location, type LocationFeature, type NewPerception, type RelationshipPatch,\n} from 'dsh-roleplay-model'\nimport { InvalidEditError, InvalidMoveError } from '../errors.ts'\nimport { lookupKey } from '../sqlite/support.ts'\nimport { characterKey, locationKey, type EditResult, type NewExit, type NewPlace, type PerceivedBy, type RecordsEdit, type RecordsTarget } from './edit-types.ts'\nimport { prepareAgenda, writeAgenda } from './agenda-edit.ts'\nimport { ITEM_ACTIONS, changeItem } from './items.ts'\nimport { moveCharacter } from './movement.ts'\nimport { triggerReferenceProblems } from './trigger-rules.ts'\nimport { changeVariable, planVariableChange } from './variables.ts'\n\nexport * from './edit-types.ts'\nexport { parseRecordsEdit, recordsEditSchema } from './wire.ts'\n\nconst present = (value: string | undefined): boolean => value !== undefined && value.trim() !== ''\nconst list = <T>(value: readonly T[] | undefined): readonly T[] => value ?? []\n\n/** Makes the triggers of an edit, after everything else in it, so that they can name what it made. @throws {InvalidEditError} naming each problem. */\nfunction createTriggers(target: RecordsTarget, edit: RecordsEdit): string[] {\n const made = list(edit.triggers)\n const keys = made.map(definition => definition.key)\n const problems = [\n ...made.flatMap(definition => triggerReferenceProblems(target, definition, keys)),\n ...keys.flatMap((key, index) => (keys.indexOf(key) === index ? [] : [`${key}: made twice in this edit`])),\n ...keys.flatMap(key => (target.triggers.getByKey(key) === undefined ? [] : [`${key}: there is already a trigger with this key`])),\n ]\n if (problems.length > 0) throw new InvalidEditError(problems)\n for (const definition of made) target.triggers.add(definition, 'story', edit.turn)\n return keys\n}\n\n/**\n * Apply an edit. Every problem is found before anything is written, so a bad edit changes nothing.\n * @throws {InvalidEditError} naming each problem.\n */\nfunction applyChanges(target: RecordsTarget, edit: RecordsEdit): EditResult {\n const characters = target.characters.list()\n const byKey = new Map(characters.map(character => [characterKey(character), character]))\n const problems: string[] = []\n const known = (): string => [...byKey.keys()].join(', ')\n const idOf = (key: string, where: string): CharacterId | undefined => {\n const found = byKey.get(key)\n if (found === undefined) problems.push(`${where}: there is no character \"${key}\" (the characters are: ${known()})`)\n return found?.id\n }\n const ids = (keys: readonly string[] | undefined, where: string): CharacterId[] => list(keys).flatMap(key => idOf(key, where) ?? [])\n const factionByKey = new Map(target.factions.list().map(faction => [faction.sourceId ?? String(faction.id), faction]))\n const factionIdOf = (key: string, where: string): number | undefined => { const found = factionByKey.get(key); if (found === undefined) problems.push(`${where}: there is no faction \"${key}\"`); return found?.id }\n const socialIdOf = (kind: 'character' | 'faction', key: string, where: string): number | undefined => kind === 'character' ? idOf(key, where) : factionIdOf(key, where)\n const importance = (value: number | undefined, where: string): void => {\n if (value !== undefined && (!Number.isInteger(value) || value < IMPORTANCE_MIN || value > IMPORTANCE_MAX)) problems.push(`${where}: importance must be a whole number from ${IMPORTANCE_MIN} to ${IMPORTANCE_MAX}`)\n }\n const perceptions = (text: string, given: readonly PerceivedBy[] | undefined, where: string): NewPerception[] => {\n const seen = new Set<string>()\n return list(given).flatMap((entry, index): NewPerception[] => {\n const at = `${where}.perceived_by[${index}]`\n const characterId = idOf(entry.character, at)\n if (seen.has(entry.character)) problems.push(`${at}: ${entry.character} is listed twice`)\n seen.add(entry.character)\n if (!PERCEPTION_MODES.includes(entry.mode)) problems.push(`${at}: unknown mode \"${String(entry.mode)}\"`)\n if (entry.accuracy !== undefined && !ACCURACIES.includes(entry.accuracy)) problems.push(`${at}: unknown accuracy \"${String(entry.accuracy)}\"`)\n if (characterId === undefined) return []\n const content = present(entry.content) ? entry.content!.trim() : text\n const gist = present(entry.gist) ? entry.gist!.trim() : content.length <= 80 ? content : `${content.slice(0, 77).trimEnd()}…`\n return [{ characterId, mode: entry.mode, content, gist, accuracy: entry.accuracy ?? 'accurate' }]\n })\n }\n const tags = (given: readonly string[] | undefined): string[] => [...new Set(list(given).map(tag => tag.trim().toLowerCase()).filter(tag => tag !== ''))]\n\n const existingPlaces = new Map(target.locations.list().map(place => [locationKey(place), place]))\n const newPlaceKeys = new Set<string>()\n const placeKnown = (key: string, where: string): void => {\n if (!existingPlaces.has(key) && !newPlaceKeys.has(key)) problems.push(`${where}: there is no place \"${key}\" (list_locations shows the keys)`)\n }\n const placeKeys = new Set(list(edit.places).map(place => place.key))\n list(edit.places).forEach((place, index) => {\n const where = `places[${index}]`\n if (!present(place.key)) problems.push(`${where}: give the place a key`)\n else if (existingPlaces.has(place.key) || newPlaceKeys.has(place.key)) problems.push(`${where}: the key \"${place.key}\" is already used by a place`)\n if (!present(place.name)) problems.push(`${where}: give the place a name`)\n if (place.parent !== undefined) placeKnown(place.parent, `${where}.parent`)\n if (list(place.features).length > MAX_LOCATION_FEATURES) problems.push(`${where}: a place has at most ${MAX_LOCATION_FEATURES} features`)\n newPlaceKeys.add(place.key)\n for (const [at, exit] of list(place.exits).entries()) {\n if (!existingPlaces.has(exit.to) && !placeKeys.has(exit.to)) problems.push(`${where}.exits[${at}]: there is no place \"${exit.to}\"`)\n if (exit.to === place.key) problems.push(`${where}.exits[${at}]: an exit must lead to another place`)\n if (exit.state !== undefined && !EXIT_STATES.includes(exit.state)) problems.push(`${where}.exits[${at}]: unknown state \"${String(exit.state)}\"`)\n }\n })\n list(edit.placeEdits).forEach((change, index) => {\n const where = `place_edits[${index}]`\n placeKnown(change.place, where)\n if (change.name !== undefined && !present(change.name)) problems.push(`${where}: a place needs a name`)\n if (list(change.features).length > MAX_LOCATION_FEATURES) problems.push(`${where}: a place has at most ${MAX_LOCATION_FEATURES} features`)\n })\n list(edit.exitChanges).forEach((change, index) => {\n const where = `exit_changes[${index}]`\n placeKnown(change.from, `${where}.from`)\n placeKnown(change.to, `${where}.to`)\n if (change.state !== undefined && !EXIT_STATES.includes(change.state)) problems.push(`${where}: unknown state \"${String(change.state)}\"`)\n const from = existingPlaces.get(change.from)\n const to = existingPlaces.get(change.to)\n if (from !== undefined && to !== undefined && target.locations.getExit(from.id, to.id) === undefined) problems.push(`${where}: there is no exit from \"${change.from}\" to \"${change.to}\"`)\n })\n list(edit.moves).forEach((move, index) => {\n const where = `moves[${index}]`\n idOf(move.character, where)\n placeKnown(move.to, `${where}.to`)\n })\n list(edit.exits).forEach((wanted, index) => {\n const where = `exits[${index}]`\n placeKnown(wanted.from, `${where}.from`)\n placeKnown(wanted.to, `${where}.to`)\n if (wanted.from === wanted.to) problems.push(`${where}: an exit must lead to another place`)\n if (wanted.state !== undefined && !EXIT_STATES.includes(wanted.state)) problems.push(`${where}: unknown state \"${String(wanted.state)}\"`)\n const from = existingPlaces.get(wanted.from)\n const to = existingPlaces.get(wanted.to)\n if (from !== undefined && to !== undefined && target.locations.getExit(from.id, to.id) !== undefined && wanted.oneWay === true) problems.push(`${where}: there already is an exit from \"${wanted.from}\" to \"${wanted.to}\" (change it with exit_changes)`)\n })\n const RELATION_RANGES = { familiarity: [0, 1], trust: [-1, 1], affinity: [-1, 1], tension: [0, 1] } as const\n list(edit.relationships).forEach((relation, index) => {\n const where = `relationships[${index}]`\n const from = idOf(relation.from, `${where}.from`)\n const to = idOf(relation.to, `${where}.to`)\n if (relation.from === relation.to) problems.push(`${where}: a character has no relationship with itself`)\n for (const [axis, [min, max]] of Object.entries(RELATION_RANGES) as [keyof typeof RELATION_RANGES, readonly [number, number]][]) {\n const value = relation[axis]\n if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) problems.push(`${where}: ${axis} must be a number from ${min} to ${max}`)\n }\n if (relation.label !== undefined && !present(relation.label)) problems.push(`${where}: the label cannot be empty`)\n if (from !== undefined && to !== undefined && target.relationships.get(from, to) === undefined && !present(relation.label)) problems.push(`${where}: a new relationship needs a label (\"${relation.from}\" towards \"${relation.to}\")`)\n })\n list(edit.relationshipRetractions).forEach((retraction, index) => {\n const where = `relationship_retractions[${index}]`\n const from = idOf(retraction.from, `${where}.from`)\n const to = idOf(retraction.to, `${where}.to`)\n if (from !== undefined && to !== undefined && target.relationships.get(from, to) === undefined) problems.push(`${where}: \"${retraction.from}\" has no relationship with \"${retraction.to}\"`)\n })\n const itemFor = (key: string) => target.items.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.items.get(Number(key)) : undefined)\n const knowledgeSubject = (entry: { kind: string; subject?: string; from?: string; to?: string }, where: string): { kind: 'location' | 'item' | 'exit'; id: number } | undefined => {\n if (!KNOWLEDGE_KINDS.includes(entry.kind as never)) { problems.push(`${where}: unknown kind \"${entry.kind}\"`); return undefined }\n if (entry.kind === 'location') {\n const place = entry.subject === undefined ? undefined : existingPlaces.get(entry.subject)\n if (place === undefined) problems.push(`${where}.subject: there is no place \"${entry.subject ?? ''}\"`)\n return place === undefined ? undefined : { kind: 'location', id: place.id }\n }\n if (entry.kind === 'item') {\n const item = entry.subject === undefined ? undefined : itemFor(entry.subject)\n if (item === undefined) problems.push(`${where}.subject: there is no item \"${entry.subject ?? ''}\"`)\n return item === undefined ? undefined : { kind: 'item', id: item.id }\n }\n const from = entry.from === undefined ? undefined : existingPlaces.get(entry.from)\n const to = entry.to === undefined ? undefined : existingPlaces.get(entry.to)\n const exit = from === undefined || to === undefined ? undefined : target.locations.getExit(from.id, to.id)\n if (exit === undefined) problems.push(`${where}: there is no exit from \"${entry.from ?? ''}\" to \"${entry.to ?? ''}\"`)\n return exit === undefined ? undefined : { kind: 'exit', id: exit.id }\n }\n const knowledge = list(edit.knowledge).map((entry, index) => ({ entry, character: idOf(entry.character, `knowledge[${index}].character`), subject: knowledgeSubject(entry, `knowledge[${index}]`) }))\n const knowledgeRetractions = list(edit.knowledgeRetractions).map((entry, index) => {\n const character = idOf(entry.character, `knowledge_retractions[${index}].character`)\n const subject = knowledgeSubject(entry, `knowledge_retractions[${index}]`)\n if (character !== undefined && subject !== undefined && !target.knowledge.knows(character, subject.kind, subject.id)) problems.push(`knowledge_retractions[${index}]: the character does not know that entity`)\n return { character, subject }\n })\n const factionStates = list(edit.factionStates).map((entry, index) => {\n const where = `faction_states[${index}]`\n if (entry.publicState === undefined && entry.innerState === undefined) problems.push(`${where}: nothing to change`)\n return { entry, faction: factionIdOf(entry.faction, where) }\n })\n const factionMemberships = list(edit.factionMemberships).map((entry, index) => {\n const where = `faction_memberships[${index}]`\n const faction = factionIdOf(entry.faction, `${where}.faction`)\n const character = idOf(entry.character, `${where}.character`)\n if (entry.status !== undefined && !MEMBERSHIP_STATUSES.includes(entry.status)) problems.push(`${where}: unknown status \"${String(entry.status)}\"`)\n if (entry.commitment !== undefined && (!Number.isFinite(entry.commitment) || entry.commitment < 0 || entry.commitment > 1)) problems.push(`${where}: commitment must be a number from 0 to 1`)\n return { entry, faction, character }\n })\n const factionRelationships = list(edit.factionRelationships).map((entry, index) => {\n const where = `faction_relationships[${index}]`\n if (!['character', 'faction'].includes(entry.fromKind)) problems.push(`${where}.from_kind: must be character or faction`)\n if (!['character', 'faction'].includes(entry.toKind)) problems.push(`${where}.to_kind: must be character or faction`)\n const from = socialIdOf(entry.fromKind, entry.from, `${where}.from`)\n const to = socialIdOf(entry.toKind, entry.to, `${where}.to`)\n if (entry.fromKind === entry.toKind && entry.from === entry.to) problems.push(`${where}: an entity has no relationship with itself`)\n if (from !== undefined && to !== undefined && target.factionRelationships.get(entry.fromKind, from, entry.toKind, to) === undefined && !present(entry.label)) problems.push(`${where}: a new relationship needs a label`)\n for (const [axis, [min, max]] of Object.entries(RELATION_RANGES) as [keyof typeof RELATION_RANGES, readonly [number, number]][]) { const value = entry[axis]; if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) problems.push(`${where}: ${axis} must be a number from ${min} to ${max}`) }\n return { entry, from, to }\n })\n const factionIntents = list(edit.factionIntentsAdded).map((entry, index) => {\n const where = `faction_intents_added[${index}]`\n const faction = factionIdOf(entry.faction, `${where}.faction`)\n if (!INTENT_TYPES.includes(entry.type)) problems.push(`${where}: unknown type \"${String(entry.type)}\"`)\n if (!INTENT_HORIZONS.includes(entry.horizon)) problems.push(`${where}: unknown horizon \"${String(entry.horizon)}\"`)\n if (!present(entry.name)) problems.push(`${where}: give the goal a name`)\n for (const [key, value] of [['priority', entry.priority], ['urgency', entry.urgency]] as const) if (!Number.isFinite(value) || value < 0 || value > 1) problems.push(`${where}.${key}: must be a number from 0 to 1`)\n return { entry, faction }\n })\n list(edit.itemChanges).forEach((change, index) => {\n const where = `item_changes[${index}]`\n idOf(change.character, where)\n if (!ITEM_ACTIONS.includes(change.action)) problems.push(`${where}: unknown action \"${String(change.action)}\" (the actions are: ${ITEM_ACTIONS.join(', ')})`)\n if (change.exit === undefined && itemFor(change.item) === undefined) problems.push(`${where}: there is no item \"${change.item}\" (list_items shows the keys)`)\n })\n list(edit.itemEdits).forEach((change, index) => {\n const where = `item_edits[${index}]`\n const item = itemFor(change.item)\n if (item === undefined) { problems.push(`${where}: there is no item \"${change.item}\"`); return }\n if (change.state !== undefined && (item.container === undefined || !CONTAINER_STATES.includes(change.state))) problems.push(`${where}: ${item.container === undefined ? `${item.name} is not a container` : `unknown container state \"${String(change.state)}\"`}`)\n if (change.quantity !== undefined && (!Number.isInteger(change.quantity) || change.quantity < 1)) problems.push(`${where}: the quantity must be a whole number from 1`)\n if (change.owner !== undefined && !byKey.has(change.owner)) problems.push(`${where}.owner: there is no character \"${change.owner}\"`)\n for (const key of list(change.openedBy)) if (itemFor(key) === undefined) problems.push(`${where}.opened_by: there is no item \"${key}\"`)\n if (change.openedBy !== undefined && item.container === undefined) problems.push(`${where}: ${item.name} is not a container, so nothing opens it`)\n if (change.description !== undefined && !present(change.description)) problems.push(`${where}: the description cannot be empty`)\n })\n list(edit.events).forEach((event, index) => { for (const key of list(event.items)) if (itemFor(key) === undefined) problems.push(`events[${index}].items: there is no item \"${key}\"`) })\n const placeIn = (key: string | undefined, where: string): void => { if (key !== undefined) placeKnown(key, where) }\n list(edit.events).forEach((event, index) => { placeIn(event.location, `events[${index}].location`) })\n list(edit.eventEdits).forEach((change, index) => { placeIn(change.location, `event_edits[${index}].location`) })\n\n if (!Number.isInteger(edit.turn) || edit.turn < 1) problems.push('turn must be a whole number from 1')\n\n const states = list(edit.states).flatMap((patch, index) => {\n const where = `states[${index}]`\n const id = idOf(patch.character, where)\n if (!present(patch.publicState) && !present(patch.innerState) && !present(patch.activity)) problems.push(`${where}: nothing to change`)\n return id === undefined ? [] : [{ id, patch }]\n })\n\n const events = list(edit.events).flatMap((event, index) => {\n const where = `events[${index}]`\n if (!present(event.text)) problems.push(`${where}: say what happened`)\n if (!Number.isInteger(event.turn) || event.turn < 1 || !Number.isInteger(event.round) || event.round < 1) problems.push(`${where}: turn and round must be whole numbers from 1`)\n importance(event.importance, where)\n return [{ event, involves: ids(event.involves, `${where}.involves`), perceived: perceptions(event.text.trim(), event.perceivedBy, where) }]\n })\n\n const eventEdits = list(edit.eventEdits).map((change, index) => {\n const where = `event_edits[${index}]`\n const current = target.events.get(change.id)\n if (current === undefined) problems.push(`${where}: there is no event ${change.id}`)\n else if (current.sealed) problems.push(`${where}: event ${change.id} is sealed and cannot change; what a character took in of it can be revised with perception_edits, and later knowledge added with perceptions_added`)\n if (change.text !== undefined && !present(change.text)) problems.push(`${where}: say what happened`)\n importance(change.importance, where)\n return { change, current, involves: change.involves === undefined ? undefined : ids(change.involves, `${where}.involves`), perceived: change.perceivedBy === undefined ? undefined : perceptions((change.text ?? current?.text ?? '').trim(), change.perceivedBy, where) }\n })\n for (const id of list(edit.eventRetractions)) {\n const current = target.events.get(id)\n if (current === undefined) problems.push(`event_retractions: there is no event ${id}`)\n else if (current.sealed) problems.push(`event_retractions: event ${id} is sealed and cannot be removed`)\n }\n\n const perceptionEdits = list(edit.perceptionEdits).map((change, index) => {\n const where = `perception_edits[${index}]`\n const current = target.events.getPerception(change.id)\n if (current === undefined) problems.push(`${where}: there is no perception ${change.id}`)\n if (change.mode !== undefined && !PERCEPTION_MODES.includes(change.mode)) problems.push(`${where}: unknown mode \"${String(change.mode)}\"`)\n if (change.accuracy !== undefined && !ACCURACIES.includes(change.accuracy)) problems.push(`${where}: unknown accuracy \"${String(change.accuracy)}\"`)\n if (change.content !== undefined && !present(change.content)) problems.push(`${where}: content cannot be empty`)\n return change\n })\n const perceptionsAdded = list(edit.perceptionsAdded).flatMap((added, index) => {\n const where = `perceptions_added[${index}]`\n const event = target.events.get(added.event)\n if (event === undefined) { problems.push(`${where}: there is no event ${added.event}`); return [] }\n const [one] = perceptions(event.text, [added], where)\n const characterId = byKey.get(added.character)?.id\n if (characterId !== undefined && target.events.perceptionsOf(added.event).some(entry => entry.characterId === characterId)) problems.push(`${where}: ${added.character} already has a perception of event ${added.event}: revise it with perception_edits`)\n return one === undefined ? [] : [{ eventId: added.event, perception: one }]\n })\n\n const confidence = (value: unknown, where: string): void => {\n if (value !== undefined && !MEMORY_CONFIDENCES.includes(value as never)) problems.push(`${where}: confidence is one of ${MEMORY_CONFIDENCES.join(', ')}`)\n }\n /** Perceptions a belief of one character is said to rest on, or to be contradicted by: they must be the character's own. */\n const evidence = (value: readonly number[] | undefined, characterId: CharacterId | undefined, where: string): number[] => (value ?? []).flatMap((id) => {\n const seen = target.events.getPerception(id)\n if (seen === undefined) { problems.push(`${where}: there is no perception ${id}`); return [] }\n if (characterId !== undefined && seen.characterId !== characterId) { problems.push(`${where}: perception ${id} is not one the character took in`); return [] }\n return [id]\n })\n const beliefs = list(edit.beliefs).flatMap((belief, index) => {\n const where = `beliefs[${index}]`\n const character = idOf(belief.character, where)\n if (!MEMORY_KINDS.includes(belief.kind)) problems.push(`${where}: unknown kind \"${String(belief.kind)}\"`)\n if (!present(belief.text)) problems.push(`${where}: say what the character believes or knows`)\n importance(belief.importance, where)\n confidence(belief.confidence, where)\n return character === undefined ? [] : [{ belief, character, about: ids(belief.about, `${where}.about`), evidenceFor: evidence(belief.evidenceFor, character, `${where}.evidence_for`), evidenceAgainst: evidence(belief.evidenceAgainst, character, `${where}.evidence_against`) }]\n })\n const beliefEdits = list(edit.beliefEdits).map((change, index) => {\n const where = `belief_edits[${index}]`\n const current = target.memories.get(change.id)\n if (current === undefined) problems.push(`${where}: there is no belief ${change.id}`)\n if (change.text !== undefined && !present(change.text)) problems.push(`${where}: say what the character believes or knows`)\n importance(change.importance, where)\n confidence(change.confidence, where)\n return { change, about: change.about === undefined ? undefined : ids(change.about, `${where}.about`), evidenceFor: evidence(change.evidenceFor, current?.characterId, `${where}.evidence_for`), evidenceAgainst: evidence(change.evidenceAgainst, current?.characterId, `${where}.evidence_against`) }\n })\n for (const id of list(edit.beliefRetractions)) if (target.memories.get(id) === undefined) problems.push(`belief_retractions: there is no belief ${id}`)\n for (const [index, text] of list(edit.threadsOpened).entries()) if (!present(text)) problems.push(`threads_opened[${index}]: say what is unsettled`)\n for (const id of list(edit.threadsResolved)) if (target.threads.get(id) === undefined) problems.push(`threads_resolved: there is no thread ${id}`)\n\n list(edit.variableChanges).forEach((change, index) => {\n const where = `variable_changes[${index}]`\n if (list(edit.variables).some(def => def.key === change.variable)) return\n const planned = planVariableChange(target, change)\n if (!planned.ok) problems.push(...planned.problems.map(problem => `${where}: ${problem}`))\n })\n const agenda = prepareAgenda(target, edit, { idOf, placeKnown, places: existingPlaces, problems })\n\n if (problems.length > 0) throw new InvalidEditError(problems)\n\n return target.transaction(() => {\n const result: EditResult = { eventIds: [], beliefIds: [], writes: 0 }\n const learnEventEntities = (event: { turn: number; locationId?: number; items: readonly number[]; involves: readonly number[] }, characterId: number): void => {\n if (event.locationId !== undefined) target.knowledge.learn(characterId, 'location', event.locationId, event.turn)\n for (const itemId of event.items) target.knowledge.learn(characterId, 'item', itemId, event.turn)\n for (const otherId of event.involves) if (otherId !== characterId && target.relationships.get(characterId, otherId) === undefined) target.relationships.upsert(characterId, otherId, { label: 'acquaintance' }, event.turn)\n }\n const placeOf = (key: string): Location => {\n const found = target.locations.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.locations.get(Number(key)) : undefined)\n if (found === undefined) throw new InvalidEditError([`there is no place \"${key}\"`])\n return found\n }\n const features = (given: readonly { key: string; name: string; description?: string }[] | undefined): LocationFeature[] => list(given).map(feature => ({ key: feature.key, name: feature.name, description: feature.description ?? '' }))\n const exit = (from: Location, to: Location, description: string | undefined, rest: Pick<NewExit, 'travelSeconds' | 'state' | 'note'>): void => {\n if (target.locations.getExit(from.id, to.id) !== undefined) return\n target.locations.addExit({ fromId: from.id, toId: to.id, description: description ?? '', ...(rest.travelSeconds === undefined ? {} : { travelSeconds: rest.travelSeconds }), ...(rest.state === undefined ? {} : { state: rest.state }), ...(rest.note === undefined ? {} : { note: rest.note }) })\n result.writes += 1\n }\n result.placeKeys = []\n for (const place of list(edit.places)) {\n const added = target.locations.add({ sourceId: place.key, name: place.name, description: place.description ?? '', ...(place.parent === undefined ? {} : { parentId: placeOf(place.parent).id }), features: features(place.features) })\n target.consolidation.enqueue({ kind: 'location', subjectId: added.id, note: place.note ?? 'made up in play', turn: edit.turn })\n result.placeKeys.push(place.key)\n result.writes += 1\n }\n for (const place of list(edit.places)) {\n const from = placeOf(place.key)\n for (const wanted of list(place.exits)) {\n const to = placeOf(wanted.to)\n exit(from, to, wanted.description, wanted)\n if (wanted.oneWay !== true) exit(to, from, wanted.backDescription ?? wanted.description, wanted)\n }\n }\n for (const wanted of list(edit.exits)) {\n const from = placeOf(wanted.from)\n const to = placeOf(wanted.to)\n exit(from, to, wanted.description, wanted)\n if (wanted.oneWay !== true) exit(to, from, wanted.backDescription ?? wanted.description, wanted)\n }\n for (const relation of list(edit.relationships)) {\n const { from, to, ...fields } = relation\n const patch: RelationshipPatch = {\n ...(fields.label === undefined ? {} : { label: fields.label }), ...(fields.summary === undefined ? {} : { summary: fields.summary }),\n ...(fields.familiarity === undefined ? {} : { familiarity: fields.familiarity }), ...(fields.trust === undefined ? {} : { trust: fields.trust }),\n ...(fields.affinity === undefined ? {} : { affinity: fields.affinity }), ...(fields.tension === undefined ? {} : { tension: fields.tension }),\n }\n target.relationships.upsert(byKey.get(from)!.id, byKey.get(to)!.id, patch, edit.turn)\n result.writes += 1\n }\n for (const retraction of list(edit.relationshipRetractions)) {\n target.relationships.remove(byKey.get(retraction.from)!.id, byKey.get(retraction.to)!.id)\n result.writes += 1\n }\n for (const { entry, character, subject } of knowledge) {\n target.knowledge.learn(character!, subject!.kind, subject!.id, edit.turn, entry.observed === true)\n result.writes += 1\n }\n for (const { character, subject } of knowledgeRetractions) {\n target.knowledge.forget(character!, subject!.kind, subject!.id)\n result.writes += 1\n }\n for (const { entry, faction } of factionStates) {\n target.factionStates.update(faction!, { ...(entry.publicState === undefined ? {} : { publicState: entry.publicState }), ...(entry.innerState === undefined ? {} : { innerState: entry.innerState }) })\n result.writes += 1\n }\n for (const { entry, faction, character } of factionMemberships) {\n const { faction: _faction, character: _character, ...patch } = entry\n target.factionMemberships.upsert(faction!, character!, patch, edit.turn)\n if (target.factionRelationships.get('character', character!, 'faction', faction!) === undefined) target.factionRelationships.upsert('character', character!, 'faction', faction!, { label: entry.role || 'member', familiarity: 1 }, edit.turn)\n result.writes += 1\n }\n for (const { entry, from, to } of factionRelationships) {\n const { fromKind, from: _from, toKind, to: _to, ...patch } = entry\n target.factionRelationships.upsert(fromKind, from!, toKind, to!, patch, edit.turn)\n result.writes += 1\n }\n for (const { entry, faction } of factionIntents) {\n target.factionIntents.add(faction!, { type: entry.type, name: entry.name.trim(), description: entry.description?.trim() ?? '', status: 'active', horizon: entry.horizon, priority: entry.priority, urgency: entry.urgency, plan: entry.plan ?? [], openThreads: [], constraints: entry.constraints ?? [], ...(entry.deadline === undefined ? {} : { deadline: entry.deadline }) })\n result.writes += 1\n }\n for (const change of list(edit.placeEdits)) {\n target.locations.update(placeOf(change.place).id, {\n ...(change.name === undefined ? {} : { name: change.name }),\n ...(change.description === undefined ? {} : { description: change.description }),\n ...(change.features === undefined ? {} : { features: features(change.features) }),\n })\n result.writes += 1\n }\n for (const change of list(edit.exitChanges)) {\n const from = placeOf(change.from)\n const to = placeOf(change.to)\n const sides = change.oneWay === true ? [[from, to]] as const : [[from, to], [to, from]] as const\n let found = false\n for (const [a, b] of sides) {\n const current = target.locations.getExit(a.id, b.id)\n if (current === undefined) continue\n found = true\n target.locations.updateExit(current.id, {\n ...(change.state === undefined ? {} : { state: change.state }),\n ...(change.description === undefined || a !== from ? {} : { description: change.description }),\n ...(change.note === undefined ? {} : { note: change.note }),\n ...(change.travelSeconds === undefined ? {} : { travelSeconds: change.travelSeconds }),\n })\n result.writes += 1\n }\n if (!found) throw new InvalidEditError([`there is no exit from \"${change.from}\" to \"${change.to}\"`])\n }\n for (const [index, change] of list(edit.itemChanges).entries()) {\n const { character: who, ...spec } = change\n try {\n changeItem(target, byKey.get(who)!.id, spec)\n } catch (error) {\n if (error instanceof InvalidMoveError) throw new InvalidEditError(error.problems.map(problem => `item_changes[${index}]: ${problem}`))\n throw error\n }\n result.writes += 1\n }\n for (const change of list(edit.itemEdits)) {\n const item = itemFor(change.item)!\n target.items.update(item.id, {\n ...(change.description === undefined ? {} : { description: change.description }), ...(change.quality === undefined ? {} : { quality: change.quality }),\n ...(change.quantity === undefined ? {} : { quantity: change.quantity }), ...(change.notable === undefined ? {} : { notable: change.notable }),\n ...(change.hidden === undefined ? {} : { hidden: change.hidden }), ...(change.state === undefined ? {} : { container: { state: change.state } }),\n ...(change.owner === undefined ? {} : { ownerId: byKey.get(change.owner)!.id }),\n })\n if (change.openedBy !== undefined) target.items.setOpeners({ kind: 'item', id: item.id }, change.openedBy.map(key => itemFor(key)!.id))\n result.writes += 1\n }\n for (const [index, move] of list(edit.moves).entries()) {\n const character = byKey.get(move.character)!\n try {\n moveCharacter(target, character.id, { to: placeOf(move.to).id, ...(move.position === undefined ? {} : { position: move.position }), ...(move.feature === undefined ? {} : { featureKey: move.feature }), ...(move.ignoreExits === true ? { ignoreExits: true } : {}) })\n } catch (error) {\n if (error instanceof InvalidMoveError) throw new InvalidEditError(error.problems.map(problem => `moves[${index}]: ${problem}`))\n throw error\n }\n result.writes += 1\n }\n for (const { id, patch } of states) {\n const current = target.characterStates.get(id)\n const { character: _character, ...fields } = patch\n const written: CharacterStatePatch = {\n ...(present(fields.publicState) ? { publicState: fields.publicState!.trim() } : {}),\n ...(present(fields.innerState) ? { innerState: fields.innerState!.trim() } : {}),\n ...(present(fields.activity) ? { activity: fields.activity!.trim() } : {}),\n }\n if (current === undefined) {\n target.characterStates.create(id, { publicState: written.publicState ?? '', innerState: written.innerState ?? '', activity: written.activity ?? '' })\n } else {\n target.characterStates.update(id, written)\n }\n result.writes += 1\n }\n for (const { event, involves, perceived } of events) {\n const { event: stored } = target.events.add({ turn: event.turn, round: event.round, text: event.text.trim(), importance: event.importance, tags: tags(event.tags), involves, ...(event.items === undefined ? {} : { items: event.items.map(key => itemFor(key)!.id) }), ...(event.location === undefined ? {} : { locationId: placeOf(event.location).id }) }, perceived)\n for (const perception of perceived) learnEventEntities(stored, perception.characterId)\n result.eventIds.push(stored.id)\n result.writes += 1\n }\n for (const { change, involves, perceived } of eventEdits) {\n target.events.update(change.id, {\n ...(change.text === undefined ? {} : { text: change.text.trim() }),\n ...(change.importance === undefined ? {} : { importance: change.importance }),\n ...(change.tags === undefined ? {} : { tags: tags(change.tags) }),\n ...(involves === undefined ? {} : { involves }),\n ...(change.location === undefined ? {} : { locationId: placeOf(change.location).id }),\n })\n if (perceived !== undefined) target.events.setPerceptions(change.id, perceived)\n result.writes += 1\n }\n for (const id of list(edit.eventRetractions)) { target.events.remove(id); result.writes += 1 }\n for (const change of perceptionEdits) {\n target.events.updatePerception(change.id, {\n ...(change.mode === undefined ? {} : { mode: change.mode }),\n ...(change.content === undefined ? {} : { content: change.content.trim() }),\n ...(change.gist === undefined ? {} : { gist: change.gist.trim() }),\n ...(change.accuracy === undefined ? {} : { accuracy: change.accuracy }),\n })\n result.writes += 1\n }\n for (const { eventId, perception } of perceptionsAdded) {\n target.events.addPerception(eventId, perception)\n learnEventEntities(target.events.get(eventId)!, perception.characterId)\n result.writes += 1\n }\n for (const { belief, character, about, evidenceFor, evidenceAgainst } of beliefs) {\n const added = target.memories.add({ characterId: character, kind: belief.kind, text: belief.text.trim(), about, importance: belief.importance, ...(belief.confidence === undefined ? {} : { confidence: belief.confidence }), turn: edit.turn })\n result.beliefIds.push(added.id)\n for (const id of evidenceFor) target.memories.addEvidence(added.id, id, 'supports', edit.turn)\n for (const id of evidenceAgainst) target.memories.addEvidence(added.id, id, 'contradicts', edit.turn)\n result.writes += 1\n }\n for (const { change, about, evidenceFor, evidenceAgainst } of beliefEdits) {\n target.memories.update(change.id, {\n ...(change.text === undefined ? {} : { text: change.text.trim() }),\n ...(about === undefined ? {} : { about }),\n ...(change.importance === undefined ? {} : { importance: change.importance }),\n ...(change.confidence === undefined ? {} : { confidence: change.confidence }),\n })\n for (const id of evidenceFor) target.memories.addEvidence(change.id, id, 'supports', edit.turn)\n for (const id of evidenceAgainst) target.memories.addEvidence(change.id, id, 'contradicts', edit.turn)\n result.writes += 1\n }\n for (const id of list(edit.beliefRetractions)) { target.memories.remove(id); result.writes += 1 }\n for (const text of list(edit.threadsOpened)) { target.threads.open(text.trim(), edit.turn); result.writes += 1 }\n for (const id of list(edit.threadsResolved)) { target.threads.resolve(id, edit.turn); result.writes += 1 }\n result.variableKeys = []\n for (const [index, spec] of list(edit.variables).entries()) {\n try {\n target.variables.define(spec)\n result.variableKeys.push(spec.key)\n } catch (error) {\n throw error instanceof Error ? new InvalidEditError([`variables[${index}]: ${error.message}`]) : error\n }\n result.writes += 1\n }\n for (const [index, change] of list(edit.variableChanges).entries()) {\n try {\n changeVariable(target, change, edit.turn)\n } catch (error) {\n if (error instanceof InvalidEditError) throw new InvalidEditError(error.problems.map(problem => `variable_changes[${index}]: ${problem}`))\n throw error\n }\n result.writes += 1\n }\n result.writes += writeAgenda(target, agenda, edit.turn, key => placeOf(key).id)\n return result\n })\n}\n\n/**\n * Make up the characters of an edit: validated first, then written with their state and place, and each\n * one is queued to be fitted into the rest of the world. Nothing is written when anything is wrong.\n */\nfunction createCharacters(target: RecordsTarget, edit: RecordsEdit): { keys: string[]; writes: number } {\n const problems: string[] = []\n const taken = new Set(target.characters.list().flatMap(character => [lookupKey(character.name), ...character.aliases.map(lookupKey)]))\n const keys = new Set(target.characters.list().map(characterKey))\n const placeFor = (key: string): Location | undefined => target.locations.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.locations.get(Number(key)) : undefined)\n const wanted = list(edit.characters)\n wanted.forEach((spec, index) => {\n const where = `characters[${index}]`\n if (!present(spec.key) || !/^[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,59}$/u.test(spec.key)) problems.push(`${where}: give the character a key of letters (any script), digits, \"-\" or \"_\"`)\n else if (keys.has(spec.key)) problems.push(`${where}: the key \"${spec.key}\" is already used by a character`)\n keys.add(spec.key)\n if (!present(spec.name)) problems.push(`${where}: give the character a name`)\n if (!present(spec.summary)) problems.push(`${where}: give the character a summary of a sentence or two`)\n for (const name of [spec.name, ...list(spec.aliases)]) {\n const found = lookupKey(name ?? '')\n if (found === '') continue\n if (taken.has(found)) problems.push(`${where}: \"${name}\" is already the name of a character: reuse that one instead of making another`)\n taken.add(found)\n }\n if (spec.kind !== undefined && !CHARACTER_KINDS.includes(spec.kind)) problems.push(`${where}: unknown kind \"${String(spec.kind)}\"`)\n if (spec.tier !== undefined && !CHARACTER_TIERS.includes(spec.tier)) problems.push(`${where}: unknown tier \"${String(spec.tier)}\"`)\n if (spec.place !== undefined) {\n const place = placeFor(spec.place.location)\n if (place === undefined) problems.push(`${where}.place: there is no place \"${spec.place.location}\" (list_locations shows the keys)`)\n else if (spec.place.feature !== undefined && !place.features.some(feature => feature.key === spec.place!.feature)) problems.push(`${where}.place: ${place.name} has no feature \"${spec.place.feature}\"`)\n }\n })\n if (problems.length > 0) throw new InvalidEditError(problems)\n for (const spec of wanted) {\n const character = target.characters.add({\n sourceId: spec.key, name: spec.name.trim(), aliases: list(spec.aliases).map(alias => alias.trim()).filter(alias => alias !== '' && lookupKey(alias) !== lookupKey(spec.name)),\n ...(spec.age === undefined ? {} : { age: spec.age }), ...(spec.gender === undefined ? {} : { gender: spec.gender }), ...(spec.pronouns === undefined ? {} : { pronouns: spec.pronouns }),\n kind: spec.kind ?? 'person', tier: spec.tier ?? 'supporting', role: 'npc', control: 'agent',\n summary: spec.summary.trim(), personality: (spec.personality ?? '').trim(), background: (spec.background ?? '').trim(), appearance: (spec.appearance ?? '').trim(),\n speech: { style: (spec.speech?.style ?? '').trim(), examples: list(spec.speech?.examples) as string[] },\n })\n target.characterStates.create(character.id, { publicState: (spec.state?.publicState ?? '').trim(), innerState: (spec.state?.innerState ?? '').trim(), activity: (spec.state?.activity ?? '').trim() })\n if (spec.place !== undefined) {\n target.placements.place('character', character.id, { locationId: placeFor(spec.place.location)!.id, ...(spec.place.position === undefined ? {} : { position: spec.place.position }), ...(spec.place.feature === undefined ? {} : { featureKey: spec.place.feature }) })\n }\n target.consolidation.enqueue({ kind: 'character', subjectId: character.id, note: spec.note ?? 'made up in play', turn: edit.turn })\n }\n return { keys: wanted.map(spec => spec.key), writes: wanted.length }\n}\n\n/**\n * Make up the slots and items of an edit: validated first, then written, each item put where it starts and\n * queued to be fitted into the world. Containers that hold other new items are made first.\n */\nfunction createItems(target: RecordsTarget, edit: RecordsEdit): { keys: string[]; writes: number } {\n const problems: string[] = []\n const slotsWanted = list(edit.slots)\n slotsWanted.forEach((slot, index) => {\n const where = `slots[${index}]`\n if (!SLOT_ID.test(slot.id)) problems.push(`${where}: the id must be lowercase letters, digits, \"-\" or \"_\"`)\n if (!present(slot.name)) problems.push(`${where}: give the slot a name`)\n if (!Number.isInteger(slot.capacity) || slot.capacity < 1) problems.push(`${where}: the capacity must be a whole number from 1`)\n })\n const slotIds = new Set([...target.slots.list().map(slot => slot.id), ...slotsWanted.map(slot => slot.id)])\n const wanted = list(edit.items)\n const newKeys = new Set(wanted.map(spec => spec.key))\n const known = (key: string): boolean => target.items.getBySourceId(key) !== undefined || (Number.isInteger(Number(key)) && target.items.get(Number(key)) !== undefined) || newKeys.has(key)\n const placeFor = (key: string): Location | undefined => target.locations.getBySourceId(key) ?? (Number.isInteger(Number(key)) ? target.locations.get(Number(key)) : undefined)\n const characterFor = (key: string) => target.characters.list().find(character => characterKey(character) === key)\n const seen = new Set<string>()\n wanted.forEach((spec, index) => {\n const where = `items[${index}]`\n if (!present(spec.key) || !/^[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,59}$/u.test(spec.key)) problems.push(`${where}: give the item a key of letters (any script), digits, \"-\" or \"_\"`)\n else if (target.items.getBySourceId(spec.key) !== undefined || seen.has(spec.key)) problems.push(`${where}: the key \"${spec.key}\" is already used by an item`)\n seen.add(spec.key)\n if (!present(spec.name)) problems.push(`${where}: give the item a name`)\n if (spec.quantity !== undefined && (!Number.isInteger(spec.quantity) || spec.quantity < 1)) problems.push(`${where}: the quantity must be a whole number from 1`)\n if (spec.unique === true && (spec.quantity ?? 1) > 1) problems.push(`${where}: a unique item is one thing`)\n if (spec.wearable !== undefined && !slotIds.has(spec.wearable)) problems.push(`${where}: there is no slot \"${spec.wearable}\" (the slots are: ${[...slotIds].join(', ')}; make a new one in slots when the world needs it)`)\n if (spec.container?.state !== undefined && !CONTAINER_STATES.includes(spec.container.state)) problems.push(`${where}: unknown container state \"${String(spec.container.state)}\"`)\n for (const key of list(spec.container?.openedBy)) if (!known(key)) problems.push(`${where}.container.opened_by: there is no item \"${key}\"`)\n if (spec.owner !== undefined && characterFor(spec.owner) === undefined) problems.push(`${where}.owner: there is no character \"${spec.owner}\"`)\n const holders = [spec.at, spec.heldBy, spec.wornBy, spec.inside].filter(holder => holder !== undefined).length\n if (holders !== 1) problems.push(`${where}: say where it starts with exactly one of at (lying in a place: {\"location\": place key}), held_by (a character's key), worn_by (a character's key) or inside (a container item's key)${holders === 0 ? '; it has none yet' : '; it has more than one'}`)\n if (spec.at !== undefined) {\n const place = placeFor(spec.at.location)\n if (place === undefined) problems.push(`${where}.at: there is no place \"${spec.at.location}\"`)\n else if (spec.at.feature !== undefined && !place.features.some(feature => feature.key === spec.at!.feature)) problems.push(`${where}.at: ${place.name} has no feature \"${spec.at.feature}\"`)\n }\n for (const [field, key] of [['held_by', spec.heldBy], ['worn_by', spec.wornBy]] as const) {\n if (key !== undefined && characterFor(key) === undefined) problems.push(`${where}.${field}: there is no character \"${key}\"`)\n }\n if (spec.wornBy !== undefined && spec.wearable === undefined) problems.push(`${where}: it is worn but not wearable: give it a wearable slot`)\n if (spec.inside !== undefined && !known(spec.inside)) problems.push(`${where}.inside: there is no item \"${spec.inside}\"`)\n if (spec.inside === spec.key) problems.push(`${where}: an item cannot be inside itself`)\n // The same thing twice in the same hands or place is the same thing: change its quantity instead.\n const duplicate = (holder: Holder | undefined): boolean => holder !== undefined && target.items.contents(holder.kind === 'location' ? { kind: 'location', id: holder.locationId } : holder.kind === 'character' ? { kind: 'character', id: holder.characterId } : { kind: 'item', id: holder.itemId }).some(({ item }) => lookupKey(item.name) === lookupKey(spec.name ?? ''))\n const where2: Holder | undefined = spec.at !== undefined && placeFor(spec.at.location) !== undefined ? { kind: 'location', locationId: placeFor(spec.at.location)!.id } : spec.heldBy !== undefined && characterFor(spec.heldBy) !== undefined ? { kind: 'character', characterId: characterFor(spec.heldBy)!.id, mode: 'held' } : undefined\n if (duplicate(where2)) problems.push(`${where}: \"${spec.name}\" is already there: change its quantity instead of making another`)\n })\n if (problems.length > 0) throw new InvalidEditError(problems)\n\n for (const slot of slotsWanted) target.slots.upsert(slot)\n const made = new Map<string, number>()\n const itemId = (key: string): number => made.get(key) ?? (target.items.getBySourceId(key) ?? target.items.get(Number(key)))!.id\n const pending = [...wanted]\n while (pending.length > 0) {\n const index = pending.findIndex(spec => spec.inside === undefined || !newKeys.has(spec.inside) || made.has(spec.inside))\n if (index < 0) throw new InvalidEditError(['items: they are inside each other in a circle'])\n const [spec] = pending.splice(index, 1)\n const holder: Holder = spec!.at !== undefined\n ? { kind: 'location', locationId: placeFor(spec!.at.location)!.id, ...(spec!.at.position === undefined ? {} : { position: spec!.at.position }), ...(spec!.at.feature === undefined ? {} : { featureKey: spec!.at.feature }) }\n : spec!.heldBy !== undefined ? { kind: 'character', characterId: characterFor(spec!.heldBy)!.id, mode: 'held' }\n : spec!.wornBy !== undefined ? { kind: 'character', characterId: characterFor(spec!.wornBy)!.id, mode: 'worn', slot: spec!.wearable!, ...(spec!.wornPosition === undefined ? {} : { position: spec!.wornPosition }) }\n : { kind: 'item', itemId: itemId(spec!.inside!), ...(spec!.insidePosition === undefined ? {} : { position: spec!.insidePosition }) }\n const added = target.items.add({\n sourceId: spec!.key, name: spec!.name.trim(), description: spec!.description ?? '', quantity: spec!.quantity ?? 1, unique: spec!.unique ?? false, quality: spec!.quality ?? '',\n notable: spec!.notable ?? false, hidden: spec!.hidden ?? false, ...(spec!.wearable === undefined ? {} : { wearableSlot: spec!.wearable }),\n ...(spec!.container === undefined ? {} : { container: { state: spec!.container.state ?? 'closed' } }), ...(spec!.owner === undefined ? {} : { ownerId: characterFor(spec!.owner)!.id }),\n }, holder)\n made.set(spec!.key, added.id)\n target.consolidation.enqueue({ kind: 'item', subjectId: added.id, note: spec!.note ?? 'made up in play', turn: edit.turn })\n }\n for (const spec of wanted) {\n if (spec.container?.openedBy !== undefined && spec.container.openedBy.length > 0) target.items.setOpeners({ kind: 'item', id: made.get(spec.key)! }, spec.container.openedBy.map(itemId))\n }\n return { keys: wanted.map(spec => spec.key), writes: wanted.length + slotsWanted.length }\n}\n\n/**\n * Apply an edit. Every problem is found before anything is written, so a bad edit changes nothing.\n * Characters made up by the edit are created after its places and before everything else, so that the rest\n * of the edit (relationships, events, moves) can name them; the whole is still one transaction.\n * @throws {InvalidEditError} naming each problem.\n */\nexport function applyRecordsEdit(target: RecordsTarget, edit: RecordsEdit): EditResult {\n if (list(edit.triggers).length > 0) {\n return target.transaction(() => {\n const done = applyRecordsEdit(target, { ...edit, triggers: [] })\n return { ...done, triggerKeys: createTriggers(target, edit) }\n })\n }\n if (list(edit.characters).length === 0 && list(edit.items).length === 0 && list(edit.slots).length === 0) return applyChanges(target, edit)\n return target.transaction(() => {\n const placesFirst = applyChanges(target, { turn: edit.turn, places: list(edit.places) as NewPlace[] })\n const people = list(edit.characters).length === 0 ? { keys: [] as string[], writes: 0 } : createCharacters(target, edit)\n const things = list(edit.items).length === 0 && list(edit.slots).length === 0 ? { keys: [] as string[], writes: 0 } : createItems(target, edit)\n const rest = applyChanges(target, { ...edit, places: [], characters: [], items: [], slots: [] })\n return {\n eventIds: rest.eventIds, beliefIds: rest.beliefIds, writes: placesFirst.writes + people.writes + things.writes + rest.writes,\n characterKeys: people.keys, placeKeys: placesFirst.placeKeys ?? [], itemKeys: things.keys,\n }\n })\n}\n","import { type Trigger, type TriggerNote } from 'dsh-roleplay-model'\nimport { InvalidEditError } from '../errors.ts'\nimport { applyRecordsEdit } from './edit.ts'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { audienceIds, conditionHolds, seededRoll, type TriggerClock, type Wire } from './trigger-rules.ts'\nimport { parseInstant } from './time.ts'\nimport { parseRecordsEdit } from './wire.ts'\n\nconst isObject = (value: unknown): value is Wire => typeof value === 'object' && value !== null && !Array.isArray(value)\n\nexport interface FiredTrigger {\n trigger: Trigger\n /** What the game master is to weave in. */\n beats: string[]\n /** What characters are to notice. */\n cues: { characters: string[]; text: string }[]\n /** The texts of the events an edit effect wrote. */\n events: string[]\n}\n\nexport interface TriggerRun {\n fired: FiredTrigger[]\n /** The triggers whose effects could not be applied: they are not tried again. */\n failed: { trigger: Trigger; problem: string }[]\n}\n\nexport interface TriggerRunOptions extends TriggerClock {\n turn: number\n round: number\n /** The most that fire in one run; the rest wait for the next. */\n maxFires?: number\n}\n\nconst DEFAULT_MAX_FIRES = 3\n\n/** An edit effect, as it is applied at this turn and round: events default to now and to what those in their place saw. */\nfunction editOf(target: RecordsTarget, raw: Wire, options: TriggerRunOptions) {\n // A trigger looked at when a turn begins has no round yet; the events it makes belong to the first.\n const round = Math.max(1, options.round)\n const events = Array.isArray(raw['events']) ? raw['events'].filter(isObject).map((event) => {\n const where = typeof event['location'] === 'string' ? target.locations.list().find(entry => locationKey(entry) === event['location'])?.id : undefined\n if (event['perceived_by'] === 'everyone') return { turn: options.turn, round, importance: 3, tags: [], involves: [], ...event, perceived_by: target.characters.list().map(entry => ({ character: characterKey(entry), mode: 'told' })) }\n const present = where === undefined ? [] : target.characters.list().filter(entry => target.placements.get('character', entry.id)?.locationId === where).map(entry => ({ character: characterKey(entry), mode: 'witnessed' }))\n return { turn: options.turn, round, importance: 3, tags: [], involves: [], ...(present.length === 0 ? {} : { perceived_by: present }), ...event }\n }) : undefined\n return parseRecordsEdit({ ...raw, turn: options.turn, time_zone: options.zone, ...(events === undefined ? {} : { events }) })\n}\n\nfunction applyEffects(target: RecordsTarget, trigger: Trigger, options: TriggerRunOptions): FiredTrigger {\n const fired: FiredTrigger = { trigger, beats: [], cues: [], events: [] }\n for (const effect of trigger.effects) {\n if (effect.type === 'edit') {\n const edit = editOf(target, effect.edit, options)\n const result = applyRecordsEdit(target, edit)\n target.events.seal(result.eventIds)\n fired.events.push(...(edit.events ?? []).map(event => event.text))\n } else if (effect.type === 'beat') {\n target.triggers.addNote({ triggerId: trigger.id, kind: 'beat', text: effect.text, turn: options.turn })\n fired.beats.push(effect.text)\n } else {\n const heard = audienceIds(target, effect.audience)\n for (const id of heard) target.triggers.addNote({ triggerId: trigger.id, kind: 'cue', text: effect.text, characterIds: [id], turn: options.turn })\n fired.cues.push({ characters: target.characters.list().filter(entry => heard.includes(entry.id)).map(characterKey), text: effect.text })\n }\n }\n return fired\n}\n\n/**\n * Look at every trigger that can still fire and fire those whose condition has just become true (not those that stay true), by priority.\n * A trigger that fires once stays fired; one that repeats fires again after its condition went false and true, and its cooldown passed. The\n * effects of one trigger are applied together or not at all; one that cannot be applied is marked failed and not tried again.\n */\nexport function runTriggers(target: RecordsTarget, options: TriggerRunOptions): TriggerRun {\n const run: TriggerRun = { fired: [], failed: [] }\n const limit = options.maxFires ?? DEFAULT_MAX_FIRES\n for (const trigger of target.triggers.list()) {\n if (trigger.status === 'failed' || trigger.status === 'expired' || (trigger.status === 'fired' && !trigger.repeat)) continue\n if (trigger.expires !== undefined && options.now >= parseInstant(trigger.expires, options.zone)) { target.triggers.update(trigger.id, { status: 'expired' }); continue }\n const result = conditionHolds(target, trigger.condition, options)\n const rose = result && !trigger.lastResult\n if (!rose) {\n if (result !== trigger.lastResult) target.triggers.update(trigger.id, { lastResult: result })\n continue\n }\n if (run.fired.length >= limit) continue\n const cooling = trigger.cooldownSeconds !== undefined && trigger.lastFiredMs !== undefined && options.now - trigger.lastFiredMs < trigger.cooldownSeconds * 1000\n const lucky = trigger.chance === undefined || seededRoll(`${trigger.key}:${options.turn}:${options.round}:${trigger.fireCount}`) < trigger.chance\n if (cooling || !lucky) { target.triggers.update(trigger.id, { lastResult: true }); continue }\n try {\n const fired = target.transaction(() => {\n const effects = applyEffects(target, trigger, options)\n effects.trigger = target.triggers.update(trigger.id, { status: trigger.repeat ? 'dormant' : 'fired', fireCount: trigger.fireCount + 1, lastFiredMs: options.now, lastResult: true })\n return effects\n })\n run.fired.push(fired)\n } catch (error) {\n const problem = error instanceof InvalidEditError ? error.problems.join('; ') : error instanceof Error ? error.message : String(error)\n run.failed.push({ trigger: target.triggers.update(trigger.id, { status: 'failed', lastResult: true, problem }), problem })\n }\n }\n return run\n}\n\n/** Notes nobody took up in this many turns are let go: a beat the game master never wove in, a cue nobody acted on. */\nexport function lapseNotes(target: RecordsTarget, turn: number, kept: { beats: number; cues: number }): TriggerNote[] {\n const lapsed = target.triggers.notes({ status: 'pending' }).filter(note => turn - note.turn >= (note.kind === 'beat' ? kept.beats : kept.cues))\n for (const note of lapsed) target.triggers.resolveNote(note.id, 'lapsed')\n return lapsed\n}\n","import { SELF, type Trigger, type TriggerCondition, type TriggerNote } from 'dsh-roleplay-model'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\nimport { localTime } from './time.ts'\nimport { placeholdersOf, type Placeholder } from './template.ts'\nimport { conditionHolds, type TriggerClock } from './trigger-rules.ts'\nimport { describeValue, subjectOf } from './variables.ts'\n\ntype Reading = RecordsTarget\n\n/** The words cannot be written as the story stands: something they name is not there. */\nexport class UnwritableError extends Error {}\n\nconst pad = (value: number): string => String(value).padStart(2, '0')\n\nfunction resolve(target: Reading, placeholder: Placeholder, clock: TriggerClock, self: string | undefined): string {\n const key = (index: number): string => (placeholder.args[index] === SELF ? (self ?? SELF) : placeholder.args[index]!)\n const character = (wanted: string) => {\n const found = target.characters.list().find(entry => characterKey(entry) === wanted)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: there is no character \"${wanted}\"`)\n return found\n }\n const place = (wanted: string) => {\n const found = target.locations.list().find(entry => locationKey(entry) === wanted)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: there is no place \"${wanted}\"`)\n return found\n }\n const item = (wanted: string) => {\n const found = target.items.list().find(entry => itemKey(entry) === wanted)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: there is no item \"${wanted}\"`)\n return found\n }\n switch (placeholder.kind) {\n case 'character': return character(key(0)).name\n case 'place': return place(key(0)).name\n case 'item': return item(key(0)).name\n case 'where': {\n const who = character(key(0))\n const at = target.placements.get('character', who.id)\n const found = at === undefined ? undefined : target.locations.get(at.locationId)\n if (found === undefined) throw new UnwritableError(`${placeholder.raw}: ${who.name} is nowhere in particular`)\n return found.name\n }\n case 'holder': {\n const thing = item(key(0))\n const where = target.items.where(thing.id)\n const holder = where.characterId !== undefined ? target.characters.get(where.characterId)?.name : where.locationId !== undefined ? target.locations.get(where.locationId)?.name : undefined\n if (holder === undefined) throw new UnwritableError(`${placeholder.raw}: ${thing.name} is nowhere that is known`)\n return holder\n }\n case 'value': {\n const def = target.variables.def(placeholder.args[0]!)\n if (def === undefined) throw new UnwritableError(`${placeholder.raw}: there is no variable \"${placeholder.args[0]}\"`)\n const subject = def.subject === 'world' ? { id: 0 } : placeholder.args[1] === undefined ? undefined : subjectOf(target, def.subject, key(1))\n if (subject === undefined) throw new UnwritableError(`${placeholder.raw}: ${def.subject === 'world' ? 'a world variable has no subject' : `give the ${def.subject} it is about`}`)\n return describeValue(def, target.variables.value(def.key, def.subject, subject.id))\n }\n case 'time': {\n const local = localTime(clock.now, clock.zone)\n return `${pad(local.hour)}:${pad(local.minute)}`\n }\n }\n}\n\n/** Words as the story stands now. @throws {UnwritableError} when something they name is not there. */\nexport function renderWords(target: Reading, text: string, clock: TriggerClock, self?: string): string {\n const { found } = placeholdersOf(text)\n let at = 0\n let out = ''\n for (const placeholder of found) {\n const start = text.indexOf(placeholder.raw, at)\n out += text.slice(at, start) + resolve(target, placeholder, clock, self)\n at = start + placeholder.raw.length\n }\n return out + text.slice(at)\n}\n\n/** A condition with `@self` taken as a character. */\nexport function bindSelf(condition: TriggerCondition, self: string): TriggerCondition {\n const bound = (value: string): string => (value === SELF ? self : value)\n switch (condition.type) {\n case 'place': return { ...condition, character: bound(condition.character) }\n case 'variable': return condition.subject === undefined ? condition : { ...condition, subject: bound(condition.subject) }\n case 'item': return { ...condition, item: bound(condition.item), ...(condition.heldBy === undefined ? {} : { heldBy: bound(condition.heldBy) }) }\n case 'all': case 'any': return { ...condition, conditions: condition.conditions.map(part => bindSelf(part, self)) }\n case 'not': return { ...condition, condition: bindSelf(condition.condition, self) }\n default: return condition\n }\n}\n\n/** The effect of a trigger that a note was made from: the beat or cue whose words it carries. */\nexport function noteEffect(trigger: Trigger | undefined, note: Pick<TriggerNote, 'kind' | 'text'>): (Trigger['effects'][number] & { type: 'beat' | 'cue' }) | undefined {\n return trigger?.effects.find((effect): effect is Trigger['effects'][number] & { type: 'beat' | 'cue' } => effect.type === note.kind && effect.text === note.text)\n}\n\nexport interface Delivery {\n /** What is to be told now, in words as the story stands. */\n shown: { note: TriggerNote; text: string }[]\n /** What is not to be told, and why: the beat or cue no longer applies, or cannot be written. */\n withdrawn: { note: TriggerNote; reason: string }[]\n}\n\n/**\n * Decides, at the moment notes are about to be told, what is still to be told and in what words. A note whose effect says something must\n * still hold and does not hold any more is withdrawn; so is one whose words name something that is not there. Nothing is changed.\n */\nexport function deliverNotes(target: Reading, notes: readonly TriggerNote[], clock: TriggerClock): Delivery {\n const delivery: Delivery = { shown: [], withdrawn: [] }\n for (const note of notes) {\n const effect = noteEffect(target.triggers.get(note.triggerId), note)\n const self = note.kind === 'cue' && note.characterIds[0] !== undefined ? target.characters.list().find(entry => entry.id === note.characterIds[0]) : undefined\n const who = self === undefined ? undefined : characterKey(self)\n if (effect?.while !== undefined && !conditionHolds(target, who === undefined ? effect.while : bindSelf(effect.while, who), clock)) {\n delivery.withdrawn.push({ note, reason: 'what it was waiting on no longer holds' })\n continue\n }\n try {\n delivery.shown.push({ note, text: renderWords(target, note.text, clock, who) })\n } catch (error) {\n if (!(error instanceof UnwritableError)) throw error\n delivery.withdrawn.push({ note, reason: error.message })\n }\n }\n return delivery\n}\n","import type { Character, CharacterId, CharacterMemory, MemoryConfidence, PerceivedEvent } from 'dsh-roleplay-model'\nimport type { ClockRepository, EventRepository, MemoryRepository, RelationshipRepository } from '../repositories.ts'\n\nconst DAY = 86_400_000\n\n/** How a character remembers. */\nexport interface MemoryPolicy {\n /** Whether memories fade with age and unimportance. Off for exact recall. */\n flaky: boolean\n /** The most things a character is reminded of at once. */\n recall: number\n /**\n * How many times `recall` candidates are retrieved before the best are chosen: the wider net is what a\n * reranker judges, and it also gives importance and recency something to choose between. At least 1.\n */\n overRetrieve?: number\n /**\n * How many more things come to mind because they are strongly tied to what the moment recalled (the same people together with the same\n * place or tags) and matter enough. 0 or absent: none.\n */\n associate?: number\n /**\n * How much a memory that says what one already chosen says counts against it, from 0 (the best by score, repeats\n * included) to 1 (only what adds something new): maximal marginal relevance over the pool. 0 or absent: none.\n */\n diversity?: number\n /**\n * How long what a character took in lasts once a belief rests on it, as a share of how long it would last: below 1 it fades sooner, the\n * belief having taken over, and it is not told again when that belief is told. 1 or absent: no change.\n */\n foldedFade?: number\n}\n\nexport const DEFAULT_MEMORY_POLICY: MemoryPolicy = { flaky: true, recall: 12, overRetrieve: 4, associate: 2, diversity: 0.3, foldedFade: 0.5 }\n\n/** How much of a memory is left: what the character is told of it. */\nexport type Clarity = 'clear' | 'faded' | 'vague'\n\n/** One thing a character is reminded of, as it comes back to it. */\nexport interface Recalled {\n clarity: Clarity\n /** What the character remembers; less of it the fainter the memory. */\n text: string\n /** The turn it comes from. */\n turn: number\n /** When it happened in story time, when the story clock records it. */\n at?: number\n source: { kind: 'perception' | 'memory'; id: number }\n /** It did not match the moment itself: it came to mind with something that did ({@link MemoryPolicy.associate}). */\n linked?: true\n /** For what the character believes: how sure it is. */\n confidence?: MemoryConfidence\n /** For what the character believes: something it took in since speaks against it. */\n disputed?: true\n /** Why it came back, when the query asked to be told ({@link RecallQuery.explain}). */\n why?: RecallWhy\n}\n\n/** What made one thing come back, for finding out why a character was or was not reminded of something. */\nexport interface RecallWhy {\n /** What the cues of the moment gave, in the units of a cue: people named (a name counts 3, more for social weight), words and tags shared (at most 6), being where it happened. */\n cues: { people: number; words: number; place: number }\n /** What each search scored it, from 0 to 1; absent when that search did not run or did not find it. */\n lexical?: number\n dense?: number\n rerank?: number\n /** What it counted for in the end: the fused retrieval score, blended with the reranker's when there was one. */\n relevance: number\n importance: number\n /** How long ago it was in story days; 0 when the story has no clock. */\n ageDays: number\n /** How much of it is left in mind, from 1 to 0, when memories fade. */\n retention?: number\n /** What it was ranked by, together with how much it matters and how recent it is. */\n score: number\n /** For something that came to mind with another: what it shares with the closest of the things recalled for the moment. */\n linked?: { people: number; tags: number; place: boolean }\n}\n\nexport interface RecallQuery {\n characterId: CharacterId\n /** Everyone in the story, so that names in the situation can be told. */\n characters: readonly Character[]\n /** What is happening now, which is what reminds the character of things. */\n situation: string\n /** Where the character is. What happened in the same place comes back to it more readily. */\n locationId?: number\n turn: number\n policy: MemoryPolicy\n /** Say why each thing came back ({@link Recalled.why}). */\n explain?: boolean\n /** Only what involves or is about one of these people comes back: \"what do I know about her\", which a name in the words would not reliably find. */\n about?: readonly CharacterId[]\n}\n\n/** What recall reads: the events a character took in and what it believes. */\nexport interface RecallSource {\n events: Pick<EventRepository, 'perceivedBy'>\n memories: Pick<MemoryRepository, 'list'> & Partial<Pick<MemoryRepository, 'evidenceIndex'>>\n clock: Pick<ClockRepository, 'get' | 'log'>\n /** Optional for lightweight callers; a session supplies it so socially charged people are stronger cues. */\n relationships?: Pick<RelationshipRepository, 'from'>\n}\n\n/** Story days for the memory of an unimportant event to halve; each step of importance doubles it. */\nconst HALF_LIFE_DAYS = 6\n/** Beliefs and what a character knows last longer than the memory of single events. */\nconst BELIEF_DURABILITY = 4\n/** Each time something is recalled it lasts longer, up to this many times as long. */\nconst REHEARSAL_STEP = 0.25\nconst MAX_REHEARSAL = 2\n/** What is left of a memory, from 1 (as it happened) to 0 (gone), above which it is clear, faded and vague. */\nconst CLEAR_ABOVE = 0.6\nconst FADED_ABOVE = 0.3\nconst VAGUE_ABOVE = 0.12\n/** A cue in the situation brings back something that was fading. */\nconst CUE_BOOST = 0.25\n/** What is that important stays faded at worst. */\nconst UNFORGETTABLE = 5\n\n/** A number from 0 up to 1 that is always the same for the same input: no two memories fade at quite the same rate. */\nexport function jitter(seed: number): number {\n let h = (seed + 0x9e3779b9) >>> 0\n h = Math.imul(h ^ (h >>> 16), 0x85ebca6b) >>> 0\n h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35) >>> 0\n return ((h ^ (h >>> 16)) >>> 0) / 0x100000000\n}\n\n/** What is left of a memory, from 1 down to 0, given its age, how much it matters and how often it was recalled. */\nexport function retention(input: { ageDays: number; importance: number; recalls: number; seed: number; durability?: number; cue?: boolean }): number {\n const rehearsal = 1 + Math.min(MAX_REHEARSAL, input.recalls * REHEARSAL_STEP)\n const halfLife = HALF_LIFE_DAYS * 2 ** (input.importance - 1) * rehearsal * (input.durability ?? 1)\n const faded = 0.5 ** (Math.max(0, input.ageDays) / halfLife) * (0.85 + 0.3 * jitter(input.seed))\n return Math.min(1, faded + (input.cue === true ? CUE_BOOST : 0))\n}\n\n/** How clear a memory is at a retention, or nothing when it is gone. */\nexport function clarityAt(value: number, importance: number): Clarity | undefined {\n if (value >= CLEAR_ABOVE) return 'clear'\n if (value >= FADED_ABOVE || importance >= UNFORGETTABLE) return 'faded'\n if (value >= VAGUE_ABOVE) return 'vague'\n return undefined\n}\n\nconst CJK = /\\p{Script=Han}|\\p{Script=Hiragana}|\\p{Script=Katakana}|\\p{Script=Hangul}/u\n\n/** Words a text can be matched by: words as they are, and overlapping pairs of characters for scripts written without spaces. */\nexport function tokens(text: string): Set<string> {\n const found = new Set<string>()\n for (const word of text.normalize('NFKC').toLowerCase().split(/[^\\p{L}\\p{N}]+/u)) {\n if (word === '') continue\n if (!CJK.test(word)) {\n if (word.length >= 3) found.add(word)\n continue\n }\n const chars = [...word]\n if (chars.length === 1) found.add(word)\n for (let index = 0; index + 1 < chars.length; index++) found.add(chars[index]! + chars[index + 1]!)\n }\n return found\n}\n\n/** The characters a text mentions by name or alias. */\nexport function mentioned(text: string, characters: readonly Character[]): Set<number> {\n const words = tokens(text)\n const lowered = text.normalize('NFKC').toLowerCase()\n const ids = new Set<number>()\n for (const character of characters) {\n for (const name of [character.name, ...character.aliases]) {\n const needle = name.normalize('NFKC').toLowerCase()\n if (needle.length >= 2 && (lowered.includes(needle) || tokens(needle).size > 0 && [...tokens(needle)].every(token => words.has(token)))) ids.add(character.id)\n }\n }\n return ids\n}\n\n/** What ties a candidate to others: the people it involves (other than the one remembering), its tags and where it happened. */\ninterface Links {\n people: readonly number[]\n tags: readonly string[]\n place?: number\n}\n\ninterface Candidate {\n key: string\n links: Links\n recalled: Omit<Recalled, 'clarity' | 'text' | 'why'> & { clear: string; faded: string; vague: string }\n relevance: number\n cues: RecallWhy['cues']\n importance: number\n ageDays: number\n recalls: number\n seed: number\n durability: number\n /** For something the character took in that beliefs rest on: those beliefs. */\n covered?: number[]\n}\n\nconst first = (text: string): string => {\n const match = /^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())\n const sentence = (match?.[0] ?? text).trim()\n return sentence === '' ? text.trim() : sentence\n}\n\nexport function overlap(cues: ReadonlySet<string>, text: string, tags: readonly string[]): number {\n let score = 0\n for (const tag of tags) if (cues.has(tag.toLowerCase())) score += 2\n for (const token of tokens(text)) if (cues.has(token)) score += 1\n return Math.min(score, 6)\n}\n\nfunction describeEvent({ perception, event }: PerceivedEvent, names: ReadonlyMap<number, string>, at?: number): Candidate['recalled'] {\n const who = event.involves.map(id => names.get(id)).filter((name): name is string => name !== undefined)\n const about = who.length > 0 ? who.join(', ') : event.tags.join(', ')\n return {\n turn: event.turn, ...(at === undefined ? {} : { at }),\n source: { kind: 'perception', id: perception.id },\n clear: perception.content,\n faded: perception.gist,\n vague: about === '' ? 'something happened, but you cannot say what' : `something to do with ${about}`,\n }\n}\n\nfunction describeBelief(memory: CharacterMemory, at: number | undefined, disputed: boolean): Candidate['recalled'] {\n return { turn: memory.turn, ...(at === undefined ? {} : { at }), source: { kind: 'memory', id: memory.id }, confidence: memory.confidence, ...(disputed ? { disputed: true as const } : {}), clear: memory.text, faded: first(memory.text), vague: first(memory.text) }\n}\n\n/** One thing a character could be reminded of, with the text to match it against the moment. */\nexport interface RecallCandidate {\n /** Names the candidate in the `semantic` scores given to {@link recall}: `p:<id>` for something it took in, `m:<id>` for something it believes. */\n key: string\n /** What the character remembers of it in full: what an embedding or a reranker should read. */\n text: string\n turn: number\n importance: number\n}\n\n/**\n * Retrieval is several searches (the cues of the moment, the words of the index, the meaning of the\n * stored vectors) that each score the candidates their own way. Each is brought to a score from 0 to 1\n * and the scores are fused by a weighted average over the searches that ran, so that a candidate one search\n * found and another did not is worth less than one both found; a search that found nothing takes no part,\n * so what is missing never counts against anything.\n */\nconst FUSION_WEIGHTS = { cues: 1, lexical: 1, dense: 1.5 } as const\n/** Cues of the moment add up (a name counts 3 plus up to 2 for social salience, shared words up to 6, a place 2). */\nconst FULL_CUE = 8\n/** What the fused retrieval score counts for next to how much a memory matters and how recent it is (up to about 2.6 and 2). */\nconst RELEVANCE_SCALE = 10\n/** What a reranker's judgement counts for next to the fused retrieval score, when there is one. */\nconst RERANK_BLEND = 0.7\n/** Retrieval is cut to this many candidates however wide the net, so that a reranker is never asked about more. */\nconst MAX_POOL = 60\n/** What fused retrieval has to be for a match to count as a cue for what had faded. */\nconst CUE_RELEVANCE = 0.2\n/** Cosine similarities below this are noise for the models used, and from here to this plus the range they count from nothing to full. */\nconst DENSE_FLOOR = 0.3\nconst DENSE_RANGE = 0.5\n\n/** From a cosine similarity to how much a match counts, from 0 to 1. */\nexport const denseScore = (similarity: number): number => Math.min(1, Math.max(0, (similarity - DENSE_FLOOR) / DENSE_RANGE))\n\n/** What else says how well each candidate matches the moment, by candidate key, each from 0 to 1. */\nexport interface RecallEvidence {\n /** From the search of the session's index by words. */\n lexical?: ReadonlyMap<string, number>\n /** From the search of the session's stored vectors by meaning, already mapped by {@link denseScore}. */\n dense?: ReadonlyMap<string, number>\n /** From a reranker that judged the candidates of the pool (see {@link poolCandidates}). */\n rerank?: ReadonlyMap<string, number>\n}\n\n/** Being where something happened calls it to mind, about as much as sharing two words with it. */\nconst PLACE_CUE = 2\n\nfunction gather(source: RecallSource, { characterId, characters, situation, locationId, about, policy }: Pick<RecallQuery, 'characterId' | 'characters' | 'situation' | 'turn' | 'locationId' | 'about'> & { policy?: MemoryPolicy }): Candidate[] {\n const evidence = source.memories.evidenceIndex?.(characterId)\n const folding = Math.min(1, Math.max(0.05, policy?.foldedFade ?? 1))\n const names = new Map(characters.map(character => [character.id, character.name]))\n const peers = mentioned(situation, characters)\n peers.delete(characterId)\n const social = new Map((source.relationships?.from(characterId) ?? []).map(relation => [relation.toId, Math.min(2, relation.tension + Math.abs(relation.affinity) * 0.5 + Math.max(0, -relation.trust) * 0.5)]))\n const peopleCue = (ids: readonly number[]): number => ids.filter(id => peers.has(id)).reduce((score, id) => score + 3 + (social.get(id) ?? 0), 0)\n const cues = tokens(situation)\n const now = source.clock.get()?.now\n const changes = source.clock.log()\n const start = changes.find(change => change.kind === 'start')?.from\n const turns = new Map<number, number>()\n const rounds = new Map<string, number>()\n for (const change of changes) {\n if (!turns.has(change.turn)) turns.set(change.turn, change.from)\n if ((change.kind === 'elapsed' || change.kind === 'real') && !rounds.has(`${change.turn}:${change.round}`)) rounds.set(`${change.turn}:${change.round}`, change.from)\n }\n const atTurn = (eventTurn: number): number | undefined => turns.get(eventTurn) ?? start\n const ageDays = (at: number | undefined): number => now === undefined || at === undefined ? 0 : Math.max(0, now - at) / DAY\n const concerns = (ids: readonly number[]): boolean => about === undefined || about.length === 0 || ids.some(id => about.includes(id))\n return [\n ...source.events.perceivedBy(characterId).filter(seen => concerns(seen.event.involves)).map((seen): Candidate => {\n const at = rounds.get(`${seen.event.turn}:${seen.event.round}`) ?? atTurn(seen.event.turn)\n const cue = { people: peopleCue(seen.event.involves), words: overlap(cues, `${seen.perception.content} ${seen.event.text}`, seen.event.tags), place: locationId !== undefined && seen.event.locationId === locationId ? PLACE_CUE : 0 }\n return ({\n key: `p:${seen.perception.id}`,\n links: { people: seen.event.involves.filter(id => id !== characterId), tags: seen.event.tags.map(tag => tag.toLowerCase()), ...(seen.event.locationId === undefined ? {} : { place: seen.event.locationId }) },\n recalled: describeEvent(seen, names, at),\n cues: cue,\n relevance: cue.people + cue.words + cue.place,\n importance: seen.event.importance,\n ageDays: ageDays(at),\n recalls: seen.perception.recalls,\n seed: seen.perception.id,\n durability: evidence?.folded.has(seen.perception.id) === true ? folding : 1,\n ...(evidence?.folded.has(seen.perception.id) === true ? { covered: evidence.folded.get(seen.perception.id)! } : {}),\n })}),\n ...source.memories.list(characterId).filter(belief => concerns(belief.about)).map((belief): Candidate => {\n const at = atTurn(belief.turn)\n const cue = { people: peopleCue(belief.about), words: overlap(cues, belief.text, []), place: 0 }\n return ({\n key: `m:${belief.id}`,\n links: { people: belief.about.filter(id => id !== characterId), tags: [] },\n recalled: describeBelief(belief, at, evidence?.disputed.has(belief.id) === true),\n cues: cue,\n relevance: cue.people + cue.words,\n importance: belief.importance,\n ageDays: ageDays(at),\n recalls: belief.recalls,\n seed: 1_000_000 + belief.id,\n durability: BELIEF_DURABILITY,\n })}),\n ]\n}\n\n/** Everything the character could be reminded of, for a caller that ranks by meaning (an embedding, a reranker) before asking for the recall. */\nexport function recallCandidates(source: RecallSource, query: Pick<RecallQuery, 'characterId' | 'characters' | 'situation' | 'turn' | 'locationId' | 'about'> & { policy?: MemoryPolicy }): RecallCandidate[] {\n return gather(source, query).map(candidate => ({ key: candidate.key, text: candidate.recalled.clear, turn: candidate.recalled.turn, importance: candidate.importance }))\n}\n\n/** Fuse scores from 0 to 1 into one, per key: the weighted average over the searches that ran (those with any score above 0). */\nexport function fuseScores(searches: readonly { weight: number; scores: ReadonlyMap<string, number> | undefined }[]): Map<string, number> {\n const ran = searches.filter(search => [...(search.scores ?? [])].some(([, score]) => score > 0))\n const total = ran.reduce((sum, search) => sum + search.weight, 0)\n const fused = new Map<string, number>()\n for (const { weight, scores } of ran) {\n for (const [key, score] of scores ?? []) fused.set(key, (fused.get(key) ?? 0) + weight * Math.min(1, Math.max(0, score)) / total)\n }\n return fused\n}\n\ninterface PoolEntry {\n candidate: Candidate\n /** How well retrieval alone matches the moment, from 0 to 1. */\n fused: number\n /** What each search scored it, when it was found by it. */\n found: { lexical?: number; dense?: number }\n}\n\n/** What retrieval over-retrieved for one recall, waiting for a reranker's judgement and the final choice. */\nexport interface RecallPool {\n entries: readonly PoolEntry[]\n /** What retrieval left out, which an association may still bring to mind. */\n others: readonly Candidate[]\n query: Pick<RecallQuery, 'policy' | 'explain'>\n}\n\n/** How well a candidate stands once its relevance is known: what the moment calls to mind, how much it matters and how recent it is. */\nfunction judged(candidate: Candidate, relevance: number, policy: MemoryPolicy): { clarity: Clarity; score: number; text: string; retention?: number } | undefined {\n let clarity: Clarity | undefined = 'clear'\n let kept: number | undefined\n if (policy.flaky) {\n kept = retention({ ageDays: candidate.ageDays, importance: candidate.importance, recalls: candidate.recalls, seed: candidate.seed, durability: candidate.durability, cue: relevance >= CUE_RELEVANCE })\n clarity = clarityAt(kept, candidate.importance)\n }\n if (clarity === undefined) return undefined\n const score = RELEVANCE_SCALE * relevance + 0.6 * candidate.importance + 2 / (1 + Math.max(0, candidate.ageDays)) + (clarity === 'vague' ? -1 : 0)\n return { clarity, score, text: candidate.recalled[clarity === 'clear' ? 'clear' : clarity === 'faded' ? 'faded' : 'vague'], ...(kept === undefined ? {} : { retention: kept }) }\n}\n\n/**\n * The first stage of reminding a character of what the moment calls to mind: retrieve, by the cues\n * of the moment (who is named, shared words and tags, where it happened), by the words of the index\n * and by meaning, fuse the scores of each, and keep more than will be used (`policy.overRetrieve` times\n * `policy.recall`, the best by fused relevance together with how much each matters and how recent it\n * is, and not what has faded from memory altogether). A reranker may then judge that pool.\n */\nexport function recallPool(source: RecallSource, query: RecallQuery, evidence: Omit<RecallEvidence, 'rerank'> = {}): RecallPool {\n const { policy, explain } = query\n const candidates = gather(source, query)\n const fused = fuseScores([\n { weight: FUSION_WEIGHTS.cues, scores: new Map(candidates.map(candidate => [candidate.key, candidate.relevance / FULL_CUE])) },\n { weight: FUSION_WEIGHTS.lexical, scores: evidence.lexical },\n { weight: FUSION_WEIGHTS.dense, scores: evidence.dense },\n ])\n const width = Math.min(MAX_POOL, Math.max(policy.recall, Math.ceil(policy.recall * Math.max(1, policy.overRetrieve ?? 1))))\n const ranked = candidates\n .map(candidate => ({ candidate, fused: fused.get(candidate.key) ?? 0, found: { ...(evidence.lexical?.get(candidate.key) === undefined ? {} : { lexical: evidence.lexical.get(candidate.key)! }), ...(evidence.dense?.get(candidate.key) === undefined ? {} : { dense: evidence.dense.get(candidate.key)! }) } }))\n .flatMap((entry) => {\n const standing = judged(entry.candidate, entry.fused, policy)\n return standing === undefined ? [] : [{ entry, score: standing.score }]\n })\n .sort((a, b) => b.score - a.score || b.entry.candidate.recalled.turn - a.entry.candidate.recalled.turn)\n .map(({ entry }) => entry)\n const entries = ranked.slice(0, width)\n const kept = new Set(entries.map(entry => entry.candidate.key))\n return { entries, others: candidates.filter(candidate => !kept.has(candidate.key)), query: { policy, ...(explain === true ? { explain } : {}) } }\n}\n\n/** What a reranker is asked to judge: every candidate of the pool, with the text it would be recalled by. */\nexport function poolCandidates(pool: RecallPool): RecallCandidate[] {\n return pool.entries.map(({ candidate }) => ({ key: candidate.key, text: candidate.recalled.clear, turn: candidate.recalled.turn, importance: candidate.importance }))\n}\n\n/** Two things are tied by the same people, the same tags and the same place; this is how strongly (people count most, tags and place add a little). */\nfunction tie(a: Links, b: Links): { strength: number; people: number; tags: number; place: boolean } {\n const people = a.people.filter(id => b.people.includes(id)).length\n const tags = a.tags.filter(tag => b.tags.includes(tag)).length\n const place = a.place !== undefined && a.place === b.place\n return { strength: 2 * Math.min(people, 2) + Math.min(tags, 2) + (place ? 1 : 0), people, tags, place }\n}\n/** The least a tie has to be for one thing to bring the other to mind. */\nconst STRONG_TIE = 3\n/** What does not matter much is not brought back by association. */\nconst ASSOCIABLE_IMPORTANCE = 3\n\n/** How much two texts say the same, from 0 to 1: the share of their words (or pairs of characters) they have in common. */\nexport function resemblance(a: ReadonlySet<string>, b: ReadonlySet<string>): number {\n if (a.size === 0 || b.size === 0) return 0\n let shared = 0\n for (const word of a) if (b.has(word)) shared++\n return shared / (a.size + b.size - shared)\n}\n\n/**\n * Choose `count` of the ranked entries by maximal marginal relevance: each pick is the one with the best score\n * discounted by how much it resembles what is already chosen, so that three memories of the same moment do not\n * crowd out one of another. `diversity` 0 keeps the ranking as it is.\n */\nfunction diversified<T extends { candidate: Candidate; score: number }>(ranked: readonly T[], count: number, diversity: number): T[] {\n const weight = Math.min(1, Math.max(0, diversity))\n if (weight === 0 || ranked.length <= 1) return ranked.slice(0, count)\n const top = Math.max(...ranked.map(entry => entry.score), Number.EPSILON)\n const words = new Map(ranked.map(entry => [entry, tokens(entry.candidate.recalled.clear)]))\n const left = [...ranked]\n const chosen: T[] = []\n while (chosen.length < count && left.length > 0) {\n let best = 0\n let bestValue = -Infinity\n left.forEach((entry, index) => {\n const repeat = Math.max(0, ...chosen.map(picked => resemblance(words.get(entry)!, words.get(picked)!)))\n const value = (1 - weight) * Math.max(0, entry.score) / top - weight * repeat\n if (value > bestValue) { best = index; bestValue = value }\n })\n chosen.push(left.splice(best, 1)[0]!)\n }\n return chosen\n}\n\n/** How sure the character is of a belief, and whether something since speaks against it. */\nfunction beliefOf(candidate: Candidate): Pick<Recalled, 'confidence' | 'disputed'> {\n const { confidence, disputed } = candidate.recalled\n return { ...(confidence === undefined ? {} : { confidence }), ...(disputed === undefined ? {} : { disputed }) }\n}\n\n/**\n * Chooses as {@link diversified} does, but does not tell what the character took in when a belief resting on it is told as well: the belief says it,\n * and the place goes to the next best.\n */\nfunction chooseUncovered<T extends { candidate: Candidate; score: number }>(standing: readonly T[], count: number, diversity: number): T[] {\n let pool = standing\n for (;;) {\n const chosen = diversified(pool, count, diversity)\n const told = new Set(chosen.filter(entry => entry.candidate.recalled.source.kind === 'memory').map(entry => entry.candidate.recalled.source.id))\n const repeated = chosen.filter(entry => entry.candidate.covered?.some(id => told.has(id)) === true)\n if (repeated.length === 0) return chosen\n pool = pool.filter(entry => !repeated.includes(entry))\n }\n}\n\n/**\n * The last stage: choose the `policy.recall` best of the pool, spread by `policy.diversity`. With a reranker's judgement each\n * candidate's relevance is mostly that (a candidate it left out counts as 0), and the rest is what\n * retrieval found; without, it is what retrieval found.\n */\nexport function finishRecall(pool: RecallPool, rerank?: ReadonlyMap<string, number>): Recalled[] {\n const { policy } = pool.query\n const standing = pool.entries\n .flatMap(({ candidate, fused, found }) => {\n const relevance = rerank === undefined ? fused : RERANK_BLEND * Math.min(1, Math.max(0, rerank.get(candidate.key) ?? 0)) + (1 - RERANK_BLEND) * fused\n const judgement = judged(candidate, relevance, policy)\n if (judgement === undefined) return []\n const why: RecallWhy | undefined = pool.query.explain === true\n ? { cues: candidate.cues, ...found, ...(rerank === undefined ? {} : { rerank: rerank.get(candidate.key) ?? 0 }), relevance, importance: candidate.importance, ageDays: candidate.ageDays, ...(judgement.retention === undefined ? {} : { retention: judgement.retention }), score: judgement.score }\n : undefined\n return [{ candidate, relevance, ...judgement, why }]\n })\n .sort((a, b) => b.score - a.score || b.candidate.recalled.turn - a.candidate.recalled.turn)\n const chosen = chooseUncovered(standing, policy.recall, policy.diversity ?? 0)\n const result = chosen.map(({ candidate, clarity, text, why }): Recalled => ({ clarity, text, turn: candidate.recalled.turn, ...(candidate.recalled.at === undefined ? {} : { at: candidate.recalled.at }), source: candidate.recalled.source, ...beliefOf(candidate), ...(why === undefined ? {} : { why }) }))\n const anchors = chosen.filter(entry => entry.relevance >= CUE_RELEVANCE)\n const wanted = anchors.length === 0 ? 0 : Math.max(0, policy.associate ?? 0)\n if (wanted > 0) {\n const taken = new Set(chosen.map(entry => entry.candidate.key))\n const rest = [...standing.filter(entry => !chosen.includes(entry)).map(entry => entry.candidate), ...pool.others].filter(candidate => !taken.has(candidate.key) && candidate.importance >= ASSOCIABLE_IMPORTANCE)\n const tied = rest.flatMap((candidate) => {\n const best = anchors.map(anchor => tie(anchor.candidate.links, candidate.links)).sort((a, b) => b.strength - a.strength)[0]\n const judgement = best === undefined || best.strength < STRONG_TIE ? undefined : judged(candidate, 0, policy)\n return best === undefined || judgement === undefined || judgement.clarity === 'vague' ? [] : [{ candidate, best, judgement }]\n })\n .sort((a, b) => b.best.strength - a.best.strength || b.candidate.importance - a.candidate.importance || b.candidate.recalled.turn - a.candidate.recalled.turn)\n .slice(0, wanted)\n for (const { candidate, best, judgement } of tied) {\n result.push({\n clarity: judgement.clarity, text: judgement.text, turn: candidate.recalled.turn, ...(candidate.recalled.at === undefined ? {} : { at: candidate.recalled.at }), source: candidate.recalled.source, ...beliefOf(candidate), linked: true,\n ...(pool.query.explain === true ? { why: { cues: candidate.cues, relevance: 0, importance: candidate.importance, ageDays: candidate.ageDays, ...(judgement.retention === undefined ? {} : { retention: judgement.retention }), score: judgement.score, linked: { people: best.people, tags: best.tags, place: best.place } } } : {}),\n })\n }\n }\n return result.sort((a, b) => a.turn - b.turn)\n}\n\n/** Remind a character of what the moment calls to mind, in one call: {@link recallPool}, then {@link finishRecall} with the `rerank` evidence if there is any. */\nexport function recall(source: RecallSource, query: RecallQuery, evidence: RecallEvidence = {}): Recalled[] {\n return finishRecall(recallPool(source, query, evidence), evidence.rerank)\n}\n","import type { CharacterId } from 'dsh-roleplay-model'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\nimport { localIso } from './time.ts'\nimport { describeValue } from './variables.ts'\n\n/** Which part of the story's records to read; all of it when left out. */\nexport interface RecordsScope {\n rounds?: readonly { turn: number; round: number }[]\n /** The time zone times are shown in; UTC when not given. */\n timeZone?: string\n /** Only these parts of the records; the others come back empty. Everything when left out. */\n only?: readonly (keyof RecordsView)[]\n /** Of the relationships, only those that changed in this turn or later. */\n relationshipsSince?: number\n}\n\n/** The records as models read them (snake_case, characters by key), the counterpart of the edit's wire format. */\nexport interface RecordsView {\n factions: { faction: string; name: string; public_state: string; inner_state: string; values: string[]; structure: string; goals: { id: number; name: string; status: string; horizon: string; priority: number; urgency: number; plan: string[] }[]; members: { character: string; role: string; rank: string; status: string; public: boolean; commitment: number }[] }[]\n faction_relationships: { from_kind: string; from: string; to_kind: string; to: string; label: string; summary: string; familiarity: number; trust: number; affinity: number; tension: number; updated_turn: number }[]\n characters: {\n character: string\n name: string\n controlled_by: 'the player' | 'an agent'\n public_state: string\n inner_state: string\n activity: string\n /** The key of the place it is in, and where in it; null while it is nowhere. */\n location: string | null\n position: string\n /** What it is after that is still live (active or paused), with the ids an edit refers to. */\n goals: { id: number; type: string; name: string; status: string; horizon: string; priority: number; urgency: number; deadline: string | null; plan: string[] }[]\n }[]\n events: {\n id: number\n turn: number\n round: number\n text: string\n importance: number\n tags: string[]\n involves: string[]\n /** The key of the place it happened in. */\n location: string | null\n sealed: boolean\n perceived_by: { id: number; character: string; mode: string; accuracy: string; content: string; gist: string }[]\n }[]\n beliefs: { id: number; character: string; kind: string; text: string; about: string[]; importance: number; confidence: string; evidence_for: number[]; evidence_against: number[]; turn: number }[]\n open_threads: { id: number; text: string; opened_turn: number }[]\n /** How characters stand towards each other, most recently changed first (at most 80). */\n /** Things, notable first (at most 100), each with where it is. */\n items: { key: string; name: string; quantity: number; quality: string; state: string | null; hidden: boolean; notable: boolean; owner: string | null; holder: string }[]\n /** What is tracked: how each kind of variable is declared. */\n variable_defs: { key: string; name: string; description: string; kind: string; subject: string; only: string[]; min: number | null; max: number | null; options: string[]; default: string | number | boolean; visibility: string; baseline: boolean }[]\n /** What each subject holds that is not the default (at most 200, most recently changed first). */\n variables: { variable: string; subject: string; about: string; value: string | number | boolean; described: string; baseline: string | number | boolean | null; visibility: string }[]\n /** What characters have committed to that is still pending, in the order they are due (at most 40); times in the story's time zone. */\n engagements: { id: number; title: string; at: string; until: string | null; location: string | null; participants: string[]; note: string }[]\n relationships: { from: string; to: string; label: string; summary: string; familiarity: number; trust: number; affinity: number; tension: number; updated_turn: number }[]\n knowledge: { character: string; kind: string; subject: string; learned_turn: number; last_observed_turn: number | null }[]\n}\n\nconst MAX_RELATIONSHIPS_SHOWN = 80\nconst MAX_KNOWLEDGE_SHOWN = 200\nconst MAX_ITEMS_SHOWN = 100\nconst MAX_ENGAGEMENTS_SHOWN = 40\nconst MAX_VARIABLES_SHOWN = 200\n\n/** Where an item is, in words. */\nexport function describeHolder(target: Pick<RecordsTarget, 'items' | 'locations' | 'characters'>, id: number, keyOfCharacter: (id: number) => string = String): string {\n const holding = target.items.holding(id)\n if (holding === undefined) return 'nowhere'\n const { holder } = holding\n if (holder.kind === 'location') return `at ${target.locations.get(holder.locationId)?.name ?? holder.locationId}${holder.position === undefined ? '' : ` (${holder.position})`}`\n if (holder.kind === 'item') return `inside ${target.items.get(holder.itemId)?.name ?? holder.itemId}`\n const who = keyOfCharacter(holder.characterId)\n return holder.mode === 'worn' ? `worn by ${who} on the ${holder.slot}` : `carried by ${who}`\n}\n\n/** Read the records back from the database, as the edit wrote them. */\nexport function readRecords(target: Omit<RecordsTarget, 'transaction'>, scope: RecordsScope = {}): RecordsView {\n const characters = target.characters.list()\n const factions = target.factions.list()\n const keyOf = (id: CharacterId): string => {\n const found = characters.find(character => character.id === id)\n return found === undefined ? String(id) : characterKey(found)\n }\n const factionKey = (id: number): string => { const faction = factions.find(entry => entry.id === id); return faction?.sourceId ?? String(id) }\n const socialKey = (kind: 'character' | 'faction', id: number): string => kind === 'character' ? keyOf(id) : factionKey(id)\n const places = new Map(target.locations.list().map(place => [place.id, locationKey(place)]))\n const placeKey = (id: number): string => places.get(id) ?? String(id)\n const where = (id: CharacterId): { location: string | null; position: string } => {\n const placement = target.placements.get('character', id)\n return placement === undefined ? { location: null, position: '' } : { location: placeKey(placement.locationId), position: placement.position }\n }\n const zone = scope.timeZone ?? 'UTC'\n const inScope = (turn: number, round?: number): boolean =>\n scope.rounds === undefined || scope.rounds.some(entry => entry.turn === turn && (round === undefined || entry.round === round))\n const view: RecordsView = {\n factions: factions.map((faction) => {\n const state = target.factionStates.get(faction.id)\n return { faction: factionKey(faction.id), name: faction.name, public_state: state?.publicState ?? '', inner_state: state?.innerState ?? '', values: faction.values, structure: faction.structure, goals: target.factionIntents.list(faction.id).filter(goal => goal.status === 'active' || goal.status === 'paused').map(goal => ({ id: goal.id, name: goal.name, status: goal.status, horizon: goal.horizon, priority: goal.priority, urgency: goal.urgency, plan: goal.plan })), members: target.factionMemberships.ofFaction(faction.id).map(member => ({ character: keyOf(member.characterId), role: member.role, rank: member.rank, status: member.status, public: member.public, commitment: member.commitment })) }\n }),\n faction_relationships: target.factionRelationships.list().filter(relation => scope.relationshipsSince === undefined || relation.updatedTurn >= scope.relationshipsSince).map(relation => ({ from_kind: relation.fromKind, from: socialKey(relation.fromKind, relation.fromId), to_kind: relation.toKind, to: socialKey(relation.toKind, relation.toId), label: relation.label, summary: relation.summary, familiarity: relation.familiarity, trust: relation.trust, affinity: relation.affinity, tension: relation.tension, updated_turn: relation.updatedTurn })),\n characters: characters.map((character) => {\n const state = target.characterStates.get(character.id)\n return {\n character: characterKey(character),\n name: character.name,\n controlled_by: character.control === 'player' ? 'the player' : 'an agent',\n public_state: state?.publicState ?? '',\n inner_state: state?.innerState ?? '',\n activity: state?.activity ?? '',\n ...where(character.id),\n goals: target.intents.list(character.id).filter(goal => goal.status === 'active' || goal.status === 'paused').map(goal => ({ id: goal.id, type: goal.type, name: goal.name, status: goal.status, horizon: goal.horizon, priority: goal.priority, urgency: goal.urgency, deadline: goal.deadline ?? null, plan: goal.plan })),\n }\n }),\n events: target.events.list().filter(event => inScope(event.turn, event.round)).map(event => ({\n id: event.id, turn: event.turn, round: event.round, text: event.text, importance: event.importance, tags: event.tags,\n involves: event.involves.map(keyOf), location: event.locationId === undefined ? null : placeKey(event.locationId), sealed: event.sealed,\n perceived_by: target.events.perceptionsOf(event.id).map(entry => ({ id: entry.id, character: keyOf(entry.characterId), mode: entry.mode, accuracy: entry.accuracy, content: entry.content, gist: entry.gist })),\n })),\n beliefs: characters.flatMap(character => target.memories.list(character.id)\n .filter(belief => inScope(belief.turn))\n .map(belief => { const evidence = target.memories.evidenceOf(belief.id); return { id: belief.id, character: characterKey(character), kind: belief.kind, text: belief.text, about: belief.about.map(keyOf), importance: belief.importance, confidence: belief.confidence, evidence_for: evidence.filter(entry => entry.relation === 'supports').map(entry => entry.perceptionId), evidence_against: evidence.filter(entry => entry.relation === 'contradicts').map(entry => entry.perceptionId), turn: belief.turn } })),\n open_threads: target.threads.list('open').map(thread => ({ id: thread.id, text: thread.text, opened_turn: thread.openedTurn })),\n items: [...target.items.list()].sort((a, b) => Number(b.notable) - Number(a.notable) || a.id - b.id).slice(0, MAX_ITEMS_SHOWN).map(item => ({\n key: itemKey(item), name: item.name, quantity: item.quantity, quality: item.quality, state: item.container?.state ?? null, hidden: item.hidden, notable: item.notable,\n owner: item.ownerId === undefined ? null : keyOf(item.ownerId), holder: describeHolder(target, item.id, keyOf),\n })),\n variable_defs: target.variables.defs().map(def => ({\n key: def.key, name: def.name, description: def.description, kind: def.kind, subject: def.subject, only: def.only, min: def.min ?? null, max: def.max ?? null, options: def.options, default: def.default, visibility: def.visibility, baseline: def.baseline,\n })),\n variables: target.variables.all().flatMap((entry) => {\n const def = target.variables.def(entry.variable)\n if (def === undefined || entry.value === def.default) return []\n const key = entry.subject === 'world' ? 'world' : entry.subject === 'character' ? keyOf(entry.subjectId) : entry.subject === 'item' ? (target.items.get(entry.subjectId) === undefined ? String(entry.subjectId) : itemKey(target.items.get(entry.subjectId)!)) : placeKey(entry.subjectId)\n const about = entry.subject === 'world' ? 'the world' : entry.subject === 'character' ? characters.find(character => character.id === entry.subjectId)?.name ?? key : entry.subject === 'item' ? target.items.get(entry.subjectId)?.name ?? key : target.locations.get(entry.subjectId)?.name ?? key\n return [{ variable: def.key, subject: key, about, value: entry.value, described: describeValue(def, entry.value), baseline: entry.baseline ?? null, visibility: def.visibility }]\n }).slice(0, MAX_VARIABLES_SHOWN),\n engagements: target.engagements.list({ status: 'pending' }).slice(0, MAX_ENGAGEMENTS_SHOWN).map(engagement => ({\n id: engagement.id, title: engagement.title, at: localIso(engagement.at, zone), until: engagement.until === undefined ? null : localIso(engagement.until, zone),\n location: engagement.locationId === undefined ? null : placeKey(engagement.locationId), participants: engagement.participants.map(keyOf), note: engagement.note,\n })),\n relationships: [...target.relationships.list()].filter(relation => scope.relationshipsSince === undefined || relation.updatedTurn >= scope.relationshipsSince).sort((a, b) => b.updatedTurn - a.updatedTurn || b.id - a.id).slice(0, MAX_RELATIONSHIPS_SHOWN).map(relation => ({\n from: keyOf(relation.fromId), to: keyOf(relation.toId), label: relation.label, summary: relation.summary,\n familiarity: relation.familiarity, trust: relation.trust, affinity: relation.affinity, tension: relation.tension, updated_turn: relation.updatedTurn,\n })),\n knowledge: characters.flatMap(character => target.knowledge.list(character.id).flatMap(entry => {\n let subject: string | undefined\n if (entry.subjectKind === 'location') {\n const place = target.locations.get(entry.subjectId)\n subject = place === undefined ? undefined : locationKey(place)\n } else if (entry.subjectKind === 'item') {\n const item = target.items.get(entry.subjectId)\n subject = item === undefined ? undefined : itemKey(item)\n } else {\n const exit = target.locations.allExits().find(candidate => candidate.id === entry.subjectId)\n subject = exit === undefined ? undefined : `${placeKey(exit.fromId)} -> ${placeKey(exit.toId)}`\n }\n return subject === undefined ? [] : [{ character: characterKey(character), kind: entry.subjectKind, subject, learned_turn: entry.learnedTurn, last_observed_turn: entry.lastObservedTurn ?? null }]\n })).slice(0, MAX_KNOWLEDGE_SHOWN),\n }\n return scope.only === undefined ? view : Object.fromEntries(Object.entries(view).map(([key, part]) => [key, scope.only!.includes(key as keyof RecordsView) ? part : []])) as unknown as RecordsView\n}\n","import type { CharacterId, EventId, LocationId, NewPerception, NewStoryEvent, PerceivedEvent, Perception, PerceptionId, PerceptionPatch, StoryEvent, StoryEventFilter, StoryEventPatch } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, NotFoundError } from '../errors.ts'\nimport type { EventRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface EventRow {\n id: number\n turn: number\n round: number\n text: string\n importance: number\n tags: string\n sealed: number\n location_id: number | null\n created_at: string\n}\n\ninterface PerceptionRow {\n id: number\n event_id: number\n character_id: number\n mode: Perception['mode']\n content: string\n gist: string\n accuracy: Perception['accuracy']\n recalls: number\n last_recalled_turn: number | null\n created_at: string\n}\n\nconst toPerception = (row: PerceptionRow): Perception => ({\n id: row.id,\n eventId: row.event_id,\n characterId: row.character_id,\n mode: row.mode,\n content: row.content,\n gist: row.gist,\n accuracy: row.accuracy,\n recalls: row.recalls,\n ...(row.last_recalled_turn === null ? {} : { lastRecalledTurn: row.last_recalled_turn }),\n createdAt: row.created_at,\n})\n\n/** What the repository tells the index about its texts. */\nexport interface IndexWrites {\n put(item: { kind: 'perception' | 'memory' | 'event'; refId: number; characterId: number; text: string; extra?: string }): void\n remove(kind: 'perception' | 'memory' | 'event', refId: number): void\n}\n\nexport class SqliteEventRepository implements EventRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly clock: Clock,\n private readonly index: IndexWrites,\n /** The name of a place, so that what happened there can be found by it. */\n private readonly placeName: (id: LocationId) => string | undefined = () => undefined,\n /** The name of an item, so that what happened to it can be found by it. */\n private readonly itemName: (id: number) => string | undefined = () => undefined,\n ) {}\n\n add(event: NewStoryEvent, perceptions: readonly NewPerception[]): { event: StoryEvent; perceptions: Perception[] } {\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO events (turn, round, text, importance, tags, location_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n [event.turn, event.round, event.text, event.importance, toJson(event.tags), event.locationId ?? null, this.clock().toISOString()],\n )\n const id = Number(lastInsertRowid)\n this.setInvolves(id, event.involves)\n this.setItems(id, event.items ?? [])\n const stored = this.replacePerceptions(id, perceptions)\n const kept = this.require(id)\n this.indexEvent(kept, stored)\n return { event: kept, perceptions: stored }\n }))\n }\n\n get(id: EventId): StoryEvent | undefined {\n const row = this.db.get<EventRow>('SELECT * FROM events WHERE id = ?', [id])\n return row === undefined ? undefined : this.toEvent(row)\n }\n\n list(filter: StoryEventFilter = {}): StoryEvent[] {\n const where: string[] = []\n const params: SqlValue[] = []\n const add = (clause: string, value: SqlValue): void => { where.push(clause); params.push(value) }\n if (filter.turn !== undefined) add('turn = ?', filter.turn)\n if (filter.round !== undefined) add('round = ?', filter.round)\n if (filter.fromTurn !== undefined) add('turn >= ?', filter.fromTurn)\n if (filter.toTurn !== undefined) add('turn <= ?', filter.toTurn)\n if (filter.minImportance !== undefined) add('importance >= ?', filter.minImportance)\n if (filter.locationId !== undefined) add('location_id = ?', filter.locationId)\n if (filter.aboutItem !== undefined) add('id IN (SELECT event_id FROM event_items WHERE item_id = ?)', filter.aboutItem)\n if (filter.involving !== undefined) add('id IN (SELECT event_id FROM event_involves WHERE character_id = ?)', filter.involving)\n const clause = where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`\n return this.db.all<EventRow>(`SELECT * FROM events ${clause} ORDER BY turn, round, id`, params).map(row => this.toEvent(row))\n }\n\n update(id: EventId, patch: StoryEventPatch): StoryEvent {\n return guard(() => this.db.transaction(() => {\n const current = this.draft(id)\n this.db.run('UPDATE events SET text = ?, importance = ?, tags = ?, location_id = ? WHERE id = ?', [\n patch.text ?? current.text, patch.importance ?? current.importance, toJson(patch.tags ?? current.tags), patch.locationId ?? current.locationId ?? null, id,\n ])\n if (patch.involves !== undefined) this.setInvolves(id, patch.involves)\n if (patch.items !== undefined) this.setItems(id, patch.items)\n const kept = this.require(id)\n this.indexEvent(kept, this.perceptionsOf(id))\n return kept\n }))\n }\n\n setPerceptions(id: EventId, perceptions: readonly NewPerception[]): Perception[] {\n return guard(() => this.db.transaction(() => {\n const event = this.draft(id)\n const stored = this.replacePerceptions(id, perceptions)\n this.indexEvent(event, stored)\n return stored\n }))\n }\n\n seal(ids?: readonly EventId[]): number {\n if (ids === undefined) return this.db.run('UPDATE events SET sealed = 1 WHERE sealed = 0').changes\n return this.db.transaction(() => ids.reduce((count, id) => count + this.db.run('UPDATE events SET sealed = 1 WHERE id = ? AND sealed = 0', [id]).changes, 0))\n }\n\n getPerception(id: PerceptionId): Perception | undefined {\n const row = this.db.get<PerceptionRow>('SELECT * FROM perceptions WHERE id = ?', [id])\n return row === undefined ? undefined : toPerception(row)\n }\n\n addPerception(id: EventId, perception: NewPerception): Perception {\n return guard(() => this.db.transaction(() => {\n const event = this.require(id)\n if (this.db.get('SELECT 1 FROM perceptions WHERE event_id = ? AND character_id = ?', [id, perception.characterId]) !== undefined) {\n throw new ConflictError(`character ${perception.characterId} already has a perception of event ${id}: revise that one`)\n }\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO perceptions (event_id, character_id, mode, content, gist, accuracy, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n [id, perception.characterId, perception.mode, perception.content, perception.gist, perception.accuracy, this.clock().toISOString()],\n )\n const added = this.requirePerception(Number(lastInsertRowid))\n this.indexPerception(event, added)\n return added\n }))\n }\n\n updatePerception(id: PerceptionId, patch: PerceptionPatch): Perception {\n return guard(() => this.db.transaction(() => {\n const current = this.requirePerception(id)\n this.db.run('UPDATE perceptions SET mode = ?, content = ?, gist = ?, accuracy = ? WHERE id = ?', [\n patch.mode ?? current.mode, patch.content ?? current.content, patch.gist ?? current.gist, patch.accuracy ?? current.accuracy, id,\n ])\n const revised = this.requirePerception(id)\n this.indexPerception(this.require(revised.eventId), revised)\n return revised\n }))\n }\n\n perceptionsOf(id: EventId): Perception[] {\n return this.db.all<PerceptionRow>('SELECT * FROM perceptions WHERE event_id = ? ORDER BY id', [id]).map(toPerception)\n }\n\n perceivedBy(characterId: CharacterId, filter: { fromTurn?: number; toTurn?: number } = {}): PerceivedEvent[] {\n const params: SqlValue[] = [characterId]\n let extra = ''\n if (filter.fromTurn !== undefined) { extra += ' AND e.turn >= ?'; params.push(filter.fromTurn) }\n if (filter.toTurn !== undefined) { extra += ' AND e.turn <= ?'; params.push(filter.toTurn) }\n const rows = this.db.all<PerceptionRow & { e_id: number }>(\n `SELECT p.*, e.id AS e_id FROM perceptions p JOIN events e ON e.id = p.event_id\n WHERE p.character_id = ?${extra} ORDER BY e.turn, e.round, e.id`,\n params,\n )\n return rows.flatMap((row) => {\n const event = this.get(row.e_id)\n return event === undefined ? [] : [{ perception: toPerception(row), event }]\n })\n }\n\n touchPerceptions(ids: readonly number[], turn: number): void {\n this.db.transaction(() => {\n for (const id of ids) this.db.run('UPDATE perceptions SET recalls = recalls + 1, last_recalled_turn = ? WHERE id = ?', [turn, id])\n })\n }\n\n remove(id: EventId): boolean {\n return this.db.transaction(() => {\n if (this.get(id)?.sealed === true) throw new ConflictError(`event ${id} is sealed: events cannot be removed once their records are complete`)\n for (const perception of this.perceptionsOf(id)) this.index.remove('perception', perception.id)\n this.index.remove('event', id)\n return this.db.run('DELETE FROM events WHERE id = ?', [id]).changes > 0\n })\n }\n\n /** Index again what happened in a place, after the place was renamed. */\n reindexPlace(id: LocationId): void {\n for (const event of this.list({ locationId: id })) this.indexEvent(event, this.perceptionsOf(event.id))\n }\n\n /** What an event is found by besides its text: its tags and where it happened. */\n private extraOf(event: StoryEvent): string {\n const place = event.locationId === undefined ? undefined : this.placeName(event.locationId)\n const things = event.items.flatMap(id => this.itemName(id) ?? [])\n return [...event.tags, ...(place === undefined ? [] : [place]), ...things].join(' ')\n }\n\n /** Keep the index of an event and of what each character took in of it up to date. */\n private indexEvent(event: StoryEvent, perceptions: readonly Perception[]): void {\n this.index.put({ kind: 'event', refId: event.id, characterId: 0, text: event.text, extra: this.extraOf(event) })\n for (const perception of perceptions) this.indexPerception(event, perception)\n }\n\n private indexPerception(event: StoryEvent, perception: Perception): void {\n this.index.put({ kind: 'perception', refId: perception.id, characterId: perception.characterId, text: perception.content, extra: this.extraOf(event) })\n }\n\n private toEvent(row: EventRow): StoryEvent {\n const involves = this.db.all<{ character_id: number }>('SELECT character_id FROM event_involves WHERE event_id = ? ORDER BY character_id', [row.id]).map(entry => entry.character_id)\n const items = this.db.all<{ item_id: number }>('SELECT item_id FROM event_items WHERE event_id = ? ORDER BY item_id', [row.id]).map(entry => entry.item_id)\n return {\n items,\n id: row.id, turn: row.turn, round: row.round, text: row.text, importance: row.importance,\n tags: parseStringList(row.tags, 'events.tags'), involves, ...(row.location_id === null ? {} : { locationId: row.location_id }), sealed: row.sealed === 1, createdAt: row.created_at,\n }\n }\n\n private require(id: EventId): StoryEvent {\n const event = this.get(id)\n if (event === undefined) throw new NotFoundError(`event ${id} does not exist`)\n return event\n }\n\n private draft(id: EventId): StoryEvent {\n const event = this.require(id)\n if (event.sealed) throw new ConflictError(`event ${id} is sealed: events cannot change once their records are complete`)\n return event\n }\n\n private requirePerception(id: PerceptionId): Perception {\n const found = this.getPerception(id)\n if (found === undefined) throw new NotFoundError(`perception ${id} does not exist`)\n return found\n }\n\n private setItems(id: EventId, items: readonly number[]): void {\n this.db.run('DELETE FROM event_items WHERE event_id = ?', [id])\n for (const itemId of new Set(items)) this.db.run('INSERT INTO event_items (event_id, item_id) VALUES (?, ?)', [id, itemId])\n }\n\n private setInvolves(id: EventId, characters: readonly CharacterId[]): void {\n this.db.run('DELETE FROM event_involves WHERE event_id = ?', [id])\n for (const characterId of new Set(characters)) this.db.run('INSERT INTO event_involves (event_id, character_id) VALUES (?, ?)', [id, characterId])\n }\n\n private replacePerceptions(id: EventId, perceptions: readonly NewPerception[]): Perception[] {\n const now = this.clock().toISOString()\n for (const old of this.perceptionsOf(id)) this.index.remove('perception', old.id)\n this.db.run('DELETE FROM perceptions WHERE event_id = ?', [id])\n for (const perception of perceptions) {\n this.db.run(\n 'INSERT INTO perceptions (event_id, character_id, mode, content, gist, accuracy, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n [id, perception.characterId, perception.mode, perception.content, perception.gist, perception.accuracy, now],\n )\n }\n return this.perceptionsOf(id)\n }\n}\n","import { DEFAULT_CONFIDENCE, type CharacterMemory, type CharacterMemoryPatch, type EvidenceRelation, type MemoryEvidence, type MemoryId, type NewCharacterMemory, type PerceptionId } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { MemoryRepository } from '../repositories.ts'\nimport type { IndexWrites } from './event-repository.ts'\nimport { guard, parseNumberList, toJson } from './support.ts'\n\ninterface MemoryRow {\n id: number\n character_id: number\n kind: CharacterMemory['kind']\n text: string\n about: string\n importance: number\n confidence: CharacterMemory['confidence']\n turn: number\n recalls: number\n last_recalled_turn: number | null\n created_at: string\n}\n\nconst toMemory = (row: MemoryRow): CharacterMemory => ({\n id: row.id,\n characterId: row.character_id,\n kind: row.kind,\n text: row.text,\n about: parseNumberList(row.about, 'memories.about'),\n importance: row.importance,\n confidence: row.confidence,\n turn: row.turn,\n recalls: row.recalls,\n ...(row.last_recalled_turn === null ? {} : { lastRecalledTurn: row.last_recalled_turn }),\n createdAt: row.created_at,\n})\n\nexport class SqliteMemoryRepository implements MemoryRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock, private readonly index: IndexWrites) {}\n\n add(memory: NewCharacterMemory): CharacterMemory {\n return guard(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO memories (character_id, kind, text, about, importance, confidence, turn, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',\n [memory.characterId, memory.kind, memory.text, toJson(memory.about), memory.importance, memory.confidence ?? DEFAULT_CONFIDENCE, memory.turn, this.clock().toISOString()],\n )\n const added = this.require(Number(lastInsertRowid))\n this.index.put({ kind: 'memory', refId: added.id, characterId: added.characterId, text: added.text })\n return added\n })\n }\n\n get(id: MemoryId): CharacterMemory | undefined {\n const row = this.db.get<MemoryRow>('SELECT * FROM memories WHERE id = ?', [id])\n return row === undefined ? undefined : toMemory(row)\n }\n\n list(characterId: number): CharacterMemory[] {\n return this.db.all<MemoryRow>('SELECT * FROM memories WHERE character_id = ? ORDER BY id', [characterId]).map(toMemory)\n }\n\n update(id: MemoryId, patch: CharacterMemoryPatch): CharacterMemory {\n return guard(() => {\n const current = this.require(id)\n this.db.run('UPDATE memories SET text = ?, about = ?, importance = ?, confidence = ? WHERE id = ?', [\n patch.text ?? current.text, toJson(patch.about ?? current.about), patch.importance ?? current.importance, patch.confidence ?? current.confidence, id,\n ])\n const changed = this.require(id)\n this.index.put({ kind: 'memory', refId: id, characterId: changed.characterId, text: changed.text })\n return changed\n })\n }\n\n touch(ids: readonly MemoryId[], turn: number): void {\n this.db.transaction(() => {\n for (const id of ids) this.db.run('UPDATE memories SET recalls = recalls + 1, last_recalled_turn = ? WHERE id = ?', [turn, id])\n })\n }\n\n remove(id: MemoryId): boolean {\n this.index.remove('memory', id)\n return this.db.run('DELETE FROM memories WHERE id = ?', [id]).changes > 0\n }\n\n addEvidence(memoryId: MemoryId, perceptionId: PerceptionId, relation: EvidenceRelation, turn: number): void {\n this.require(memoryId)\n guard(() => this.db.run('INSERT INTO memory_evidence (memory_id, perception_id, relation, turn) VALUES (?, ?, ?, ?) ON CONFLICT (memory_id, perception_id) DO UPDATE SET relation = excluded.relation, turn = excluded.turn', [memoryId, perceptionId, relation, turn]))\n }\n\n evidenceOf(memoryId: MemoryId): MemoryEvidence[] {\n return this.db.all<{ memory_id: number; perception_id: number; relation: EvidenceRelation; turn: number }>('SELECT * FROM memory_evidence WHERE memory_id = ? ORDER BY perception_id', [memoryId])\n .map(row => ({ memoryId: row.memory_id, perceptionId: row.perception_id, relation: row.relation, turn: row.turn }))\n }\n\n evidenceIndex(characterId: number): { folded: Map<PerceptionId, MemoryId[]>; disputed: Set<MemoryId> } {\n const rows = this.db.all<{ memory_id: number; perception_id: number; relation: EvidenceRelation }>('SELECT e.memory_id, e.perception_id, e.relation FROM memory_evidence e JOIN memories m ON m.id = e.memory_id WHERE m.character_id = ? ORDER BY e.memory_id', [characterId])\n const folded = new Map<PerceptionId, MemoryId[]>()\n const disputed = new Set<MemoryId>()\n for (const row of rows) {\n folded.set(row.perception_id, [...(folded.get(row.perception_id) ?? []), row.memory_id])\n if (row.relation === 'contradicts') disputed.add(row.memory_id)\n }\n return { folded, disputed }\n }\n\n private require(id: MemoryId): CharacterMemory {\n const memory = this.get(id)\n if (memory === undefined) throw new NotFoundError(`memory ${id} does not exist`)\n return memory\n }\n}\n","import type { JsonValue, NewSummary, PendingCommit, StoryThread, Summary, SummaryId, SummaryLevel, ThreadId, ThreadStatus } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { CorruptDataError, NotFoundError } from '../errors.ts'\nimport type { PendingCommitRepository, SummaryRepository, ThreadRepository } from '../repositories.ts'\nimport { toJson } from './support.ts'\n\ninterface ThreadRow {\n id: number\n text: string\n status: ThreadStatus\n opened_turn: number\n resolved_turn: number | null\n}\n\nconst toThread = (row: ThreadRow): StoryThread => ({\n id: row.id,\n text: row.text,\n status: row.status,\n openedTurn: row.opened_turn,\n ...(row.resolved_turn === null ? {} : { resolvedTurn: row.resolved_turn }),\n})\n\nexport class SqliteThreadRepository implements ThreadRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n open(text: string, turn: number): StoryThread {\n const { lastInsertRowid } = this.db.run('INSERT INTO story_threads (text, status, opened_turn, created_at) VALUES (?, ?, ?, ?)', [text, 'open', turn, this.clock().toISOString()])\n return this.require(Number(lastInsertRowid))\n }\n\n get(id: ThreadId): StoryThread | undefined {\n const row = this.db.get<ThreadRow>('SELECT * FROM story_threads WHERE id = ?', [id])\n return row === undefined ? undefined : toThread(row)\n }\n\n list(status?: ThreadStatus): StoryThread[] {\n const rows = status === undefined\n ? this.db.all<ThreadRow>('SELECT * FROM story_threads ORDER BY id')\n : this.db.all<ThreadRow>('SELECT * FROM story_threads WHERE status = ? ORDER BY id', [status])\n return rows.map(toThread)\n }\n\n resolve(id: ThreadId, turn: number): StoryThread {\n this.require(id)\n this.db.run(\"UPDATE story_threads SET status = 'resolved', resolved_turn = ? WHERE id = ?\", [turn, id])\n return this.require(id)\n }\n\n remove(id: ThreadId): boolean {\n return this.db.run('DELETE FROM story_threads WHERE id = ?', [id]).changes > 0\n }\n\n private require(id: ThreadId): StoryThread {\n const thread = this.get(id)\n if (thread === undefined) throw new NotFoundError(`thread ${id} does not exist`)\n return thread\n }\n}\n\ninterface SummaryRow {\n id: number\n level: SummaryLevel\n from_turn: number\n to_turn: number\n text: string\n created_at: string\n}\n\nconst toSummary = (row: SummaryRow): Summary => ({ id: row.id, level: row.level, fromTurn: row.from_turn, toTurn: row.to_turn, text: row.text, createdAt: row.created_at })\n\nexport class SqliteSummaryRepository implements SummaryRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(summary: NewSummary): Summary {\n const { lastInsertRowid } = this.db.run('INSERT INTO summaries (level, from_turn, to_turn, text, created_at) VALUES (?, ?, ?, ?, ?)', [summary.level, summary.fromTurn, summary.toTurn, summary.text, this.clock().toISOString()])\n const row = this.db.get<SummaryRow>('SELECT * FROM summaries WHERE id = ?', [Number(lastInsertRowid)])\n if (row === undefined) throw new NotFoundError('the summary was not stored')\n return toSummary(row)\n }\n\n list(level?: SummaryLevel): Summary[] {\n const rows = level === undefined\n ? this.db.all<SummaryRow>('SELECT * FROM summaries ORDER BY from_turn, id')\n : this.db.all<SummaryRow>('SELECT * FROM summaries WHERE level = ? ORDER BY from_turn, id', [level])\n return rows.map(toSummary)\n }\n\n remove(ids: readonly SummaryId[]): void {\n this.db.transaction(() => { for (const id of ids) this.db.run('DELETE FROM summaries WHERE id = ?', [id]) })\n }\n}\n\nexport class SqlitePendingCommitRepository implements PendingCommitRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n enqueue(turn: number, round: number, payload: JsonValue): void {\n this.db.run('INSERT OR REPLACE INTO pending_commits (turn, round, payload, created_at) VALUES (?, ?, ?, ?)', [turn, round, toJson(payload), this.clock().toISOString()])\n }\n\n list(): PendingCommit[] {\n return this.db.all<{ turn: number; round: number; payload: string; created_at: string }>('SELECT * FROM pending_commits ORDER BY turn, round').map((row) => {\n try {\n return { turn: row.turn, round: row.round, payload: JSON.parse(row.payload) as JsonValue, createdAt: row.created_at }\n } catch (error) {\n throw new CorruptDataError(`pending commit ${row.turn}.${row.round} does not hold JSON`, { cause: error })\n }\n })\n }\n\n complete(rounds: readonly { turn: number; round: number }[]): void {\n this.db.transaction(() => { for (const { turn, round } of rounds) this.db.run('DELETE FROM pending_commits WHERE turn = ? AND round = ?', [turn, round]) })\n }\n}\n","import type { EmbeddingIndexInfo, PendingEmbedding, RecallHit, RecallItemKind } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError } from '../errors.ts'\nimport { tokens } from '../memory/recall.ts'\nimport type { MetadataRepository, RecallIndexRepository, RecallSearch, VectorSearch, VectorSupport } from '../repositories.ts'\n\nconst METADATA_KEY = 'embedding.index'\nconst KEY_LETTER: Record<RecallItemKind, string> = { perception: 'p', memory: 'm', event: 'e' }\n/** The most terms a lexical query uses: a long situation would otherwise match nearly everything. */\nconst MAX_QUERY_TERMS = 32\n/** A term in more than this share of the indexed texts says little about any of them (\"the\", a character's name in a story about them). */\nconst COMMON_SHARE = 0.5\n/** The common terms are only dropped once there are enough texts to tell, and never all of them. */\nconst MIN_TEXTS_FOR_COMMON = 6\n/** Hits scoring less than this against the best hit are noise from a shared word. */\nconst MIN_RELATIVE_SCORE = 0.2\n\ninterface ItemRow { id: number; kind: RecallItemKind; ref_id: number; character_id: number; text: string; embedded: number }\n\nconst keyOf = (kind: RecallItemKind, refId: number): string => `${KEY_LETTER[kind]}:${refId}`\nconst blob = (vector: readonly number[]): Uint8Array => new Uint8Array(new Float32Array(vector).buffer)\n\n/**\n * The texts a session can be searched by, and how: what was said or believed or happened is\n * indexed for lexical search (SQLite FTS5 over the same tokens recall uses, so that scripts written\n * without spaces match too), and, once something gives each text a vector, for dense search\n * (the sqlite-vec extension, one vector per text, with the character as a partition so that a\n * search of one character's memory never sees another's).\n *\n * Vectors are made elsewhere: this keeps the texts, says which still need one, and stores them.\n * A change to a text drops its vector, because it no longer describes it.\n */\nexport class SqliteRecallIndex implements RecallIndexRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly metadata: Pick<MetadataRepository, 'getValue' | 'setValue' | 'deleteValue'>,\n readonly vectors: VectorSupport,\n ) {}\n\n put(item: { kind: RecallItemKind; refId: number; characterId: number; text: string; extra?: string }): void {\n const existing = this.db.get<ItemRow>('SELECT * FROM recall_items WHERE kind = ? AND ref_id = ?', [item.kind, item.refId])\n const terms = [...tokens(`${item.text} ${item.extra ?? ''}`)].join(' ')\n if (existing === undefined) {\n const { lastInsertRowid } = this.db.run('INSERT INTO recall_items (kind, ref_id, character_id, text) VALUES (?, ?, ?, ?)', [item.kind, item.refId, item.characterId, item.text])\n this.db.run('INSERT INTO recall_fts (rowid, tokens) VALUES (?, ?)', [lastInsertRowid, terms])\n return\n }\n const changed = existing.text !== item.text || existing.character_id !== item.characterId\n this.db.run('UPDATE recall_items SET text = ?, character_id = ?, embedded = CASE WHEN ? THEN 0 ELSE embedded END WHERE id = ?', [item.text, item.characterId, changed ? 1 : 0, existing.id])\n this.db.run('DELETE FROM recall_fts WHERE rowid = ?', [existing.id])\n this.db.run('INSERT INTO recall_fts (rowid, tokens) VALUES (?, ?)', [existing.id, terms])\n if (changed) this.dropVector(existing.id)\n }\n\n remove(kind: RecallItemKind, refId: number): void {\n const existing = this.db.get<ItemRow>('SELECT * FROM recall_items WHERE kind = ? AND ref_id = ?', [kind, refId])\n if (existing === undefined) return\n this.db.run('DELETE FROM recall_fts WHERE rowid = ?', [existing.id])\n this.dropVector(existing.id)\n this.db.run('DELETE FROM recall_items WHERE id = ?', [existing.id])\n }\n\n lexical({ text, characterId, kinds, limit }: RecallSearch): RecallHit[] {\n const terms = this.informative([...tokens(text)].slice(0, MAX_QUERY_TERMS))\n if (terms.length === 0) return []\n const params: SqlValue[] = [terms.map(term => `\"${term.replaceAll('\"', '\"\"')}\"`).join(' OR ')]\n let where = ''\n if (characterId !== undefined) { where += ' AND i.character_id = ?'; params.push(characterId) }\n if (kinds !== undefined && kinds.length > 0) { where += ` AND i.kind IN (${kinds.map(() => '?').join(', ')})`; params.push(...kinds) }\n params.push(limit)\n const rows = this.db.all<ItemRow & { rank: number }>(\n `SELECT i.*, bm25(recall_fts) AS rank FROM recall_fts JOIN recall_items i ON i.id = recall_fts.rowid\n WHERE recall_fts MATCH ?${where} ORDER BY rank LIMIT ?`,\n params,\n )\n // bm25 is smaller for a better match, and negative: the best hit counts as 1 and the rest relative to it.\n const best = rows.reduce((top, row) => Math.max(top, -row.rank), 0)\n return rows\n .map(row => ({ key: keyOf(row.kind, row.ref_id), kind: row.kind, refId: row.ref_id, score: best === 0 ? 0 : Math.max(0, -row.rank) / best }))\n .filter(hit => hit.score >= MIN_RELATIVE_SCORE)\n }\n\n /** The terms that tell texts apart: those found in most of the texts are left out, unless that would leave none. */\n private informative(terms: readonly string[]): string[] {\n if (terms.length === 0) return []\n const total = this.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM recall_items')?.n ?? 0\n if (total < MIN_TEXTS_FOR_COMMON) return [...terms]\n const counts = new Map(this.db.all<{ term: string; doc: number }>(\n `SELECT term, doc FROM recall_vocab WHERE term IN (${terms.map(() => '?').join(', ')})`, [...terms],\n ).map(row => [row.term, row.doc]))\n const kept = terms.filter(term => (counts.get(term) ?? 0) <= COMMON_SHARE * total)\n return kept.length > 0 ? kept : [...terms]\n }\n\n vector({ vector, characterId, limit }: VectorSearch): RecallHit[] {\n const info = this.info()\n if (info === undefined || !this.vectors.available) return []\n if (vector.length !== info.dimensions) throw new InvalidValueError(`the query has ${vector.length} dimensions, the vectors of this session have ${info.dimensions}`)\n const params: SqlValue[] = [blob(vector), limit]\n let where = ''\n if (characterId !== undefined) { where = ' AND character_id = ?'; params.push(characterId) }\n const near = this.db.all<{ rowid: number; distance: number }>(`SELECT rowid, distance FROM recall_vec WHERE embedding MATCH ? AND k = ?${where}`, params)\n if (near.length === 0) return []\n const items = this.db.all<ItemRow>(`SELECT * FROM recall_items WHERE id IN (${near.map(() => '?').join(', ')})`, near.map(entry => entry.rowid))\n const byId = new Map(items.map(item => [item.id, item]))\n return near.flatMap((entry) => {\n const item = byId.get(entry.rowid)\n // The vectors are compared by cosine distance, which is 0 for the same direction and 2 for the opposite.\n return item === undefined ? [] : [{ key: keyOf(item.kind, item.ref_id), kind: item.kind, refId: item.ref_id, score: Math.min(1, Math.max(0, 1 - entry.distance)) }]\n })\n }\n\n info(): EmbeddingIndexInfo | undefined {\n const stored = this.metadata.getValue(METADATA_KEY) as { model: string; dimensions: number } | undefined\n if (stored === undefined) return undefined\n const counts = this.db.get<{ embedded: number; pending: number }>(\"SELECT COALESCE(SUM(embedded = 1), 0) AS embedded, COALESCE(SUM(embedded = 0), 0) AS pending FROM recall_items\")\n return { model: stored.model, dimensions: stored.dimensions, embedded: counts?.embedded ?? 0, pending: counts?.pending ?? 0 }\n }\n\n pending(limit: number): PendingEmbedding[] {\n return this.db.all<ItemRow>('SELECT * FROM recall_items WHERE embedded = 0 ORDER BY id LIMIT ?', [limit]).map(row => ({ id: row.id, kind: row.kind, text: row.text }))\n }\n\n store(model: string, vectors: readonly { id: number; vector: readonly number[] }[]): number {\n if (!this.vectors.available) throw new ConflictError(`vector search is not available here: ${this.vectors.error ?? 'the extension is not loaded'}`)\n if (vectors.length === 0) return 0\n const dimensions = vectors[0]!.vector.length\n return this.db.transaction(() => {\n const info = this.info()\n if (info === undefined) {\n if (dimensions < 1) throw new InvalidValueError('a vector has no dimensions')\n this.db.exec(`CREATE VIRTUAL TABLE recall_vec USING vec0(character_id integer partition key, embedding float[${Math.trunc(dimensions)}] distance_metric=cosine)`)\n this.metadata.setValue(METADATA_KEY, { model, dimensions })\n } else if (info.model !== model || info.dimensions !== dimensions) {\n throw new ConflictError(`this session's vectors are from ${info.model} with ${info.dimensions} dimensions, not ${model} with ${dimensions}: reset the vectors to change them`)\n }\n let stored = 0\n for (const { id, vector } of vectors) {\n if (vector.length !== dimensions) throw new InvalidValueError(`vector of text ${id} has ${vector.length} dimensions, not ${dimensions}`)\n const item = this.db.get<ItemRow>('SELECT * FROM recall_items WHERE id = ?', [id])\n if (item === undefined) continue\n this.db.run('DELETE FROM recall_vec WHERE rowid = ?', [BigInt(id)])\n this.db.run('INSERT INTO recall_vec (rowid, character_id, embedding) VALUES (?, ?, ?)', [BigInt(id), BigInt(item.character_id), blob(vector)])\n this.db.run('UPDATE recall_items SET embedded = 1 WHERE id = ?', [id])\n stored++\n }\n return stored\n })\n }\n\n reset(): void {\n this.db.transaction(() => {\n if (this.info() === undefined) return\n this.db.exec('DROP TABLE IF EXISTS recall_vec')\n this.db.run('UPDATE recall_items SET embedded = 0')\n this.metadata.deleteValue(METADATA_KEY)\n })\n }\n\n private dropVector(id: number): void {\n if (this.vectors.available && this.info() !== undefined) this.db.run('DELETE FROM recall_vec WHERE rowid = ?', [BigInt(id)])\n }\n}\n","import { MAX_TRIGGERS, type NewTriggerNote, type Trigger, type TriggerAnnouncement, type TriggerCondition, type TriggerDefinition, type TriggerEffect, type TriggerId, type TriggerNote, type TriggerNoteKind, type TriggerStatus } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { TriggerRepository } from '../repositories.ts'\nimport { guard, parseNumberList, toJson } from './support.ts'\n\ninterface TriggerRow {\n id: number\n key: string\n name: string\n condition: string\n effects: string\n repeat: number\n cooldown_seconds: number | null\n chance: number | null\n priority: number\n expires: string | null\n announce: string | null\n status: TriggerStatus\n fire_count: number\n last_fired_ms: number | null\n last_result: number\n problem: string | null\n origin: Trigger['origin']\n created_turn: number\n}\n\ninterface NoteRow {\n id: number\n trigger_id: number\n kind: TriggerNoteKind\n text: string\n character_ids: string\n turn: number\n status: TriggerNote['status']\n}\n\nconst MAX_TEXT = 2000\n\nfunction parse<T>(text: string, what: string): T {\n try {\n return JSON.parse(text) as T\n } catch (error) {\n throw new CorruptDataError(`a trigger's ${what} is not valid JSON`, { cause: error })\n }\n}\n\nexport class SqliteTriggerRepository implements TriggerRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n add(definition: TriggerDefinition, origin: Trigger['origin'], turn: number): Trigger {\n this.check(definition)\n if ((this.db.get<{ count: number }>('SELECT count(*) AS count FROM triggers')?.count ?? 0) >= MAX_TRIGGERS) throw new InvalidValueError(`a story has at most ${MAX_TRIGGERS} triggers`)\n return guard(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO triggers (key, name, condition, effects, repeat, cooldown_seconds, chance, priority, expires, announce, origin, created_turn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [definition.key, definition.name, toJson(definition.condition), toJson(definition.effects), definition.repeat ? 1 : 0, definition.cooldownSeconds ?? null, definition.chance ?? null, definition.priority, definition.expires ?? null, definition.announce === undefined ? null : toJson(definition.announce), origin, turn],\n )\n return this.require(Number(lastInsertRowid))\n })\n }\n\n get(id: TriggerId): Trigger | undefined {\n const row = this.db.get<TriggerRow>('SELECT * FROM triggers WHERE id = ?', [id])\n return row === undefined ? undefined : this.toTrigger(row)\n }\n\n getByKey(key: string): Trigger | undefined {\n const row = this.db.get<TriggerRow>('SELECT * FROM triggers WHERE key = ?', [key])\n return row === undefined ? undefined : this.toTrigger(row)\n }\n\n list(filter: { status?: TriggerStatus } = {}): Trigger[] {\n const rows = filter.status === undefined\n ? this.db.all<TriggerRow>('SELECT * FROM triggers ORDER BY priority DESC, id')\n : this.db.all<TriggerRow>('SELECT * FROM triggers WHERE status = ? ORDER BY priority DESC, id', [filter.status])\n return rows.map(row => this.toTrigger(row))\n }\n\n update(id: TriggerId, patch: { status?: TriggerStatus; fireCount?: number; lastFiredMs?: number; lastResult?: boolean; problem?: string }): Trigger {\n const current = this.require(id)\n this.db.run('UPDATE triggers SET status = ?, fire_count = ?, last_fired_ms = ?, last_result = ?, problem = ? WHERE id = ?', [\n patch.status ?? current.status, patch.fireCount ?? current.fireCount, patch.lastFiredMs ?? current.lastFiredMs ?? null,\n (patch.lastResult ?? current.lastResult) ? 1 : 0, patch.problem ?? current.problem ?? null, id,\n ])\n return this.require(id)\n }\n\n addNote(note: NewTriggerNote): TriggerNote {\n if (note.text.trim() === '' || note.text.length > MAX_TEXT) throw new InvalidValueError(`a note needs a text of at most ${MAX_TEXT} characters`)\n return guard(() => {\n const { lastInsertRowid } = this.db.run('INSERT INTO trigger_notes (trigger_id, kind, text, character_ids, turn) VALUES (?, ?, ?, ?, ?)', [note.triggerId, note.kind, note.text.trim(), toJson([...new Set(note.characterIds ?? [])]), note.turn])\n return this.requireNote(Number(lastInsertRowid))\n })\n }\n\n notes(filter: { status?: TriggerNote['status']; kind?: TriggerNoteKind } = {}): TriggerNote[] {\n const where: string[] = []\n const params: SqlValue[] = []\n if (filter.status !== undefined) { where.push('status = ?'); params.push(filter.status) }\n if (filter.kind !== undefined) { where.push('kind = ?'); params.push(filter.kind) }\n return this.db.all<NoteRow>(`SELECT * FROM trigger_notes ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`} ORDER BY id`, params).map(row => this.toNote(row))\n }\n\n resolveNote(id: number, status: 'done' | 'lapsed'): void {\n if (this.db.run('UPDATE trigger_notes SET status = ? WHERE id = ?', [status, id]).changes === 0) throw new NotFoundError(`trigger note ${id} does not exist`)\n }\n\n private check(definition: TriggerDefinition): void {\n if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(definition.key)) throw new InvalidValueError('a trigger key is lowercase letters, digits, hyphens and underscores, at most 64')\n if (definition.name.trim() === '' || definition.name.length > 200) throw new InvalidValueError('a trigger needs a name of at most 200 characters')\n if (definition.effects.length === 0) throw new InvalidValueError('a trigger needs at least one effect')\n if (definition.chance !== undefined && !(definition.chance >= 0 && definition.chance <= 1)) throw new InvalidValueError('a chance is from 0 to 1')\n if (definition.cooldownSeconds !== undefined && (!Number.isSafeInteger(definition.cooldownSeconds) || definition.cooldownSeconds < 0)) throw new InvalidValueError('a cooldown is a whole number of seconds')\n if (!Number.isSafeInteger(definition.priority)) throw new InvalidValueError('a priority is a whole number')\n }\n\n private toTrigger(row: TriggerRow): Trigger {\n return {\n id: row.id, key: row.key, name: row.name, condition: parse<TriggerCondition>(row.condition, 'condition'), effects: parse<TriggerEffect[]>(row.effects, 'effects'),\n repeat: row.repeat === 1, ...(row.cooldown_seconds === null ? {} : { cooldownSeconds: row.cooldown_seconds }), ...(row.chance === null ? {} : { chance: row.chance }),\n priority: row.priority, ...(row.expires === null ? {} : { expires: row.expires }), ...(row.announce === null ? {} : { announce: parse<TriggerAnnouncement>(row.announce, 'announcement') }), status: row.status, fireCount: row.fire_count,\n ...(row.last_fired_ms === null ? {} : { lastFiredMs: row.last_fired_ms }), lastResult: row.last_result === 1, ...(row.problem === null ? {} : { problem: row.problem }),\n origin: row.origin, createdTurn: row.created_turn,\n }\n }\n\n private toNote(row: NoteRow): TriggerNote {\n return { id: row.id, triggerId: row.trigger_id, kind: row.kind, text: row.text, characterIds: parseNumberList(row.character_ids, 'trigger_notes.character_ids'), turn: row.turn, status: row.status }\n }\n\n private require(id: TriggerId): Trigger {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`trigger ${id} does not exist`)\n return found\n }\n\n private requireNote(id: number): TriggerNote {\n const row = this.db.get<NoteRow>('SELECT * FROM trigger_notes WHERE id = ?', [id])\n if (row === undefined) throw new NotFoundError(`trigger note ${id} does not exist`)\n return this.toNote(row)\n }\n}\n","import { MAX_DICE_CHECKS, type DiceCheck, type DiceCheckDefinition, type DiceReadout, type DiceRoll, type NewDiceRoll } from 'dsh-roleplay-model'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { DiceRepository } from '../repositories.ts'\nimport { guard, parseNumberList, toJson } from './support.ts'\n\ninterface CheckRow { id: number; key: string; name: string; use_text: string; definition: string }\n\ninterface RollRow {\n id: number; turn: number; check_key: string | null; expression: string; faces: string; kept: string; modifier: number; target: number | null\n total: number; value: number; readout: string | null; reason: string; character: string | null; by: 'agent' | 'player'; at: string\n}\n\nconst MAX_ROLLS_LISTED = 200\n\nfunction parseDefinition(text: string): Omit<DiceCheckDefinition, 'key' | 'name' | 'use'> {\n try {\n return JSON.parse(text) as Omit<DiceCheckDefinition, 'key' | 'name' | 'use'>\n } catch (error) {\n throw new CorruptDataError('a dice check\\'s definition is not valid JSON', { cause: error })\n }\n}\n\nexport class SqliteDiceRepository implements DiceRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: () => Date) {}\n\n define(definition: DiceCheckDefinition): DiceCheck {\n if ((this.db.get<{ count: number }>('SELECT count(*) AS count FROM dice_checks')?.count ?? 0) >= MAX_DICE_CHECKS) throw new InvalidValueError(`a story has at most ${MAX_DICE_CHECKS} dice checks`)\n const { key, name, use, ...rest } = definition\n return guard(() => {\n const { lastInsertRowid } = this.db.run('INSERT INTO dice_checks (key, name, use_text, definition) VALUES (?, ?, ?, ?)', [key, name, use, toJson(rest)])\n return this.require(Number(lastInsertRowid))\n })\n }\n\n checks(): DiceCheck[] {\n return this.db.all<CheckRow>('SELECT * FROM dice_checks ORDER BY id').map(row => this.toCheck(row))\n }\n\n check(key: string): DiceCheck | undefined {\n const row = this.db.get<CheckRow>('SELECT * FROM dice_checks WHERE key = ?', [key])\n return row === undefined ? undefined : this.toCheck(row)\n }\n\n removeCheck(key: string): void {\n if (this.db.run('DELETE FROM dice_checks WHERE key = ?', [key]).changes === 0) throw new NotFoundError(`there is no dice check \"${key}\"`)\n }\n\n record(roll: NewDiceRoll): DiceRoll {\n const at = this.clock().toISOString()\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO dice_rolls (turn, check_key, expression, faces, kept, modifier, target, total, value, readout, reason, character, by, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [roll.turn, roll.check ?? null, roll.expression, toJson(roll.faces), toJson(roll.kept), roll.modifier, roll.target ?? null, roll.total, roll.value, roll.readout === undefined ? null : toJson(roll.readout), roll.reason, roll.character ?? null, roll.by, at],\n )\n return { ...roll, id: Number(lastInsertRowid), at }\n }\n\n rolls(filter: { turn?: number; limit?: number } = {}): DiceRoll[] {\n const limit = Math.min(filter.limit ?? MAX_ROLLS_LISTED, MAX_ROLLS_LISTED)\n const rows = filter.turn === undefined\n ? this.db.all<RollRow>('SELECT * FROM (SELECT * FROM dice_rolls ORDER BY id DESC LIMIT ?) ORDER BY id', [limit])\n : this.db.all<RollRow>('SELECT * FROM dice_rolls WHERE turn = ? ORDER BY id LIMIT ?', [filter.turn, limit])\n return rows.map(row => this.toRoll(row))\n }\n\n private require(id: number): DiceCheck {\n const row = this.db.get<CheckRow>('SELECT * FROM dice_checks WHERE id = ?', [id])\n if (row === undefined) throw new NotFoundError(`there is no dice check ${id}`)\n return this.toCheck(row)\n }\n\n private toCheck(row: CheckRow): DiceCheck {\n return { id: row.id, key: row.key, name: row.name, use: row.use_text, ...parseDefinition(row.definition) } as DiceCheck\n }\n\n private toRoll(row: RollRow): DiceRoll {\n return {\n id: row.id, turn: row.turn, expression: row.expression, faces: parseNumberList(row.faces, 'dice_rolls.faces'), kept: parseNumberList(row.kept, 'dice_rolls.kept'),\n modifier: row.modifier, total: row.total, value: row.value, reason: row.reason, by: row.by, at: row.at,\n ...(row.check_key === null ? {} : { check: row.check_key }),\n ...(row.target === null ? {} : { target: row.target }),\n ...(row.readout === null ? {} : { readout: JSON.parse(row.readout) as DiceReadout }),\n ...(row.character === null ? {} : { character: row.character }),\n }\n }\n}\n","import type { ClockMode, ClockState, TimeChange, TimeChangeFilter, TimeChangeKind } from 'dsh-roleplay-model'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { ClockRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface ClockRow { mode: ClockMode; now_ms: number }\ninterface LogRow { id: number; turn: number; round: number; kind: TimeChangeKind; from_ms: number; to_ms: number; reason: string }\n\nconst toChange = (row: LogRow): TimeChange => ({ id: row.id, turn: row.turn, round: row.round, kind: row.kind, from: row.from_ms, to: row.to_ms, reason: row.reason })\n\nexport class SqliteClockRepository implements ClockRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n get(): ClockState | undefined {\n const row = this.db.get<ClockRow>('SELECT mode, now_ms FROM clock WHERE id = 1')\n return row === undefined ? undefined : { mode: row.mode, now: row.now_ms }\n }\n\n start(mode: ClockMode, now: number): ClockState {\n assertInstant(now)\n return guard(() => this.db.transaction(() => {\n if (this.get() !== undefined) throw new ConflictError('the clock is already started')\n this.db.run('INSERT INTO clock (id, mode, now_ms) VALUES (1, ?, ?)', [mode, now])\n this.db.run('INSERT INTO time_log (turn, round, kind, from_ms, to_ms, reason) VALUES (0, 0, ?, ?, ?, ?)', ['start', now, now, ''])\n return { mode, now }\n }))\n }\n\n advance(step: { to: number; turn: number; round: number; kind: Exclude<TimeChangeKind, 'start' | 'resync'>; reason?: string }): TimeChange {\n assertInstant(step.to)\n return guard(() => this.db.transaction(() => {\n const current = this.require()\n if (step.to < current.now) throw new InvalidValueError(`the story's time cannot go back: it is ${current.now} and ${step.to} is earlier`)\n return this.record(current.mode, current.now, step.to, step.turn, step.round, step.kind, step.reason ?? '')\n }))\n }\n\n resync(mode: ClockMode, now: number, turn: number, reason = ''): TimeChange {\n assertInstant(now)\n return guard(() => this.db.transaction(() => this.record(mode, this.require().now, now, turn, 0, 'resync', reason)))\n }\n\n log(filter: TimeChangeFilter = {}): TimeChange[] {\n const where: string[] = []\n const params: SqlValue[] = []\n const add = (clause: string, value: SqlValue): void => { where.push(clause); params.push(value) }\n if (filter.turn !== undefined) add('turn = ?', filter.turn)\n if (filter.round !== undefined) add('round = ?', filter.round)\n if (filter.fromTurn !== undefined) add('turn >= ?', filter.fromTurn)\n if (filter.toTurn !== undefined) add('turn <= ?', filter.toTurn)\n if (filter.kind !== undefined) add('kind = ?', filter.kind)\n return this.db.all<LogRow>(`SELECT * FROM time_log ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`} ORDER BY id`, params).map(toChange)\n }\n\n at(turn: number, round: number): number | undefined {\n return this.db.get<{ from_ms: number }>(\"SELECT from_ms FROM time_log WHERE turn = ? AND round = ? AND kind IN ('elapsed', 'real') ORDER BY id LIMIT 1\", [turn, round])?.from_ms\n }\n\n private require(): ClockState {\n const state = this.get()\n if (state === undefined) throw new NotFoundError('the clock is not started')\n return state\n }\n\n private record(mode: ClockMode, from: number, to: number, turn: number, round: number, kind: TimeChangeKind, reason: string): TimeChange {\n this.db.run('UPDATE clock SET mode = ?, now_ms = ? WHERE id = 1', [mode, to])\n const { lastInsertRowid } = this.db.run('INSERT INTO time_log (turn, round, kind, from_ms, to_ms, reason) VALUES (?, ?, ?, ?, ?, ?)', [turn, round, kind, from, to, reason])\n return { id: Number(lastInsertRowid), turn, round, kind, from, to, reason }\n }\n}\n\nfunction assertInstant(value: number): void {\n if (!Number.isSafeInteger(value) || Math.abs(value) > 8_640_000_000_000_000) throw new InvalidValueError(`${value} is not an instant (whole milliseconds since 1970)`)\n}\n","import {\n CONTAINER_STATES, DEFAULT_SLOTS, SLOT_ID,\n type CharacterId, type Holder, type Holding, type Item, type ItemId, type ItemPatch, type LocationId, type NewItem, type Slot,\n} from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { ItemRepository, SlotRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface ItemRow {\n id: number\n source_id: string | null\n name: string\n description: string\n quantity: number\n unique_item: number\n quality: string\n notable: number\n hidden: number\n wearable_slot: string | null\n container_state: Item['container'] extends infer C ? (C extends { state: infer S } ? S : never) | null : never\n owner_id: number | null\n created_at: string\n}\n\ninterface HoldingRow {\n item_id: number\n holder_kind: 'location' | 'character' | 'item'\n holder_id: number\n mode: 'at' | 'held' | 'worn' | 'inside'\n slot: string | null\n position: string\n feature_key: string | null\n}\n\nconst toItem = (row: ItemRow): Item => ({\n id: row.id,\n ...(row.source_id === null ? {} : { sourceId: row.source_id }),\n name: row.name,\n description: row.description,\n quantity: row.quantity,\n unique: row.unique_item === 1,\n quality: row.quality,\n notable: row.notable === 1,\n hidden: row.hidden === 1,\n ...(row.wearable_slot === null ? {} : { wearableSlot: row.wearable_slot }),\n ...(row.container_state === null ? {} : { container: { state: row.container_state } }),\n ...(row.owner_id === null ? {} : { ownerId: row.owner_id }),\n createdAt: row.created_at,\n})\n\nconst toHolder = (row: HoldingRow): Holder => {\n switch (row.holder_kind) {\n case 'location': return { kind: 'location', locationId: row.holder_id, ...(row.position === '' ? {} : { position: row.position }), ...(row.feature_key === null ? {} : { featureKey: row.feature_key }) }\n case 'character': return row.mode === 'worn'\n ? { kind: 'character', characterId: row.holder_id, mode: 'worn', slot: row.slot!, ...(row.position === '' ? {} : { position: row.position }) }\n : { kind: 'character', characterId: row.holder_id, mode: 'held' }\n case 'item': return { kind: 'item', itemId: row.holder_id, ...(row.position === '' ? {} : { position: row.position }) }\n }\n}\n\nexport class SqliteSlotRepository implements SlotRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n ensureDefaults(): void {\n for (const slot of DEFAULT_SLOTS) this.db.run('INSERT OR IGNORE INTO slots (id, name, capacity) VALUES (?, ?, ?)', [slot.id, slot.name, slot.capacity])\n }\n\n list(): Slot[] {\n return this.db.all<Slot>('SELECT id, name, capacity FROM slots ORDER BY rowid')\n }\n\n get(id: string): Slot | undefined {\n return this.db.get<Slot>('SELECT id, name, capacity FROM slots WHERE id = ?', [id])\n }\n\n upsert(slot: Slot): Slot {\n if (!SLOT_ID.test(slot.id)) throw new InvalidValueError(`slot id \"${slot.id}\" must be lowercase letters, digits, \"-\" or \"_\"`)\n if (slot.name.trim() === '') throw new InvalidValueError(`slot \"${slot.id}\" needs a name`)\n if (!Number.isInteger(slot.capacity) || slot.capacity < 1) throw new InvalidValueError(`slot \"${slot.id}\" needs a capacity of at least 1`)\n const worn = this.db.get<{ n: number }>(\"SELECT MAX(c) AS n FROM (SELECT COUNT(*) AS c FROM item_holdings WHERE mode = 'worn' AND slot = ? GROUP BY holder_id)\", [slot.id])?.n ?? 0\n if (slot.capacity < worn) throw new ConflictError(`slot \"${slot.id}\" already has ${worn} things worn in it, more than ${slot.capacity}`)\n this.db.run('INSERT INTO slots (id, name, capacity) VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, capacity = excluded.capacity', [slot.id, slot.name.trim(), slot.capacity])\n return this.get(slot.id)!\n }\n}\n\nexport class SqliteItemRepository implements ItemRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(item: NewItem, holder: Holder): Item {\n if (item.name.trim() === '') throw new InvalidValueError('an item needs a name')\n if (!Number.isInteger(item.quantity) || item.quantity < 1) throw new InvalidValueError('the quantity must be a whole number from 1')\n if (item.container !== undefined && !CONTAINER_STATES.includes(item.container.state)) throw new InvalidValueError(`unknown container state \"${String(item.container.state)}\"`)\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO items (source_id, name, description, quantity, unique_item, quality, notable, hidden, wearable_slot, container_state, owner_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [item.sourceId ?? null, item.name.trim(), item.description.trim(), item.quantity, item.unique ? 1 : 0, item.quality.trim(), item.notable ? 1 : 0, item.hidden ? 1 : 0, item.wearableSlot ?? null, item.container?.state ?? null, item.ownerId ?? null, this.clock().toISOString()],\n )\n const id = Number(lastInsertRowid)\n this.place(id, holder)\n return this.require(id)\n }))\n }\n\n get(id: ItemId): Item | undefined {\n const row = this.db.get<ItemRow>('SELECT * FROM items WHERE id = ?', [id])\n return row === undefined ? undefined : toItem(row)\n }\n\n getBySourceId(sourceId: string): Item | undefined {\n const row = this.db.get<ItemRow>('SELECT * FROM items WHERE source_id = ?', [sourceId])\n return row === undefined ? undefined : toItem(row)\n }\n\n list(): Item[] {\n return this.db.all<ItemRow>('SELECT * FROM items ORDER BY id').map(toItem)\n }\n\n update(id: ItemId, patch: ItemPatch): Item {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const name = patch.name === undefined ? current.name : patch.name.trim()\n if (name === '') throw new InvalidValueError('an item needs a name')\n const quantity = patch.quantity ?? current.quantity\n if (!Number.isInteger(quantity) || quantity < 1) throw new InvalidValueError('the quantity must be a whole number from 1')\n if (patch.container !== undefined && current.container === undefined) throw new InvalidValueError(`${current.name} is not a container`)\n if (patch.container !== undefined && !CONTAINER_STATES.includes(patch.container.state)) throw new InvalidValueError(`unknown container state \"${String(patch.container.state)}\"`)\n this.db.run('UPDATE items SET name = ?, description = ?, quantity = ?, quality = ?, notable = ?, hidden = ?, container_state = ?, owner_id = ? WHERE id = ?', [\n name, (patch.description ?? current.description).trim(), quantity, (patch.quality ?? current.quality).trim(), (patch.notable ?? current.notable) ? 1 : 0, (patch.hidden ?? current.hidden) ? 1 : 0,\n patch.container?.state ?? current.container?.state ?? null, patch.ownerId === undefined ? current.ownerId ?? null : patch.ownerId, id,\n ])\n return this.require(id)\n }))\n }\n\n remove(id: ItemId): boolean {\n return this.db.transaction(() => {\n if (this.contents({ kind: 'item', id }).length > 0) throw new ConflictError(`${this.get(id)?.name ?? id} still holds things: take them out first`)\n this.db.run(\"DELETE FROM openers WHERE target_kind = 'item' AND target_id = ?\", [id])\n return this.db.run('DELETE FROM items WHERE id = ?', [id]).changes > 0\n })\n }\n\n holding(id: ItemId): Holding | undefined {\n const row = this.db.get<HoldingRow>('SELECT * FROM item_holdings WHERE item_id = ?', [id])\n return row === undefined ? undefined : { itemId: id, holder: toHolder(row) }\n }\n\n place(id: ItemId, holder: Holder): Holding {\n return guard(() => this.db.transaction(() => {\n const item = this.require(id)\n let slot: string | null = null\n let mode: HoldingRow['mode'] = 'at'\n let holderId: number\n let position = ''\n let feature: string | null = null\n switch (holder.kind) {\n case 'location':\n if (this.db.get('SELECT 1 FROM locations WHERE id = ?', [holder.locationId]) === undefined) throw new NotFoundError(`place ${holder.locationId} does not exist`)\n if (holder.featureKey !== undefined) {\n const features = this.db.get<{ features: string }>('SELECT features FROM locations WHERE id = ?', [holder.locationId])!.features\n if (!(JSON.parse(features) as { key: string }[]).some(feature => feature.key === holder.featureKey)) throw new InvalidValueError(`that place has no feature \"${holder.featureKey}\"`)\n feature = holder.featureKey\n }\n holderId = holder.locationId\n position = holder.position ?? ''\n break\n case 'character':\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [holder.characterId]) === undefined) throw new NotFoundError(`character ${holder.characterId} does not exist`)\n holderId = holder.characterId\n mode = holder.mode\n if (holder.mode === 'worn') {\n if (item.wearableSlot === undefined) throw new InvalidValueError(`${item.name} cannot be worn`)\n if (holder.slot !== item.wearableSlot) throw new InvalidValueError(`${item.name} is worn on the ${item.wearableSlot}, not the ${holder.slot}`)\n const place = this.db.get<{ capacity: number }>('SELECT capacity FROM slots WHERE id = ?', [holder.slot])\n if (place === undefined) throw new NotFoundError(`there is no slot \"${holder.slot}\"`)\n const taken = this.db.get<{ n: number }>(\"SELECT COUNT(*) AS n FROM item_holdings WHERE mode = 'worn' AND holder_id = ? AND slot = ? AND item_id <> ?\", [holder.characterId, holder.slot, id])!.n\n if (taken >= place.capacity) throw new ConflictError(`the ${holder.slot} is full (${place.capacity} worn there already)`)\n slot = holder.slot\n position = holder.position ?? ''\n }\n break\n case 'item': {\n const container = this.get(holder.itemId)\n if (container === undefined) throw new NotFoundError(`item ${holder.itemId} does not exist`)\n if (container.container === undefined) throw new InvalidValueError(`${container.name} cannot hold things`)\n if (holder.itemId === id || this.ancestors(holder.itemId).includes(id)) throw new InvalidValueError(`${item.name} cannot be put inside itself`)\n holderId = holder.itemId\n mode = 'inside'\n position = holder.position ?? ''\n break\n }\n }\n this.db.run(\n `INSERT INTO item_holdings (item_id, holder_kind, holder_id, mode, slot, position, feature_key) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (item_id) DO UPDATE SET holder_kind = excluded.holder_kind, holder_id = excluded.holder_id, mode = excluded.mode, slot = excluded.slot, position = excluded.position, feature_key = excluded.feature_key`,\n [id, holder.kind, holderId, mode, slot, position.trim(), feature],\n )\n return this.holding(id)!\n }))\n }\n\n contents(holder: { kind: 'location' | 'character' | 'item'; id: number }): { item: Item; holding: Holding }[] {\n const rows = this.db.all<HoldingRow>('SELECT * FROM item_holdings WHERE holder_kind = ? AND holder_id = ? ORDER BY item_id', [holder.kind, holder.id])\n return rows.flatMap((row) => {\n const item = this.get(row.item_id)\n return item === undefined ? [] : [{ item, holding: { itemId: row.item_id, holder: toHolder(row) } }]\n })\n }\n\n ancestors(id: ItemId): ItemId[] {\n const chain: ItemId[] = []\n for (let holding = this.holding(id); holding?.holder.kind === 'item'; holding = this.holding(holding.holder.itemId)) {\n if (chain.includes(holding.holder.itemId)) break\n chain.push(holding.holder.itemId)\n }\n return chain\n }\n\n where(id: ItemId): { locationId?: LocationId; characterId?: CharacterId } {\n let holding = this.holding(id)\n for (let guardCount = 0; holding !== undefined && guardCount < 64; guardCount++) {\n const { holder } = holding\n if (holder.kind === 'location') return { locationId: holder.locationId }\n if (holder.kind === 'character') {\n const placement = this.db.get<{ location_id: number }>(\"SELECT location_id FROM placements WHERE kind = 'character' AND entity_id = ?\", [holder.characterId])\n return { characterId: holder.characterId, ...(placement === undefined ? {} : { locationId: placement.location_id }) }\n }\n holding = this.holding(holder.itemId)\n }\n return {}\n }\n\n openers(target: { kind: 'item' | 'exit'; id: number }): ItemId[] {\n return this.db.all<{ key_item_id: number }>('SELECT key_item_id FROM openers WHERE target_kind = ? AND target_id = ? ORDER BY key_item_id', [target.kind, target.id]).map(row => row.key_item_id)\n }\n\n setOpeners(target: { kind: 'item' | 'exit'; id: number }, items: readonly ItemId[]): void {\n this.db.transaction(() => {\n if (target.kind === 'item' && this.get(target.id)?.container === undefined) throw new InvalidValueError(`item ${target.id} is not a container`)\n this.db.run('DELETE FROM openers WHERE target_kind = ? AND target_id = ?', [target.kind, target.id])\n for (const item of new Set(items)) {\n if (this.get(item) === undefined) throw new NotFoundError(`item ${item} does not exist`)\n this.db.run('INSERT INTO openers (target_kind, target_id, key_item_id) VALUES (?, ?, ?)', [target.kind, target.id, item])\n }\n })\n }\n\n private require(id: ItemId): Item {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`item ${id} does not exist`)\n return found\n }\n}\n","import type { CharacterId, ConsolidationItem, ConsolidationItemId, ConsolidationKind, Relationship, RelationshipPatch } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { ConsolidationRepository, RelationshipRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface RelationshipRow {\n id: number\n from_id: number\n to_id: number\n label: string\n summary: string\n familiarity: number\n trust: number\n affinity: number\n tension: number\n updated_turn: number\n created_at: string\n}\n\ninterface ItemRow {\n id: number\n kind: ConsolidationKind\n subject_id: number\n note: string\n created_turn: number\n resolved_turn: number | null\n resolution: string | null\n}\n\nconst toRelationship = (row: RelationshipRow): Relationship => ({\n id: row.id, fromId: row.from_id, toId: row.to_id, label: row.label, summary: row.summary,\n familiarity: row.familiarity, trust: row.trust, affinity: row.affinity, tension: row.tension,\n updatedTurn: row.updated_turn, createdAt: row.created_at,\n})\n\nconst toItem = (row: ItemRow): ConsolidationItem => ({\n id: row.id, kind: row.kind, subjectId: row.subject_id, note: row.note, createdTurn: row.created_turn,\n ...(row.resolved_turn === null ? {} : { resolvedTurn: row.resolved_turn }),\n ...(row.resolution === null ? {} : { resolution: row.resolution }),\n})\n\nconst RANGES = { familiarity: [0, 1], trust: [-1, 1], affinity: [-1, 1], tension: [0, 1] } as const\n\nfunction checked(patch: RelationshipPatch): void {\n for (const [key, [min, max]] of Object.entries(RANGES) as [keyof typeof RANGES, readonly [number, number]][]) {\n const value = patch[key]\n if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) throw new InvalidValueError(`${key} must be a number from ${min} to ${max}`)\n }\n if (patch.label !== undefined && patch.label.trim() === '') throw new InvalidValueError('a relationship needs a label')\n}\n\nexport class SqliteRelationshipRepository implements RelationshipRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n upsert(fromId: CharacterId, toId: CharacterId, patch: RelationshipPatch, turn: number): Relationship {\n if (fromId === toId) throw new InvalidValueError('a character has no relationship with itself')\n checked(patch)\n return guard(() => this.db.transaction(() => {\n const current = this.get(fromId, toId)\n if (current === undefined) {\n if (patch.label === undefined) throw new InvalidValueError('a new relationship needs a label')\n this.db.run(\n 'INSERT INTO relationships (from_id, to_id, label, summary, familiarity, trust, affinity, tension, updated_turn, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [fromId, toId, patch.label.trim(), (patch.summary ?? '').trim(), patch.familiarity ?? 0, patch.trust ?? 0, patch.affinity ?? 0, patch.tension ?? 0, turn, this.clock().toISOString()],\n )\n } else {\n this.db.run('UPDATE relationships SET label = ?, summary = ?, familiarity = ?, trust = ?, affinity = ?, tension = ?, updated_turn = ? WHERE id = ?', [\n (patch.label ?? current.label).trim(), (patch.summary ?? current.summary).trim(), patch.familiarity ?? current.familiarity, patch.trust ?? current.trust,\n patch.affinity ?? current.affinity, patch.tension ?? current.tension, turn, current.id,\n ])\n }\n return this.get(fromId, toId)!\n }))\n }\n\n get(fromId: CharacterId, toId: CharacterId): Relationship | undefined {\n const row = this.db.get<RelationshipRow>('SELECT * FROM relationships WHERE from_id = ? AND to_id = ?', [fromId, toId])\n return row === undefined ? undefined : toRelationship(row)\n }\n\n from(characterId: CharacterId): Relationship[] {\n return this.db.all<RelationshipRow>('SELECT * FROM relationships WHERE from_id = ? ORDER BY id', [characterId]).map(toRelationship)\n }\n\n to(characterId: CharacterId): Relationship[] {\n return this.db.all<RelationshipRow>('SELECT * FROM relationships WHERE to_id = ? ORDER BY id', [characterId]).map(toRelationship)\n }\n\n list(): Relationship[] {\n return this.db.all<RelationshipRow>('SELECT * FROM relationships ORDER BY id').map(toRelationship)\n }\n\n remove(fromId: CharacterId, toId: CharacterId): boolean {\n return this.db.run('DELETE FROM relationships WHERE from_id = ? AND to_id = ?', [fromId, toId]).changes > 0\n }\n}\n\nexport class SqliteConsolidationRepository implements ConsolidationRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n enqueue(item: { kind: ConsolidationKind; subjectId: number; note: string; turn: number }): ConsolidationItem {\n const { lastInsertRowid } = this.db.run('INSERT INTO consolidation_items (kind, subject_id, note, created_turn) VALUES (?, ?, ?, ?)', [item.kind, item.subjectId, item.note.trim(), item.turn])\n return this.require(Number(lastInsertRowid))\n }\n\n get(id: ConsolidationItemId): ConsolidationItem | undefined {\n const row = this.db.get<ItemRow>('SELECT * FROM consolidation_items WHERE id = ?', [id])\n return row === undefined ? undefined : toItem(row)\n }\n\n pending(): ConsolidationItem[] {\n return this.db.all<ItemRow>('SELECT * FROM consolidation_items WHERE resolved_turn IS NULL ORDER BY id').map(toItem)\n }\n\n createdIn(turn: number): ConsolidationItem[] {\n return this.db.all<ItemRow>('SELECT * FROM consolidation_items WHERE created_turn = ? ORDER BY id', [turn]).map(toItem)\n }\n\n resolve(id: ConsolidationItemId, turn: number, resolution: string): ConsolidationItem {\n const current = this.require(id)\n if (current.resolvedTurn !== undefined) return current\n this.db.run('UPDATE consolidation_items SET resolved_turn = ?, resolution = ? WHERE id = ?', [turn, resolution.trim(), id])\n return this.require(id)\n }\n\n private require(id: ConsolidationItemId): ConsolidationItem {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`consolidation item ${id} does not exist`)\n return found\n }\n}\n","import {\n EXIT_STATES, MAX_LOCATION_FEATURES,\n type Exit, type ExitId, type ExitPatch, type ExitState, type Location, type LocationFeature, type LocationId, type LocationPatch, type NewExit, type NewLocation, type NewPlacement, type PlaceableKind, type Placement,\n} from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, CorruptDataError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { LocationRepository, PlacementRepository } from '../repositories.ts'\nimport { guard, toJson } from './support.ts'\n\ninterface LocationRow {\n id: number\n source_id: string | null\n name: string\n description: string\n parent_id: number | null\n features: string\n created_at: string\n}\n\ninterface ExitRow {\n id: number\n from_id: number\n to_id: number\n description: string\n travel_seconds: number | null\n state: ExitState\n note: string\n}\n\ninterface PlacementRow {\n kind: PlaceableKind\n entity_id: number\n location_id: number\n position: string\n feature_key: string | null\n}\n\nconst FEATURE_KEY = /^[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,59}$/u\n\nfunction parseFeatures(text: string): LocationFeature[] {\n try {\n const value: unknown = JSON.parse(text)\n if (Array.isArray(value) && value.every(entry => typeof entry === 'object' && entry !== null && typeof (entry as LocationFeature).key === 'string' && typeof (entry as LocationFeature).name === 'string' && typeof (entry as LocationFeature).description === 'string')) return value as LocationFeature[]\n } catch {\n // reported below\n }\n throw new CorruptDataError('locations.features does not hold a list of features')\n}\n\n/** The features, or why they are not acceptable. */\nfunction checkedFeatures(features: readonly LocationFeature[]): LocationFeature[] {\n if (features.length > MAX_LOCATION_FEATURES) throw new InvalidValueError(`a place has at most ${MAX_LOCATION_FEATURES} features`)\n const seen = new Set<string>()\n return features.map((feature) => {\n if (!FEATURE_KEY.test(feature.key)) throw new InvalidValueError(`feature key \"${feature.key}\" must be letters, digits, \"-\" or \"_\"`)\n if (seen.has(feature.key)) throw new ConflictError(`feature key \"${feature.key}\" is used twice`)\n seen.add(feature.key)\n if (feature.name.trim() === '') throw new InvalidValueError(`feature \"${feature.key}\" needs a name`)\n return { key: feature.key, name: feature.name.trim(), description: feature.description.trim() }\n })\n}\n\nconst toLocation = (row: LocationRow): Location => ({\n id: row.id,\n ...(row.source_id === null ? {} : { sourceId: row.source_id }),\n name: row.name,\n description: row.description,\n ...(row.parent_id === null ? {} : { parentId: row.parent_id }),\n features: parseFeatures(row.features),\n createdAt: row.created_at,\n})\n\nconst toExit = (row: ExitRow): Exit => ({\n id: row.id,\n fromId: row.from_id,\n toId: row.to_id,\n description: row.description,\n ...(row.travel_seconds === null ? {} : { travelSeconds: row.travel_seconds }),\n state: row.state,\n note: row.note,\n})\n\nconst toPlacement = (row: PlacementRow): Placement => ({\n kind: row.kind,\n entityId: row.entity_id,\n locationId: row.location_id,\n position: row.position,\n ...(row.feature_key === null ? {} : { featureKey: row.feature_key }),\n})\n\nexport class SqliteLocationRepository implements LocationRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly clock: Clock,\n /** Told when a place is renamed, so that what is indexed by its name can follow. */\n private readonly renamed: (id: LocationId) => void = () => undefined,\n ) {}\n\n add(location: NewLocation): Location {\n if (location.name.trim() === '') throw new InvalidValueError('a place needs a name')\n const features = checkedFeatures(location.features)\n return guard(() => {\n if (location.parentId !== undefined && this.get(location.parentId) === undefined) throw new NotFoundError(`the parent place ${location.parentId} does not exist`)\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO locations (source_id, name, description, parent_id, features, created_at) VALUES (?, ?, ?, ?, ?, ?)',\n [location.sourceId ?? null, location.name.trim(), location.description.trim(), location.parentId ?? null, toJson(features), this.clock().toISOString()],\n )\n return this.require(Number(lastInsertRowid))\n })\n }\n\n get(id: LocationId): Location | undefined {\n const row = this.db.get<LocationRow>('SELECT * FROM locations WHERE id = ?', [id])\n return row === undefined ? undefined : toLocation(row)\n }\n\n getBySourceId(sourceId: string): Location | undefined {\n const row = this.db.get<LocationRow>('SELECT * FROM locations WHERE source_id = ?', [sourceId])\n return row === undefined ? undefined : toLocation(row)\n }\n\n list(): Location[] {\n return this.db.all<LocationRow>('SELECT * FROM locations ORDER BY id').map(toLocation)\n }\n\n childrenOf(id: LocationId): Location[] {\n return this.db.all<LocationRow>('SELECT * FROM locations WHERE parent_id = ? ORDER BY id', [id]).map(toLocation)\n }\n\n update(id: LocationId, patch: LocationPatch): Location {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const name = patch.name === undefined ? current.name : patch.name.trim()\n if (name === '') throw new InvalidValueError('a place needs a name')\n const features = patch.features === undefined ? current.features : checkedFeatures(patch.features)\n const removed = current.features.filter(feature => !features.some(kept => kept.key === feature.key))\n for (const feature of removed) {\n const standing = this.db.get('SELECT 1 FROM placements WHERE location_id = ? AND feature_key = ?', [id, feature.key])\n if (standing !== undefined) throw new ConflictError(`feature \"${feature.key}\" cannot be removed while someone is at it`)\n }\n const parentId = patch.parentId === undefined ? current.parentId ?? null : patch.parentId\n if (parentId !== null && parentId !== (current.parentId ?? null)) {\n if (this.get(parentId) === undefined) throw new NotFoundError(`the parent place ${parentId} does not exist`)\n for (let ancestor: number | null = parentId; ancestor !== null; ancestor = this.get(ancestor)?.parentId ?? null) {\n if (ancestor === id) throw new InvalidValueError(`${current.name} cannot be inside itself or a place within it`)\n }\n }\n this.db.run('UPDATE locations SET name = ?, description = ?, features = ?, parent_id = ? WHERE id = ?', [name, (patch.description ?? current.description).trim(), toJson(features), parentId, id])\n if (name !== current.name) this.renamed(id)\n return this.require(id)\n }))\n }\n\n addExit(exit: NewExit): Exit {\n return guard(() => {\n if (this.get(exit.fromId) === undefined) throw new NotFoundError(`place ${exit.fromId} does not exist`)\n if (this.get(exit.toId) === undefined) throw new NotFoundError(`place ${exit.toId} does not exist`)\n if (exit.fromId === exit.toId) throw new InvalidValueError('an exit must lead to another place')\n if (exit.state !== undefined && !EXIT_STATES.includes(exit.state)) throw new InvalidValueError(`unknown exit state \"${String(exit.state)}\"`)\n if (exit.travelSeconds !== undefined && (!Number.isInteger(exit.travelSeconds) || exit.travelSeconds < 0)) throw new InvalidValueError('travel time must be a whole number of seconds')\n const { lastInsertRowid } = this.db.run(\n 'INSERT INTO exits (from_id, to_id, description, travel_seconds, state, note) VALUES (?, ?, ?, ?, ?, ?)',\n [exit.fromId, exit.toId, exit.description.trim(), exit.travelSeconds ?? null, exit.state ?? 'open', (exit.note ?? '').trim()],\n )\n return this.requireExit(Number(lastInsertRowid))\n })\n }\n\n getExit(fromId: LocationId, toId: LocationId): Exit | undefined {\n const row = this.db.get<ExitRow>('SELECT * FROM exits WHERE from_id = ? AND to_id = ?', [fromId, toId])\n return row === undefined ? undefined : toExit(row)\n }\n\n exitsFrom(id: LocationId): Exit[] {\n return this.db.all<ExitRow>('SELECT * FROM exits WHERE from_id = ? ORDER BY id', [id]).map(toExit)\n }\n\n allExits(): Exit[] {\n return this.db.all<ExitRow>('SELECT * FROM exits ORDER BY id').map(toExit)\n }\n\n updateExit(id: ExitId, patch: ExitPatch): Exit {\n return guard(() => {\n const current = this.requireExit(id)\n if (patch.state !== undefined && !EXIT_STATES.includes(patch.state)) throw new InvalidValueError(`unknown exit state \"${String(patch.state)}\"`)\n if (patch.travelSeconds !== undefined && patch.travelSeconds !== null && (!Number.isInteger(patch.travelSeconds) || patch.travelSeconds < 0)) throw new InvalidValueError('travel time must be a whole number of seconds')\n this.db.run('UPDATE exits SET description = ?, travel_seconds = ?, state = ?, note = ? WHERE id = ?', [\n (patch.description ?? current.description).trim(), patch.travelSeconds === undefined ? current.travelSeconds ?? null : patch.travelSeconds, patch.state ?? current.state, (patch.note ?? current.note).trim(), id,\n ])\n return this.requireExit(id)\n })\n }\n\n removeExit(id: ExitId): boolean {\n return this.db.run('DELETE FROM exits WHERE id = ?', [id]).changes > 0\n }\n\n private require(id: LocationId): Location {\n const found = this.get(id)\n if (found === undefined) throw new NotFoundError(`place ${id} does not exist`)\n return found\n }\n\n private requireExit(id: ExitId): Exit {\n const row = this.db.get<ExitRow>('SELECT * FROM exits WHERE id = ?', [id])\n if (row === undefined) throw new NotFoundError(`exit ${id} does not exist`)\n return toExit(row)\n }\n}\n\nexport class SqlitePlacementRepository implements PlacementRepository {\n constructor(private readonly db: SqlDatabase, private readonly locations: Pick<LocationRepository, 'get'>) {}\n\n place(kind: PlaceableKind, entityId: number, placement: NewPlacement): Placement {\n return guard(() => this.db.transaction(() => {\n const location = this.locations.get(placement.locationId)\n if (location === undefined) throw new NotFoundError(`place ${placement.locationId} does not exist`)\n if (kind === 'character' && this.db.get('SELECT 1 FROM characters WHERE id = ?', [entityId]) === undefined) throw new NotFoundError(`character ${entityId} does not exist`)\n if (placement.featureKey !== undefined && !location.features.some(feature => feature.key === placement.featureKey)) {\n throw new InvalidValueError(`${location.name} has no feature \"${placement.featureKey}\" (it has: ${location.features.map(feature => feature.key).join(', ') || 'none'})`)\n }\n this.db.run(\n `INSERT INTO placements (kind, entity_id, location_id, position, feature_key) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT (kind, entity_id) DO UPDATE SET location_id = excluded.location_id, position = excluded.position, feature_key = excluded.feature_key`,\n [kind, entityId, placement.locationId, (placement.position ?? '').trim(), placement.featureKey ?? null],\n )\n return this.require(kind, entityId)\n }))\n }\n\n get(kind: PlaceableKind, entityId: number): Placement | undefined {\n const row = this.db.get<PlacementRow>('SELECT * FROM placements WHERE kind = ? AND entity_id = ?', [kind, entityId])\n return row === undefined ? undefined : toPlacement(row)\n }\n\n at(locationId: LocationId, kind?: PlaceableKind): Placement[] {\n const params: SqlValue[] = [locationId]\n if (kind !== undefined) params.push(kind)\n return this.db.all<PlacementRow>(`SELECT * FROM placements WHERE location_id = ?${kind === undefined ? '' : ' AND kind = ?'} ORDER BY kind, entity_id`, params).map(toPlacement)\n }\n\n list(kind?: PlaceableKind): Placement[] {\n return (kind === undefined\n ? this.db.all<PlacementRow>('SELECT * FROM placements ORDER BY kind, entity_id')\n : this.db.all<PlacementRow>('SELECT * FROM placements WHERE kind = ? ORDER BY entity_id', [kind])).map(toPlacement)\n }\n\n private require(kind: PlaceableKind, entityId: number): Placement {\n const found = this.get(kind, entityId)\n if (found === undefined) throw new NotFoundError(`${kind} ${entityId} is not placed`)\n return found\n }\n}\n","import { createRequire } from 'node:module'\n\n/**\n * Where the sqlite-vec extension is, or why it cannot be used here. The package carries a\n * prebuilt binary for each platform it supports; elsewhere there is none, and a session works\n * without vector search.\n */\nexport function vectorExtension(): { path: string } | { error: string } {\n try {\n const { getLoadablePath } = createRequire(import.meta.url)('sqlite-vec') as { getLoadablePath(): string }\n return { path: getLoadablePath() }\n } catch (error) {\n return { error: error instanceof Error ? error.message : String(error) }\n }\n}\n","import type { Character, CharacterControl, CharacterFilter, CharacterId, CharacterPatch, NewCharacter } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { CharacterRepository } from '../repositories.ts'\nimport { guard, lookupKey, parseStringList, toJson } from './support.ts'\n\ninterface CharacterRow {\n id: number\n source_id: string | null\n name: string\n age: string | null\n gender: string | null\n pronouns: string | null\n kind: Character['kind']\n tier: Character['tier']\n role: Character['role']\n control: CharacterControl\n summary: string\n personality: string\n background: string\n appearance: string\n speech_style: string\n speech_examples: string\n voice: string | null\n created_at: string\n}\n\ninterface AliasRow {\n character_id: number\n alias: string\n}\n\nfunction toCharacter(row: CharacterRow, aliases: string[]): Character {\n return {\n id: row.id,\n ...(row.source_id === null ? {} : { sourceId: row.source_id }),\n name: row.name,\n aliases,\n ...(row.age === null ? {} : { age: row.age }),\n ...(row.gender === null ? {} : { gender: row.gender }),\n ...(row.pronouns === null ? {} : { pronouns: row.pronouns }),\n kind: row.kind,\n tier: row.tier,\n role: row.role,\n control: row.control,\n summary: row.summary,\n personality: row.personality,\n background: row.background,\n appearance: row.appearance,\n speech: { style: row.speech_style, examples: parseStringList(row.speech_examples, 'characters.speech_examples') },\n ...(row.voice === null ? {} : { voice: row.voice }),\n createdAt: row.created_at,\n }\n}\n\nexport class SqliteCharacterRepository implements CharacterRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(character: NewCharacter): Character {\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid: id } = this.db.run(\n `INSERT INTO characters (\n source_id, name, name_key, age, gender, pronouns, kind, tier, role, control,\n summary, personality, background, appearance, speech_style, speech_examples, voice, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n character.sourceId ?? null, character.name, lookupKey(character.name),\n character.age ?? null, character.gender ?? null, character.pronouns ?? null,\n character.kind, character.tier, character.role, character.control,\n character.summary, character.personality, character.background, character.appearance,\n character.speech.style, toJson(character.speech.examples), character.voice ?? null, this.clock().toISOString(),\n ],\n )\n const stored = new Set<string>()\n for (const alias of character.aliases) {\n const key = lookupKey(alias)\n if (stored.has(key)) continue\n this.db.run(\n 'INSERT INTO character_aliases (character_id, position, alias, alias_key) VALUES (?, ?, ?, ?)',\n [id, stored.size, alias, key],\n )\n stored.add(key)\n }\n return this.require(id)\n }))\n }\n\n get(id: CharacterId): Character | undefined {\n return this.read('WHERE id = ?', [id])[0]\n }\n\n getBySourceId(sourceId: string): Character | undefined {\n return this.read('WHERE source_id = ?', [sourceId])[0]\n }\n\n list(filter: CharacterFilter = {}): Character[] {\n const conditions: string[] = []\n const params: SqlValue[] = []\n for (const column of ['role', 'tier', 'kind', 'control'] as const) {\n const value = filter[column]\n if (value === undefined) continue\n conditions.push(`${column} = ?`)\n params.push(value)\n }\n return this.read(conditions.length === 0 ? '' : `WHERE ${conditions.join(' AND ')}`, params)\n }\n\n findByName(name: string): Character[] {\n const key = lookupKey(name)\n return this.read(\n 'WHERE name_key = ?1 OR id IN (SELECT character_id FROM character_aliases WHERE alias_key = ?1)',\n [key],\n )\n }\n\n setControl(id: CharacterId, control: CharacterControl): Character {\n return guard(() => this.db.transaction(() => {\n if (this.db.run('UPDATE characters SET control = ? WHERE id = ?', [control, id]).changes === 0) {\n throw new NotFoundError(`character ${id} does not exist`)\n }\n return this.require(id)\n }))\n }\n\n update(id: CharacterId, patch: CharacterPatch): Character {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const next: Character = {\n ...current,\n ...(patch.name === undefined ? {} : { name: patch.name.trim() }),\n ...(patch.aliases === undefined ? {} : { aliases: patch.aliases }),\n ...(patch.kind === undefined ? {} : { kind: patch.kind }),\n ...(patch.tier === undefined ? {} : { tier: patch.tier }),\n ...(patch.role === undefined ? {} : { role: patch.role }),\n ...(patch.summary === undefined ? {} : { summary: patch.summary }),\n ...(patch.personality === undefined ? {} : { personality: patch.personality }),\n ...(patch.background === undefined ? {} : { background: patch.background }),\n ...(patch.appearance === undefined ? {} : { appearance: patch.appearance }),\n ...(patch.speech === undefined ? {} : { speech: patch.speech }),\n }\n if (patch.voice !== undefined) { if (patch.voice === null || patch.voice.trim() === '') delete next.voice; else next.voice = patch.voice.trim() }\n for (const field of ['age', 'gender', 'pronouns'] as const) {\n const value = patch[field]\n if (value === undefined) continue\n const text = value?.trim()\n if (text === undefined || text === '') delete next[field]\n else next[field] = text\n }\n if (next.name === '') throw new InvalidValueError('a character needs a name')\n if (next.role === 'playable' && (next.kind === 'group' || next.tier === 'background')) throw new InvalidValueError('a playable character cannot be a group or a background character')\n this.db.run(\n `UPDATE characters SET name = ?, name_key = ?, age = ?, gender = ?, pronouns = ?, kind = ?, tier = ?, role = ?, summary = ?, personality = ?, background = ?, appearance = ?, speech_style = ?, speech_examples = ?, voice = ? WHERE id = ?`,\n [next.name, lookupKey(next.name), next.age ?? null, next.gender ?? null, next.pronouns ?? null, next.kind, next.tier, next.role, next.summary, next.personality, next.background, next.appearance, next.speech.style, toJson(next.speech.examples), next.voice ?? null, id],\n )\n if (patch.aliases !== undefined) {\n this.db.run('DELETE FROM character_aliases WHERE character_id = ?', [id])\n const stored = new Set<string>()\n for (const alias of patch.aliases.map(entry => entry.trim()).filter(entry => entry !== '')) {\n const key = lookupKey(alias)\n if (stored.has(key)) continue\n this.db.run('INSERT INTO character_aliases (character_id, position, alias, alias_key) VALUES (?, ?, ?, ?)', [id, stored.size, alias, key])\n stored.add(key)\n }\n }\n return this.require(id)\n }))\n }\n\n private require(id: CharacterId): Character {\n const character = this.get(id)\n if (character === undefined) throw new NotFoundError(`character ${id} does not exist`)\n return character\n }\n\n private read(where: string, params: readonly SqlValue[]): Character[] {\n const rows = this.db.all<CharacterRow>(`SELECT * FROM characters ${where} ORDER BY id`, params)\n if (rows.length === 0) return []\n const aliases = new Map<number, string[]>()\n for (const row of this.db.all<AliasRow>(\n `SELECT character_id, alias FROM character_aliases\n WHERE character_id IN (SELECT id FROM characters ${where}) ORDER BY character_id, position`,\n params,\n )) {\n aliases.set(row.character_id, [...aliases.get(row.character_id) ?? [], row.alias])\n }\n return rows.map(row => toCharacter(row, aliases.get(row.id) ?? []))\n }\n}\n","import type { CharacterId, CharacterIntent, Intent, IntentFilter, IntentId, IntentPatch } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { IntentRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface IntentRow {\n id: number\n character_id: number\n type: Intent['type']\n name: string\n description: string\n status: Intent['status']\n horizon: Intent['horizon']\n priority: number\n urgency: number\n plan: string\n open_threads: string\n constraints: string\n deadline: string | null\n created_at: string\n updated_at: string\n}\n\nfunction toIntent(row: IntentRow): CharacterIntent {\n return {\n id: row.id,\n characterId: row.character_id,\n type: row.type,\n name: row.name,\n description: row.description,\n status: row.status,\n horizon: row.horizon,\n priority: row.priority,\n urgency: row.urgency,\n plan: parseStringList(row.plan, 'intents.plan'),\n openThreads: parseStringList(row.open_threads, 'intents.open_threads'),\n constraints: parseStringList(row.constraints, 'intents.constraints'),\n ...(row.deadline === null ? {} : { deadline: row.deadline }),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n }\n}\n\nexport class SqliteIntentRepository implements IntentRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(characterId: CharacterId, intent: Intent): CharacterIntent {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) {\n throw new NotFoundError(`character ${characterId} does not exist`)\n }\n const now = this.clock().toISOString()\n const { lastInsertRowid } = this.db.run(\n `INSERT INTO intents (\n character_id, type, name, description, status, horizon, priority, urgency,\n plan, open_threads, constraints, deadline, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n characterId, intent.type, intent.name, intent.description, intent.status, intent.horizon,\n intent.priority, intent.urgency, toJson(intent.plan), toJson(intent.openThreads), toJson(intent.constraints),\n intent.deadline ?? null, now, now,\n ],\n )\n return this.require(lastInsertRowid)\n }))\n }\n\n get(id: IntentId): CharacterIntent | undefined {\n const row = this.db.get<IntentRow>('SELECT * FROM intents WHERE id = ?', [id])\n return row === undefined ? undefined : toIntent(row)\n }\n\n list(characterId: CharacterId, filter: IntentFilter = {}): CharacterIntent[] {\n const params: SqlValue[] = [characterId]\n let where = 'character_id = ?'\n if (filter.status !== undefined) {\n where += ' AND status = ?'\n params.push(filter.status)\n }\n return this.db.all<IntentRow>(`SELECT * FROM intents WHERE ${where} ORDER BY id`, params).map(toIntent)\n }\n\n update(id: IntentId, patch: IntentPatch): CharacterIntent {\n return guard(() => this.db.transaction(() => {\n const current = this.require(id)\n const deadline = patch.deadline === undefined ? current.deadline ?? null : patch.deadline\n this.db.run(\n `UPDATE intents SET type = ?, name = ?, description = ?, status = ?, horizon = ?, priority = ?, urgency = ?,\n plan = ?, open_threads = ?, constraints = ?, deadline = ?, updated_at = ?\n WHERE id = ?`,\n [\n patch.type ?? current.type, patch.name ?? current.name, patch.description ?? current.description,\n patch.status ?? current.status, patch.horizon ?? current.horizon,\n patch.priority ?? current.priority, patch.urgency ?? current.urgency,\n toJson(patch.plan ?? current.plan), toJson(patch.openThreads ?? current.openThreads),\n toJson(patch.constraints ?? current.constraints), deadline, this.clock().toISOString(), id,\n ],\n )\n return this.require(id)\n }))\n }\n\n remove(id: IntentId): boolean {\n return this.db.run('DELETE FROM intents WHERE id = ?', [id]).changes > 0\n }\n\n private require(id: IntentId): CharacterIntent {\n const intent = this.get(id)\n if (intent === undefined) throw new NotFoundError(`intent ${id} does not exist`)\n return intent\n }\n}\n","import type { JsonValue, NewSession, SessionMetadata, WorldReference } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, CorruptDataError, NotFoundError } from '../errors.ts'\nimport type { MetadataRepository } from '../repositories.ts'\n\nconst SESSION_ID = 'session.id'\nconst SESSION_NAME = 'session.name'\nconst SESSION_CREATED_AT = 'session.created_at'\nconst SESSION_LAST_PLAYED_AT = 'session.last_played_at'\nconst SESSION_TURNS = 'session.turns'\nconst WORLD = 'world'\nconst RESERVED = new Set([SESSION_ID, SESSION_NAME, SESSION_CREATED_AT, SESSION_LAST_PLAYED_AT, SESSION_TURNS, WORLD])\n\nfunction parseJson(text: string, key: string): JsonValue {\n try {\n return JSON.parse(text) as JsonValue\n } catch (error) {\n throw new CorruptDataError(`metadata \"${key}\" is not valid JSON`, { cause: error })\n }\n}\n\nfunction parseWorld(text: string): WorldReference {\n const value = parseJson(text, WORLD)\n if (typeof value !== 'object' || value === null || Array.isArray(value) || typeof value.id !== 'string' || typeof value.name !== 'string') {\n throw new CorruptDataError('metadata \"world\" is not a world reference')\n }\n return value as unknown as WorldReference\n}\n\nexport class SqliteMetadataRepository implements MetadataRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n /** Write the session's identity; only the store does this, once, when the database is created. */\n create(session: NewSession): SessionMetadata {\n if (session.id.trim() === '') throw new RangeError('a session needs an id')\n if (session.name.trim() === '') throw new RangeError('a session needs a name')\n return this.db.transaction(() => {\n if (this.read(SESSION_ID) !== undefined) throw new ConflictError('the session already has metadata')\n this.write(SESSION_ID, session.id)\n this.write(SESSION_NAME, session.name.trim())\n this.write(SESSION_CREATED_AT, this.clock().toISOString())\n this.write(SESSION_TURNS, '0')\n this.write(WORLD, JSON.stringify(session.world))\n return this.get()\n })\n }\n\n get(): SessionMetadata {\n const id = this.read(SESSION_ID)\n const name = this.read(SESSION_NAME)\n const createdAt = this.read(SESSION_CREATED_AT)\n const world = this.read(WORLD)\n if (id === undefined || name === undefined || createdAt === undefined || world === undefined) {\n throw new NotFoundError('the session has no metadata')\n }\n const lastPlayedAt = this.read(SESSION_LAST_PLAYED_AT)\n return {\n id,\n name,\n world: parseWorld(world),\n createdAt,\n ...(lastPlayedAt === undefined ? {} : { lastPlayedAt }),\n turns: this.turns(),\n }\n }\n\n setName(name: string): void {\n if (name.trim() === '') throw new RangeError('a session needs a name')\n this.write(SESSION_NAME, name.trim())\n }\n\n rebrand(id: string, name: string, createdAt?: string): void {\n if (id.trim() === '') throw new RangeError('a session needs an id')\n if (name.trim() === '') throw new RangeError('a session needs a name')\n this.db.transaction(() => {\n this.write(SESSION_ID, id)\n this.write(SESSION_NAME, name.trim())\n this.write(SESSION_CREATED_AT, createdAt ?? this.clock().toISOString())\n })\n }\n\n recordTurn(): SessionMetadata {\n return this.db.transaction(() => {\n this.write(SESSION_TURNS, String(this.turns() + 1))\n this.write(SESSION_LAST_PLAYED_AT, this.clock().toISOString())\n return this.get()\n })\n }\n\n setWorld(world: WorldReference): void {\n this.write(WORLD, JSON.stringify(world))\n }\n\n getValue(key: string): JsonValue | undefined {\n this.assertFree(key)\n const text = this.read(key)\n return text === undefined ? undefined : parseJson(text, key)\n }\n\n setValue(key: string, value: JsonValue): void {\n this.assertFree(key)\n this.write(key, JSON.stringify(value))\n }\n\n deleteValue(key: string): boolean {\n this.assertFree(key)\n return this.db.run('DELETE FROM metadata WHERE key = ?', [key]).changes > 0\n }\n\n private turns(): number {\n const count = Number(this.read(SESSION_TURNS) ?? '0')\n if (!Number.isInteger(count) || count < 0) throw new CorruptDataError('metadata \"session.turns\" is not a count')\n return count\n }\n\n private assertFree(key: string): void {\n if (RESERVED.has(key)) throw new RangeError(`\"${key}\" is reserved for the session`)\n }\n\n private read(key: string): string | undefined {\n return this.db.get<{ value: string }>('SELECT value FROM metadata WHERE key = ?', [key])?.value\n }\n\n private write(key: string, value: string): void {\n this.db.run('INSERT INTO metadata (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value', [key, value])\n }\n}\n","export interface Migration {\n /** Becomes the database's `user_version` once applied. Versions are consecutive from 1. */\n version: number\n sql: string\n}\n\n/**\n * Migrations are applied in order and never edited once released (0.1.0 released\n * versions 1 to 6; tests/sqlite/migrate.spec.ts pins the released ones): a change to the schema\n * is a new entry. Enumerations are spelled out so that a later change to the model\n * cannot alter what an old migration did.\n */\nexport const MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n sql: `\n CREATE TABLE metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE characters (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n name_key TEXT NOT NULL,\n age TEXT,\n gender TEXT,\n pronouns TEXT,\n kind TEXT NOT NULL CHECK (kind IN ('person', 'group')),\n tier TEXT NOT NULL CHECK (tier IN ('principal', 'supporting', 'background')),\n role TEXT NOT NULL CHECK (role IN ('playable', 'npc')),\n control TEXT NOT NULL CHECK (control IN ('player', 'agent')),\n summary TEXT NOT NULL DEFAULT '',\n personality TEXT NOT NULL DEFAULT '',\n background TEXT NOT NULL DEFAULT '',\n appearance TEXT NOT NULL DEFAULT '',\n speech_style TEXT NOT NULL DEFAULT '',\n speech_examples TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX characters_name_key ON characters (name_key);\n\n CREATE TABLE character_aliases (\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n position INTEGER NOT NULL,\n alias TEXT NOT NULL,\n alias_key TEXT NOT NULL,\n PRIMARY KEY (character_id, position),\n UNIQUE (character_id, alias_key)\n ) STRICT;\n CREATE INDEX character_aliases_key ON character_aliases (alias_key);\n\n CREATE TABLE character_state (\n character_id INTEGER PRIMARY KEY REFERENCES characters (id) ON DELETE CASCADE,\n public_state TEXT NOT NULL DEFAULT '',\n inner_state TEXT NOT NULL DEFAULT '',\n activity TEXT NOT NULL DEFAULT '',\n version INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE variable_defs (\n key TEXT PRIMARY KEY,\n ordinal INTEGER NOT NULL,\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n kind TEXT NOT NULL CHECK (kind IN ('number', 'flag', 'choice')),\n subject TEXT NOT NULL CHECK (subject IN ('character', 'item', 'location', 'world')),\n only_keys TEXT NOT NULL DEFAULT '[]',\n min_value REAL,\n max_value REAL,\n is_integer INTEGER NOT NULL DEFAULT 0 CHECK (is_integer IN (0, 1)),\n options TEXT NOT NULL DEFAULT '[]',\n default_value TEXT NOT NULL,\n has_baseline INTEGER NOT NULL DEFAULT 0 CHECK (has_baseline IN (0, 1)),\n visibility TEXT NOT NULL CHECK (visibility IN ('public', 'private', 'hidden')),\n bands TEXT NOT NULL DEFAULT '[]',\n always_shown INTEGER NOT NULL DEFAULT 0 CHECK (always_shown IN (0, 1)),\n builtin INTEGER NOT NULL DEFAULT 0 CHECK (builtin IN (0, 1))\n ) STRICT;\n\n CREATE TABLE variable_values (\n variable TEXT NOT NULL REFERENCES variable_defs (key) ON DELETE CASCADE,\n subject TEXT NOT NULL CHECK (subject IN ('character', 'item', 'location', 'world')),\n subject_id INTEGER NOT NULL,\n value TEXT NOT NULL,\n baseline TEXT,\n updated_turn INTEGER NOT NULL,\n PRIMARY KEY (variable, subject, subject_id)\n ) STRICT;\n CREATE INDEX variable_values_subject ON variable_values (subject, subject_id);\n\n CREATE TABLE intents (\n id INTEGER PRIMARY KEY,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n type TEXT NOT NULL CHECK (type IN ('need', 'obligation', 'quest', 'agenda', 'aspiration', 'relationship', 'habit', 'reaction')),\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n status TEXT NOT NULL CHECK (status IN ('active', 'paused', 'completed', 'failed', 'abandoned')),\n horizon TEXT NOT NULL CHECK (horizon IN ('immediate', 'short', 'day', 'long', 'open_ended')),\n priority REAL NOT NULL CHECK (priority BETWEEN 0 AND 1),\n urgency REAL NOT NULL CHECK (urgency BETWEEN 0 AND 1),\n plan TEXT NOT NULL DEFAULT '[]',\n open_threads TEXT NOT NULL DEFAULT '[]',\n constraints TEXT NOT NULL DEFAULT '[]',\n deadline TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX intents_character ON intents (character_id, status);\n\n CREATE TABLE locations (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n parent_id INTEGER REFERENCES locations (id) ON DELETE RESTRICT,\n features TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX locations_parent ON locations (parent_id);\n\n CREATE TABLE exits (\n id INTEGER PRIMARY KEY,\n from_id INTEGER NOT NULL REFERENCES locations (id) ON DELETE CASCADE,\n to_id INTEGER NOT NULL REFERENCES locations (id) ON DELETE CASCADE,\n description TEXT NOT NULL DEFAULT '',\n travel_seconds INTEGER CHECK (travel_seconds IS NULL OR travel_seconds >= 0),\n state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'locked', 'blocked')),\n note TEXT NOT NULL DEFAULT '',\n UNIQUE (from_id, to_id),\n CHECK (from_id <> to_id)\n ) STRICT;\n\n CREATE TABLE placements (\n kind TEXT NOT NULL CHECK (kind IN ('character')),\n entity_id INTEGER NOT NULL,\n location_id INTEGER NOT NULL REFERENCES locations (id) ON DELETE RESTRICT,\n position TEXT NOT NULL DEFAULT '',\n feature_key TEXT,\n PRIMARY KEY (kind, entity_id)\n ) STRICT;\n CREATE INDEX placements_location ON placements (location_id, kind);\n\n CREATE TABLE relationships (\n id INTEGER PRIMARY KEY,\n from_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n to_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n label TEXT NOT NULL,\n summary TEXT NOT NULL DEFAULT '',\n familiarity REAL NOT NULL DEFAULT 0 CHECK (familiarity BETWEEN 0 AND 1),\n trust REAL NOT NULL DEFAULT 0 CHECK (trust BETWEEN -1 AND 1),\n affinity REAL NOT NULL DEFAULT 0 CHECK (affinity BETWEEN -1 AND 1),\n tension REAL NOT NULL DEFAULT 0 CHECK (tension BETWEEN 0 AND 1),\n updated_turn INTEGER NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE (from_id, to_id),\n CHECK (from_id <> to_id)\n ) STRICT;\n CREATE INDEX relationships_to ON relationships (to_id);\n\n CREATE TABLE consolidation_items (\n id INTEGER PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('character', 'location', 'item')),\n subject_id INTEGER NOT NULL,\n note TEXT NOT NULL DEFAULT '',\n created_turn INTEGER NOT NULL,\n resolved_turn INTEGER,\n resolution TEXT\n ) STRICT;\n CREATE INDEX consolidation_pending ON consolidation_items (resolved_turn, id);\n\n CREATE TABLE clock (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n mode TEXT NOT NULL CHECK (mode IN ('simulated', 'real')),\n now_ms INTEGER NOT NULL\n ) STRICT;\n\n CREATE TABLE time_log (\n id INTEGER PRIMARY KEY,\n turn INTEGER NOT NULL,\n round INTEGER NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('start', 'elapsed', 'real', 'skip', 'resync')),\n from_ms INTEGER NOT NULL,\n to_ms INTEGER NOT NULL,\n reason TEXT NOT NULL DEFAULT ''\n ) STRICT;\n CREATE INDEX time_log_turn ON time_log (turn, round, id);\n\n CREATE TABLE routine_windows (\n id INTEGER PRIMARY KEY,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n ordinal INTEGER NOT NULL,\n days TEXT NOT NULL DEFAULT '[]',\n start_minute INTEGER NOT NULL CHECK (start_minute BETWEEN 0 AND 1439),\n end_minute INTEGER NOT NULL CHECK (end_minute BETWEEN 0 AND 1439 AND end_minute <> start_minute),\n activity TEXT NOT NULL,\n location_id INTEGER REFERENCES locations (id) ON DELETE SET NULL,\n feature_key TEXT,\n position TEXT NOT NULL DEFAULT '',\n interruptible INTEGER NOT NULL DEFAULT 1 CHECK (interruptible IN (0, 1))\n ) STRICT;\n CREATE INDEX routine_windows_character ON routine_windows (character_id, ordinal);\n\n CREATE TABLE engagements (\n id INTEGER PRIMARY KEY,\n title TEXT NOT NULL,\n at_ms INTEGER NOT NULL,\n until_ms INTEGER,\n location_id INTEGER REFERENCES locations (id) ON DELETE SET NULL,\n status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'kept', 'missed', 'cancelled')),\n note TEXT NOT NULL DEFAULT '',\n created_turn INTEGER NOT NULL,\n updated_turn INTEGER NOT NULL\n ) STRICT;\n CREATE INDEX engagements_due ON engagements (status, at_ms);\n CREATE TABLE engagement_participants (\n engagement_id INTEGER NOT NULL REFERENCES engagements (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n PRIMARY KEY (engagement_id, character_id)\n ) STRICT;\n CREATE INDEX engagement_participants_character ON engagement_participants (character_id);\n\n CREATE TABLE slots (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n capacity INTEGER NOT NULL CHECK (capacity >= 1)\n ) STRICT;\n\n CREATE TABLE items (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n quantity INTEGER NOT NULL DEFAULT 1 CHECK (quantity >= 1),\n unique_item INTEGER NOT NULL DEFAULT 0 CHECK (unique_item IN (0, 1)),\n quality TEXT NOT NULL DEFAULT '',\n notable INTEGER NOT NULL DEFAULT 0 CHECK (notable IN (0, 1)),\n hidden INTEGER NOT NULL DEFAULT 0 CHECK (hidden IN (0, 1)),\n wearable_slot TEXT REFERENCES slots (id),\n container_state TEXT CHECK (container_state IS NULL OR container_state IN ('open', 'closed', 'locked')),\n owner_id INTEGER REFERENCES characters (id) ON DELETE SET NULL,\n created_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE item_holdings (\n item_id INTEGER PRIMARY KEY REFERENCES items (id) ON DELETE CASCADE,\n holder_kind TEXT NOT NULL CHECK (holder_kind IN ('location', 'character', 'item')),\n holder_id INTEGER NOT NULL,\n mode TEXT NOT NULL CHECK (mode IN ('at', 'held', 'worn', 'inside')),\n slot TEXT REFERENCES slots (id),\n position TEXT NOT NULL DEFAULT '',\n feature_key TEXT\n ) STRICT;\n CREATE INDEX item_holdings_holder ON item_holdings (holder_kind, holder_id);\n\n CREATE TABLE openers (\n target_kind TEXT NOT NULL CHECK (target_kind IN ('item', 'exit')),\n target_id INTEGER NOT NULL,\n key_item_id INTEGER NOT NULL REFERENCES items (id) ON DELETE CASCADE,\n PRIMARY KEY (target_kind, target_id, key_item_id)\n ) STRICT;\n\n CREATE TABLE events (\n id INTEGER PRIMARY KEY,\n turn INTEGER NOT NULL,\n round INTEGER NOT NULL,\n text TEXT NOT NULL,\n importance INTEGER NOT NULL CHECK (importance BETWEEN 1 AND 5),\n tags TEXT NOT NULL DEFAULT '[]',\n sealed INTEGER NOT NULL DEFAULT 0 CHECK (sealed IN (0, 1)),\n location_id INTEGER REFERENCES locations (id) ON DELETE SET NULL,\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX events_turn ON events (turn, round, id);\n CREATE INDEX events_location ON events (location_id);\n\n CREATE TABLE event_involves (\n event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n PRIMARY KEY (event_id, character_id)\n ) STRICT;\n CREATE INDEX event_involves_character ON event_involves (character_id);\n\n CREATE TABLE event_items (\n event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE CASCADE,\n item_id INTEGER NOT NULL REFERENCES items (id) ON DELETE CASCADE,\n PRIMARY KEY (event_id, item_id)\n ) STRICT;\n\n CREATE TABLE perceptions (\n id INTEGER PRIMARY KEY,\n event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n mode TEXT NOT NULL CHECK (mode IN ('witnessed', 'heard', 'told', 'inferred')),\n content TEXT NOT NULL,\n gist TEXT NOT NULL,\n accuracy TEXT NOT NULL CHECK (accuracy IN ('accurate', 'partial', 'mistaken')),\n recalls INTEGER NOT NULL DEFAULT 0,\n last_recalled_turn INTEGER,\n created_at TEXT NOT NULL,\n UNIQUE (event_id, character_id)\n ) STRICT;\n CREATE INDEX perceptions_character ON perceptions (character_id, event_id);\n\n CREATE TABLE memories (\n id INTEGER PRIMARY KEY,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK (kind IN ('belief', 'relationship', 'knowledge')),\n text TEXT NOT NULL,\n about TEXT NOT NULL DEFAULT '[]',\n importance INTEGER NOT NULL CHECK (importance BETWEEN 1 AND 5),\n turn INTEGER NOT NULL,\n recalls INTEGER NOT NULL DEFAULT 0,\n last_recalled_turn INTEGER,\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX memories_character ON memories (character_id, id);\n\n CREATE TABLE story_threads (\n id INTEGER PRIMARY KEY,\n text TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('open', 'resolved')),\n opened_turn INTEGER NOT NULL,\n resolved_turn INTEGER,\n created_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE summaries (\n id INTEGER PRIMARY KEY,\n level TEXT NOT NULL CHECK (level IN ('digest', 'chapter')),\n from_turn INTEGER NOT NULL,\n to_turn INTEGER NOT NULL,\n text TEXT NOT NULL,\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX summaries_range ON summaries (level, from_turn);\n\n CREATE TABLE recall_items (\n id INTEGER PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('perception', 'memory', 'event')),\n ref_id INTEGER NOT NULL,\n character_id INTEGER NOT NULL DEFAULT 0,\n text TEXT NOT NULL,\n embedded INTEGER NOT NULL DEFAULT 0 CHECK (embedded IN (0, 1)),\n UNIQUE (kind, ref_id)\n ) STRICT;\n CREATE INDEX recall_items_character ON recall_items (character_id, kind);\n CREATE INDEX recall_items_pending ON recall_items (embedded, id);\n\n CREATE VIRTUAL TABLE recall_fts USING fts5(tokens, tokenize = 'unicode61 remove_diacritics 2');\n CREATE VIRTUAL TABLE recall_vocab USING fts5vocab(recall_fts, 'row');\n\n CREATE TABLE pending_commits (\n turn INTEGER NOT NULL,\n round INTEGER NOT NULL,\n payload TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (turn, round)\n ) STRICT;\n\n CREATE TABLE triggers (\n id INTEGER PRIMARY KEY,\n key TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n condition TEXT NOT NULL,\n effects TEXT NOT NULL,\n repeat INTEGER NOT NULL DEFAULT 0 CHECK (repeat IN (0, 1)),\n cooldown_seconds INTEGER,\n chance REAL CHECK (chance IS NULL OR (chance >= 0 AND chance <= 1)),\n priority INTEGER NOT NULL DEFAULT 0,\n expires TEXT,\n announce TEXT,\n status TEXT NOT NULL DEFAULT 'dormant' CHECK (status IN ('dormant', 'fired', 'failed', 'expired')),\n fire_count INTEGER NOT NULL DEFAULT 0,\n last_fired_ms INTEGER,\n last_result INTEGER NOT NULL DEFAULT 0 CHECK (last_result IN (0, 1)),\n problem TEXT,\n origin TEXT NOT NULL CHECK (origin IN ('world', 'story')),\n created_turn INTEGER NOT NULL\n ) STRICT;\n CREATE INDEX triggers_open ON triggers (status, priority DESC, id);\n\n CREATE TABLE trigger_notes (\n id INTEGER PRIMARY KEY,\n trigger_id INTEGER NOT NULL REFERENCES triggers (id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK (kind IN ('beat', 'cue')),\n text TEXT NOT NULL,\n character_ids TEXT NOT NULL DEFAULT '[]',\n turn INTEGER NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'done', 'lapsed'))\n ) STRICT;\n CREATE INDEX trigger_notes_pending ON trigger_notes (status, kind, id);\n `,\n },\n {\n version: 2,\n sql: `\n CREATE TABLE visual_identities (\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('character', 'location', 'item')),\n subject_id INTEGER NOT NULL,\n global_id TEXT UNIQUE,\n description TEXT NOT NULL,\n tags TEXT NOT NULL DEFAULT '[]',\n negative_tags TEXT NOT NULL DEFAULT '[]',\n version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),\n updated_at TEXT NOT NULL,\n PRIMARY KEY (subject_kind, subject_id)\n ) STRICT;\n CREATE INDEX visual_identities_subject ON visual_identities (subject_kind, subject_id);\n `,\n },\n {\n version: 3,\n sql: `\n CREATE TABLE entity_knowledge (\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('location', 'item', 'exit')),\n subject_id INTEGER NOT NULL,\n learned_turn INTEGER NOT NULL,\n last_observed_turn INTEGER,\n PRIMARY KEY (character_id, subject_kind, subject_id)\n ) STRICT;\n CREATE INDEX entity_knowledge_subject ON entity_knowledge (subject_kind, subject_id);\n\n INSERT OR IGNORE INTO entity_knowledge (character_id, subject_kind, subject_id, learned_turn)\n SELECT perceptions.character_id, 'location', events.location_id, events.turn\n FROM perceptions JOIN events ON events.id = perceptions.event_id\n WHERE events.location_id IS NOT NULL;\n INSERT OR IGNORE INTO entity_knowledge (character_id, subject_kind, subject_id, learned_turn)\n SELECT perceptions.character_id, 'item', event_items.item_id, events.turn\n FROM perceptions JOIN events ON events.id = perceptions.event_id JOIN event_items ON event_items.event_id = events.id;\n INSERT OR IGNORE INTO relationships (from_id, to_id, label, summary, familiarity, trust, affinity, tension, updated_turn, created_at)\n SELECT perceptions.character_id, event_involves.character_id, 'acquaintance', '', 0, 0, 0, 0, min(events.turn), min(perceptions.created_at)\n FROM perceptions JOIN events ON events.id = perceptions.event_id JOIN event_involves ON event_involves.event_id = events.id\n WHERE perceptions.character_id <> event_involves.character_id\n GROUP BY perceptions.character_id, event_involves.character_id;\n `,\n },\n {\n version: 4,\n sql: `\n CREATE TABLE factions (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n name TEXT NOT NULL,\n name_key TEXT NOT NULL,\n summary TEXT NOT NULL DEFAULT '',\n description TEXT NOT NULL DEFAULT '',\n values_json TEXT NOT NULL DEFAULT '[]',\n structure TEXT NOT NULL DEFAULT '',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX factions_name_key ON factions (name_key);\n\n CREATE TABLE faction_aliases (\n faction_id INTEGER NOT NULL REFERENCES factions (id) ON DELETE CASCADE,\n position INTEGER NOT NULL,\n alias TEXT NOT NULL,\n alias_key TEXT NOT NULL,\n PRIMARY KEY (faction_id, position),\n UNIQUE (faction_id, alias_key)\n ) STRICT;\n CREATE INDEX faction_aliases_key ON faction_aliases (alias_key);\n\n CREATE TABLE faction_state (\n faction_id INTEGER PRIMARY KEY REFERENCES factions (id) ON DELETE CASCADE,\n public_state TEXT NOT NULL DEFAULT '',\n inner_state TEXT NOT NULL DEFAULT '',\n version INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL\n ) STRICT;\n\n CREATE TABLE faction_memberships (\n faction_id INTEGER NOT NULL REFERENCES factions (id) ON DELETE CASCADE,\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n role TEXT NOT NULL DEFAULT '',\n rank TEXT NOT NULL DEFAULT '',\n status TEXT NOT NULL CHECK (status IN ('active', 'inactive', 'former')),\n is_public INTEGER NOT NULL DEFAULT 1 CHECK (is_public IN (0, 1)),\n commitment REAL NOT NULL DEFAULT 0 CHECK (commitment BETWEEN 0 AND 1),\n joined_turn INTEGER NOT NULL,\n left_turn INTEGER,\n PRIMARY KEY (faction_id, character_id)\n ) STRICT;\n CREATE INDEX faction_memberships_character ON faction_memberships (character_id, status);\n\n CREATE TABLE faction_relationships (\n id INTEGER PRIMARY KEY,\n from_kind TEXT NOT NULL CHECK (from_kind IN ('character', 'faction')),\n from_id INTEGER NOT NULL,\n to_kind TEXT NOT NULL CHECK (to_kind IN ('character', 'faction')),\n to_id INTEGER NOT NULL,\n label TEXT NOT NULL,\n summary TEXT NOT NULL DEFAULT '',\n familiarity REAL NOT NULL DEFAULT 0 CHECK (familiarity BETWEEN 0 AND 1),\n trust REAL NOT NULL DEFAULT 0 CHECK (trust BETWEEN -1 AND 1),\n affinity REAL NOT NULL DEFAULT 0 CHECK (affinity BETWEEN -1 AND 1),\n tension REAL NOT NULL DEFAULT 0 CHECK (tension BETWEEN 0 AND 1),\n updated_turn INTEGER NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE (from_kind, from_id, to_kind, to_id),\n CHECK (from_kind <> to_kind OR from_id <> to_id)\n ) STRICT;\n CREATE INDEX faction_relationships_to ON faction_relationships (to_kind, to_id);\n\n CREATE TABLE faction_intents (\n id INTEGER PRIMARY KEY,\n faction_id INTEGER NOT NULL REFERENCES factions (id) ON DELETE CASCADE,\n type TEXT NOT NULL CHECK (type IN ('need', 'obligation', 'quest', 'agenda', 'aspiration', 'relationship', 'habit', 'reaction')),\n name TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n status TEXT NOT NULL CHECK (status IN ('active', 'paused', 'completed', 'failed', 'abandoned')),\n horizon TEXT NOT NULL CHECK (horizon IN ('immediate', 'short', 'day', 'long', 'open_ended')),\n priority REAL NOT NULL CHECK (priority BETWEEN 0 AND 1),\n urgency REAL NOT NULL CHECK (urgency BETWEEN 0 AND 1),\n plan TEXT NOT NULL DEFAULT '[]',\n open_threads TEXT NOT NULL DEFAULT '[]',\n constraints TEXT NOT NULL DEFAULT '[]',\n deadline TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX faction_intents_faction ON faction_intents (faction_id, status);\n `,\n },\n {\n version: 5,\n sql: `ALTER TABLE characters ADD COLUMN voice TEXT;`,\n },\n {\n version: 6,\n sql: `\n CREATE TABLE lore (\n id INTEGER PRIMARY KEY,\n source_id TEXT UNIQUE,\n title TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('history', 'culture', 'religion', 'politics', 'geography', 'science', 'custom', 'legend', 'other')),\n summary TEXT NOT NULL DEFAULT '',\n body TEXT NOT NULL DEFAULT '',\n starts_at INTEGER,\n ends_at INTEGER,\n sources_json TEXT NOT NULL DEFAULT '[]',\n created_at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE lore_subjects (\n lore_id INTEGER NOT NULL REFERENCES lore (id) ON DELETE CASCADE,\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('character', 'faction', 'location', 'item', 'lore')),\n subject_id INTEGER NOT NULL,\n PRIMARY KEY (lore_id, subject_kind, subject_id)\n ) STRICT;\n CREATE INDEX lore_subjects_subject ON lore_subjects (subject_kind, subject_id);\n CREATE TABLE lore_relations (\n lore_id INTEGER NOT NULL REFERENCES lore (id) ON DELETE CASCADE,\n related_lore_id INTEGER NOT NULL REFERENCES lore (id) ON DELETE CASCADE,\n PRIMARY KEY (lore_id, related_lore_id),\n CHECK (lore_id <> related_lore_id)\n ) STRICT;\n\n ALTER TABLE entity_knowledge RENAME TO old_entity_knowledge;\n CREATE TABLE entity_knowledge (\n character_id INTEGER NOT NULL REFERENCES characters (id) ON DELETE CASCADE,\n subject_kind TEXT NOT NULL CHECK (subject_kind IN ('location', 'item', 'exit', 'lore')),\n subject_id INTEGER NOT NULL,\n learned_turn INTEGER NOT NULL,\n last_observed_turn INTEGER,\n PRIMARY KEY (character_id, subject_kind, subject_id)\n ) STRICT;\n INSERT INTO entity_knowledge SELECT * FROM old_entity_knowledge;\n DROP TABLE old_entity_knowledge;\n CREATE INDEX entity_knowledge_subject ON entity_knowledge (subject_kind, subject_id);\n `,\n },\n {\n version: 7,\n sql: `\n ALTER TABLE memories ADD COLUMN confidence TEXT NOT NULL DEFAULT 'likely' CHECK (confidence IN ('doubtful', 'likely', 'sure'));\n CREATE TABLE memory_evidence (\n memory_id INTEGER NOT NULL REFERENCES memories (id) ON DELETE CASCADE,\n perception_id INTEGER NOT NULL REFERENCES perceptions (id) ON DELETE CASCADE,\n relation TEXT NOT NULL CHECK (relation IN ('supports', 'contradicts')),\n turn INTEGER NOT NULL,\n PRIMARY KEY (memory_id, perception_id)\n ) STRICT;\n CREATE INDEX memory_evidence_perception ON memory_evidence (perception_id);\n ALTER TABLE routine_windows ADD COLUMN filters TEXT NOT NULL DEFAULT '[]';\n `,\n },\n {\n version: 8,\n sql: `\n CREATE TABLE dice_checks (\n id INTEGER PRIMARY KEY,\n key TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n use_text TEXT NOT NULL,\n definition TEXT NOT NULL\n ) STRICT;\n CREATE TABLE dice_rolls (\n id INTEGER PRIMARY KEY,\n turn INTEGER NOT NULL,\n check_key TEXT,\n expression TEXT NOT NULL,\n faces TEXT NOT NULL,\n kept TEXT NOT NULL,\n modifier INTEGER NOT NULL,\n target INTEGER,\n total INTEGER NOT NULL,\n value INTEGER NOT NULL,\n readout TEXT,\n reason TEXT NOT NULL,\n character TEXT,\n by TEXT NOT NULL CHECK (by IN ('agent', 'player')),\n at TEXT NOT NULL\n ) STRICT;\n CREATE INDEX dice_rolls_turn ON dice_rolls (turn, id);\n `,\n },\n]\n\nexport const LATEST_VERSION = MIGRATIONS[MIGRATIONS.length - 1]?.version ?? 0\n\n/** Marks the file as a roleplay session database (\"DRSS\"). */\nexport const APPLICATION_ID = 0x44525353\n","import type { SqlDatabase } from '../driver/types.ts'\nimport { SchemaError } from '../errors.ts'\nimport { APPLICATION_ID, LATEST_VERSION, MIGRATIONS } from './schema.ts'\n\nexport interface DatabaseState {\n version: number\n applicationId: number\n /** Whether the file holds any tables at all. */\n empty: boolean\n}\n\nexport function inspect(db: SqlDatabase): DatabaseState {\n const version = db.get<{ user_version: number }>('PRAGMA user_version')?.user_version ?? 0\n const applicationId = db.get<{ application_id: number }>('PRAGMA application_id')?.application_id ?? 0\n const tables = db.get<{ count: number }>(\"SELECT count(*) AS count FROM sqlite_master WHERE type = 'table'\")?.count ?? 0\n return { version, applicationId, empty: tables === 0 }\n}\n\n/**\n * Bring the database up to the latest schema, applying each missing migration\n * in its own transaction.\n * @throws {SchemaError} when the file belongs to something else, or was written by a newer version.\n */\nexport function migrate(db: SqlDatabase): void {\n const state = inspect(db)\n if (state.version === 0 && !state.empty) throw new SchemaError('the file is not a session database')\n if (state.version > 0 && state.applicationId !== APPLICATION_ID) throw new SchemaError('the file is not a session database')\n if (state.version > LATEST_VERSION) {\n throw new SchemaError(`the database has schema version ${state.version}, but this version understands up to ${LATEST_VERSION}`)\n }\n for (const migration of MIGRATIONS.filter(candidate => candidate.version > state.version)) {\n db.transaction(() => {\n db.exec(migration.sql)\n if (migration.version === 1) db.exec(`PRAGMA application_id = ${APPLICATION_ID}`)\n db.exec(`PRAGMA user_version = ${migration.version}`)\n })\n }\n}\n","import type { CharacterId, CharacterState, CharacterStatePatch, NewCharacterState } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { ConflictError, NotFoundError } from '../errors.ts'\nimport type { CharacterStateRepository } from '../repositories.ts'\nimport { guard } from './support.ts'\n\ninterface StateRow {\n character_id: number\n public_state: string\n inner_state: string\n activity: string\n version: number\n updated_at: string\n}\n\nfunction toState(row: StateRow): CharacterState {\n return { characterId: row.character_id, publicState: row.public_state, innerState: row.inner_state, activity: row.activity, version: row.version, updatedAt: row.updated_at }\n}\n\nexport class SqliteCharacterStateRepository implements CharacterStateRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n create(characterId: CharacterId, state: NewCharacterState): CharacterState {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) {\n throw new NotFoundError(`character ${characterId} does not exist`)\n }\n this.db.run(\n 'INSERT INTO character_state (character_id, public_state, inner_state, activity, updated_at) VALUES (?, ?, ?, ?, ?)',\n [characterId, state.publicState, state.innerState, state.activity, this.clock().toISOString()],\n )\n return this.require(characterId)\n }))\n }\n\n get(characterId: CharacterId): CharacterState | undefined {\n const row = this.db.get<StateRow>('SELECT * FROM character_state WHERE character_id = ?', [characterId])\n return row === undefined ? undefined : toState(row)\n }\n\n update(characterId: CharacterId, patch: CharacterStatePatch, options: { expectedVersion?: number } = {}): CharacterState {\n return guard(() => this.db.transaction(() => {\n const current = this.require(characterId)\n if (options.expectedVersion !== undefined && current.version !== options.expectedVersion) {\n throw new ConflictError(`the state of character ${characterId} is at version ${current.version}, not ${options.expectedVersion}`)\n }\n if (Object.keys(patch).length === 0) return current\n this.db.run(\n `UPDATE character_state\n SET public_state = ?, inner_state = ?, activity = ?, version = version + 1, updated_at = ?\n WHERE character_id = ?`,\n [\n patch.publicState ?? current.publicState,\n patch.innerState ?? current.innerState,\n patch.activity ?? current.activity,\n this.clock().toISOString(),\n characterId,\n ],\n )\n return this.require(characterId)\n }))\n }\n\n private require(characterId: CharacterId): CharacterState {\n const state = this.get(characterId)\n if (state === undefined) throw new NotFoundError(`character ${characterId} has no state`)\n return state\n }\n}\n","import type { VisualIdentity, VisualIdentityInput, VisualIdentityPatch, VisualSubjectKind } from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { VisualIdentityRepository } from '../repositories.ts'\nimport { guard, parseStringList, toJson } from './support.ts'\n\ninterface VisualIdentityRow {\n subject_kind: VisualSubjectKind\n subject_id: number\n global_id: string | null\n description: string\n tags: string\n negative_tags: string\n version: number\n updated_at: string\n}\n\nconst MAX_DESCRIPTION = 2_000\nconst MAX_TAGS = 40\n\nfunction clean(identity: VisualIdentityInput): VisualIdentityInput {\n const description = identity.description.trim()\n const tags = [...new Set(identity.tags.map(tag => tag.trim()).filter(Boolean))]\n const negativeTags = [...new Set(identity.negativeTags.map(tag => tag.trim()).filter(Boolean))]\n const globalId = identity.globalId?.trim()\n if (description === '') throw new InvalidValueError('a visual identity needs a description')\n if (description.length > MAX_DESCRIPTION) throw new InvalidValueError(`a visual identity description has at most ${MAX_DESCRIPTION} characters`)\n if (tags.length > MAX_TAGS || negativeTags.length > MAX_TAGS) throw new InvalidValueError(`a visual identity has at most ${MAX_TAGS} positive and ${MAX_TAGS} negative tags`)\n if (globalId !== undefined && (globalId === '' || globalId.length > 200)) throw new InvalidValueError('a global visual id must be from 1 to 200 characters')\n return { description, tags, negativeTags, ...(globalId === undefined ? {} : { globalId }) }\n}\n\nfunction fromRow(row: VisualIdentityRow): VisualIdentity {\n return {\n subjectKind: row.subject_kind, subjectId: row.subject_id,\n ...(row.global_id === null ? {} : { globalId: row.global_id }),\n description: row.description, tags: parseStringList(row.tags, 'visual_identities.tags'),\n negativeTags: parseStringList(row.negative_tags, 'visual_identities.negative_tags'),\n version: row.version, updatedAt: row.updated_at,\n }\n}\n\nexport class SqliteVisualIdentityRepository implements VisualIdentityRepository {\n constructor(\n private readonly db: SqlDatabase,\n private readonly clock: Clock,\n private readonly exists: (kind: VisualSubjectKind, id: number) => boolean,\n ) {}\n\n set(subjectKind: VisualSubjectKind, subjectId: number, input: VisualIdentityInput): VisualIdentity {\n if (!this.exists(subjectKind, subjectId)) throw new NotFoundError(`${subjectKind} ${subjectId} does not exist`)\n const identity = clean(input)\n return guard(() => {\n this.db.run(\n `INSERT INTO visual_identities (subject_kind, subject_id, global_id, description, tags, negative_tags, version, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, 1, ?)\n ON CONFLICT (subject_kind, subject_id) DO UPDATE SET\n global_id = excluded.global_id, description = excluded.description, tags = excluded.tags,\n negative_tags = excluded.negative_tags, version = visual_identities.version + 1, updated_at = excluded.updated_at`,\n [subjectKind, subjectId, identity.globalId ?? null, identity.description, toJson(identity.tags), toJson(identity.negativeTags), this.clock().toISOString()],\n )\n return this.require(subjectKind, subjectId)\n })\n }\n\n get(subjectKind: VisualSubjectKind, subjectId: number): VisualIdentity | undefined {\n const row = this.db.get<VisualIdentityRow>('SELECT * FROM visual_identities WHERE subject_kind = ? AND subject_id = ?', [subjectKind, subjectId])\n return row === undefined ? undefined : fromRow(row)\n }\n\n list(subjectKind?: VisualSubjectKind): VisualIdentity[] {\n const rows = subjectKind === undefined\n ? this.db.all<VisualIdentityRow>('SELECT * FROM visual_identities ORDER BY subject_kind, subject_id')\n : this.db.all<VisualIdentityRow>('SELECT * FROM visual_identities WHERE subject_kind = ? ORDER BY subject_id', [subjectKind])\n return rows.map(fromRow)\n }\n\n update(subjectKind: VisualSubjectKind, subjectId: number, patch: VisualIdentityPatch): VisualIdentity {\n const current = this.require(subjectKind, subjectId)\n return this.set(subjectKind, subjectId, {\n description: patch.description ?? current.description,\n tags: patch.tags ?? current.tags,\n negativeTags: patch.negativeTags ?? current.negativeTags,\n ...(patch.globalId === undefined ? current.globalId === undefined ? {} : { globalId: current.globalId } : { globalId: patch.globalId }),\n })\n }\n\n remove(subjectKind: VisualSubjectKind, subjectId: number): boolean {\n return this.db.run('DELETE FROM visual_identities WHERE subject_kind = ? AND subject_id = ?', [subjectKind, subjectId]).changes > 0\n }\n\n private require(subjectKind: VisualSubjectKind, subjectId: number): VisualIdentity {\n const identity = this.get(subjectKind, subjectId)\n if (identity === undefined) throw new NotFoundError(`${subjectKind} ${subjectId} has no visual identity`)\n return identity\n }\n}\n","import type { CharacterId, EntityKnowledge, KnowledgeKind } from 'dsh-roleplay-model'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { KnowledgeRepository } from '../repositories.ts'\n\ninterface Row { character_id: number; subject_kind: KnowledgeKind; subject_id: number; learned_turn: number; last_observed_turn: number | null }\n\nconst fromRow = (row: Row): EntityKnowledge => ({\n characterId: row.character_id, subjectKind: row.subject_kind, subjectId: row.subject_id, learnedTurn: row.learned_turn,\n ...(row.last_observed_turn === null ? {} : { lastObservedTurn: row.last_observed_turn }),\n})\n\nexport class SqliteKnowledgeRepository implements KnowledgeRepository {\n constructor(private readonly db: SqlDatabase) {}\n\n learn(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number, turn: number, observed = false): EntityKnowledge {\n this.requireSubject(characterId, subjectKind, subjectId)\n this.db.run(`INSERT INTO entity_knowledge (character_id, subject_kind, subject_id, learned_turn, last_observed_turn)\n VALUES (?, ?, ?, ?, ?) ON CONFLICT (character_id, subject_kind, subject_id) DO UPDATE SET\n last_observed_turn = CASE WHEN excluded.last_observed_turn IS NULL THEN entity_knowledge.last_observed_turn ELSE excluded.last_observed_turn END`,\n [characterId, subjectKind, subjectId, turn, observed ? turn : null])\n return this.get(characterId, subjectKind, subjectId)!\n }\n\n knows(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number): boolean {\n return this.get(characterId, subjectKind, subjectId) !== undefined\n }\n\n get(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number): EntityKnowledge | undefined {\n const row = this.db.get<Row>('SELECT * FROM entity_knowledge WHERE character_id = ? AND subject_kind = ? AND subject_id = ?', [characterId, subjectKind, subjectId])\n return row === undefined ? undefined : fromRow(row)\n }\n\n list(characterId: CharacterId, subjectKind?: KnowledgeKind): EntityKnowledge[] {\n return this.db.all<Row>(`SELECT * FROM entity_knowledge WHERE character_id = ?${subjectKind === undefined ? '' : ' AND subject_kind = ?'} ORDER BY subject_kind, subject_id`, subjectKind === undefined ? [characterId] : [characterId, subjectKind]).map(fromRow)\n }\n\n forget(characterId: CharacterId, subjectKind: KnowledgeKind, subjectId: number): boolean {\n return this.db.run('DELETE FROM entity_knowledge WHERE character_id = ? AND subject_kind = ? AND subject_id = ?', [characterId, subjectKind, subjectId]).changes > 0\n }\n\n private requireSubject(characterId: CharacterId, kind: KnowledgeKind, id: number): void {\n if (this.db.get('SELECT id FROM characters WHERE id = ?', [characterId]) === undefined) throw new NotFoundError(`character ${characterId} does not exist`)\n const table = kind === 'location' ? 'locations' : kind === 'item' ? 'items' : kind === 'exit' ? 'exits' : 'lore'\n if (this.db.get(`SELECT id FROM ${table} WHERE id = ?`, [id]) === undefined) throw new NotFoundError(`${kind} ${id} does not exist`)\n }\n}\n","import type {\n Faction, FactionId, FactionIntent, FactionMembership, FactionPatch, FactionRelationship, FactionState, FactionStatePatch,\n Intent, IntentFilter, IntentPatch, MembershipPatch, MembershipStatus, NewFaction, NewFactionState, RelationshipPatch, SocialSubjectKind,\n} from 'dsh-roleplay-model'\nimport type { Clock } from '../clock.ts'\nimport type { SqlDatabase, SqlValue } from '../driver/types.ts'\nimport { ConflictError, InvalidValueError, NotFoundError } from '../errors.ts'\nimport type { FactionIntentRepository, FactionMembershipRepository, FactionRelationshipRepository, FactionRepository, FactionStateRepository } from '../repositories.ts'\nimport { guard, lookupKey, parseStringList, toJson } from './support.ts'\n\ninterface FactionRow { id: number; source_id: string | null; name: string; summary: string; description: string; values_json: string; structure: string; created_at: string }\ninterface AliasRow { faction_id: number; alias: string }\ninterface StateRow { faction_id: number; public_state: string; inner_state: string; version: number; updated_at: string }\ninterface MembershipRow { faction_id: number; character_id: number; role: string; rank: string; status: MembershipStatus; is_public: number; commitment: number; joined_turn: number; left_turn: number | null }\ninterface RelationshipRow { id: number; from_kind: SocialSubjectKind; from_id: number; to_kind: SocialSubjectKind; to_id: number; label: string; summary: string; familiarity: number; trust: number; affinity: number; tension: number; updated_turn: number; created_at: string }\ninterface IntentRow { id: number; faction_id: number; type: Intent['type']; name: string; description: string; status: Intent['status']; horizon: Intent['horizon']; priority: number; urgency: number; plan: string; open_threads: string; constraints: string; deadline: string | null; created_at: string; updated_at: string }\n\nexport class SqliteFactionRepository implements FactionRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n\n add(faction: NewFaction): Faction {\n return guard(() => this.db.transaction(() => {\n const { lastInsertRowid: id } = this.db.run('INSERT INTO factions (source_id, name, name_key, summary, description, values_json, structure, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [faction.sourceId ?? null, faction.name, lookupKey(faction.name), faction.summary, faction.description, toJson(faction.values), faction.structure, this.clock().toISOString()])\n const stored = new Set<string>()\n for (const alias of faction.aliases) {\n const key = lookupKey(alias)\n if (stored.has(key)) continue\n this.db.run('INSERT INTO faction_aliases (faction_id, position, alias, alias_key) VALUES (?, ?, ?, ?)', [id, stored.size, alias, key])\n stored.add(key)\n }\n return this.get(Number(id))!\n }))\n }\n\n get(id: FactionId): Faction | undefined { return this.read('WHERE id = ?', [id])[0] }\n getBySourceId(sourceId: string): Faction | undefined { return this.read('WHERE source_id = ?', [sourceId])[0] }\n list(): Faction[] { return this.read('', []) }\n findByName(name: string): Faction[] { return this.read('WHERE name_key = ?1 OR id IN (SELECT faction_id FROM faction_aliases WHERE alias_key = ?1)', [lookupKey(name)]) }\n update(id: FactionId, patch: FactionPatch): Faction {\n const current = this.get(id)\n if (current === undefined) throw new NotFoundError(`faction ${id} does not exist`)\n return guard(() => this.db.transaction(() => {\n const name = patch.name?.trim() ?? current.name\n if (name === '') throw new InvalidValueError('a faction needs a name')\n this.db.run('UPDATE factions SET name = ?, name_key = ?, summary = ?, description = ?, values_json = ?, structure = ? WHERE id = ?', [name, lookupKey(name), patch.summary ?? current.summary, patch.description ?? current.description, toJson(patch.values ?? current.values), patch.structure ?? current.structure, id])\n if (patch.aliases !== undefined) {\n this.db.run('DELETE FROM faction_aliases WHERE faction_id = ?', [id])\n const stored = new Set<string>()\n for (const alias of patch.aliases.map(value => value.trim()).filter(Boolean)) {\n const key = lookupKey(alias)\n if (stored.has(key) || key === lookupKey(name)) continue\n this.db.run('INSERT INTO faction_aliases (faction_id, position, alias, alias_key) VALUES (?, ?, ?, ?)', [id, stored.size, alias, key])\n stored.add(key)\n }\n }\n return this.get(id)!\n }))\n }\n\n private read(where: string, params: readonly SqlValue[]): Faction[] {\n const rows = this.db.all<FactionRow>(`SELECT * FROM factions ${where} ORDER BY id`, params)\n const aliases = new Map<number, string[]>()\n for (const row of this.db.all<AliasRow>(`SELECT faction_id, alias FROM faction_aliases WHERE faction_id IN (SELECT id FROM factions ${where}) ORDER BY faction_id, position`, params)) aliases.set(row.faction_id, [...aliases.get(row.faction_id) ?? [], row.alias])\n return rows.map(row => ({ id: row.id, ...(row.source_id === null ? {} : { sourceId: row.source_id }), name: row.name, aliases: aliases.get(row.id) ?? [], summary: row.summary, description: row.description, values: parseStringList(row.values_json, 'factions.values_json'), structure: row.structure, createdAt: row.created_at }))\n }\n}\n\nexport class SqliteFactionStateRepository implements FactionStateRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n create(factionId: FactionId, state: NewFactionState): FactionState {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM factions WHERE id = ?', [factionId]) === undefined) throw new NotFoundError(`faction ${factionId} does not exist`)\n this.db.run('INSERT INTO faction_state (faction_id, public_state, inner_state, updated_at) VALUES (?, ?, ?, ?)', [factionId, state.publicState ?? '', state.innerState ?? '', this.clock().toISOString()])\n return this.get(factionId)!\n }))\n }\n get(factionId: FactionId): FactionState | undefined {\n const row = this.db.get<StateRow>('SELECT * FROM faction_state WHERE faction_id = ?', [factionId])\n return row === undefined ? undefined : { factionId: row.faction_id, publicState: row.public_state, innerState: row.inner_state, version: row.version, updatedAt: row.updated_at }\n }\n update(factionId: FactionId, patch: FactionStatePatch, options: { expectedVersion?: number } = {}): FactionState {\n const current = this.get(factionId)\n if (current === undefined) throw new NotFoundError(`faction ${factionId} has no state`)\n if (options.expectedVersion !== undefined && options.expectedVersion !== current.version) throw new ConflictError(`the state of faction ${factionId} is at version ${current.version}, not ${options.expectedVersion}`)\n if (Object.keys(patch).length === 0) return current\n this.db.run('UPDATE faction_state SET public_state = ?, inner_state = ?, version = version + 1, updated_at = ? WHERE faction_id = ?', [patch.publicState ?? current.publicState, patch.innerState ?? current.innerState, this.clock().toISOString(), factionId])\n return this.get(factionId)!\n }\n}\n\nconst membership = (row: MembershipRow): FactionMembership => ({ factionId: row.faction_id, characterId: row.character_id, role: row.role, rank: row.rank, status: row.status, public: row.is_public === 1, commitment: row.commitment, joinedTurn: row.joined_turn, ...(row.left_turn === null ? {} : { leftTurn: row.left_turn }) })\n\nexport class SqliteFactionMembershipRepository implements FactionMembershipRepository {\n constructor(private readonly db: SqlDatabase) {}\n upsert(factionId: FactionId, characterId: number, patch: MembershipPatch, turn: number): FactionMembership {\n if (patch.commitment !== undefined && (!Number.isFinite(patch.commitment) || patch.commitment < 0 || patch.commitment > 1)) throw new InvalidValueError('commitment must be a number from 0 to 1')\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM factions WHERE id = ?', [factionId]) === undefined) throw new NotFoundError(`faction ${factionId} does not exist`)\n if (this.db.get('SELECT 1 FROM characters WHERE id = ?', [characterId]) === undefined) throw new NotFoundError(`character ${characterId} does not exist`)\n const current = this.get(factionId, characterId)\n if (current === undefined) this.db.run('INSERT INTO faction_memberships (faction_id, character_id, role, rank, status, is_public, commitment, joined_turn, left_turn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [factionId, characterId, patch.role ?? '', patch.rank ?? '', patch.status ?? 'active', patch.public === false ? 0 : 1, patch.commitment ?? 0, turn, patch.leftTurn ?? null])\n else this.db.run('UPDATE faction_memberships SET role = ?, rank = ?, status = ?, is_public = ?, commitment = ?, left_turn = ? WHERE faction_id = ? AND character_id = ?', [patch.role ?? current.role, patch.rank ?? current.rank, patch.status ?? current.status, (patch.public ?? current.public) ? 1 : 0, patch.commitment ?? current.commitment, patch.leftTurn ?? current.leftTurn ?? null, factionId, characterId])\n return this.get(factionId, characterId)!\n }))\n }\n get(factionId: FactionId, characterId: number): FactionMembership | undefined { const row = this.db.get<MembershipRow>('SELECT * FROM faction_memberships WHERE faction_id = ? AND character_id = ?', [factionId, characterId]); return row === undefined ? undefined : membership(row) }\n ofFaction(factionId: FactionId, status?: MembershipStatus): FactionMembership[] { return this.db.all<MembershipRow>(`SELECT * FROM faction_memberships WHERE faction_id = ?${status === undefined ? '' : ' AND status = ?'} ORDER BY character_id`, status === undefined ? [factionId] : [factionId, status]).map(membership) }\n ofCharacter(characterId: number, status?: MembershipStatus): FactionMembership[] { return this.db.all<MembershipRow>(`SELECT * FROM faction_memberships WHERE character_id = ?${status === undefined ? '' : ' AND status = ?'} ORDER BY faction_id`, status === undefined ? [characterId] : [characterId, status]).map(membership) }\n remove(factionId: FactionId, characterId: number): boolean { return this.db.run('DELETE FROM faction_memberships WHERE faction_id = ? AND character_id = ?', [factionId, characterId]).changes > 0 }\n}\n\nconst RANGES = { familiarity: [0, 1], trust: [-1, 1], affinity: [-1, 1], tension: [0, 1] } as const\nconst relationship = (row: RelationshipRow): FactionRelationship => ({ id: row.id, fromKind: row.from_kind, fromId: row.from_id, toKind: row.to_kind, toId: row.to_id, label: row.label, summary: row.summary, familiarity: row.familiarity, trust: row.trust, affinity: row.affinity, tension: row.tension, updatedTurn: row.updated_turn, createdAt: row.created_at })\n\nexport class SqliteFactionRelationshipRepository implements FactionRelationshipRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n upsert(fromKind: SocialSubjectKind, fromId: number, toKind: SocialSubjectKind, toId: number, patch: RelationshipPatch, turn: number): FactionRelationship {\n if (fromKind === toKind && fromId === toId) throw new InvalidValueError('an entity has no relationship with itself')\n for (const [key, [min, max]] of Object.entries(RANGES) as [keyof typeof RANGES, readonly [number, number]][]) { const value = patch[key]; if (value !== undefined && (!Number.isFinite(value) || value < min || value > max)) throw new InvalidValueError(`${key} must be a number from ${min} to ${max}`) }\n if (patch.label !== undefined && patch.label.trim() === '') throw new InvalidValueError('a relationship needs a label')\n return guard(() => this.db.transaction(() => {\n this.requireSubject(fromKind, fromId); this.requireSubject(toKind, toId)\n const current = this.get(fromKind, fromId, toKind, toId)\n if (current === undefined) {\n if (patch.label === undefined) throw new InvalidValueError('a new relationship needs a label')\n this.db.run('INSERT INTO faction_relationships (from_kind, from_id, to_kind, to_id, label, summary, familiarity, trust, affinity, tension, updated_turn, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [fromKind, fromId, toKind, toId, patch.label.trim(), (patch.summary ?? '').trim(), patch.familiarity ?? 0, patch.trust ?? 0, patch.affinity ?? 0, patch.tension ?? 0, turn, this.clock().toISOString()])\n } else this.db.run('UPDATE faction_relationships SET label = ?, summary = ?, familiarity = ?, trust = ?, affinity = ?, tension = ?, updated_turn = ? WHERE id = ?', [(patch.label ?? current.label).trim(), (patch.summary ?? current.summary).trim(), patch.familiarity ?? current.familiarity, patch.trust ?? current.trust, patch.affinity ?? current.affinity, patch.tension ?? current.tension, turn, current.id])\n return this.get(fromKind, fromId, toKind, toId)!\n }))\n }\n get(fromKind: SocialSubjectKind, fromId: number, toKind: SocialSubjectKind, toId: number): FactionRelationship | undefined { const row = this.db.get<RelationshipRow>('SELECT * FROM faction_relationships WHERE from_kind = ? AND from_id = ? AND to_kind = ? AND to_id = ?', [fromKind, fromId, toKind, toId]); return row === undefined ? undefined : relationship(row) }\n from(kind: SocialSubjectKind, id: number): FactionRelationship[] { return this.db.all<RelationshipRow>('SELECT * FROM faction_relationships WHERE from_kind = ? AND from_id = ? ORDER BY id', [kind, id]).map(relationship) }\n to(kind: SocialSubjectKind, id: number): FactionRelationship[] { return this.db.all<RelationshipRow>('SELECT * FROM faction_relationships WHERE to_kind = ? AND to_id = ? ORDER BY id', [kind, id]).map(relationship) }\n list(): FactionRelationship[] { return this.db.all<RelationshipRow>('SELECT * FROM faction_relationships ORDER BY id').map(relationship) }\n remove(fromKind: SocialSubjectKind, fromId: number, toKind: SocialSubjectKind, toId: number): boolean { return this.db.run('DELETE FROM faction_relationships WHERE from_kind = ? AND from_id = ? AND to_kind = ? AND to_id = ?', [fromKind, fromId, toKind, toId]).changes > 0 }\n private requireSubject(kind: SocialSubjectKind, id: number): void { if (this.db.get(`SELECT 1 FROM ${kind === 'character' ? 'characters' : 'factions'} WHERE id = ?`, [id]) === undefined) throw new NotFoundError(`${kind} ${id} does not exist`) }\n}\n\nconst factionIntent = (row: IntentRow): FactionIntent => ({ id: row.id, factionId: row.faction_id, type: row.type, name: row.name, description: row.description, status: row.status, horizon: row.horizon, priority: row.priority, urgency: row.urgency, plan: parseStringList(row.plan, 'faction_intents.plan'), openThreads: parseStringList(row.open_threads, 'faction_intents.open_threads'), constraints: parseStringList(row.constraints, 'faction_intents.constraints'), ...(row.deadline === null ? {} : { deadline: row.deadline }), createdAt: row.created_at, updatedAt: row.updated_at })\n\nexport class SqliteFactionIntentRepository implements FactionIntentRepository {\n constructor(private readonly db: SqlDatabase, private readonly clock: Clock) {}\n add(factionId: FactionId, intent: Intent): FactionIntent {\n return guard(() => this.db.transaction(() => {\n if (this.db.get('SELECT 1 FROM factions WHERE id = ?', [factionId]) === undefined) throw new NotFoundError(`faction ${factionId} does not exist`)\n const now = this.clock().toISOString()\n const { lastInsertRowid } = this.db.run('INSERT INTO faction_intents (faction_id, type, name, description, status, horizon, priority, urgency, plan, open_threads, constraints, deadline, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [factionId, intent.type, intent.name, intent.description, intent.status, intent.horizon, intent.priority, intent.urgency, toJson(intent.plan), toJson(intent.openThreads), toJson(intent.constraints), intent.deadline ?? null, now, now])\n return this.get(Number(lastInsertRowid))!\n }))\n }\n get(id: number): FactionIntent | undefined { const row = this.db.get<IntentRow>('SELECT * FROM faction_intents WHERE id = ?', [id]); return row === undefined ? undefined : factionIntent(row) }\n list(factionId: FactionId, filter: IntentFilter = {}): FactionIntent[] { const params: SqlValue[] = [factionId]; let where = 'faction_id = ?'; if (filter.status !== undefined) { where += ' AND status = ?'; params.push(filter.status) }; return this.db.all<IntentRow>(`SELECT * FROM faction_intents WHERE ${where} ORDER BY id`, params).map(factionIntent) }\n update(id: number, patch: IntentPatch): FactionIntent {\n const current = this.get(id); if (current === undefined) throw new NotFoundError(`faction intent ${id} does not exist`)\n this.db.run('UPDATE faction_intents SET type = ?, name = ?, description = ?, status = ?, horizon = ?, priority = ?, urgency = ?, plan = ?, open_threads = ?, constraints = ?, deadline = ?, updated_at = ? WHERE id = ?', [patch.type ?? current.type, patch.name ?? current.name, patch.description ?? current.description, patch.status ?? current.status, patch.horizon ?? current.horizon, patch.priority ?? current.priority, patch.urgency ?? current.urgency, toJson(patch.plan ?? current.plan), toJson(patch.openThreads ?? current.openThreads), toJson(patch.constraints ?? current.constraints), patch.deadline === undefined ? current.deadline ?? null : patch.deadline, this.clock().toISOString(), id])\n return this.get(id)!\n }\n remove(id: number): boolean { return this.db.run('DELETE FROM faction_intents WHERE id = ?', [id]).changes > 0 }\n}\n","import type { Lore, LoreId, LoreKind, LorePatch, LoreSubject, NewLore } from 'dsh-roleplay-model'\nimport type { SqlDatabase } from '../driver/types.ts'\nimport { NotFoundError } from '../errors.ts'\nimport type { LoreRepository } from '../repositories.ts'\n\ninterface Row { id: number; source_id: string | null; title: string; kind: LoreKind; summary: string; body: string; starts_at: number | null; ends_at: number | null; sources_json: string; created_at: string }\ninterface SubjectRow { subject_kind: LoreSubject['kind']; subject_id: number }\n\nexport class SqliteLoreRepository implements LoreRepository {\n constructor(private readonly db: SqlDatabase, private readonly now: () => string) {}\n\n add(entry: NewLore): Lore {\n return this.db.transaction(() => {\n const result = this.db.run('INSERT INTO lore (source_id, title, kind, summary, body, starts_at, ends_at, sources_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [entry.sourceId ?? null, required(entry.title), entry.kind, entry.summary, entry.body, entry.startsAt ?? null, entry.endsAt ?? null, JSON.stringify(entry.sources), this.now()])\n this.replaceLinks(result.lastInsertRowid, entry.subjects, entry.related)\n return this.get(result.lastInsertRowid)!\n })\n }\n\n get(id: LoreId): Lore | undefined {\n const row = this.db.get<Row>('SELECT * FROM lore WHERE id = ?', [id])\n return row === undefined ? undefined : this.fromRow(row)\n }\n\n getBySourceId(sourceId: string): Lore | undefined {\n const row = this.db.get<Row>('SELECT * FROM lore WHERE source_id = ?', [sourceId])\n return row === undefined ? undefined : this.fromRow(row)\n }\n\n list(): Lore[] { return this.db.all<Row>('SELECT * FROM lore ORDER BY title COLLATE NOCASE, id').map(row => this.fromRow(row)) }\n\n update(id: LoreId, patch: LorePatch): Lore {\n const current = this.get(id)\n if (current === undefined) throw new NotFoundError(`lore ${id} does not exist`)\n const next = { ...current, ...patch, startsAt: patch.startsAt === null ? undefined : patch.startsAt ?? current.startsAt, endsAt: patch.endsAt === null ? undefined : patch.endsAt ?? current.endsAt }\n this.db.transaction(() => {\n this.db.run('UPDATE lore SET title = ?, kind = ?, summary = ?, body = ?, starts_at = ?, ends_at = ?, sources_json = ? WHERE id = ?', [required(next.title), next.kind, next.summary, next.body, next.startsAt ?? null, next.endsAt ?? null, JSON.stringify(next.sources), id])\n if (patch.subjects !== undefined || patch.related !== undefined) this.replaceLinks(id, next.subjects, next.related)\n })\n return this.get(id)!\n }\n\n remove(id: LoreId): boolean { return this.db.run('DELETE FROM lore WHERE id = ?', [id]).changes > 0 }\n\n private replaceLinks(id: number, subjects: readonly LoreSubject[], related: readonly number[]): void {\n this.db.run('DELETE FROM lore_subjects WHERE lore_id = ?', [id]); this.db.run('DELETE FROM lore_relations WHERE lore_id = ?', [id])\n for (const subject of subjects) this.db.run('INSERT INTO lore_subjects (lore_id, subject_kind, subject_id) VALUES (?, ?, ?)', [id, subject.kind, subject.id])\n for (const other of related) this.db.run('INSERT INTO lore_relations (lore_id, related_lore_id) VALUES (?, ?)', [id, other])\n }\n\n private fromRow(row: Row): Lore {\n return { id: row.id, ...(row.source_id === null ? {} : { sourceId: row.source_id }), title: row.title, kind: row.kind, summary: row.summary, body: row.body, ...(row.starts_at === null ? {} : { startsAt: row.starts_at }), ...(row.ends_at === null ? {} : { endsAt: row.ends_at }), subjects: this.db.all<SubjectRow>('SELECT subject_kind, subject_id FROM lore_subjects WHERE lore_id = ? ORDER BY subject_kind, subject_id', [row.id]).map(x => ({ kind: x.subject_kind, id: x.subject_id })), related: this.db.all<{ related_lore_id: number }>('SELECT related_lore_id FROM lore_relations WHERE lore_id = ? ORDER BY related_lore_id', [row.id]).map(x => x.related_lore_id), sources: JSON.parse(row.sources_json) as string[], createdAt: row.created_at }\n }\n}\n\nfunction required(value: string): string { const clean = value.trim(); if (clean === '') throw new RangeError('lore title cannot be blank'); return clean }\n","import { existsSync, mkdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { CharacterId, Move, MovePlan, NewSession, StoryEvent, TriggerNote } from 'dsh-roleplay-model'\nimport { lapseNotes, runTriggers, type TriggerRun, type TriggerRunOptions } from './records/triggers.ts'\nimport { deliverNotes, type Delivery } from './records/deferred.ts'\nimport type { TriggerClock } from './records/trigger-rules.ts'\nimport { moveCharacter, planKnownMove, planMove } from './records/movement.ts'\nimport { systemClock, type Clock } from './clock.ts'\nimport { nodeSqliteDriver } from './driver/node-sqlite.ts'\nimport type { OpenOptions, SqlDatabase, SqlDriver } from './driver/types.ts'\nimport { ConflictError, CorruptDataError, NotFoundError, SchemaError } from './errors.ts'\nimport type {\n ClockRepository, VariableRepository, EngagementRepository, TriggerRepository, DiceRepository, RoutineRepository, CharacterRepository, CharacterStateRepository, EventRepository, IntentRepository, MemoryRepository, MetadataRepository,\n ConsolidationRepository, ItemRepository, KnowledgeRepository, LocationRepository, PendingCommitRepository, RelationshipRepository, PlacementRepository, RecallIndexRepository, SlotRepository, SummaryRepository, ThreadRepository, VectorSupport, VisualIdentityRepository,\n FactionRepository, FactionStateRepository, FactionMembershipRepository, FactionRelationshipRepository, FactionIntentRepository,\n LoreRepository,\n} from './repositories.ts'\nimport { denseScore, finishRecall, recall, recallCandidates, recallPool, type RecallPool, type MemoryPolicy, type RecallCandidate, type RecallEvidence, type RecallQuery, type Recalled } from './memory/recall.ts'\nimport { applyRecordsEdit, type EditResult, type RecordsEdit } from './records/edit.ts'\nimport { readRecords, type RecordsScope, type RecordsView } from './records/read.ts'\nimport { SqliteEventRepository } from './sqlite/event-repository.ts'\nimport { SqliteMemoryRepository } from './sqlite/memory-repository.ts'\nimport { SqlitePendingCommitRepository, SqliteSummaryRepository, SqliteThreadRepository } from './sqlite/narrative-repositories.ts'\nimport { SqliteRecallIndex } from './sqlite/recall-index.ts'\nimport { SqliteEngagementRepository, SqliteRoutineRepository } from './sqlite/agenda-repositories.ts'\nimport { SqliteTriggerRepository } from './sqlite/trigger-repository.ts'\nimport { SqliteDiceRepository } from './sqlite/dice-repository.ts'\nimport { SqliteClockRepository } from './sqlite/clock-repository.ts'\nimport { SqliteVariableRepository } from './sqlite/variable-repository.ts'\nimport { SqliteItemRepository, SqliteSlotRepository } from './sqlite/item-repository.ts'\nimport { SqliteConsolidationRepository, SqliteRelationshipRepository } from './sqlite/relationship-repository.ts'\nimport { SqliteLocationRepository, SqlitePlacementRepository } from './sqlite/location-repository.ts'\nimport { vectorExtension } from './sqlite/vector-extension.ts'\nimport { SqliteCharacterRepository } from './sqlite/character-repository.ts'\nimport { SqliteIntentRepository } from './sqlite/intent-repository.ts'\nimport { SqliteMetadataRepository } from './sqlite/metadata-repository.ts'\nimport { inspect, migrate } from './sqlite/migrate.ts'\nimport { APPLICATION_ID, LATEST_VERSION } from './sqlite/schema.ts'\nimport { SqliteCharacterStateRepository } from './sqlite/state-repository.ts'\nimport { SqliteVisualIdentityRepository } from './sqlite/visual-identity-repository.ts'\nimport { SqliteKnowledgeRepository } from './sqlite/knowledge-repository.ts'\nimport { SqliteFactionIntentRepository, SqliteFactionMembershipRepository, SqliteFactionRelationshipRepository, SqliteFactionRepository, SqliteFactionStateRepository } from './sqlite/faction-repositories.ts'\nimport { SqliteLoreRepository } from './sqlite/lore-repository.ts'\n\nexport interface StoreOptions extends OpenOptions {\n /** Defaults to the driver on Node's built-in SQLite. */\n driver?: SqlDriver\n /** Supplies the time stamped on rows; defaults to the system clock. */\n clock?: Clock\n /** Whether to load the sqlite-vec extension for vector search. On by default; a session works without it when it is missing. */\n vectors?: boolean\n}\n\n/** One session: everything stored about it, reached through repositories. */\nexport interface SessionStore {\n readonly metadata: MetadataRepository\n readonly characters: CharacterRepository\n readonly characterStates: CharacterStateRepository\n readonly factions: FactionRepository\n readonly factionStates: FactionStateRepository\n readonly factionMemberships: FactionMembershipRepository\n readonly factionRelationships: FactionRelationshipRepository\n readonly factionIntents: FactionIntentRepository\n readonly lore: LoreRepository\n readonly intents: IntentRepository\n readonly events: EventRepository\n readonly memories: MemoryRepository\n readonly threads: ThreadRepository\n readonly summaries: SummaryRepository\n readonly pendingCommits: PendingCommitRepository\n readonly locations: LocationRepository\n readonly placements: PlacementRepository\n readonly relationships: RelationshipRepository\n readonly knowledge: KnowledgeRepository\n readonly consolidation: ConsolidationRepository\n readonly slots: SlotRepository\n readonly items: ItemRepository\n readonly visualIdentities: VisualIdentityRepository\n /** The story's own time. */\n readonly clock: ClockRepository\n /** What the story keeps track of: feelings, and whatever the world or the story declares. */\n readonly variables: VariableRepository\n /** The recurring day of each character. */\n readonly routines: RoutineRepository\n /** What characters have committed to, by date. */\n readonly engagements: EngagementRepository\n readonly triggers: TriggerRepository\n readonly dice: DiceRepository\n /** What the session can be searched by: its texts by words, and by meaning once vectors are stored. */\n readonly recallIndex: RecallIndexRepository\n /** Run `fn` atomically across the repositories; see {@link SqlDatabase.transaction}. */\n transaction<T>(fn: () => T): T\n /**\n * What a character is reminded of at this moment: what it took in and believes, chosen by what\n * the situation calls to mind and, with flaky memory, by how much of it is left.\n */\n recall(query: Omit<RecallQuery, 'characters'>, evidence?: RecallEvidence): Recalled[]\n /** The first stage of {@link SessionStore.recall}: retrieve by the cues, the words and the meaning of the moment, fuse, and over-retrieve. */\n recallPool(query: Omit<RecallQuery, 'characters'>, evidence?: Omit<RecallEvidence, 'rerank'>): RecallPool\n /** The last stage: choose the best of a pool, by a reranker's judgement when there is one, and count what is recalled. */\n finishRecall(pool: RecallPool, turn: number, rerank?: ReadonlyMap<string, number>): Recalled[]\n /**\n * What a character is reminded of, using the session's index as well as the cues: texts that match the\n * moment by words, and, when the vector of the moment is given (from the model that made the stored\n * vectors), texts that match it by meaning.\n * @throws {InvalidValueError} when the vector has other dimensions than the stored ones.\n */\n recallStored(query: Omit<RecallQuery, 'characters'>, options?: { queryVector?: readonly number[] }): Recalled[]\n /** What the session's index says about each candidate for a moment: by words, and by meaning when the vector of the moment is given. */\n storedEvidence(query: Omit<RecallQuery, 'characters'>, queryVector?: readonly number[]): Pick<RecallEvidence, 'lexical' | 'dense'>\n /**\n * Look up what happened (not what any character took in) by words and, with a vector, by meaning, best first.\n * The two searches are merged by reciprocal rank, so what ranks well in either comes first.\n */\n searchEvents(search: { text: string; vector?: readonly number[]; limit?: number; fromTurn?: number; toTurn?: number; minImportance?: number; locationId?: number; itemId?: number }): StoryEvent[]\n /** What a character could be reminded of, to be ranked by meaning before {@link recall}. */\n recallCandidates(query: Omit<RecallQuery, 'characters' | 'policy'>): RecallCandidate[]\n /**\n * Change the story's records (state, events and who took them in, beliefs, threads), together or not at all.\n * @throws {InvalidEditError} naming every problem; nothing was written then.\n */\n /** Whether a character can go there, and the way it would take. */\n planMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove>\n /** Plan over only the places and directed exits this character knows. */\n planKnownMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove>\n /** Move a character: its place changes, at the position or feature given. @throws {InvalidMoveError} naming every reason. */\n move(characterId: CharacterId, move: Move): MovePlan\n /** Apply an edit atomically; with `seal`, the events it adds are final at once (otherwise they stay drafts until sealed). */\n edit(edit: RecordsEdit, options?: { seal?: boolean }): EditResult\n /** Read the records back in the form models read them. */\n records(scope?: RecordsScope): RecordsView\n /** Fire the triggers whose conditions just came true, each together with its effects or not at all. */\n runTriggers(options: TriggerRunOptions): TriggerRun\n /** Let go of the beats and cues nobody took up in this many turns. */\n lapseNotes(turn: number, kept: { beats: number; cues: number }): TriggerNote[]\n /** Which of these notes are still to be told, and in what words as the story stands now; the others are withdrawn, with the reason. Nothing is changed. */\n deliverNotes(notes: readonly TriggerNote[], clock: TriggerClock): Delivery\n /** Write a consistent copy of the whole database to `path`, which must not exist. */\n snapshotTo(path: string): void\n close(): void\n}\n\n/** How many hits of each search are weighed when recalling. */\nconst STORED_CANDIDATES = 50\n/** Reciprocal rank fusion: how much the first places count against the later ones. */\nconst RANK_OFFSET = 60\n\nclass SqliteSessionStore implements SessionStore {\n readonly metadata: SqliteMetadataRepository\n readonly characters: CharacterRepository\n readonly characterStates: CharacterStateRepository\n readonly factions: FactionRepository\n readonly factionStates: FactionStateRepository\n readonly factionMemberships: FactionMembershipRepository\n readonly factionRelationships: FactionRelationshipRepository\n readonly factionIntents: FactionIntentRepository\n readonly lore: LoreRepository\n readonly intents: IntentRepository\n readonly events: EventRepository\n readonly memories: MemoryRepository\n readonly threads: ThreadRepository\n readonly summaries: SummaryRepository\n readonly pendingCommits: PendingCommitRepository\n readonly locations: LocationRepository\n readonly placements: PlacementRepository\n readonly relationships: RelationshipRepository\n readonly knowledge: KnowledgeRepository\n readonly consolidation: ConsolidationRepository\n readonly slots: SlotRepository\n readonly items: ItemRepository\n readonly visualIdentities: VisualIdentityRepository\n readonly clock: ClockRepository\n readonly variables: VariableRepository\n readonly routines: RoutineRepository\n readonly engagements: EngagementRepository\n readonly triggers: TriggerRepository\n readonly dice: DiceRepository\n readonly recallIndex: SqliteRecallIndex\n private readonly eventRepository: SqliteEventRepository\n\n constructor(private readonly db: SqlDatabase, clock: Clock, vectors: VectorSupport) {\n this.metadata = new SqliteMetadataRepository(db, clock)\n this.recallIndex = new SqliteRecallIndex(db, this.metadata, vectors)\n this.characters = new SqliteCharacterRepository(db, clock)\n this.characterStates = new SqliteCharacterStateRepository(db, clock)\n this.factions = new SqliteFactionRepository(db, clock)\n this.factionStates = new SqliteFactionStateRepository(db, clock)\n this.factionMemberships = new SqliteFactionMembershipRepository(db)\n this.factionRelationships = new SqliteFactionRelationshipRepository(db, clock)\n this.factionIntents = new SqliteFactionIntentRepository(db, clock)\n this.lore = new SqliteLoreRepository(db, () => clock().toISOString())\n this.intents = new SqliteIntentRepository(db, clock)\n this.locations = new SqliteLocationRepository(db, clock, id => { this.eventRepository.reindexPlace(id) })\n this.placements = new SqlitePlacementRepository(db, this.locations)\n this.relationships = new SqliteRelationshipRepository(db, clock)\n this.knowledge = new SqliteKnowledgeRepository(db)\n this.consolidation = new SqliteConsolidationRepository(db)\n this.slots = new SqliteSlotRepository(db)\n this.items = new SqliteItemRepository(db, clock)\n this.visualIdentities = new SqliteVisualIdentityRepository(db, clock, (kind, id) => (\n kind === 'character' ? this.characters.get(id) !== undefined : kind === 'location' ? this.locations.get(id) !== undefined : this.items.get(id) !== undefined\n ))\n this.clock = new SqliteClockRepository(db)\n this.variables = new SqliteVariableRepository(db)\n this.routines = new SqliteRoutineRepository(db)\n this.engagements = new SqliteEngagementRepository(db)\n this.triggers = new SqliteTriggerRepository(db)\n this.dice = new SqliteDiceRepository(db, clock)\n this.eventRepository = new SqliteEventRepository(db, clock, this.recallIndex, id => this.locations.get(id)?.name, id => this.items.get(id)?.name)\n this.events = this.eventRepository\n this.memories = new SqliteMemoryRepository(db, clock, this.recallIndex)\n this.threads = new SqliteThreadRepository(db, clock)\n this.summaries = new SqliteSummaryRepository(db, clock)\n this.pendingCommits = new SqlitePendingCommitRepository(db, clock)\n }\n\n transaction<T>(fn: () => T): T {\n return this.db.transaction(fn)\n }\n\n recallCandidates(query: Omit<RecallQuery, 'characters' | 'policy'>): RecallCandidate[] {\n return recallCandidates(this, { ...query, characters: this.characters.list() })\n }\n\n recall(query: Omit<RecallQuery, 'characters'>, evidence?: RecallEvidence): Recalled[] {\n return this.finishRecall(this.recallPool(query, evidence), query.turn, evidence?.rerank)\n }\n\n recallPool(query: Omit<RecallQuery, 'characters'>, evidence?: Omit<RecallEvidence, 'rerank'>): RecallPool {\n return recallPool(this, { ...query, characters: this.characters.list() }, evidence)\n }\n\n finishRecall(pool: RecallPool, turn: number, rerank?: ReadonlyMap<string, number>): Recalled[] {\n const found = finishRecall(pool, rerank)\n this.events.touchPerceptions(found.flatMap(entry => (entry.source.kind === 'perception' ? [entry.source.id] : [])), turn)\n this.memories.touch(found.flatMap(entry => (entry.source.kind === 'memory' ? [entry.source.id] : [])), turn)\n return found\n }\n\n storedEvidence(query: Omit<RecallQuery, 'characters'>, queryVector?: readonly number[]): Pick<RecallEvidence, 'lexical' | 'dense'> {\n const found = (hits: { key: string; score: number }[], map: (score: number) => number = score => score): ReadonlyMap<string, number> =>\n new Map(hits.map(hit => [hit.key, map(hit.score)]))\n const lexical = found(this.recallIndex.lexical({ text: query.situation, characterId: query.characterId, kinds: ['perception', 'memory'], limit: STORED_CANDIDATES }))\n const dense = queryVector === undefined ? undefined : found(this.recallIndex.vector({ vector: queryVector, characterId: query.characterId, limit: STORED_CANDIDATES }), denseScore)\n return { lexical, ...(dense === undefined ? {} : { dense }) }\n }\n\n recallStored(query: Omit<RecallQuery, 'characters'>, options: { queryVector?: readonly number[] } = {}): Recalled[] {\n return this.recall(query, this.storedEvidence(query, options.queryVector))\n }\n\n searchEvents({ text, vector, limit = 10, fromTurn, toTurn, minImportance, locationId, itemId }: { text: string; vector?: readonly number[]; limit?: number; fromTurn?: number; toTurn?: number; minImportance?: number; locationId?: number; itemId?: number }): StoryEvent[] {\n const lexical = this.recallIndex.lexical({ text, kinds: ['event'], limit: STORED_CANDIDATES })\n const dense = vector === undefined ? [] : this.recallIndex.vector({ vector, characterId: 0, limit: STORED_CANDIDATES })\n const scores = new Map<number, number>()\n for (const hits of [lexical, dense]) hits.forEach((hit, rank) => { scores.set(hit.refId, (scores.get(hit.refId) ?? 0) + 1 / (RANK_OFFSET + rank)) })\n return [...scores].sort((a, b) => b[1] - a[1]).flatMap(([id]) => {\n const event = this.events.get(id)\n if (event === undefined) return []\n if ((fromTurn !== undefined && event.turn < fromTurn) || (toTurn !== undefined && event.turn > toTurn) || (minImportance !== undefined && event.importance < minImportance) || (locationId !== undefined && event.locationId !== locationId) || (itemId !== undefined && !event.items.includes(itemId))) return []\n return [event]\n }).slice(0, limit)\n }\n\n planMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove> {\n return planMove(this, characterId, move)\n }\n\n planKnownMove(characterId: CharacterId, move: Move): ReturnType<typeof planMove> {\n return planKnownMove(this, characterId, move)\n }\n\n move(characterId: CharacterId, move: Move): MovePlan {\n return this.transaction(() => moveCharacter(this, characterId, move))\n }\n\n edit(edit: RecordsEdit, options: { seal?: boolean } = {}): EditResult {\n return this.transaction(() => {\n const result = applyRecordsEdit(this, edit)\n if (options.seal === true) this.events.seal(result.eventIds)\n return result\n })\n }\n\n records(scope?: RecordsScope): RecordsView {\n return readRecords(this, scope)\n }\n\n runTriggers(options: TriggerRunOptions): TriggerRun {\n return runTriggers(this, options)\n }\n\n deliverNotes(notes: readonly TriggerNote[], clock: TriggerClock): Delivery {\n return deliverNotes(this, notes, clock)\n }\n\n lapseNotes(turn: number, kept: { beats: number; cues: number }): TriggerNote[] {\n return this.transaction(() => lapseNotes(this, turn, kept))\n }\n\n /** Write a consistent copy of the whole database to `path`, which must not exist (`VACUUM INTO`). */\n snapshotTo(path: string): void {\n this.db.run('VACUUM INTO ?', [path])\n }\n\n close(): void {\n this.db.close()\n }\n}\n\n/** Open the database, with the vector extension when there is one; without it the session still works, minus vector search. */\nfunction connect(location: string, options: StoreOptions): { db: SqlDatabase; vectors: VectorSupport } {\n const { driver = nodeSqliteDriver, clock: _clock, vectors: wanted = true, ...open } = options\n if (!wanted) return { db: driver.open(location, open), vectors: { available: false, error: 'switched off' } }\n const extension = vectorExtension()\n if ('error' in extension) return { db: driver.open(location, open), vectors: { available: false, error: extension.error } }\n try {\n return { db: driver.open(location, { ...open, extensions: [extension.path] }), vectors: { available: true } }\n } catch (error) {\n return { db: driver.open(location, open), vectors: { available: false, error: error instanceof Error ? error.message : String(error) } }\n }\n}\n\n/**\n * Create the database of a new session at `location` (the file must not hold a\n * session yet, and its folder must exist).\n * @throws {ConflictError} when the location already holds a session database.\n */\nexport function createSessionStore(location: string, session: NewSession, options: StoreOptions = {}): SessionStore {\n const { db, vectors } = connect(location, options)\n try {\n if (inspect(db).version > 0) throw new ConflictError(`${location} already holds a session database`)\n migrate(db)\n const store = new SqliteSessionStore(db, options.clock ?? systemClock, vectors)\n store.metadata.create(session)\n store.slots.ensureDefaults()\n store.variables.ensureDefaults()\n return store\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n/**\n * Open the database of an existing session, bringing an older schema up to date.\n * @throws {NotFoundError} when there is no file at `location`.\n * @throws {SchemaError} when the file is not a session database, or is from a newer version.\n */\nexport function openSessionStore(location: string, options: StoreOptions = {}): SessionStore {\n if (location !== ':memory:' && !existsSync(location)) throw new NotFoundError(`no session database at ${location}`)\n const { db, vectors } = connect(location, options)\n try {\n const state = inspect(db)\n if (state.version === 0 || state.applicationId !== APPLICATION_ID) throw new SchemaError(`${location} is not a session database`)\n if (state.version < LATEST_VERSION && location !== ':memory:') backUpBeforeMigrating(db, location, state.version)\n migrate(db)\n return new SqliteSessionStore(db, options.clock ?? systemClock, vectors)\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n/** Folder, beside the database, holding the copies made before a schema upgrade. */\nexport const MIGRATION_BACKUP_FOLDER = 'migration-backups'\n\n/** Where the copy of a database as it was at schema `version` is kept. */\nexport function migrationBackupPath(location: string, version: number): string {\n return join(dirname(location), MIGRATION_BACKUP_FOLDER, `schema-${version}.sqlite`)\n}\n\n/**\n * A released session cannot be rebuilt, so an upgrade starts from a copy that passed the integrity check; one copy per old version is kept.\n * @throws {CorruptDataError} when the database is damaged, before anything is changed.\n */\nfunction backUpBeforeMigrating(db: SqlDatabase, location: string, version: number): void {\n const check = db.get<{ quick_check: string }>('PRAGMA quick_check')?.quick_check\n if (check !== 'ok') throw new CorruptDataError(`${location} failed its integrity check, so it was not upgraded: ${check ?? 'no result'}`)\n const target = migrationBackupPath(location, version)\n if (existsSync(target)) return\n mkdirSync(dirname(target), { recursive: true })\n db.run('VACUUM INTO ?', [target])\n}\n\nexport { LATEST_VERSION as SCHEMA_VERSION }\nexport type { MemoryPolicy }\n","import { randomUUID } from 'node:crypto'\nimport { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { NewSession, SessionMetadata } from 'dsh-roleplay-model'\nimport { ConflictError, NotFoundError } from './errors.ts'\nimport { createSessionStore, openSessionStore, type SessionStore, type StoreOptions } from './store.ts'\n\nexport const SESSION_DATABASE_FILE = 'session.sqlite'\n\nconst SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/\n\n/** A new session; its id is generated unless one is given. */\nexport type SessionInit = Omit<NewSession, 'id'> & { id?: string }\n\nexport function isSessionId(value: string): boolean {\n return SESSION_ID.test(value)\n}\n\n/** The id becomes a folder name, so only a UUID v4 is accepted. */\nfunction checked(id: string): string {\n if (!isSessionId(id)) throw new RangeError(`\"${id}\" is not a session id`)\n return id\n}\n\n/** Folder holding everything about one session. */\nexport function sessionFolder(sessionsDir: string, id: string): string {\n return join(sessionsDir, checked(id))\n}\n\nexport function sessionDatabase(sessionsDir: string, id: string): string {\n return join(sessionFolder(sessionsDir, id), SESSION_DATABASE_FILE)\n}\n\n/**\n * Create `<sessionsDir>/<id>/session.sqlite` for a new session. Nothing is\n * left behind when creating the database fails.\n * @throws {ConflictError} when a session with that id already exists.\n */\nexport function createSession(sessionsDir: string, init: SessionInit, options: StoreOptions = {}): SessionStore {\n const id = checked(init.id ?? randomUUID())\n const folder = sessionFolder(sessionsDir, id)\n mkdirSync(sessionsDir, { recursive: true })\n try {\n mkdirSync(folder)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new ConflictError(`session ${id} already exists`, { cause: error })\n throw error\n }\n try {\n return createSessionStore(sessionDatabase(sessionsDir, id), { ...init, id }, options)\n } catch (error) {\n rmSync(folder, { recursive: true, force: true })\n throw error\n }\n}\n\n/** @throws {NotFoundError} when the session does not exist. */\nexport function openSession(sessionsDir: string, id: string, options: StoreOptions = {}): SessionStore {\n return openSessionStore(sessionDatabase(sessionsDir, id), options)\n}\n\n/** Remove a session's folder and everything in it. */\nexport function deleteSession(sessionsDir: string, id: string): void {\n rmSync(sessionFolder(sessionsDir, id), { recursive: true, force: true })\n}\n\n/** The sessions found under a sessions folder, and those that could not be read. */\nexport interface SessionListing {\n sessions: SessionMetadata[]\n problems: { id: string; message: string }[]\n}\n\n/**\n * Read the metadata of every session under `sessionsDir`. Folders that are not\n * named like a session are ignored; a session that cannot be read is reported\n * and left out. Order is not defined.\n * @param reuse - supplies a connection that is already open, so it is not opened twice.\n */\nexport function listSessions(\n sessionsDir: string,\n options: StoreOptions = {},\n reuse?: (id: string) => SessionStore | undefined,\n): SessionListing {\n const listing: SessionListing = { sessions: [], problems: [] }\n let ids: string[]\n try {\n ids = readdirSync(sessionsDir, { withFileTypes: true }).filter(entry => entry.isDirectory() && isSessionId(entry.name)).map(entry => entry.name)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return listing\n throw error\n }\n for (const id of ids) {\n const open = reuse?.(id)\n try {\n const store = open ?? openSession(sessionsDir, id, options)\n try {\n listing.sessions.push(store.metadata.get())\n } finally {\n if (open === undefined) store.close()\n }\n } catch (error) {\n listing.problems.push({ id, message: error instanceof Error ? error.message : String(error) })\n }\n }\n return listing\n}\n\n/** What a copy of a session is made from: a snapshot of it, or its database as it is. */\nexport type ForkSource = { snapshot: string } | { live: Pick<SessionStore, 'snapshotTo'> }\n\nexport interface ForkOptions {\n name: string\n /** The snapshots the copy keeps, besides its database; each must exist. */\n keep: readonly string[]\n}\n\n/**\n * Make a new session from a state of another: a folder of its own with the database, the settings and the named snapshots, and\n * the identity of the new session in place of the old. Nothing is left behind when it fails.\n * @throws {ConflictError} when the new id exists. @throws {NotFoundError} when the snapshot or a kept snapshot does not exist.\n */\nexport function forkSession(sessionsDir: string, fromId: string, toId: string, source: ForkSource, options: ForkOptions, storeOptions: StoreOptions = {}): void {\n const target = sessionFolder(sessionsDir, toId)\n const from = sessionFolder(sessionsDir, fromId)\n const used = 'snapshot' in source ? [source.snapshot] : []\n for (const name of [...options.keep, ...used]) {\n if (!existsSync(snapshotPath(sessionsDir, fromId, name))) throw new NotFoundError(`session ${fromId} has no snapshot \"${name}\"`)\n }\n try {\n mkdirSync(target)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new ConflictError(`session ${toId} already exists`, { cause: error })\n throw error\n }\n try {\n const file = sessionDatabase(sessionsDir, toId)\n if ('snapshot' in source) copyFileSync(snapshotPath(sessionsDir, fromId, source.snapshot), file)\n else source.live.snapshotTo(file)\n if (existsSync(join(from, 'settings.json'))) copyFileSync(join(from, 'settings.json'), join(target, 'settings.json'))\n if (options.keep.length > 0) mkdirSync(join(target, SNAPSHOT_FOLDER))\n for (const name of options.keep) copyFileSync(snapshotPath(sessionsDir, fromId, name), snapshotPath(sessionsDir, toId, name))\n const store = openSessionStore(file, storeOptions)\n try { store.metadata.rebrand(toId, options.name) } finally { store.close() }\n } catch (error) {\n rmSync(target, { recursive: true, force: true })\n throw error\n }\n}\n\nconst SNAPSHOT_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst SNAPSHOT_FOLDER = 'snapshots'\n\n/** The place of a named snapshot of a session's database. @throws {RangeError} for a name that is not lowercase letters, digits and hyphens. */\nexport function snapshotPath(sessionsDir: string, id: string, name: string): string {\n if (!SNAPSHOT_NAME.test(name)) throw new RangeError(`\"${name}\" is not a snapshot name`)\n return join(sessionFolder(sessionsDir, id), SNAPSHOT_FOLDER, `${name}.sqlite`)\n}\n\n/** Take a snapshot of an open session under a name, replacing one of that name; it is written aside and renamed, so a snapshot is never half written. */\nexport function takeSnapshot(sessionsDir: string, id: string, name: string, store: Pick<SessionStore, 'snapshotTo'>): string {\n const target = snapshotPath(sessionsDir, id, name)\n mkdirSync(join(sessionFolder(sessionsDir, id), SNAPSHOT_FOLDER), { recursive: true })\n const aside = `${target}.writing`\n rmSync(aside, { force: true })\n store.snapshotTo(aside)\n renameSync(aside, target)\n return target\n}\n\n/** The names of a session's snapshots. */\nexport function snapshotNames(sessionsDir: string, id: string): string[] {\n try {\n return readdirSync(join(sessionFolder(sessionsDir, id), SNAPSHOT_FOLDER)).filter(file => file.endsWith('.sqlite')).map(file => file.slice(0, -'.sqlite'.length)).sort()\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n}\n\nexport function removeSnapshot(sessionsDir: string, id: string, name: string): void {\n rmSync(snapshotPath(sessionsDir, id, name), { force: true })\n}\n\n/**\n * Put a snapshot in the place of the session's database. The session must not be open (the service\n * closes it first); the copy is made aside and renamed over the database.\n * @throws {NotFoundError} when there is no such snapshot.\n */\nexport function restoreSnapshot(sessionsDir: string, id: string, name: string, storeOptions: StoreOptions = {}): void {\n const source = snapshotPath(sessionsDir, id, name)\n if (!existsSync(source)) throw new NotFoundError(`session ${id} has no snapshot \"${name}\"`)\n const database = sessionDatabase(sessionsDir, id)\n const aside = `${database}.restoring`\n copyFileSync(source, aside)\n for (const sidecar of ['-wal', '-shm', '-journal']) rmSync(`${database}${sidecar}`, { force: true })\n const previous = identityOf(database, storeOptions)\n renameSync(aside, database)\n if (previous !== undefined) {\n const store = openSessionStore(database, storeOptions)\n try { store.metadata.rebrand(previous.id, previous.name, previous.createdAt) } finally { store.close() }\n }\n}\n\n/** The identity the database has now, which a snapshot taken under another id (a fork's parent) must not take away. */\nfunction identityOf(database: string, storeOptions: StoreOptions): { id: string; name: string; createdAt: string } | undefined {\n if (!existsSync(database)) return undefined\n const store = openSessionStore(database, storeOptions)\n try {\n const { id, name, createdAt } = store.metadata.get()\n return { id, name, createdAt }\n } finally { store.close() }\n}\n","import { randomInt } from 'node:crypto'\nimport { DICE_COMPARISONS, DICE_READINGS, DICE_RESULTS, MAX_DICE_BANDS, MAX_DICE_PER_ROLL, MAX_DICE_SIDES, MAX_DICE_TERMS, type DiceBand, type DiceCheckDefinition, type DiceReadout } from 'dsh-roleplay-model'\nimport { InvalidValueError } from '../errors.ts'\n\n/** A die with this many sides shows a number from 1 to `sides`. The system's own source of randomness is the default. */\nexport type Roller = (sides: number) => number\n\nexport const systemRoller: Roller = sides => randomInt(1, sides + 1)\n\ntype KeepMode = 'kh' | 'kl' | 'dh' | 'dl'\n\ntype Term =\n | { sign: 1 | -1; count: number; sides: number; keep?: { mode: KeepMode; n: number } }\n | { sign: 1 | -1; constant: number }\n\nexport interface Notation {\n /** The expression written the same way whatever the spacing and case. */\n text: string\n terms: Term[]\n}\n\nconst TERM = /^(?:(\\d*)d(\\d+|%)(?:(kh|kl|dh|dl)(\\d*))?|(\\d+))$/\n\n/** Reads dice notation: `2d6+1`, `d20`, `4d6kh3`, `d%`, `1d8+1d4-1`. @throws {InvalidValueError} with what is wrong. */\nexport function parseNotation(input: string): Notation {\n const source = input.toLowerCase().replace(/\\s+/g, '')\n if (source === '') throw new InvalidValueError('dice notation is empty: write it like 2d6+1')\n const parts = source.split(/(?=[+-])/)\n if (parts.length > MAX_DICE_TERMS) throw new InvalidValueError(`dice notation has more than ${MAX_DICE_TERMS} terms`)\n const terms = parts.map((part, index): Term => {\n const sign: 1 | -1 = part.startsWith('-') ? -1 : 1\n const body = part.replace(/^[+-]/, '')\n if (index > 0 && !/^[+-]/.test(part)) throw new InvalidValueError(`\"${input}\" is not dice notation: write it like 2d6+1`)\n const match = TERM.exec(body)\n if (match === null) throw new InvalidValueError(`\"${part}\" is not dice notation: write it like 2d6+1, 4d6kh3 or d100`)\n if (match[5] !== undefined) return { sign, constant: Number(match[5]) }\n const count = match[1] === '' || match[1] === undefined ? 1 : Number(match[1])\n const sides = match[2] === '%' ? 100 : Number(match[2])\n if (count < 1 || count > MAX_DICE_PER_ROLL) throw new InvalidValueError(`\"${part}\": roll from 1 to ${MAX_DICE_PER_ROLL} dice at a time`)\n if (sides < 2 || sides > MAX_DICE_SIDES) throw new InvalidValueError(`\"${part}\": a die has from 2 to ${MAX_DICE_SIDES} sides`)\n const mode = match[3] as KeepMode | undefined\n if (mode === undefined) return { sign, count, sides }\n const n = match[4] === '' || match[4] === undefined ? 1 : Number(match[4])\n if (n < 1 || n >= count) throw new InvalidValueError(`\"${part}\": ${mode.startsWith('k') ? 'keep' : 'drop'} at least 1 and fewer than the ${count} dice`)\n return { sign, count, sides, keep: { mode, n } }\n })\n if (!terms.some(term => 'sides' in term)) throw new InvalidValueError(`\"${input}\" has no dice: write it like 2d6+1`)\n return { text: source, terms }\n}\n\n/** The lowest and highest total the dice and constants can give. */\nexport function notationRange(notation: Notation): { min: number; max: number } {\n let min = 0\n let max = 0\n for (const term of notation.terms) {\n if ('constant' in term) {\n min += term.sign * term.constant\n max += term.sign * term.constant\n continue\n }\n const kept = term.keep === undefined ? term.count : term.keep.mode.startsWith('k') ? term.keep.n : term.count - term.keep.n\n const low = kept\n const high = kept * term.sides\n min += term.sign === 1 ? low : -high\n max += term.sign === 1 ? high : -low\n }\n return { min, max }\n}\n\nexport interface Rolled {\n /** Every die, in the order of the terms. */\n faces: number[]\n /** The dice that count. */\n kept: number[]\n /** The constants of the expression, signed. */\n constant: number\n /** The dice that count with their signs, plus the constants. */\n total: number\n}\n\nfunction keepOf(faces: readonly number[], keep: NonNullable<Extract<Term, { sides: number }>['keep']>): number[] {\n const ordered = faces.map((face, index) => ({ face, index })).sort((a, b) => a.face - b.face || a.index - b.index)\n const count = keep.mode.startsWith('k') ? keep.n : faces.length - keep.n\n const chosen = keep.mode === 'kh' || keep.mode === 'dl' ? ordered.slice(ordered.length - count) : ordered.slice(0, count)\n return chosen.sort((a, b) => a.index - b.index).map(entry => entry.face)\n}\n\nexport function rollNotation(notation: Notation, roll: Roller = systemRoller): Rolled {\n const faces: number[] = []\n const kept: number[] = []\n let constant = 0\n let total = 0\n for (const term of notation.terms) {\n if ('constant' in term) {\n constant += term.sign * term.constant\n total += term.sign * term.constant\n continue\n }\n const thrown = Array.from({ length: term.count }, () => roll(term.sides))\n const counted = term.keep === undefined ? thrown : keepOf(thrown, term.keep)\n faces.push(...thrown)\n kept.push(...counted)\n total += term.sign * counted.reduce((sum, face) => sum + face, 0)\n }\n return { faces, kept, constant, total }\n}\n\nconst within = (band: DiceBand, value: number): boolean => (band.min === undefined || value >= band.min) && (band.max === undefined || value <= band.max)\n\n/** What the bands of a check make of a value. @throws {InvalidValueError} when no band holds it. */\nexport function readBands(bands: readonly DiceBand[], value: number): DiceReadout {\n const band = bands.find(candidate => within(candidate, value))\n if (band === undefined) throw new InvalidValueError(`no band of this check holds ${value}: the check's bands leave a gap`)\n return { label: band.label, result: band.result, critical: band.critical === true }\n}\n\nexport interface CheckRoll {\n faces: number[]\n kept: number[]\n modifier: number\n target?: number\n total: number\n value: number\n readout: DiceReadout\n}\n\n/**\n * Rolls a check: the dice, the character's modifier and any bonus added, then the value read against the bands. With the reading\n * `successes` the total is the number of dice that hit. A check read against a target needs one.\n * @throws {InvalidValueError} for a target a check needs and is not given, or bands that leave the value unread.\n */\nexport function rollCheck(check: DiceCheckDefinition, input: { modifier?: number; bonus?: number; target?: number }, roll: Roller = systemRoller): CheckRoll {\n const notation = parseNotation(check.dice)\n const rolled = rollNotation(notation, roll)\n const comparison = check.compare ?? 'absolute'\n if (comparison !== 'absolute' && input.target === undefined) {\n throw new InvalidValueError(`the check \"${check.key}\" is read against a target (${comparison === 'over' ? 'the number to meet or beat' : 'the number to stay under'}): give one`)\n }\n const added = (input.modifier ?? 0) + (input.bonus ?? 0)\n const total = check.reading === 'successes' ? rolled.kept.filter(face => face >= (check.hit ?? 0)).length + (input.bonus ?? 0) : rolled.total + added\n const value = comparison === 'over' ? total - (input.target ?? 0) : comparison === 'under' ? (input.target ?? 0) - total : total\n return {\n faces: rolled.faces, kept: rolled.kept, modifier: check.reading === 'successes' ? (input.bonus ?? 0) : rolled.constant + added,\n ...(input.target === undefined ? {} : { target: input.target }), total, value, readout: readBands(check.bands, value),\n }\n}\n\n/** What is wrong with a check as a world defines it; nothing when it is sound. */\nexport function checkProblems(check: DiceCheckDefinition): string[] {\n const problems: string[] = []\n if (!/^[a-z][a-z0-9_-]{0,39}$/.test(check.key)) problems.push(`the key \"${check.key}\" must be lower-case letters, digits, - or _, starting with a letter`)\n if (check.name.trim() === '') problems.push('it needs a name')\n if (check.use.trim() === '') problems.push('it needs a \"use\": when the game master rolls it')\n if (check.compare !== undefined && !DICE_COMPARISONS.includes(check.compare)) problems.push(`\"compare\" must be one of: ${DICE_COMPARISONS.join(', ')}`)\n if (check.reading !== undefined && !DICE_READINGS.includes(check.reading)) problems.push(`\"reading\" must be one of: ${DICE_READINGS.join(', ')}`)\n let notation: Notation | undefined\n try { notation = parseNotation(check.dice) } catch (error) { problems.push(`\"dice\": ${error instanceof Error ? error.message : String(error)}`) }\n if (check.bands.length === 0) problems.push('it needs at least one band')\n if (check.bands.length > MAX_DICE_BANDS) problems.push(`it has more than ${MAX_DICE_BANDS} bands`)\n check.bands.forEach((band, index) => {\n if (band.label.trim() === '') problems.push(`band ${index + 1} needs a label`)\n if (!DICE_RESULTS.includes(band.result)) problems.push(`band ${index + 1}: \"result\" must be one of: ${DICE_RESULTS.join(', ')}`)\n if (band.min !== undefined && band.max !== undefined && band.min > band.max) problems.push(`band ${index + 1}: min is above max`)\n })\n if (check.reading === 'successes') {\n const sides = notation?.terms.flatMap(term => ('sides' in term ? [term.sides] : [])) ?? []\n if (check.hit === undefined || !Number.isInteger(check.hit) || check.hit < 1 || (sides.length > 0 && check.hit > Math.max(...sides))) problems.push('the reading \"successes\" needs \"hit\": the lowest face that counts')\n }\n if (notation !== undefined && problems.length === 0 && (check.compare ?? 'absolute') === 'absolute' && check.modifier === undefined) {\n const { min, max } = check.reading === 'successes' ? { min: 0, max: notation.terms.reduce((sum, term) => sum + ('count' in term ? term.count : 0), 0) } : notationRange(notation)\n for (let value = min; value <= max; value += 1) {\n if (!check.bands.some(band => within(band, value))) {\n problems.push(`no band holds ${value}, which the dice can give`)\n break\n }\n }\n }\n return problems\n}\n\n/** A roll of dice with no meaning attached, for what the world has no check for. */\nexport interface PlainRoll {\n expression: string\n faces: number[]\n kept: number[]\n modifier: number\n total: number\n}\n\nexport function rollPlain(expression: string, roll: Roller = systemRoller): PlainRoll {\n const notation = parseNotation(expression)\n const rolled = rollNotation(notation, roll)\n return { expression: notation.text, faces: rolled.faces, kept: rolled.kept, modifier: rolled.constant, total: rolled.total }\n}\n","import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'\nimport type { DiceCheck, DiceRoll } from 'dsh-roleplay-model'\nimport { NotFoundError } from '../errors.ts'\nimport { rollCheck, rollPlain, systemRoller, type Roller } from '../records/dice.ts'\nimport { characterKey } from '../records/edit-types.ts'\nimport type { AgentLink } from './index.ts'\n\nexport const ROLL_DICE_TOOL = 'roll_dice'\nexport const ROLL_CHECK_TOOL = 'roll_check'\nexport const LIST_CHECKS_TOOL = 'list_checks'\n\n/** The tools that need the dice and nothing else of the story. */\nexport type DiceLink = Pick<AgentLink, 'turn'> & { session: Pick<AgentLink['session'], 'dice' | 'characters' | 'variables'> }\n\nconst sign = (value: number): string => (value >= 0 ? `+${value}` : String(value))\n\n/** How a roll reads to the agent that asked for it: what fell, what it adds up to, and what the world's check makes of it. */\nexport function describeRoll(roll: DiceRoll, check?: DiceCheck): string {\n const dice = `[${roll.faces.join(', ')}]${roll.kept.length < roll.faces.length ? ` keeping [${roll.kept.join(', ')}]` : ''}`\n const lines = [`Roll ${roll.id}: ${roll.expression}${check === undefined ? '' : ` for the check \"${check.name}\"`}${roll.character === undefined ? '' : ` (${roll.character})`} - ${dice}${roll.modifier === 0 ? '' : ` ${sign(roll.modifier)}`} = ${roll.total}${check?.reading === 'successes' ? ' successes' : ''}.`]\n if (roll.target !== undefined) lines.push(`Against ${roll.target}: ${roll.value >= 0 ? '+' : ''}${roll.value}.`)\n if (roll.readout !== undefined) lines.push(`That is: ${roll.readout.label}${roll.readout.critical ? ' (critical)' : ''}; the result is ${roll.readout.result}. This is decided by the dice: do not change it, narrate it.${check === undefined || roll.character === undefined ? '' : ` In resolve_round give ${roll.character}'s outcome this result and cite the roll: roll ${roll.id}.`}`)\n return lines.join(' ')\n}\n\nconst rolled = (_args: unknown, value: unknown) => [{ type: 'text' as const, text: (value as { text: string }).text }]\n\n/**\n * Tools that roll dice for an agent, so that numbers are not made up. `roll_check` rolls a check the story defines and reads\n * the result with the check's own bands; `roll_dice` rolls plain notation for what has no check. The roller is the system's\n * source of randomness unless one is given.\n */\nexport function createDiceTools(resolve: (agentSessionId: string) => DiceLink | undefined, options: { roller?: Roller; by?: 'agent' | 'player' } = {}): ToolDefinition[] {\n const roller = options.roller ?? systemRoller\n const linkOf = (agent: { session: { id: string } } | undefined): DiceLink => {\n const found = agent === undefined ? undefined : resolve(agent.session.id)\n if (found === undefined) throw new NotFoundError('this agent is not working in a roleplay session, so there are no dice to roll')\n return found\n }\n return [\n defineTool({\n name: LIST_CHECKS_TOOL,\n description: 'List the checks this story defines for settling uncertain attempts: when each is used, the dice it rolls and how its result is read.',\n parameters: {},\n output: { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }] },\n isConcurrencySafe: () => true,\n execute(_args, exec) {\n const { session } = linkOf(exec.agent)\n return Promise.resolve(session.dice.checks().map(check => ({ key: check.key, name: check.name, use: check.use, dice: check.dice, compare: check.compare ?? 'absolute', ...(check.modifier === undefined ? {} : { modifier: `the character's ${check.modifier}` }), bands: check.bands.map(band => ({ ...(band.min === undefined ? {} : { from: band.min }), ...(band.max === undefined ? {} : { to: band.max }), label: band.label, result: band.result })) })) as never)\n },\n }),\n defineTool({\n name: ROLL_CHECK_TOOL,\n description: 'Roll one of the story\\'s checks for an attempt whose outcome is uncertain and matters: the dice are rolled for you and the result is read with the check\\'s own bands, so you never choose or make up a number. Use the check whose \"use\" fits (list_checks shows them). Roll once per attempt, before you decide what happens, and let the result stand: a failed roll is a failure, whatever the story would like.',\n parameters: {\n check: { type: 'string', required: true, description: 'The key of the check, as list_checks gives it.' },\n reason: { type: 'string', required: true, description: 'What is attempted, by whom, in a sentence.' },\n character: { type: 'string', required: true, description: 'The key of the character the attempt is for (the player\\'s character included): the roll is theirs, and their outcome in resolve_round takes its result from it.' },\n target: { type: 'integer', description: 'When the check is read against a target (list_checks says compare over or under): the difficulty, the number the total must meet or beat (or stay under). Set it by how hard the attempt is, using what the check\\'s \"use\" says about difficulty; never 0 to make it easy.' },\n bonus: { type: 'integer', description: 'What the circumstances add to or take from the roll, from -10 to 10; leave out for none.' },\n },\n output: { schema: { type: 'json' }, render: rolled },\n isConcurrencySafe: () => false,\n execute(args, exec) {\n const { session, turn } = linkOf(exec.agent)\n const check = session.dice.check(args.check)\n if (check === undefined) throw new NotFoundError(`there is no check \"${args.check}\"; list_checks shows the story's checks`)\n if (session.characters.list().every(entry => characterKey(entry) !== args.character)) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n let modifier: number | undefined\n if (check.modifier !== undefined) {\n const who = session.characters.list().find(entry => characterKey(entry) === args.character)\n if (who === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n const value = session.variables.value(check.modifier, 'character', who.id)\n if (typeof value !== 'number') throw new NotFoundError(`the character's ${check.modifier} is not a number, so the check cannot add it`)\n modifier = value\n }\n const bonus = Math.max(-10, Math.min(10, args.bonus ?? 0))\n const made = rollCheck(check, { ...(modifier === undefined ? {} : { modifier }), bonus, ...(args.target === undefined ? {} : { target: args.target }) }, roller)\n const roll = session.dice.record({\n turn, check: check.key, expression: check.dice, faces: made.faces, kept: made.kept, modifier: made.modifier, ...(made.target === undefined ? {} : { target: made.target }),\n total: made.total, value: made.value, readout: made.readout, reason: args.reason, character: args.character, by: options.by ?? 'agent',\n })\n return Promise.resolve({ roll: roll.id, check: check.key, total: roll.total, result: made.readout.result, label: made.readout.label, critical: made.readout.critical, text: describeRoll(roll, check) } as never)\n },\n }),\n defineTool({\n name: ROLL_DICE_TOOL,\n description: 'Roll dice for something the story has no check for (damage, a random pick, who goes first, a rumour table): the dice are rolled for you, so you never make up a number. Write the notation like 1d6, 2d4+1, 4d6kh3 (keep the highest 3) or d100. What the number means is for you to decide from the rules you were given; when a check fits the attempt, use roll_check instead.',\n parameters: {\n expression: { type: 'string', required: true, description: 'Dice notation, for example 2d6+1.' },\n reason: { type: 'string', required: true, description: 'What the roll is for, in a sentence.' },\n character: { type: 'string', description: 'The key of the character it is for, when it is for one.' },\n },\n output: { schema: { type: 'json' }, render: rolled },\n isConcurrencySafe: () => false,\n execute(args, exec) {\n const { session, turn } = linkOf(exec.agent)\n const made = rollPlain(args.expression, roller)\n const roll = session.dice.record({ turn, expression: made.expression, faces: made.faces, kept: made.kept, modifier: made.modifier, total: made.total, value: made.total, reason: args.reason, ...(args.character === undefined ? {} : { character: args.character }), by: options.by ?? 'agent' })\n return Promise.resolve({ roll: roll.id, total: roll.total, text: describeRoll(roll) } as never)\n },\n }),\n ]\n}\n","import type { Exit, Location } from 'dsh-roleplay-model'\nimport { lookupKey } from '../sqlite/support.ts'\nimport { characterKey, locationKey, type RecordsTarget } from './edit-types.ts'\nimport { itemKey } from './items.ts'\n\nexport type LintSeverity = 'error' | 'warning' | 'info'\n\nexport interface LintFinding {\n /** An error leaves the world inconsistent (nobody can get to a place, two characters share a name); a warning is something that should be fitted in; an info is only worth knowing. */\n severity: LintSeverity\n code: string\n subject: { kind: 'character' | 'location' | 'exit' | 'relationship' | 'item'; key: string }\n message: string\n}\n\nexport type LintTarget = Pick<RecordsTarget, 'characters' | 'locations' | 'placements' | 'relationships' | 'consolidation' | 'items'>\n\n/**\n * What is inconsistent or unfinished in the world's graph of places and characters. Things made up in\n * play and not fitted in yet are held to a stricter standard than what the world was written with: a\n * place that no one can reach or leave is an error for them, and a warning for the rest.\n */\nexport function lintWorld(target: LintTarget): LintFinding[] {\n const findings: LintFinding[] = []\n const pending = target.consolidation.pending()\n const newCharacters = new Set(pending.filter(item => item.kind === 'character').map(item => item.subjectId))\n const newPlaces = new Set(pending.filter(item => item.kind === 'location').map(item => item.subjectId))\n const places = target.locations.list()\n const exits = target.locations.allExits()\n const characters = target.characters.list()\n const relationships = target.relationships.list()\n const containers = new Set(places.flatMap(place => (place.parentId === undefined ? [] : [place.parentId])))\n const keyOfPlace = (place: Pick<Location, 'id' | 'sourceId'>): string => locationKey(place)\n const placeById = new Map(places.map(place => [place.id, place]))\n const strict = (isNew: boolean): LintSeverity => (isNew ? 'error' : 'warning')\n\n // Places.\n const outgoing = new Map<number, Exit[]>()\n const touched = new Set<number>()\n for (const exit of exits) {\n outgoing.set(exit.fromId, [...(outgoing.get(exit.fromId) ?? []), exit])\n touched.add(exit.fromId)\n touched.add(exit.toId)\n }\n const walkable = places.filter(place => !containers.has(place.id))\n if (walkable.length > 1) {\n for (const place of walkable) {\n if (!touched.has(place.id)) findings.push({ severity: strict(newPlaces.has(place.id)), code: 'location-no-exit', subject: { kind: 'location', key: keyOfPlace(place) }, message: `${place.name} has no way in or out, so no one can go there or leave it` })\n }\n const player = characters.find(character => character.control === 'player')\n const start = (player === undefined ? undefined : target.placements.get('character', player.id)?.locationId) ?? walkable[0]!.id\n const reached = new Set<number>([start])\n for (const queue = [start]; queue.length > 0;) {\n const at = queue.shift()!\n for (const exit of outgoing.get(at) ?? []) if (!reached.has(exit.toId)) { reached.add(exit.toId); queue.push(exit.toId) }\n }\n for (const place of walkable) {\n if (reached.has(place.id) || !touched.has(place.id)) continue\n findings.push({ severity: 'warning', code: 'location-unreachable', subject: { kind: 'location', key: keyOfPlace(place) }, message: `${place.name} cannot be reached from ${placeById.get(start)?.name ?? 'where the story is'} by any chain of exits` })\n }\n }\n for (const exit of exits) {\n if (exits.some(other => other.fromId === exit.toId && other.toId === exit.fromId)) continue\n const from = placeById.get(exit.fromId)\n const to = placeById.get(exit.toId)\n if (from === undefined || to === undefined) continue\n findings.push({ severity: 'info', code: 'exit-no-way-back', subject: { kind: 'exit', key: `${keyOfPlace(from)}->${keyOfPlace(to)}` }, message: `there is a way from ${from.name} to ${to.name} but none back` })\n }\n const sameName = new Map<string, Location[]>()\n for (const place of places) sameName.set(`${place.parentId ?? 0}:${lookupKey(place.name)}`, [...(sameName.get(`${place.parentId ?? 0}:${lookupKey(place.name)}`) ?? []), place])\n for (const group of sameName.values()) {\n if (group.length > 1) findings.push({ severity: 'error', code: 'duplicate-name', subject: { kind: 'location', key: keyOfPlace(group[1]!) }, message: `${group.length} places in the same place are called ${group[0]!.name}: ${group.map(keyOfPlace).join(', ')}` })\n }\n\n // Characters.\n const byName = new Map<string, typeof characters>()\n for (const character of characters) byName.set(lookupKey(character.name), [...(byName.get(lookupKey(character.name)) ?? []), character])\n for (const group of byName.values()) {\n if (group.length > 1) findings.push({ severity: 'error', code: 'duplicate-name', subject: { kind: 'character', key: characterKey(group[1]!) }, message: `${group.length} characters are called ${group[0]!.name}: ${group.map(characterKey).join(', ')}` })\n }\n for (const character of characters) {\n const key = characterKey(character)\n if (places.length > 0 && target.placements.get('character', character.id) === undefined) {\n findings.push({ severity: strict(newCharacters.has(character.id)), code: 'character-unplaced', subject: { kind: 'character', key }, message: `${character.name} is not in any place` })\n }\n if (newCharacters.has(character.id) && characters.length > 1 && !relationships.some(relation => relation.fromId === character.id || relation.toId === character.id)) {\n findings.push({ severity: 'warning', code: 'character-no-relationships', subject: { kind: 'character', key }, message: `${character.name} was made up and has no relationship with anyone yet` })\n }\n }\n for (const relation of relationships) {\n if (relationships.some(other => other.fromId === relation.toId && other.toId === relation.fromId)) continue\n const from = characters.find(character => character.id === relation.fromId)\n const to = characters.find(character => character.id === relation.toId)\n if (from === undefined || to === undefined) continue\n findings.push({ severity: 'info', code: 'relationship-one-sided', subject: { kind: 'relationship', key: `${characterKey(from)}->${characterKey(to)}` }, message: `${from.name} has a profile of ${to.name} (${relation.label}) but ${to.name} has none of ${from.name}` })\n }\n // Items.\n const newItems = new Set(pending.filter(item => item.kind === 'item').map(item => item.subjectId))\n const things = target.items.list()\n const sameHolder = new Map<string, typeof things>()\n for (const item of things) {\n const holding = target.items.holding(item.id)\n const where = holding === undefined ? 'nowhere' : `${holding.holder.kind}:${'locationId' in holding.holder ? holding.holder.locationId : 'characterId' in holding.holder ? holding.holder.characterId : holding.holder.itemId}`\n const group = `${where}:${lookupKey(item.name)}`\n sameHolder.set(group, [...(sameHolder.get(group) ?? []), item])\n if (item.container?.state === 'locked' && target.items.openers({ kind: 'item', id: item.id }).length === 0) {\n findings.push({ severity: newItems.has(item.id) ? 'warning' : 'info', code: 'lock-without-key', subject: { kind: 'item', key: itemKey(item) }, message: `${item.name} is locked and no item is known to open it` })\n }\n }\n for (const group of sameHolder.values()) {\n const twins = group.filter(item => !item.unique)\n if (twins.length > 1) findings.push({ severity: 'warning', code: 'item-duplicate', subject: { kind: 'item', key: itemKey(twins[1]!) }, message: `${twins.length} separate items called ${twins[0]!.name} are in the same place: ${twins.map(itemKey).join(', ')}; they could be one with a quantity` })\n }\n for (const exit of exits) {\n if (exit.state !== 'locked' || target.items.openers({ kind: 'exit', id: exit.id }).length > 0 || exit.note !== '') continue\n const from = placeById.get(exit.fromId)\n const to = placeById.get(exit.toId)\n if (from !== undefined && to !== undefined) findings.push({ severity: 'info', code: 'lock-without-key', subject: { kind: 'exit', key: `${keyOfPlace(from)}->${keyOfPlace(to)}` }, message: `the way from ${from.name} to ${to.name} is locked and nothing says what opens it` })\n }\n const order = { error: 0, warning: 1, info: 2 } as const\n return findings.sort((a, b) => order[a.severity] - order[b.severity])\n}\n","import type { CharacterId, CharacterIntent, Engagement, StoredRoutineWindow } from 'dsh-roleplay-model'\nimport type { EngagementRepository, IntentRepository, RoutineRepository } from '../repositories.ts'\nimport { NO_CALENDAR, dayMatches, readCalendar, type Calendar } from './calendar.ts'\nimport { DAY, HOUR, MINUTE, addLocalDays, parseInstant, zonedInstant } from './time.ts'\n\n/** One occurrence of a routine window: the stretch of time it holds on a particular day. */\nexport interface Occurrence {\n window: StoredRoutineWindow\n startsAt: number\n endsAt: number\n}\n\n/** An engagement still pending this long after it was due (or over) is overdue. */\nexport const ENGAGEMENT_GRACE = 30 * MINUTE\n\nfunction occurrenceOn(window: StoredRoutineWindow, day: { year: number; month: number; day: number; weekday: number }, zone: string, calendar: Calendar): Occurrence | undefined {\n if (window.days.length > 0 && !window.days.includes(day.weekday)) return undefined\n if (window.on.length > 0 && !dayMatches(window.on, day, calendar)) return undefined\n const startsAt = zonedInstant({ ...day, hour: Math.floor(window.start / 60), minute: window.start % 60 }, zone)\n const wraps = window.end < window.start\n const endDay = wraps ? addLocalDays(startsAt, zone, 1) : day\n const endsAt = zonedInstant({ ...endDay, hour: Math.floor(window.end / 60), minute: window.end % 60 }, zone)\n return { window, startsAt, endsAt }\n}\n\n/** The window that holds at an instant (the first of the list that does), with the stretch of this occurrence of it. */\nexport function occurrenceAt(windows: readonly StoredRoutineWindow[], now: number, zone: string, calendar: Calendar = NO_CALENDAR): Occurrence | undefined {\n const days = [addLocalDays(now, zone, 0), addLocalDays(now, zone, -1)]\n for (const window of windows) {\n for (const day of days) {\n const occurrence = occurrenceOn(window, day, zone, calendar)\n if (occurrence !== undefined && occurrence.startsAt <= now && now < occurrence.endsAt) return occurrence\n }\n }\n return undefined\n}\n\n/** The window that starts next after an instant, within `horizon`. */\nexport function nextOccurrence(windows: readonly StoredRoutineWindow[], now: number, zone: string, horizon: number, calendar: Calendar = NO_CALENDAR): Occurrence | undefined {\n let best: Occurrence | undefined\n for (const offset of [0, 1, 2]) {\n const day = addLocalDays(now, zone, offset)\n for (const window of windows) {\n const occurrence = occurrenceOn(window, day, zone, calendar)\n if (occurrence === undefined || occurrence.startsAt <= now || occurrence.startsAt > now + horizon) continue\n if (best === undefined || occurrence.startsAt < best.startsAt) best = occurrence\n }\n }\n return best\n}\n\nexport interface RankedGoal {\n intent: CharacterIntent\n /** The deadline as an instant, when it has one that can be read. */\n deadlineAt?: number\n overdue: boolean\n score: number\n}\n\n/** What a character is after, most pressing first: priority and urgency, and how close or past the deadline is. Goals not active are left out. */\nexport function rankGoals(goals: readonly CharacterIntent[], now: number, zone: string, limit: number): RankedGoal[] {\n return goals.filter(goal => goal.status === 'active').map((intent): RankedGoal => {\n let deadlineAt: number | undefined\n if (intent.deadline !== undefined) {\n try { deadlineAt = parseInstant(intent.deadline, zone) } catch { /* a deadline that is not a date does not count */ }\n }\n const left = deadlineAt === undefined ? undefined : deadlineAt - now\n const bonus = left === undefined ? 0 : left < 0 ? 0.4 : left < 6 * HOUR ? 0.3 : left < DAY ? 0.2 : left < 7 * DAY ? 0.1 : 0\n return { intent, ...(deadlineAt === undefined ? {} : { deadlineAt }), overdue: left !== undefined && left < 0, score: 0.5 * intent.priority + 0.3 * intent.urgency + bonus }\n }).sort((a, b) => b.score - a.score || a.intent.id - b.intent.id).slice(0, limit)\n}\n\nexport interface AgendaEngagement {\n engagement: Engagement\n overdue: boolean\n}\n\nexport interface Agenda {\n /** What the routine has the character doing now. */\n now?: Occurrence\n /** What the routine has it doing next, within the horizon. */\n next?: Occurrence\n /** What it has committed to that is due within the horizon or is overdue, in the order they are due. */\n engagements: AgendaEngagement[]\n goals: RankedGoal[]\n}\n\nexport interface AgendaOptions {\n /** How far ahead to look, in milliseconds. */\n horizon?: number\n goals?: number\n engagements?: number\n}\n\nconst DEFAULTS = { horizon: 24 * HOUR, goals: 3, engagements: 4 } as const\n\n/** What a character is expected to be doing and to have done at an instant: its routine, its commitments and its goals. */\nexport function agendaAt(\n source: { routines: Pick<RoutineRepository, 'list'>; engagements: Pick<EngagementRepository, 'list'>; intents: Pick<IntentRepository, 'list'>; metadata?: { getValue(key: string): unknown } },\n characterId: CharacterId,\n now: number,\n zone: string,\n options: AgendaOptions = {},\n): Agenda {\n const horizon = options.horizon ?? DEFAULTS.horizon\n const windows = source.routines.list(characterId)\n const calendar = source.metadata === undefined ? NO_CALENDAR : readCalendar(source.metadata)\n const current = occurrenceAt(windows, now, zone, calendar)\n const next = nextOccurrence(windows, now, zone, horizon, calendar)\n const engagements = source.engagements.list({ status: 'pending', participant: characterId, to: now + horizon })\n .map((engagement): AgendaEngagement => ({ engagement, overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE) }))\n .slice(0, options.engagements ?? DEFAULTS.engagements)\n return {\n ...(current === undefined ? {} : { now: current }),\n ...(next === undefined ? {} : { next }),\n engagements,\n goals: rankGoals(source.intents.list(characterId), now, zone, options.goals ?? DEFAULTS.goals),\n }\n}\n","import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'\nimport { IMPORTANCE_MAX, IMPORTANCE_MIN, MEMORY_KINDS, PERCEPTION_MODES, ACCURACIES } from 'dsh-roleplay-model'\nimport { NotFoundError } from '../errors.ts'\nimport type { MemoryPolicy } from '../memory/recall.ts'\nimport { characterKey, locationKey, parseRecordsEdit, recordsEditSchema } from '../records/edit.ts'\nimport { lintWorld } from '../records/lint.ts'\nimport { describeHolder } from '../records/read.ts'\nimport { agendaAt } from '../records/agenda.ts'\nimport { describeValue, shownVariables } from '../records/variables.ts'\nimport { describeInstant, localIso, minuteText } from '../records/time.ts'\nimport { itemKey } from '../records/items.ts'\nimport type { Session } from '../plugin.ts'\n\n/** The roleplay session an agent works in, as the plugin that runs the agent knows it. */\nexport interface AgentLink {\n session: Pick<Session, 'characters' | 'factions' | 'factionStates' | 'factionMemberships' | 'factionRelationships' | 'factionIntents' | 'lore' | 'events' | 'memories' | 'threads' | 'records' | 'recallRanked' | 'searchEvents' | 'edit' | 'locations' | 'placements' | 'relationships' | 'knowledge' | 'consolidation' | 'planMove' | 'items' | 'slots' | 'variables' | 'intents' | 'routines' | 'engagements' | 'clock' | 'dice'>\n /** The time zone the story's times are written and read in; UTC when not given. */\n timeZone?: string\n /** The turn the agent is playing, which is what the age of a memory is counted from. */\n turn: number\n policy: MemoryPolicy\n /**\n * The vector of a text of the moment, from the model that made the session's stored vectors, so that\n * a search also finds what means the same in other words. `undefined` (or a promise of it) when\n * there is none, and the search then goes by words alone.\n */\n queryVector?: (text: string, signal?: AbortSignal) => Promise<readonly number[] | undefined>\n}\n\n/** The vector of a text for a search, or nothing when the agent has no way to make one. */\nexport async function vectorOf(agent: AgentLink, text: string, signal?: AbortSignal): Promise<{ queryVector: readonly number[] } | Record<string, never>> {\n const vector = await agent.queryVector?.(text, signal)\n return vector === undefined ? {} : { queryVector: vector }\n}\n\n/** Finds the session behind an agent, by the id of the agent's own session; `undefined` when it works in none. */\nexport type AgentResolver = (agentSessionId: string) => AgentLink | undefined\n\n/** The parts of the records `read_records` can be limited to. */\nconst READ_SECTIONS = ['characters', 'factions', 'faction_relationships', 'events', 'beliefs', 'open_threads', 'items', 'relationships', 'knowledge', 'variable_defs', 'variables', 'engagements']\n\nconst MAX_EVENTS = 20\nconst MAX_LISTED_PLACES = 100\nconst MAX_LISTED_ITEMS = 60\n\nconst link = (resolve: AgentResolver, agent: { session: { id: string } } | undefined): AgentLink => {\n const found = agent === undefined ? undefined : resolve(agent.session.id)\n if (found === undefined) throw new NotFoundError('this agent is not working in a roleplay session, so there are no records to use')\n return found\n}\n\nconst pretty = (_args: unknown, value: unknown) => [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }]\nconst summary = (text: string) => (_args: unknown, value: { writes: number }) => [{ type: 'text' as const, text: `${text} (${value.writes} change${value.writes === 1 ? '' : 's'})` }]\nconst strings = { type: 'array', items: { type: 'string' } } as const\nconst integers = { type: 'array', items: { type: 'integer' } } as const\n/** The members of an output object are all present. */\nconst str = { type: 'string', required: true } as const\nconst int = { type: 'integer', required: true } as const\nconst strs = { ...strings, required: true } as const\nconst ints = { ...integers, required: true } as const\n\n/**\n * The model-facing tools over a roleplay session. Reading tools show what the story has\n * recorded; writing tools change it and are registered only when the plugin is configured\n * for them. Both resolve the session from the agent that calls them.\n */\nexport function createTools(resolve: AgentResolver, options: {\n write: boolean\n /** Limits the characters a call may name to these keys, for an agent that works on one story. */\n characters?: readonly string[]\n /** Tools of the agent that makes up characters and places and fits them into the world: it makes them with `edit_world` instead of `edit_records`, and reads what is inconsistent. Never for a global registration. */\n authoring?: boolean\n}): ToolDefinition[] {\n const reads = [\n defineTool({\n name: 'search_lore',\n description: 'Search the canonical background lore of the story. Use this when history, culture, geography, institutions, customs or legends matter to the scene. This is game-master knowledge; character agents receive only lore they explicitly know.',\n parameters: { about: { type: 'string', required: true }, limit: { type: 'integer', description: 'Maximum entries, from 1 to 20.' } },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, title: str, kind: str, summary: str, body: str, sources: strs } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent); const needle = args.about.trim().toLowerCase(); const limit = Math.max(1, Math.min(20, args.limit ?? 8))\n return session.lore.list().filter(entry => `${entry.title} ${entry.summary} ${entry.body} ${entry.sources.join(' ')}`.toLowerCase().includes(needle)).slice(0, limit).map(entry => ({ key: entry.sourceId ?? String(entry.id), title: entry.title, kind: entry.kind, summary: entry.summary, body: entry.body, sources: entry.sources }))\n },\n }),\n defineTool({\n name: 'list_characters',\n description: 'List the characters of the story with the key each is named by, who controls it and a short summary.',\n parameters: {},\n output: {\n schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, name: str, role: str, controlled_by: str, summary: str } } },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n const { session } = link(resolve, exec.agent)\n return session.characters.list().map(character => ({ key: characterKey(character), name: character.name, role: character.role, controlled_by: character.control === 'player' ? 'the player' : 'an agent', summary: character.summary }))\n },\n }),\n defineTool({\n name: 'get_character',\n description: 'Read one character: who it is and its current state (what can be seen of it, what it thinks and feels, what it is doing, and what is tracked of it: its feelings and whatever else the story keeps track of).',\n parameters: { character: { type: 'string', required: true, description: 'The key of the character, as list_characters gives it.' } },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n character: str, name: str, aliases: strs, summary: str, personality: str,\n public_state: str, inner_state: str, activity: str, variables: { type: 'json', required: true },\n location: { type: 'json', required: true }, position: str,\n relationships: { type: 'json', required: true },\n carrying: { type: 'json', required: true },\n },\n },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const view = session.records().characters.find(entry => entry.character === args.character)\n const found = session.characters.list().find(character => characterKey(character) === args.character)\n if (view === undefined || found === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n return { character: view.character, name: view.name, aliases: found.aliases, summary: found.summary, personality: found.personality, public_state: view.public_state, inner_state: view.inner_state, activity: view.activity, variables: shownVariables(session, 'character', found.id, characterKey(found), 'story').map(entry => ({ variable: entry.variable.key, name: entry.variable.name, value: describeValue(entry.variable, entry.value), ...(entry.baseline === undefined ? {} : { baseline: describeValue(entry.variable, entry.baseline) }) })), location: view.location, position: view.position, relationships: session.records().relationships.filter(relation => relation.from === args.character), carrying: session.items.contents({ kind: 'character', id: found.id }).map(({ item, holding }) => ({ key: itemKey(item), name: item.name, quantity: item.quantity, how: holding.holder.kind === 'character' && holding.holder.mode === 'worn' ? `worn on the ${holding.holder.slot}` : 'carried', ...(item.container === undefined ? {} : { state: item.container.state }) })) }\n },\n }),\n defineTool({\n name: 'list_factions',\n description: 'List the persistent organisations of the story. These hold institutional state and strategy; group characters are the actors that appear in scenes.',\n parameters: {},\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n const { session } = link(resolve, exec.agent)\n return session.factions.list().map(faction => ({ key: faction.sourceId ?? String(faction.id), name: faction.name, summary: faction.summary, members: session.factionMemberships.ofFaction(faction.id, 'active').length, active_goals: session.factionIntents.list(faction.id, { status: 'active' }).length }))\n },\n }),\n defineTool({\n name: 'get_faction',\n description: 'Read one faction: its identity, institutional state, active strategy, memberships, and every directional relationship involving it.',\n parameters: { faction: { type: 'string', required: true, description: 'The key of the faction, as list_factions gives it.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const faction = session.factions.list().find(entry => (entry.sourceId ?? String(entry.id)) === args.faction)\n if (faction === undefined) throw new NotFoundError(`there is no faction \"${args.faction}\"; list_factions shows the keys`)\n const records = session.records()\n return { ...records.factions.find(entry => entry.faction === args.faction), relationships: { sees: records.faction_relationships.filter(entry => entry.from_kind === 'faction' && entry.from === args.faction), seen_by: records.faction_relationships.filter(entry => entry.to_kind === 'faction' && entry.to === args.faction) } }\n },\n }),\n defineTool({\n name: 'list_relationships',\n description: 'How characters stand towards each other: for each, the label (what the other is to it), a sentence, and how well it knows, trusts, likes and is strained with the other. Give a character to see how it sees others and how others see it.',\n parameters: { character: { type: 'string', description: 'The key of a character. Leave out for every relationship (the most recently changed first, at most 80).' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const all = session.records().relationships\n if (args.character === undefined) return JSON.parse(JSON.stringify(all)) as never\n if (!session.characters.list().some(character => characterKey(character) === args.character)) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n return JSON.parse(JSON.stringify({ sees: all.filter(relation => relation.from === args.character), seenBy: all.filter(relation => relation.to === args.character) })) as never\n },\n }),\n\n defineTool({\n name: 'list_items',\n description: 'List things, with the key each is named by and where it is. Narrow to what a character has, what is in a place, or what is inside a container; or search by words. At most 60 are listed, notable ones first.',\n parameters: {\n character: { type: 'string', description: 'The key of a character: what it carries and wears.' },\n location: { type: 'string', description: 'The key of a place: what is lying there (not what is inside containers).' },\n container: { type: 'string', description: 'The key of an item: what is inside it, whether it is open or not.' },\n text: { type: 'string', description: 'Only items whose name or description has this.' },\n },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const characters = session.characters.list()\n const keyOf = (id: number): string => { const found = characters.find(character => character.id === id); return found === undefined ? String(id) : characterKey(found) }\n const target = { items: session.items, locations: session.locations, characters: session.characters }\n let pool = session.items.list()\n if (args.character !== undefined) {\n const who = characters.find(character => characterKey(character) === args.character)\n if (who === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n pool = session.items.contents({ kind: 'character', id: who.id }).map(entry => entry.item)\n } else if (args.location !== undefined) {\n const where = session.locations.list().find(candidate => locationKey(candidate) === args.location)\n if (where === undefined) throw new NotFoundError(`there is no place \"${args.location}\"; list_locations shows the keys`)\n pool = session.items.contents({ kind: 'location', id: where.id }).map(entry => entry.item)\n } else if (args.container !== undefined) {\n const box = session.items.list().find(candidate => itemKey(candidate) === args.container)\n if (box === undefined) throw new NotFoundError(`there is no item \"${args.container}\"; list_items shows the keys`)\n pool = session.items.contents({ kind: 'item', id: box.id }).map(entry => entry.item)\n }\n const needle = args.text?.trim().toLowerCase()\n if (needle !== undefined && needle !== '') pool = pool.filter(item => item.name.toLowerCase().includes(needle) || item.description.toLowerCase().includes(needle))\n return JSON.parse(JSON.stringify([...pool].sort((a, b) => Number(b.notable) - Number(a.notable) || a.id - b.id).slice(0, MAX_LISTED_ITEMS).map(item => ({\n key: itemKey(item), name: item.name, quantity: item.quantity, quality: item.quality, state: item.container?.state ?? null, hidden: item.hidden, notable: item.notable, holder: describeHolder(target, item.id, keyOf),\n })))) as never\n },\n }),\n defineTool({\n name: 'get_item',\n description: 'Read one item: what it is, its condition, whose it is, where it is, what is inside it when it is a container, and what opens it. A hidden or closed thing is shown too: this is what the story knows.',\n parameters: { item: { type: 'string', required: true, description: 'The key of the item, as list_items gives it.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const found = session.items.list().find(candidate => itemKey(candidate) === args.item)\n if (found === undefined) throw new NotFoundError(`there is no item \"${args.item}\"; list_items shows the keys`)\n const characters = session.characters.list()\n const keyOf = (id: number): string => { const who = characters.find(character => character.id === id); return who === undefined ? String(id) : characterKey(who) }\n const keys = (ids: readonly number[]): string[] => ids.map(id => { const other = session.items.get(id); return other === undefined ? String(id) : itemKey(other) })\n return JSON.parse(JSON.stringify({\n item: itemKey(found), name: found.name, description: found.description, quantity: found.quantity, unique: found.unique, quality: found.quality, notable: found.notable, hidden: found.hidden,\n wearable: found.wearableSlot ?? null, state: found.container?.state ?? null, owner: found.ownerId === undefined ? null : keyOf(found.ownerId),\n where: describeHolder({ items: session.items, locations: session.locations, characters: session.characters }, found.id, keyOf),\n inside: found.container === undefined ? null : session.items.contents({ kind: 'item', id: found.id }).map(entry => ({ key: itemKey(entry.item), name: entry.item.name, quantity: entry.item.quantity })),\n opened_by: keys(session.items.openers({ kind: 'item', id: found.id })),\n })) as never\n },\n }),\n defineTool({\n name: 'list_slots',\n description: 'The places on the body something can be worn in this world, and how many things fit in each.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { id: str, name: str, capacity: int } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return link(resolve, exec.agent).session.slots.list()\n },\n }),\n defineTool({\n name: 'list_locations',\n description: 'List the places of the story with the key each is named by and the place it is in. Narrow to what is inside one place with `within`; at most 100 are listed.',\n parameters: { within: { type: 'string', description: 'The key of a place: list only the places inside it, at any depth.' } },\n output: {\n schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, name: str, in: { type: 'json', required: true }, exits: int } } },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const all = session.locations.list()\n const keys = new Map(all.map(place => [place.id, locationKey(place)]))\n const within = args.within === undefined ? undefined : all.find(place => locationKey(place) === args.within)\n if (args.within !== undefined && within === undefined) throw new NotFoundError(`there is no place \"${args.within}\"; list_locations shows the keys`)\n const inside = (place: (typeof all)[number]): boolean => {\n for (let up = place.parentId; up !== undefined; up = all.find(candidate => candidate.id === up)?.parentId) if (up === within?.id) return true\n return false\n }\n return all.filter(place => within === undefined || inside(place)).slice(0, MAX_LISTED_PLACES).map(place => ({ key: locationKey(place), name: place.name, in: place.parentId === undefined ? null : keys.get(place.parentId) ?? null, exits: session.locations.exitsFrom(place.id).length }))\n },\n }),\n defineTool({\n name: 'get_location',\n description: 'Read one place: what it is like, the things in it that can be pointed at, the ways out (and whether each is open, locked or blocked), and who is there.',\n parameters: { location: { type: 'string', required: true, description: 'The key of the place, as list_locations gives it.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session } = link(resolve, exec.agent)\n const place = session.locations.list().find(candidate => locationKey(candidate) === args.location)\n if (place === undefined) throw new NotFoundError(`there is no place \"${args.location}\"; list_locations shows the keys`)\n const key = (id: number): string => { const found = session.locations.get(id); return found === undefined ? String(id) : locationKey(found) }\n const people = session.characters.list()\n return JSON.parse(JSON.stringify({\n location: locationKey(place), name: place.name, description: place.description, in: place.parentId === undefined ? null : key(place.parentId),\n features: place.features,\n exits: session.locations.exitsFrom(place.id).map(exit => ({ to: key(exit.toId), name: session.locations.get(exit.toId)?.name, state: exit.state, description: exit.description, note: exit.note, travel_time_seconds: exit.travelSeconds ?? null })),\n items: session.items.contents({ kind: 'location', id: place.id }).map(({ item, holding }) => ({ key: itemKey(item), name: item.name, quantity: item.quantity, ...(item.hidden ? { hidden: true } : {}), ...(item.container === undefined ? {} : { state: item.container.state }), ...(holding.holder.kind === 'location' && holding.holder.position !== undefined ? { position: holding.holder.position } : {}) })),\n here: session.placements.at(place.id, 'character').map(placement => { const who = people.find(character => character.id === placement.entityId); return { character: who === undefined ? String(placement.entityId) : characterKey(who), position: placement.position, feature: placement.featureKey ?? null } }),\n })) as never\n },\n }),\n\n defineTool({\n name: 'search_events',\n description: 'Look up what objectively happened in the story, in the order it happened. Narrow by character, turns, importance or what it is about.',\n parameters: {\n character: { type: 'string', description: 'Only events this character is involved in.' },\n text: { type: 'string', description: 'Only events about this, found by its words or its meaning; with it, the best matches come first.' },\n location: { type: 'string', description: 'Only events that happened in this place (its key).' },\n item: { type: 'string', description: 'Only events about this item (its key).' },\n from_turn: { type: 'integer' },\n to_turn: { type: 'integer' },\n min_importance: { type: 'integer', description: `From ${IMPORTANCE_MIN} to ${IMPORTANCE_MAX}.` },\n limit: { type: 'integer', description: `At most this many (at most ${MAX_EVENTS}): the most recent, or the best matches when text is given.` },\n },\n output: {\n schema: {\n type: 'array',\n items: { type: 'object', additionalProperties: false, properties: { id: int, turn: int, round: int, text: str, importance: int, tags: strs, involves: strs } },\n },\n render: pretty,\n },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const agent = link(resolve, exec.agent)\n const { session } = agent\n const characters = session.characters.list()\n const involving = args.character === undefined ? undefined : characters.find(character => characterKey(character) === args.character)\n if (args.character !== undefined && involving === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n const place = args.location === undefined ? undefined : session.locations.list().find(candidate => locationKey(candidate) === args.location)\n if (args.location !== undefined && place === undefined) throw new NotFoundError(`there is no place \"${args.location}\"; list_locations shows the keys`)\n const thing = args.item === undefined ? undefined : session.items.list().find(candidate => itemKey(candidate) === args.item)\n if (args.item !== undefined && thing === undefined) throw new NotFoundError(`there is no item \"${args.item}\"; list_items shows the keys`)\n const needle = args.text?.trim().toLowerCase()\n const filter = {\n ...(place === undefined ? {} : { locationId: place.id }),\n ...(thing === undefined ? {} : { aboutItem: thing.id }),\n ...(involving === undefined ? {} : { involving: involving.id }),\n ...(args.from_turn === undefined ? {} : { fromTurn: args.from_turn }),\n ...(args.to_turn === undefined ? {} : { toTurn: args.to_turn }),\n ...(args.min_importance === undefined ? {} : { minImportance: args.min_importance }),\n }\n const listed = session.events.list(filter)\n const limit = Math.min(Math.max(args.limit ?? MAX_EVENTS, 1), MAX_EVENTS)\n const keyOf = (id: number): string => { const owner = characters.find(character => character.id === id); return owner === undefined ? String(id) : characterKey(owner) }\n const shown = (events: readonly (typeof listed)[number][]) => events.map(event => ({\n id: event.id, turn: event.turn, round: event.round, text: event.text, importance: event.importance, tags: event.tags, involves: event.involves.map(keyOf),\n }))\n if (needle === undefined || needle === '') return shown(listed.slice(-limit))\n // What matches the words or the meaning of the text comes first, best first; a plain substring match still counts.\n const { queryVector } = await vectorOf(agent, needle, exec.signal)\n const ranked = session.searchEvents({\n text: needle, limit: 50,\n ...(queryVector === undefined ? {} : { vector: queryVector }),\n ...(filter.fromTurn === undefined ? {} : { fromTurn: filter.fromTurn }),\n ...(filter.toTurn === undefined ? {} : { toTurn: filter.toTurn }),\n ...(filter.minImportance === undefined ? {} : { minImportance: filter.minImportance }),\n ...(filter.locationId === undefined ? {} : { locationId: filter.locationId }),\n ...(filter.aboutItem === undefined ? {} : { itemId: filter.aboutItem }),\n })\n const allowed = new Set(listed.map(event => event.id))\n const first = ranked.filter(event => allowed.has(event.id))\n const rest = listed.filter(event => !first.some(hit => hit.id === event.id) && (event.text.toLowerCase().includes(needle) || event.tags.some(tag => tag.includes(needle))))\n return shown([...first, ...rest].slice(0, limit))\n },\n }),\n defineTool({\n name: 'recall_memories',\n description: 'What a character remembers of a situation, in the way it remembers it: its own version of events and what it believes, with older and less important things faded or gone when the chat has imperfect memory.',\n parameters: {\n character: { type: 'string', required: true, description: 'The key of the character.' },\n situation: { type: 'string', required: true, description: 'What is happening now, which is what reminds the character of things.' },\n },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { clarity: str, turn: int, text: str } } }, render: pretty },\n isConcurrencySafe: () => false,\n async execute(args, exec) {\n const agent = link(resolve, exec.agent)\n const { session, turn, policy } = agent\n const found = session.characters.list().find(character => characterKey(character) === args.character)\n if (found === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n return (await session.recallRanked({ characterId: found.id, situation: args.situation, turn, policy, ...(session.placements.get('character', found.id) === undefined ? {} : { locationId: session.placements.get('character', found.id)!.locationId }) }, exec.signal, await vectorOf(agent, args.situation, exec.signal))).map(entry => ({ clarity: entry.clarity, turn: entry.turn, text: entry.text }))\n },\n }),\n defineTool({\n name: 'read_records',\n description: 'Read the records as stored: the state of every character, the events of the given rounds (or all) with who took each in and how, the beliefs formed in those turns, and the open threads.',\n parameters: {\n rounds: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { turn: { type: 'integer', required: true }, round: { type: 'integer', required: true } } }, description: 'Only the events and beliefs of these rounds. Leave out for everything.' },\n sections: { type: 'array', items: { type: 'string', enum: READ_SECTIONS }, description: 'Only these parts of the records (the others come back empty); leave out for all. Asking for what you need keeps the answer short.' },\n relationships_since: { type: 'integer', description: 'Of the relationships, only those that changed in this turn or later.' },\n },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session, timeZone } = link(resolve, exec.agent)\n const view = session.records({ ...(args.rounds === undefined ? {} : { rounds: args.rounds }), ...(timeZone === undefined ? {} : { timeZone }), ...(args.sections === undefined ? {} : { only: args.sections as (keyof ReturnType<typeof session.records>)[] }), ...(args.relationships_since === undefined ? {} : { relationshipsSince: args.relationships_since }) })\n return JSON.parse(JSON.stringify(view)) as never\n },\n }),\n defineTool({\n name: 'list_variables',\n description: 'What the story keeps track of: each variable with the key it is changed by, what it is about (every character, item or place, or the whole world), what it measures, its bounds or words, its default, and who can tell its value.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: str, name: str, description: str, kind: str, subject: str, only: strs, min: { type: 'json', required: true }, max: { type: 'json', required: true }, options: strs, default: { type: 'json', required: true }, visibility: str, baseline: { type: 'boolean', required: true } } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return link(resolve, exec.agent).session.records().variable_defs\n },\n }),\n defineTool({\n name: 'get_agenda',\n description: 'What a character is expected to be doing and to have done: its routine now and next, what it has committed to that is due soon or overdue, what it is after, and its whole day. Times are in the story\\'s time zone.',\n parameters: { character: { type: 'string', required: true, description: 'The key of the character.' } },\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(args, exec) {\n const { session, timeZone } = link(resolve, exec.agent)\n const zone = timeZone ?? 'UTC'\n const found = session.characters.list().find(character => characterKey(character) === args.character)\n const state = session.clock.get()\n if (found === undefined) throw new NotFoundError(`there is no character \"${args.character}\"; list_characters shows the keys`)\n if (state === undefined) throw new NotFoundError('the story has no clock yet')\n const places = new Map(session.locations.list().map(place => [place.id, locationKey(place)]))\n const names = new Map(session.characters.list().map(character => [character.id, characterKey(character)]))\n const agenda = agendaAt(session, found.id, state.now, zone, { horizon: 48 * 3_600_000, engagements: 10, goals: 5 })\n const place = (id: number | undefined) => (id === undefined ? null : places.get(id) ?? null)\n const occurrence = (entry: typeof agenda.now) => (entry === undefined ? null : { activity: entry.window.activity, location: place(entry.window.locationId), from: localIso(entry.startsAt, zone), until: localIso(entry.endsAt, zone), interruptible: entry.window.interruptible })\n return JSON.parse(JSON.stringify({\n now: describeInstant(state.now, zone),\n routine_now: occurrence(agenda.now),\n routine_next: occurrence(agenda.next),\n engagements: agenda.engagements.map(entry => ({ id: entry.engagement.id, title: entry.engagement.title, at: localIso(entry.engagement.at, zone), location: place(entry.engagement.locationId), with: entry.engagement.participants.map(id => names.get(id) ?? String(id)), overdue: entry.overdue })),\n goals: agenda.goals.map(entry => ({ id: entry.intent.id, name: entry.intent.name, type: entry.intent.type, priority: entry.intent.priority, urgency: entry.intent.urgency, deadline: entry.deadlineAt === undefined ? null : localIso(entry.deadlineAt, zone), overdue: entry.overdue, plan: entry.intent.plan })),\n day: session.routines.list(found.id).map(window => ({ days: window.days.length === 0 ? 'every day' : window.days.join(','), from: minuteText(window.start), to: minuteText(window.end), activity: window.activity, location: place(window.locationId), interruptible: window.interruptible })),\n })) as never\n },\n }),\n defineTool({\n name: 'list_threads',\n description: 'List what is still open in the story: promises made, mysteries raised and goals not settled yet.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { id: int, text: str, opened_turn: int } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return link(resolve, exec.agent).session.records().open_threads\n },\n }),\n ]\n const authoringReads: ToolDefinition[] = options.authoring !== true ? [] : [\n defineTool({\n name: 'world_lint',\n description: 'What is inconsistent or unfinished in the world\\'s places and characters: places no one can reach or leave, characters in no place, names used twice, characters made up and not yet connected to anyone, ways with no way back. An error leaves the world inconsistent and has to be fixed; a warning should be fitted in; an info is only worth knowing.',\n parameters: {},\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { severity: str, code: str, subject: { type: 'json', required: true }, message: str } } }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n return JSON.parse(JSON.stringify(lintWorld(link(resolve, exec.agent).session))) as never\n },\n }),\n defineTool({\n name: 'list_consolidation',\n description: 'What was made up in play and has not been fitted into the world yet: characters and places, with the turn they were made in and why.',\n parameters: {},\n output: { schema: { type: 'json' }, render: pretty },\n isConcurrencySafe: () => true,\n async execute(_args, exec) {\n const { session } = link(resolve, exec.agent)\n return JSON.parse(JSON.stringify(session.consolidation.pending().map((item) => {\n const subject = item.kind === 'character' ? session.characters.get(item.subjectId) : session.locations.get(item.subjectId)\n return { id: item.id, kind: item.kind, key: subject === undefined ? String(item.subjectId) : item.kind === 'character' ? characterKey(subject as never) : locationKey(subject as never), name: subject?.name ?? '', made_in_turn: item.createdTurn, why: item.note }\n }))) as never\n },\n }),\n ]\n reads.push(...authoringReads)\n if (!options.write) return reads\n\n const done = { type: 'object', additionalProperties: false, properties: { writes: int, event_ids: ints, belief_ids: ints } } as const\n const written = (result: { writes: number; eventIds: number[]; beliefIds: number[] }) => ({ writes: result.writes, event_ids: result.eventIds, belief_ids: result.beliefIds })\n const perceivedBy = {\n type: 'array',\n description: 'Who took the event in: only characters who could actually have perceived it, each with how and, when it differs from the event, what they took in.',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n character: { type: 'string', required: true },\n mode: { type: 'string', enum: PERCEPTION_MODES },\n content: { type: 'string' },\n gist: { type: 'string' },\n accuracy: { type: 'string', enum: ACCURACIES },\n },\n },\n } as const\n\n const editSchema = recordsEditSchema({ ...(options.characters === undefined ? {} : { characters: options.characters }), changes: true, ...(options.authoring === true ? { authoring: true } : {}) })\n const writes: ToolDefinition[] = [\n {\n name: options.authoring === true ? 'edit_world' : 'edit_records',\n description: options.authoring === true\n ? 'Make up characters and places and fit them into the world, in one call, together or not at all: new characters (with their state and where they are), new places with their features and ways, new ways between places, relationship profiles between characters (one per direction), changes to places and ways, and corrections. If anything in it is refused, nothing is written and the reasons are returned: correct them and call again.'\n : 'Change the story\\'s records in one call, together or not at all: character states, new events (with where they happened and who took them in), corrections and retractions of draft events, revisions of what characters took in, changes to places and the ways between them, how characters stand towards each other, beliefs, and story threads. If anything in it is refused, nothing is written and the reasons are returned: correct them and call again.',\n parameters: editSchema as unknown as Record<string, unknown>,\n output: {\n schema: { type: 'object', properties: { writes: { type: 'integer' }, event_ids: { type: 'array', items: { type: 'integer' } }, belief_ids: { type: 'array', items: { type: 'integer' } }, character_keys: { type: 'array', items: { type: 'string' } }, place_keys: { type: 'array', items: { type: 'string' } }, item_keys: { type: 'array', items: { type: 'string' } }, variable_keys: { type: 'array', items: { type: 'string' } }, trigger_keys: { type: 'array', items: { type: 'string' } } }, required: ['writes', 'event_ids', 'belief_ids', 'character_keys', 'place_keys', 'item_keys', 'variable_keys', 'trigger_keys'], additionalProperties: false },\n render: (_args, value) => summary(options.authoring === true ? 'World changed' : 'Records changed')(_args, value as { writes: number }),\n },\n async execute(args, exec) {\n const { session, timeZone } = link(resolve, exec.agent)\n const result = session.edit({ ...parseRecordsEdit(args), ...(timeZone === undefined ? {} : { timeZone }) })\n return { writes: result.writes, event_ids: result.eventIds, belief_ids: result.beliefIds, character_keys: result.characterKeys ?? [], place_keys: result.placeKeys ?? [], item_keys: result.itemKeys ?? [], variable_keys: result.variableKeys ?? [], trigger_keys: result.triggerKeys ?? [] }\n },\n },\n ...(options.authoring !== true ? [] : [defineTool({\n name: 'resolve_consolidation',\n description: 'Say that something made up in play has been fitted into the world, and how: what you connected it to, or why nothing more is needed. Only after you have done it.',\n parameters: {\n id: { type: 'integer', required: true, description: 'The id list_consolidation gives.' },\n resolution: { type: 'string', required: true, description: 'What was done, in a sentence.' },\n },\n output: { schema: done, render: summary('Fitted in') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n if (args.resolution.trim() === '') throw new NotFoundError('say what was done to fit it in')\n session.consolidation.resolve(args.id, turn, args.resolution)\n return { writes: 1, event_ids: [], belief_ids: [] }\n },\n })]),\n defineTool({\n name: 'update_character_state',\n description: 'Change the current state of a character. Give only what changed: public_state is what anyone present can see (a present-tense description, not a log), inner_state is private, activity is what it is doing now.',\n parameters: {\n character: { type: 'string', required: true },\n public_state: { type: 'string' },\n inner_state: { type: 'string' },\n activity: { type: 'string' },\n },\n output: { schema: done, render: summary('State updated') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n const { character, public_state, inner_state, activity } = args\n return written(session.edit({\n turn,\n states: [{ character, ...(public_state === undefined ? {} : { publicState: public_state }), ...(inner_state === undefined ? {} : { innerState: inner_state }), ...(activity === undefined ? {} : { activity }) }],\n }))\n },\n }),\n defineTool({\n name: 'move_character',\n description: 'Move a character to another place. It must be possible: there has to be a way over open exits from where it is, unless ignore_exits says the story itself carries it (carried off, teleported, falls). The reasons come back if it is not.',\n parameters: {\n character: { type: 'string', required: true },\n to: { type: 'string', required: true, description: 'The key of the place, as list_locations gives it.' },\n position: { type: 'string', description: 'Where in the place, in words: \"at the bar\", \"by the door\".' },\n feature: { type: 'string', description: 'The key of a feature of the place it is at.' },\n ignore_exits: { type: 'boolean' },\n },\n output: { schema: done, render: summary('Moved') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, moves: [{ character: args.character, to: args.to, ...(args.position === undefined ? {} : { position: args.position }), ...(args.feature === undefined ? {} : { feature: args.feature }), ...(args.ignore_exits === true ? { ignoreExits: true } : {}) }] }))\n },\n }),\n defineTool({\n name: 'record_event',\n description: 'Record something that objectively happened, as a short factual past-tense statement, and who took it in.',\n parameters: {\n text: { type: 'string', required: true },\n importance: { type: 'integer', required: true, description: `From ${IMPORTANCE_MIN} (a passing detail) to ${IMPORTANCE_MAX} (turns the story).` },\n round: { type: 'integer', description: 'The round of the turn it happened in; 1 by default.' },\n tags: strings,\n involves: { ...strings, description: 'The keys of the characters the event is about.' },\n perceived_by: perceivedBy,\n },\n output: { schema: done, render: summary('Event recorded') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n // Written directly, not by a keeper that checks it afterwards: the event is final at once.\n return written(session.edit({\n turn,\n events: [{\n turn, round: args.round ?? 1, text: args.text, importance: args.importance,\n ...(args.tags === undefined ? {} : { tags: args.tags }),\n ...(args.involves === undefined ? {} : { involves: args.involves }),\n perceivedBy: (args.perceived_by ?? []).map(entry => ({ character: entry.character, mode: (entry.mode ?? 'witnessed') as (typeof PERCEPTION_MODES)[number], ...(entry.content === undefined ? {} : { content: entry.content }), ...(entry.gist === undefined ? {} : { gist: entry.gist }), ...(entry.accuracy === undefined ? {} : { accuracy: entry.accuracy as (typeof ACCURACIES)[number] }) })),\n }],\n }, { seal: true }))\n },\n }),\n defineTool({\n name: 'remember',\n description: 'Record something a character has come to believe or know, from that character\\'s own point of view.',\n parameters: {\n character: { type: 'string', required: true },\n kind: { type: 'string', required: true, enum: MEMORY_KINDS },\n text: { type: 'string', required: true },\n about: { ...strings, description: 'The keys of the characters it is about.' },\n importance: { type: 'integer', required: true },\n },\n output: { schema: done, render: summary('Remembered') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, beliefs: [{ character: args.character, kind: args.kind as (typeof MEMORY_KINDS)[number], text: args.text, importance: args.importance, ...(args.about === undefined ? {} : { about: args.about }) }] }))\n },\n }),\n defineTool({\n name: 'open_thread',\n description: 'Open a story thread: a promise made, a mystery raised or a goal set that is not settled yet.',\n parameters: { text: { type: 'string', required: true, description: 'One sentence.' } },\n output: { schema: done, render: summary('Thread opened') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, threadsOpened: [args.text] }))\n },\n }),\n defineTool({\n name: 'resolve_thread',\n description: 'Mark an open story thread as settled.',\n parameters: { id: { type: 'integer', required: true, description: 'The id list_threads gives.' } },\n output: { schema: done, render: summary('Thread resolved') },\n async execute(args, exec) {\n const { session, turn } = link(resolve, exec.agent)\n return written(session.edit({ turn, threadsResolved: [args.id] }))\n },\n }),\n ]\n return [...reads, ...writes]\n}\n","import { resolve } from 'node:path'\nimport { Service, type Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-tools'\nimport z from '@deepseek-ai/schemastery'\nimport { createSession, deleteSession, forkSession, type ForkOptions, type ForkSource, listSessions, openSession, removeSnapshot, restoreSnapshot, sessionDatabase, snapshotNames, takeSnapshot, type SessionInit, type SessionListing } from './sessions.ts'\nimport type { SessionStore, StoreOptions } from './store.ts'\nimport type { RecallQuery, Recalled } from './memory/recall.ts'\nimport type { SemanticRanker } from './memory/ranker.ts'\nimport { poolCandidates } from './memory/recall.ts'\nimport { createDiceTools } from './tools/dice.ts'\nimport { createTools, type AgentResolver } from './tools/index.ts'\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n roleplayState: RoleplayState\n }\n}\n\nexport interface Config {\n /** `delete` keeps each session in a single file that can be copied; `wal` allows readers while writing. */\n journalMode: 'delete' | 'wal'\n /**\n * Whether the model-facing tools that change the records are registered too. The reading\n * tools are always there; leave writing off where another agent is responsible for the records.\n */\n writeTools: boolean\n /**\n * Whether the dice tools (`roll_dice`, `roll_check`, `list_checks`) are registered for every agent of a roleplay session. Leave off where another plugin\n * decides which agents may roll, as the roleplay core does with its per-agent tool settings.\n */\n diceTools: boolean\n}\n\nexport const Config: z<Config> = z.object({\n journalMode: z.union(['delete', 'wal'] as const).default('delete'),\n writeTools: z.boolean().default(false),\n diceTools: z.boolean().default(false),\n})\n\n/** A session's repositories. Connections belong to the service, so there is nothing to close. */\nexport type Session = Omit<SessionStore, 'close' | 'snapshotTo'> & {\n /**\n * {@link SessionStore.recall}, with the over-retrieved pool reranked when a ranker is registered with\n * `roleplayState.rankMemories`. The one call for anything that reminds a character of something.\n */\n recallRanked(query: Omit<RecallQuery, 'characters'>, signal?: AbortSignal, options?: { queryVector?: readonly number[] }): Promise<Recalled[]>\n}\n\n/**\n * Roleplay session state for other plugins. It creates and opens sessions\n * under a sessions folder, shares one connection per session, and closes them\n * all when the plugin unloads.\n */\nexport class RoleplayState extends Service {\n private readonly sessions = new Map<string, { store: SessionStore; session: Session }>()\n private readonly options: StoreOptions\n private readonly resolvers = new Set<AgentResolver>()\n private readonly rankers: SemanticRanker[] = []\n\n constructor(ctx: Context, config: Partial<Config> = {}) {\n super(ctx, 'roleplayState')\n this.options = { journalMode: config.journalMode ?? 'delete' }\n ctx.effect(() => () => { this.closeAll() }, 'roleplay-state: connections')\n const resolve: AgentResolver = (agentSessionId) => {\n for (const resolver of this.resolvers) {\n const found = resolver(agentSessionId)\n if (found !== undefined) return found\n }\n return undefined\n }\n ctx.inject(['tools'], (scope) => {\n for (const tool of createTools(resolve, { write: config.writeTools ?? false })) scope.tools.register(tool)\n if (config.diceTools === true) for (const tool of createDiceTools(resolve)) scope.tools.register(tool)\n })\n }\n\n /**\n * Let what characters remember be ranked by meaning, with an embedding model or a reranker\n * from another plugin. The latest one registered is used, by every recall: the tools, and the\n * plugins that run characters through `session.recallRanked`. Where it fails, recall carries on\n * with the cues alone and says so in the log.\n * @returns what removes it again.\n */\n rankMemories(ranker: SemanticRanker): () => void {\n this.rankers.push(ranker)\n return () => { this.rankers.splice(this.rankers.indexOf(ranker), 1) }\n }\n\n /**\n * Tell the tools which roleplay session an agent works in. The plugin that runs agents\n * calls this with a function from the id of an agent's session to its roleplay session,\n * the turn it is playing and how its characters remember.\n * @returns what removes the binding again.\n */\n bind(resolver: AgentResolver): () => void {\n this.resolvers.add(resolver)\n return () => { this.resolvers.delete(resolver) }\n }\n\n /**\n * Create a session and open it. Its id is `init.id` or a generated UUID, and is in `metadata.get().id`.\n * @throws {ConflictError} when a session with that id exists.\n */\n createSession(sessionsDir: string, init: SessionInit): Session {\n const store = createSession(sessionsDir, init, this.options)\n return this.track(resolve(sessionDatabase(sessionsDir, store.metadata.get().id)), store)\n }\n\n /** @throws {NotFoundError} when the session does not exist. */\n openSession(sessionsDir: string, id: string): Session {\n const key = resolve(sessionDatabase(sessionsDir, id))\n return this.sessions.get(key)?.session ?? this.track(key, openSession(sessionsDir, id, this.options))\n }\n\n /** The metadata of every session under the folder; sessions that cannot be read are reported, not thrown. */\n listSessions(sessionsDir: string): SessionListing {\n return listSessions(sessionsDir, this.options, id => this.sessions.get(resolve(sessionDatabase(sessionsDir, id)))?.store)\n }\n\n /** Release a session's connection; opening it again reconnects. */\n closeSession(sessionsDir: string, id: string): void {\n const key = resolve(sessionDatabase(sessionsDir, id))\n this.sessions.get(key)?.store.close()\n this.sessions.delete(key)\n }\n\n /** Keep a consistent copy of a session's database under a name (a lowercase name of letters, digits and hyphens), replacing one of that name. */\n snapshot(sessionsDir: string, id: string, name: string): void {\n const key = resolve(sessionDatabase(sessionsDir, id))\n const open = this.sessions.get(key)?.store\n if (open !== undefined) { takeSnapshot(sessionsDir, id, name, open); return }\n const store = openSession(sessionsDir, id, this.options)\n try { takeSnapshot(sessionsDir, id, name, store) } finally { store.close() }\n }\n\n /** The names of the snapshots a session has. */\n snapshots(sessionsDir: string, id: string): string[] {\n return snapshotNames(sessionsDir, id)\n }\n\n /** Delete a snapshot, if there is one. */\n removeSnapshot(sessionsDir: string, id: string, name: string): void {\n removeSnapshot(sessionsDir, id, name)\n }\n\n /**\n * Put the database of a session back as it was in a snapshot. The connection is released first, so anything that\n * holds the session from before has to ask for it again: nothing may be using it.\n * @throws {NotFoundError} when there is no such snapshot.\n */\n restore(sessionsDir: string, id: string, name: string): void {\n this.closeSession(sessionsDir, id)\n restoreSnapshot(sessionsDir, id, name, this.options)\n }\n\n /**\n * Make a new session from a snapshot of another, or from its database as it is (nothing may be writing to it): the new one has\n * a folder of its own with the database, the settings and the snapshots named in `keep`, and its own id and name.\n * @throws {ConflictError} when the new id exists. @throws {NotFoundError} when a snapshot does not exist.\n */\n fork(sessionsDir: string, fromId: string, toId: string, from: { snapshot: string } | { live: true }, options: ForkOptions): void {\n if ('snapshot' in from) { forkSession(sessionsDir, fromId, toId, from, options, this.options); return }\n const open = this.sessions.get(resolve(sessionDatabase(sessionsDir, fromId)))?.store\n const store = open ?? openSession(sessionsDir, fromId, this.options)\n try { forkSession(sessionsDir, fromId, toId, { live: store } satisfies ForkSource, options, this.options) } finally { if (open === undefined) store.close() }\n }\n\n /** Close a session and remove its folder, including everything else kept in it. */\n deleteSession(sessionsDir: string, id: string): void {\n this.closeSession(sessionsDir, id)\n deleteSession(sessionsDir, id)\n }\n\n private track(key: string, store: SessionStore): Session {\n const session: Session = {\n metadata: store.metadata,\n characters: store.characters,\n characterStates: store.characterStates,\n factions: store.factions,\n factionStates: store.factionStates,\n factionMemberships: store.factionMemberships,\n factionRelationships: store.factionRelationships,\n factionIntents: store.factionIntents,\n lore: store.lore,\n intents: store.intents,\n events: store.events,\n memories: store.memories,\n threads: store.threads,\n summaries: store.summaries,\n pendingCommits: store.pendingCommits,\n locations: store.locations,\n placements: store.placements,\n relationships: store.relationships,\n knowledge: store.knowledge,\n consolidation: store.consolidation,\n slots: store.slots,\n items: store.items,\n visualIdentities: store.visualIdentities,\n clock: store.clock,\n variables: store.variables,\n routines: store.routines,\n engagements: store.engagements,\n triggers: store.triggers,\n dice: store.dice,\n planMove: (characterId, move) => store.planMove(characterId, move),\n planKnownMove: (characterId, move) => store.planKnownMove(characterId, move),\n move: (characterId, move) => store.move(characterId, move),\n recallIndex: store.recallIndex,\n transaction: fn => store.transaction(fn),\n recall: (query, evidence) => store.recall(query, evidence),\n recallStored: (query, options) => store.recallStored(query, options),\n searchEvents: search => store.searchEvents(search),\n recallCandidates: query => store.recallCandidates(query),\n storedEvidence: (query, queryVector) => store.storedEvidence(query, queryVector),\n recallPool: (query, evidence) => store.recallPool(query, evidence),\n finishRecall: (pool, turn, rerank) => store.finishRecall(pool, turn, rerank),\n recallRanked: async (query, signal, options = {}) => {\n const pool = store.recallPool(query, store.storedEvidence(query, options.queryVector))\n const ranker = this.rankers.at(-1)\n if (ranker === undefined) return store.finishRecall(pool, query.turn)\n try {\n const judged = await ranker({ situation: query.situation, candidates: poolCandidates(pool), ...(signal === undefined ? {} : { signal }) })\n return store.finishRecall(pool, query.turn, judged)\n } catch (error) {\n if (signal?.aborted === true) throw error\n this.ctx.logger.warn(`roleplay-state: reranking memories failed, using retrieval alone: ${error instanceof Error ? error.message : String(error)}`)\n return store.finishRecall(pool, query.turn)\n }\n },\n edit: (edit, options) => store.edit(edit, options),\n runTriggers: options => store.runTriggers(options),\n lapseNotes: (turn, kept) => store.lapseNotes(turn, kept),\n deliverNotes: (notes, clock) => store.deliverNotes(notes, clock),\n records: scope => store.records(scope),\n }\n this.sessions.set(key, { store, session })\n return session\n }\n\n private closeAll(): void {\n for (const { store } of this.sessions.values()) store.close()\n this.sessions.clear()\n }\n}\n\nexport const name = '@dsh-agentic-roleplay/state'\n\nexport function apply(ctx: Context, config: Config): void {\n new RoleplayState(ctx, config)\n}\n","import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'\nimport type { CharacterId } from 'dsh-roleplay-model'\nimport { vectorOf, type AgentLink } from './index.ts'\nimport { characterKey, locationKey } from '../records/edit-types.ts'\nimport { itemKey } from '../records/items.ts'\nimport { mentioned } from '../memory/recall.ts'\n\n/**\n * The tools of one character's own agent. They are built for that character and registered\n * on that agent alone, so what they return is only what that character took in and believes:\n * agents running side by side for different characters each get their own, and none can\n * reach another's memory.\n */\n/** Where the character is, as a recall cue: what happened where it stands comes back more readily. */\nconst placeOf = (session: AgentLink['session'], characterId: CharacterId): { locationId?: number } => {\n const placement = session.placements.get('character', characterId)\n return placement === undefined ? {} : { locationId: placement.locationId }\n}\n\nexport function createCharacterTools(link: () => AgentLink, characterId: CharacterId): ToolDefinition[] {\n return [\n defineTool({\n name: 'recall_my_memories',\n description: 'Ask yourself what you remember about something: a person, an object, a place or an earlier moment. You get your own version of it, what you took in yourself and what you believe, and what has faded comes back as hazy or not at all. Use it only when you need a memory that the situation does not already give you.',\n parameters: {\n about: { type: 'string', required: true, description: 'What to remember: a name, an object, a topic or a short description of the moment.' },\n person: { type: 'string', description: 'Only what concerns this person (a name or alias you know): everything you remember of them.' },\n },\n output: {\n schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { clarity: { type: 'string', required: true }, turn: { type: 'integer', required: true }, text: { type: 'string', required: true } } } },\n render: (_args, value) => [{ type: 'text', text: value.length === 0 ? 'You do not remember anything about that, and there is nothing more to find: go on with what you know.' : value.map(entry => `- (${entry.clarity === 'clear' ? '' : entry.clarity === 'faded' ? 'the details are fuzzy' : 'you barely remember'}) ${entry.text}`.replace('- () ', '- ')).join('\\n') }],\n },\n isConcurrencySafe: () => false,\n async execute(args, exec) {\n const agent = link()\n const { session, turn, policy } = agent\n const who = args.person === undefined || args.person.trim() === '' ? [] : [...mentioned(args.person, session.characters.list())].filter(id => id !== characterId)\n if (args.person !== undefined && args.person.trim() !== '' && who.length === 0) return []\n const situation = who.length === 0 ? args.about : `${args.about} ${args.person}`\n return (await session.recallRanked({ characterId, situation, turn, policy, ...(who.length === 0 ? {} : { about: who }), ...placeOf(session, characterId) }, exec.signal, await vectorOf(agent, situation, exec.signal))).map(entry => ({ clarity: entry.clarity, turn: entry.turn, text: entry.text }))\n },\n }),\n defineTool({\n name: 'recall_my_known_entities',\n description: 'Recall the people, places, things and routes you know exist. This says only that you know them, not where they are now or their current state.',\n parameters: { about: { type: 'string', description: 'Optional name or word to narrow the result.' } },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { kind: { type: 'string', required: true }, key: { type: 'string', required: true }, name: { type: 'string', required: true } } } }, render: (_args, value) => [{ type: 'text', text: value.length === 0 ? 'You know of nothing matching that.' : value.map(entry => `- ${entry.kind}: ${entry.name}`).join('\\n') }] },\n isConcurrencySafe: () => true,\n async execute(args) {\n const { session } = link()\n const found = [\n ...session.relationships.from(characterId).flatMap(relation => { const character = session.characters.get(relation.toId); return character === undefined ? [] : [{ kind: 'character', key: characterKey(character), name: character.name }] }),\n ...session.factionRelationships.from('character', characterId).filter(relation => relation.toKind === 'faction').flatMap(relation => { const faction = session.factions.get(relation.toId); return faction === undefined ? [] : [{ kind: 'faction', key: faction.sourceId ?? String(faction.id), name: faction.name }] }),\n ...session.knowledge.list(characterId, 'location').flatMap(entry => { const place = session.locations.get(entry.subjectId); return place === undefined ? [] : [{ kind: 'location', key: locationKey(place), name: place.name }] }),\n ...session.knowledge.list(characterId, 'item').flatMap(entry => { const item = session.items.get(entry.subjectId); return item === undefined ? [] : [{ kind: 'item', key: itemKey(item), name: item.name }] }),\n ...session.knowledge.list(characterId, 'exit').flatMap(entry => { const exit = session.locations.allExits().find(candidate => candidate.id === entry.subjectId); const from = exit === undefined ? undefined : session.locations.get(exit.fromId); const to = exit === undefined ? undefined : session.locations.get(exit.toId); return from === undefined || to === undefined ? [] : [{ kind: 'route', key: `${locationKey(from)} -> ${locationKey(to)}`, name: `${from.name} to ${to.name}` }] }),\n ]\n const needle = args.about?.trim().toLowerCase()\n return needle === undefined || needle === '' ? found : found.filter(entry => `${entry.key} ${entry.name}`.toLowerCase().includes(needle))\n },\n }),\n defineTool({\n name: 'recall_my_lore',\n description: 'Recall established lore that you know: history, customs, legends, places and other background knowledge. Unknown lore is never returned.',\n parameters: { about: { type: 'string', required: true, description: 'A name, subject or phrase to look for in what you know.' } },\n output: { schema: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { key: { type: 'string', required: true }, title: { type: 'string', required: true }, kind: { type: 'string', required: true }, text: { type: 'string', required: true } } } }, render: (_args, value) => [{ type: 'text', text: value.length === 0 ? 'You do not know any lore matching that.' : value.map(entry => `- ${entry.title} [${entry.kind}] (${entry.key}): ${entry.text}`).join('\\n') }] },\n isConcurrencySafe: () => true,\n async execute(args) {\n const needle = args.about.trim().toLowerCase()\n return link().session.knowledge.list(characterId, 'lore').flatMap(known => {\n const lore = link().session.lore.get(known.subjectId)\n if (lore === undefined || !`${lore.title} ${lore.summary} ${lore.body}`.toLowerCase().includes(needle)) return []\n return [{ key: lore.sourceId ?? String(lore.id), title: lore.title, kind: lore.kind, text: lore.body || lore.summary }]\n })\n },\n }),\n ]\n}\n"],"mappings":";;;;;;;;;AAOA,MAAa,kBAAkB,CAAC,YAAY,KAAK;AACjD,MAAa,kBAAkB;CAAC;CAAa;CAAc;AAAY;AACvE,MAAa,kBAAkB,CAAC,UAAU,OAAO;;;ACTjD,MAAa,eAAe;CAAC;CAAQ;CAAc;CAAS;CAAU;CAAc;CAAgB;CAAS;AAAU;AACvH,MAAa,kBAAkB;CAAC;CAAU;CAAU;CAAa;CAAU;AAAW;AACtF,MAAa,kBAAkB;CAAC;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