> ## Documentation Index
> Fetch the complete documentation index at: https://trytilde.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Model your data in ontology/

> Write the ontology/ folder of a Tilde project: a source, a model, an object, reads and actions, and the Cedar policies that let people and agents use them.

The `ontology/` folder turns your data into typed objects, and gives agents and people a small set of reads and actions over them. Every call is decided by Cedar policies in the same folder. See [Ontology](https://trytilde.ai/docs/ontology/overview.md) for the concepts.

An ontology has four layers. You write one of each here:

1. A **source** brings raw records in.
2. A **model** shapes them into a table with SQL.
3. An **object** maps that table to a typed noun, such as `Customer`.
4. **Reads and actions** are the handlers agents and spaces call.

## The package

```json ontology/package.json theme={"system"}
{
  "name": "helpdesk-ontology",
  "private": true,
  "type": "module",
  "dependencies": {
    "@bufbuild/protobuf": "^2.10.0",
    "@cedar-policy/cedar-wasm": "^4.13.0",
    "@connectrpc/connect": "^2.1.0",
    "@connectrpc/connect-web": "^2.1.0",
    "zod": "^4.1.0"
  }
}
```

Tilde provides `@tilde/ontology` when it builds the project, so don't list it. List only the packages your own code imports.

## Sources, models, and objects

This example ships two customers as reference data, so you need no connection yet. Later you replace the stream with a [pipeline](https://trytilde.ai/docs/ontology/sources-and-models.md).

```ts ontology/customers.ts theme={"system"}
import { z } from "zod";
import { model, object, sql, stream, t, transactionalView } from "@tilde/ontology";

// Source: customer records shipped with the project.
export const customerRecords = stream("customers", {
  schema: z.object({ id: z.string(), name: z.string(), plan: z.enum(["free", "pro"]) }),
  key: "id",
  reference: [
    { id: "acme", name: "Acme Ltd", plan: "pro" },
    { id: "globex", name: "Globex", plan: "free" },
  ],
});

// Model: one row per customer.
export const customers = model({
  name: "customers",
  schema: "cells",
  materialized: "cell",
  uniqueKey: "customer_id",
  columns: { customer_id: t.string(), name: t.string(), plan: t.string() },
  sql: ({ src, changes, isIncremental }) =>
    sql`SELECT payload->>'id' AS customer_id, payload->>'name' AS name, payload->>'plan' AS plan
        FROM ${isIncremental ? changes(customerRecords) : src(customerRecords)}`,
});

// Object: name and plan come from the source; notes belong to the ontology.
export const Customer = object("Customer", {
  id: "customer",
  key: "customerId",
  source: customers,
  properties: {
    customerId: t.string().map(sql`customer_id`),
    name: t.string().map(sql`name`),
    plan: t.enum("free", "pro").map(sql`plan`),
    notes: t.string().optional().owned(),
  },
});

// View: one customer's data, read and changed together.
export const CustomerView = transactionalView("Customer", {
  key: "customer_id",
  tables: { customers },
  dependsOn: { objects: [Customer] },
});
```

* `.map()` properties come from the source. Only the source system changes them.
* `.owned()` properties belong to the ontology. Only its actions change them, and every edit is audited.
* A transactional view groups what changes together under one key, here one customer.

## Reads and actions

Each handler has a name, a zod input and output, and declares what it reads and edits. Tilde turns each one into an agent tool and a typed call for spaces.

```ts ontology/handlers.ts theme={"system"}
import { z } from "zod";
import { action, prop, read } from "@tilde/ontology";
import { Customer, CustomerView } from "./customers.ts";

// Across all customers: agents use it to find a key.
export const listCustomers = read("listCustomers", {
  description: "List every customer with its id, name, and plan.",
  kind: "read",
  input: z.object({}),
  output: z.array(z.object({ customerId: z.string(), name: z.string(), plan: z.string() })),
  reads: [Customer],
  handler: ({ ctx }) => ctx.lake.query(`SELECT "customerId", name, plan FROM Customer ORDER BY name`),
});

// One customer, on fresh data.
export const customerOverview = read("customerOverview", {
  description: "One customer's plan and notes.",
  view: CustomerView,
  kind: "txRead",
  input: z.object({}),
  output: z.object({ name: z.string(), plan: z.string(), notes: prop(Customer.notes) }),
  reads: [Customer],
  handler: ({ view }) => {
    const c = view.get(Customer, view.key)!;
    return { name: c.name, plan: c.plan, notes: c.notes ?? null };
  },
});

// Change one customer, in a transaction.
export const setNotes = action("setNotes", {
  description: "Replace the notes on a customer.",
  view: CustomerView,
  kind: "txWrite",
  input: z.object({ notes: z.string() }),
  output: z.null(),
  edits: [Customer.notes],
  reads: [Customer],
  handler: ({ input, view, ctx }) => {
    ctx.update(Customer, view.key, { notes: input.notes });
    return null;
  },
});
```

Write each `description` for the agent that will call it.

## Policies

Access is deny by default. These policies let signed-in people and agents use the customer handlers, and let people open the `customers` space you add next.

```ts ontology/policies.ts theme={"system"}
import { cedar, lake, openSpace, policy, query, readField, space } from "@tilde/ontology";
import { CustomerView } from "./customers.ts";
import { listCustomers } from "./handlers.ts";

const peopleAndAgents = cedar`principal.type == "user" || principal.type == "agent"`;

export const policies = [
  policy("use-customers", cedar`permit(principal, action, resource is ${CustomerView}) when { ${peopleAndAgents} };`),
  policy("list-customers", cedar`permit(principal, action == ${listCustomers}, resource == ${lake}) when { ${peopleAndAgents} };`),
  policy("query", cedar`permit(principal, action == ${query}, resource) when { ${peopleAndAgents} };`),
  policy("fields", cedar`permit(principal, action == ${readField}, resource) when { ${peopleAndAgents} };`),
  policy("open-customers", cedar`permit(principal, action == ${openSpace}, resource == ${space("customers")}) when { principal.type == "user" };`),
];
```

An agent acting for a person needs both to be allowed, so it never does more than that person. See [Policies](https://trytilde.ai/docs/ontology/policies.md) to narrow these.

## The entry point

`ontology.ts` default-exports the whole ontology.

```ts ontology/ontology.ts theme={"system"}
import { ontology } from "@tilde/ontology";
import { Customer, CustomerView, customerRecords } from "./customers.ts";
import { customerOverview, listCustomers, setNotes } from "./handlers.ts";
import { policies } from "./policies.ts";

export default ontology({
  streams: [customerRecords],
  objects: [Customer],
  views: [CustomerView],
  reads: [listCustomers, customerOverview],
  actions: [setNotes],
  policies,
});
```

Split the other files however you like. Only `ontology.ts` is fixed.

## Next

[Add a space](https://trytilde.ai/docs/project/spaces.md) that shows these customers to people.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.