> For the complete documentation index, see [llms.txt](https://docs.amigo.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.amigo.ai/data/world-model.md).

# World Model

The world model is the platform's shared event and entity layer. Connectors, agent tools, operational workflows, and analytics can contribute or consume workspace-scoped data through supported interfaces. Agents receive a bounded amount of selected context automatically and use tools for facts that are not already present.

This creates a feedback loop between data and agent activity without making every observation automatically available or writable. Session construction selects ambient context, tools perform explicit reads and writes, and accepted observations can become inputs to later projections and analytics.

The world model preserves supported observations with provenance and a source-class confidence value. Current entity state is a computed projection over retained relevant events rather than an in-place record update. Projection rules can therefore resolve conflicting inputs without discarding their retained history.

{% hint style="info" %}
This is an event-sourced architecture. If you have worked with event sourcing in other systems, the principles are the same. If you have not, the core idea is straightforward: instead of updating records in place, you append facts to a log. The current state of any entity is derived by replaying the relevant facts.
{% endhint %}

## Data Pipeline

<figure><img src="/files/6M4hFpfEaupN74V0i82m" alt="Data pipeline: external systems through connectors and unification to the world model event store, entity resolution, projections, analytics, and policy-gated outbound delivery"><figcaption></figcaption></figure>

Data enters from external systems through connectors, passes through unification into the event store, and resolves into entity projections. Agent conversations add source-attributed observations to the same model. Metrics and analytics read the resulting state and history. Outbound policies separately decide which events are eligible for delivery, and human approval creates a proposal for a specific mutation without changing the source event's confidence.

## Why Event Sourcing for Healthcare

Healthcare data varies widely in structure, freshness, and authority. The world model is designed to make those differences explicit instead of treating every input as equally reliable.

**Most clinical data is low quality.** Outside of billing, revenue cycle management, and some operational data, the information in healthcare systems is far from clean. Clinical notes are unstructured free text. Documentation outputs vary in accuracy depending on the model, source quality, and complexity of the encounter. EHR inputs are frequently copy-pasted templates carried forward from visit to visit with minor edits, making it hard to distinguish current facts from stale ones. Billing and RCM data is structured because money depends on it. Clinical data does not have the same forcing function, and the quality reflects that.

**Inbound data from patients is not trustworthy by default.** Callers give wrong dates of birth, confuse medication names, misremember their doctor's name, or provide incomplete details. Some calls are pranks. Some are from people who are confused, stressed, or in pain. You cannot treat patient-provided information as verified fact. It is input that needs to be scored, compared against existing records, and promoted or discarded based on corroboration.

**External systems have uneven reliability and throughput.** EHRs, FHIR stores, practice management systems, and insurance verification services all behave differently. Response times vary, timeouts occur, and some sources can return stale data. Integrations should therefore expose failure and freshness rather than assume constant availability.

**Traditional record-update approaches break down here.** If you update records in place, you lose the trail of what the system believed and when. When a downstream write fails, you have no clean way to know what state you were trying to reach. When two sources disagree, the last write wins by accident, not by policy. World-model observations instead carry source and confidence, with supersession data where applicable. Current state is projected without rewriting the contributing events. Historical availability remains subject to explicit lifecycle actions, retention, and the bounds of each read surface.

## Four Invariants

The world model follows four core rules, with the lifecycle exceptions called out below.

### 1. Events Are the Only Source of Truth

Supported world-model write paths add events rather than editing the projected entity row. The serving state is recomputed asynchronously from the retained events relevant to that entity.

Under normal retention, competing observations remain separate events. Projection chooses current values by confidence class and uses recency as the tiebreaker within a class, rather than blindly applying global last-write-wins behavior.

### 2. Events Are Append-Only and Immutable

An accepted event is not updated in place. If new information contradicts an earlier event, a new event can supersede it while both remain available under normal retention. Authorized retention, erasure, and workspace-lifecycle operations remain separate exceptions.

This is what makes dirty data tractable. You do not have to get it right the first time. Record what you learned, then add a correction with its own provenance. While the contributing events remain retained, the projection can select the correction without rewriting the earlier observation.

This matters for healthcare operations because it provides:

* **Projection evidence** - Retained source events can explain which observations contributed to modeled state.
* **Temporal analysis** - Historical event reads can support point-in-time reconstruction where the required events and projection logic remain available.
* **Correction without in-place mutation** - A new event can supersede an earlier observation instead of editing it.

### 3. Entity State Is a Pure Function of Events

The entity-state projection is deterministic for the same retained input set and projection version. Projection runs asynchronously from event acceptance, so a successful write can precede the updated serving view. Model-generated memory and narrative products follow separate, non-deterministic derivations.

This determinism makes current entity state explainable and repeatable. Outbound delivery is a separate path: a published event is evaluated against destination policy, and the connector sends that eligible event payload without rebuilding the entity projection at delivery time. A patient's phone number might still project from a higher-confidence EHR observation instead of a lower-confidence conversational observation, but only an event selected by outbound policy is considered for external delivery.

#### Multi-Level Projections

Entity state is one derived view, but not the only one. Different derived products use different methods. The entity-state fold and structured connector projections are deterministic. Episodic memory extraction and semantic user-model consolidation are model-generated, bounded processes that retain lineage to their supporting observations; identical inputs do not guarantee identical narrative text.

```mermaid
flowchart TD
    events["Raw Events\n(confidence-scored, append-only)"] --> entity["Entity State\n(patient, provider, appointment)"]
    events --> episodic["Episodic Observations\n(model-extracted, source-linked)"]
    episodic --> semantic["User Model\n(bounded semantic consolidation)"]
    entity --> clinical["Structured Context\n(deterministic connector projection)"]
    entity --> analytics["Analytics and Operational Views"]
```

| Level                                | What It Projects                                                                 | Derived From                              |
| ------------------------------------ | -------------------------------------------------------------------------------- | ----------------------------------------- |
| **Entity state**                     | Current state of each patient, provider, appointment, and other entity           | Raw events                                |
| **Conversation memory**              | Episodic observations and a consolidated user model with source lineage          | Conversation transcripts and prior memory |
| **Structured context**               | Connector-derived context such as current conditions, medications, and allergies | Current entity and connector records      |
| **Operational and analytical views** | Scheduling, quality, and workflow-specific summaries                             | The inputs defined by each view           |

A new event can update entity state after asynchronous projection and can become input to other derived products on their own processing schedules. Each product documents its own derivation and freshness rather than inheriting a universal deterministic chain.

### 4. Confidence Resolves Conflicts

When two sources provide conflicting information about the same fact, the projection first compares their source-class confidence. Recency breaks ties within the same class. This prevents a newer low-authority observation from automatically replacing a higher-authority one.

| Confidence | Source               | Example                                                                                                                                           |
| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| **1.0**    | Authoritative        | Manual entry, explicit relationships, authoritative API writes                                                                                    |
| **0.95**   | Human-approved class | Named confidence class retained in the world-model registry; current external-write proposal decisions do not promote source observations into it |
| **0.9**    | High                 | Operator-verified data, high-quality adapter output                                                                                               |
| **0.8**    | EHR-trusted          | Trusted clinical data from EHR systems                                                                                                            |
| **0.7**    | Verified             | LLM-verified data, browser-scraped portal data, EHR-ingested records                                                                              |
| **0.5**    | Self-report          | Patient-submitted form data, patient-confirmed information                                                                                        |
| **0.3**    | Agent raw            | Raw voice agent inference, unverified extraction from conversation                                                                                |
| **0.0**    | Rejected             | Contradicted by a higher-confidence source, or human-rejected                                                                                     |

Within the same confidence class, the most recent event wins. Across confidence classes, higher confidence always wins regardless of recency. A verified EHR record will not be overwritten by something a caller mentioned on a phone call, but two consecutive EHR updates will resolve to the most recent one.

Confidence is a source-class ranking, not model-reported certainty. Supported agent-originated clinical writes default to the `agent_raw` class unless a trusted server path supplies a different allowed value. Later observations from a higher-ranked source can supersede the projected value without erasing retained provenance.

Phone projections normalize valid numbers before caller matching. International country codes are preserved, North American numbers are standardized when the country can be inferred safely, and non-phone text is excluded. Ambiguous national formats are retained without inventing a country code. This normalization improves matching across differently formatted source values but does not replace identity verification.

Entity-state fields retain the winning event's source and confidence. Other derived products do not inherit a universal confidence rule: structured connector projections, generated memory, and analytical views each define their own derivation and evidence. Consumers should use the provenance and quality signals exposed by the specific product rather than assuming confidence propagates unchanged through every downstream view.

## Three Data Channels

{% hint style="info" %}
It is useful to think about agent data access through three channels. The exact payload and tools depend on the service, session, runtime, and workspace configuration.
{% endhint %}

### Ambient

Selected data that is pushed into the agent's context without a tool call when the session and service configuration make it available. Examples can include patient identity, upcoming appointments, or recent encounter context. Missing or unavailable source data is not invented.

This channel reduces repetitive lookups for the bounded context selected at session or turn construction. It does not guarantee that every current clinical or operational fact is loaded; the agent still uses queried tools for authoritative details outside the ambient payload.

### Queried

Data that the agent retrieves on demand through tool calls during a conversation. The agent decides it needs specific information and requests it. Examples: searching for available appointment slots, looking up insurance details, checking medication lists.

Queried data covers information that is too large, too dynamic, or too specific to include in ambient context. Tools should remain the authoritative path for details that require a current lookup.

### Extracted

Supported extraction and write tools can capture structured observations from a conversation. Agent-originated clinical writes normally use the `agent_raw` source class unless a trusted server path assigns another allowed value.

During a live voice call, the system can extract configured structured patient fields from recent conversation context, including contact, demographic, language, address, and insurance information. Captured fields are written as source-attributed events and can become available before the call ends.

Extraction is an explicit configured runtime capability. Do not assume that every statement in a conversation becomes a world-model event.

Extracted data does not go directly to the EHR. It enters the world model with source provenance and confidence. Outbound policies apply source eligibility, confidence thresholds, schema checks, and destination rules; low-confidence observations are skipped rather than promoted automatically. Where the private-preview review capability is enabled, a configured mutation can create a separate external write proposal. See [Connectors and EHR Integration](/data/connectors-and-ehr.md).

## Open Schema

Traditional healthcare systems force data into fixed schemas - FHIR resources, HL7 segments, proprietary EHR tables. If information does not fit a predefined category, it gets shoehorned, truncated, or dropped. The schema is a constraint on what the system can know.

Entity-type and event-type fields are text rather than database enums, so trusted producers can introduce a new type without an enum migration. That does not make arbitrary input self-structuring: the producer must still provide a valid event, and consumers need projection or query support for the new shape.

Free-form event and entity type fields let trusted producers represent new structures without a database enum migration. That flexibility is still bounded by the caller's write scope, registered enrichment keys, route validation, and the projection support available for a new type.

## Entity Ontology

Entity types use ontological categories rather than domain-specific roles. A `person` entity can be a patient, a practitioner, or both - the projection function detects roles from the underlying event data rather than requiring a type declaration up front.

Person projection is role-aware. It examines the FHIR resource types on an entity's events to detect which roles the person fills and produces output that includes the relevant sections for each role. A person entity with patient events gets demographics and clinical sections. One with practitioner events gets a profile section. A merged entity with both gets all sections plus a roles list. This means a single person entity can represent the same individual across clinical and operational contexts.

### FHIR-Sourced Entity Attributes

When data arrives through EHR connectors that support FHIR, the projection pipeline surfaces a rich set of fields as directly queryable entity attributes. This means agent tools can filter, search, and reason over these fields without parsing raw FHIR resources.

| Entity Type      | Projected Fields                                                                                                                                                                                                                                                                                              |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Patient**      | Full address (line, city, state, postal code, country), preferred language, marital status, race, ethnicity, emergency contact (name, phone, relationship), facility assignment, primary insurance (payer name, practice payer ID, member ID, policyholder name, policyholder relationship, policyholder DOB) |
| **Appointment**  | Participants (provider, patient, location references and display names), appointment type, modality, duration, timezone, cancellation reason                                                                                                                                                                  |
| **Slot**         | Provider, facility, specialty, visit type IDs and names                                                                                                                                                                                                                                                       |
| **Practitioner** | Member ID, scheduling eligibility                                                                                                                                                                                                                                                                             |
| **Location**     | Full address, timezone, facility identifier, geographic coordinates                                                                                                                                                                                                                                           |

State and territory values are normalized to standard two-letter abbreviations (e.g., "Virginia" becomes "VA"), so agent queries and licensed-state filters work consistently regardless of how the source system formats addresses.

These attributes participate in the same confidence-scored projection as all other entity data. When the same field arrives from multiple sources, the standard resolution rules apply - higher confidence wins, with recency as the tiebreaker within the same confidence class.

Other built-in entity types - place, organization, outbound task, call, and encounter - have dedicated projection logic. Unknown types can fall back to generic projection; richer custom projections require a supported configuration or implementation path.

## Entity Enrichment

Entities rarely arrive with every attribute an operator, connector, or agent would want to track on them. A practice might want to record a patient's preferred language, a risk tier, a preferred communication channel, a consent flag, or a dozen other workspace-specific fields that no FHIR resource or predefined schema covers. Enrichment is how those attributes are attached to an entity without giving up the confidence model that makes the rest of the world model trustworthy.

Enrichment is not a schema extension or a bag of extra columns. Each enrichment value is a per-key event, written through the same path as other world-model events, carrying provenance fields such as source, source system, confidence, and effective time. A patient's preferred language from a human operator, a configured data import, and a call transcript can coexist as separate events; the projection selects the current value by confidence class and then recency within a class.

### Registry-Governed Keys

What separates enrichment from a free-for-all custom-fields bag is the registry. Each workspace declares the keys it tracks up front - for a given entity type, what values are allowed, what type they must be, what the minimum write confidence is, whether the value is PII. Supported value types cover scalar cases (string, number, boolean, date) and richer ones (enum, JSON).

Writes against unregistered keys are rejected at the API boundary. Agent-extracted values whose key is not registered are silently dropped - they never enter the event stream or compete with governed values. This gives admins full control over which attributes are tracked without needing to gate capture at each source; uncontrolled agent enthusiasm cannot pollute the schema.

The key identifier and value type are immutable after registration. To change them, admins create a new key and migrate. Unregistering a key stops future writes but does not itself rewrite existing `entity.enriched` events; separate retention or source-lifecycle actions can still affect historical availability.

### Why This Matters

The same pattern handles manual admin edits, supported connector backfills, structured intake capture, and agent-extracted values. Each event retains its source and confidence, allowing a higher-confidence system import or human correction to outrank a conversational extraction while preserving the contributing observations.

This makes registered custom attributes source-attributed, confidence-resolved, and queryable with their event provenance.

## Entity Search

The current entity list supports case-insensitive text search across identifiers, display name, entity type, medical-record number, and phone, with additional filters for entity type, source, source system, FHIR resource type, and projection availability. The entity-intelligence search surface provides display-name search with selected filters.

Meaning-based entity retrieval is not currently available. The legacy `search_semantic` compatibility tool returns no results; use the supported text and field filters instead.

## Write Semantics

World-model writes submit events, and entity state is projected asynchronously. A successful API response does not imply that the new value is already visible in the entity projection. Use the response semantics of the specific endpoint and allow for projection delay. Supported patterns include:

* **Single-event submission** followed by asynchronous entity projection
* **Deterministic entity identifiers** when the caller supplies a canonical identifier or explicit entity ID; creation without either is not idempotent
* **FHIR upserts** that link a new event to the prior event for the same source resource through `supersedes`
* **Per-key enrichment history** with current-winner projection by confidence class and recency

## Write Scope Isolation

Supported agent write tools receive a server-constructed write scope that limits the workspace and entity they can target, whether creation is allowed, and the resource types or confidence available to the operation. The exact scope depends on the session and runtime.

Trusted system services use separate service authorization rather than an agent session's write scope. Their access is not evidence that a model-originated tool call can bypass its own scope.

Write scope constrains supported model-originated persistence paths, while source-class projection prevents a lower-ranked retained observation from winning over a higher-ranked value. Customers should validate the specific tools and runtimes they enable rather than infer one universal check across every code path.

{% hint style="info" %}
Write scope isolation is one of the platform's structural safety controls. For how this fits into the broader safety architecture, see [Runtime Safety](/operations-and-safety/runtime-safety.md).
{% endhint %}

## Direct Agent Access via Platform Functions

Beyond the three data channels, agents can query world model data directly using [platform functions](/agent/platform-functions.md). These are SQL, AI, Python, and table-valued functions that run on the platform's compute layer and return results mid-conversation. Unlike the ambient channel (pre-loaded context) or the queried channel (built-in tool calls), platform functions can join live entity data with analytical aggregations in a single call.

Built-in platform functions cover common patterns: entity confidence assessment (how trustworthy is the data for this patient?), caller history lookup (what happened in prior calls with this number?), and patient summary briefings. For the long tail of questions no pre-built function anticipated, a workspace registers parameterized data queries (`wsq_<name>`) that run against its own custom tables. Platform functions are read-only; recording new observations as world model events is done through dedicated write tools. Those tools enforce the write scope for their runtime, and accepted events become visible through the asynchronous projection semantics described above.

For the full platform functions reference, see [Platform Functions](/agent/platform-functions.md).

{% hint style="info" %}
**Developer Guide** - For API endpoints, SDK examples, and integration details, see the [Data & World Model](https://docs.amigo.ai/developer-guide/platform-api/data-world-model) section of the developer guide.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.amigo.ai/data/world-model.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
