# Build IndyKite end-to-end with the music dataset

> Download the music-dataset Postman collection and follow the chapters to set up an IndyKite environment, ingest a music graph, and wire up KBAC and ContX IQ policies, queries, and executes.

**Category:** ContX IQ

## Summary

Follow the chapters in order to import the music collection, create the IndyKite environment, ingest 16k+ nodes and 31k+ relationships, then author and execute KBAC and ContX IQ policies and queries against the music graph.

**Download the Postman collection - useful whether or not you used the Sandbox:**

- **If you didn't spin up your environment from the Sandbox** - the collection bootstraps everything from scratch over REST: project, application, application agent + credentials, Token Introspect, MCP server, the full music IKG (16k+ nodes, 31k+ relationships), all KBAC policies, and all ContX IQ policies + Knowledge Queries.
- **If you did spin it up from the Sandbox** - the collection is still your reference and workbench. Every request documents the exact REST shape of how the environment is wired, and it ships ready-to-run requests to update graph data via Capture, execute Knowledge Queries through ContX IQ, and make AuthZEN evaluations against your live environment.

[music-dataset.postman_collection.json](/assets/downloads/music-dataset.postman_collection.json) (Postman Collection format v2.1.0, ~18 MB - includes the inline music dataset).

The **Music app** - the collection plus all the data behind it (nodes, relationships, policies, queries, and executes needed to recreate the whole environment) - can be cloned from [github.com/indykite/developer-hub/music](https://github.com/indykite/developer-hub/tree/master/music) - it's also a runnable Flask web app that can click through this whole tutorial for you (see "The Music app" section below). The Person-subject flows are tuned for one end user, **Millicent Contextsworth** - the `ciq exec` requests carry her example `input_params`. You can retarget them to any other Person by changing those `input_params` in the execute requests. You'll mint her user token (via [toolbelt.indykite.com](https://toolbelt.indykite.com/)) in Chapter 10.

Import it into Postman, Bruno, Insomnia, or Newman - any client that parses the Postman Collection v2.1.0 format. The "Variables" tab lists every value the requests use; the only ones you must set yourself are `your_sa_token`, `your_agent_token`, `your_user_token`, and `organization_gid`. Everything else is auto-captured by the bundled post-response script.

**Where to find each:**

- `organization_gid` - in the IndyKite Hub under `/settings`.
- `your_sa_token` - in the credentials file you downloaded at Sandbox registration, or in the Hub under `/service-accounts`.
- `your_agent_token` - in the credentials file from Sandbox registration if you reuse that Sandbox env (the token only works for that env); if you create a new env, it's generated when you run the Postman collection / follow this tutorial.
- `your_user_token` - covered later in this tutorial.

This tutorial walks through that collection. Every chapter maps to a folder of requests inside it - run the requests in order and the collection variables fill themselves in via the bundled capture script.

### What you will have at the end

1. An IndyKite **Project**, **Application**, **Application Agent**, and credentials provisioned via the Config API.
2. A **Token Introspect** configuration that links your external IdP (Auth0) tokens to `Person` nodes in the IKG.
3. An **MCP Server** configuration so AI agents can call IndyKite over MCP.
4. A music **IKG** populated with the 6 node types and 13 relationship types listed below.
5. **10 KBAC policies** covering venue performance, entry, flash mobs, track-loudness checks, playlist sharing, family access, and DJ rights, plus **10 single AuthZEN evaluations** and a **boxcar batch**.
6. **24 ContX IQ policies** with **44 Knowledge Queries** (read / write / delete variants) and **44 paired CIQ executes** that exercise every query against the music graph.

### The music dataset at a glance

After Chapter 5 (data ingestion) your IKG holds:

| Node type | Count | Sample external_id |
| --- | --- | --- |
| Artist | 94 | `artist-1` (38 Special) |
| Album | 1k+ | `album-1` |
| Track | 14k+ | `track-1` |
| Playlist | 20 | `playlist-1` |
| Person | 86 (12 with `auth0\|...` external_ids) | `person-1` / `auth0\|69c3ee8cb9ed562744ff9326` |
| Venue | 24 | `venue-1` (Shower-Concert-Hall) |

Relationships: `CREATED`, `PART_OF`, `RELEASED`, `LIKES`, `FOLLOWS`, `SUBSCRIBED_TO`, `MARRIED_TO`, `PARENT_OF`, `PARTNERS`, `CO_PARENTS`, `WILL_ATTEND`, `APPROVED_FOR`, `PLAYED_AT`.

### Who this tutorial is for

- Developers evaluating IndyKite who want a runnable, self-contained walkthrough that touches every product surface (Capture, KBAC/AuthZEN, ContX IQ, Token Introspect, MCP).
- Platform engineers preparing a demo environment for stakeholders.
- AI agents using the collection as a runbook - every chapter names the exact request items and the variables they read/write.

### Prerequisites

- An IndyKite Hub account (EU or US). See the [Environment guide](/guides/guide-environment).
- A ServiceAccount credential at the Organization level (provides the `{{your_sa_token}}` Bearer used on Config API requests).
- Postman, Bruno, Insomnia, or Newman - any client that parses the Postman Collection format v2.1.0. Import the JSON file linked at the top of this page.
- An end-user access token from your IdP (e.g. Auth0) for Chapter 10 - the Person-subject CIQ executes send it as `Authorization: Bearer {{your_user_token}}`.

### How to use the collection alongside this tutorial

1. **Download & import** the collection (link at the top of this page) into Postman. The collection's "Variables" tab shows every variable you might need.
2. Set `your_sa_token` and `organization_gid` manually. Everything else is auto-captured by the collection's post-response script as you run create requests.
3. Run requests **in document order**. The capture script writes each created resource's `id` into the matching variable (`project_gid`, `application_gid`, `app_agent_gid`, `policy_gid`, `query_gid`, ...) so the next request can use it.
4. The chapters below explain each section. Skip ahead if you only care about one product, but the variable chain only works left-to-right.

### The Music app: a clickable alternative to the collection

If you'd rather click through the setup than fire REST requests one by one, the **Music app** ([github.com/indykite/developer-hub/music](https://github.com/indykite/developer-hub/tree/master/music)) wraps the entire collection in a small Flask web app. Every request in the collection has a matching form page, and each successful create saves its resulting ID into a local `.env` file so the next step can use it - the same variable chain as the Postman capture script, just persisted on disk.

**Run it locally:**

1. Clone the repo and `cd music`.
2. Create a `.env` file with the only values you type in yourself: `SA_TOKEN` (from the Hub under `/service-accounts`), `URL_ENDPOINTS` (`https://eu.api.indykite.com` or `https://us.api.indykite.com`), `ORGANIZATION_ID` (Organization > Settings), and optionally `USER_TOKEN` (an Auth0 ID token - only needed for the Person-subject CIQ executes and `/chat/`). Everything else (`PROJECT_ID`, `APP_TOKEN`, all the `*_ID` keys, ...) is saved automatically as you go.
3. Install pipenv, then run `pipenv install`, `pipenv shell`, and `flask run`; open the local URL (e.g. `http://127.0.0.1:5000`).

**Getting Started steps 1-5.** The five cards on the landing page mirror Chapters 2-4 of this tutorial - each needs the values saved by the previous steps and saves its own result to `.env`:

| # | Step | Page | Saves to `.env` |
| --- | --- | --- | --- |
| 1 | Create Project | `/api_project/create` | `PROJECT_ID` |
| 2 | Create Application | `/api_application/create` | `APPLICATION_ID` |
| 3 | Create App Agent | `/api_app_agent/create` | `APP_AGENT_ID`, `APP_TOKEN` |
| 4 | Token Introspect | `/api_token_introspect/create` | `TOKEN_INTROSPECT_ID` |
| 5 | MCP Server | `/api_mcp_server/create` | `MCP_SERVER_ID` |

**One-click provisioning.** Once steps 1-5 exist, **Provision Everything** (`/api_provision/run`) replays every remaining create button in click order: both captures (nodes and relationships, Chapter 5), the 10 KBAC policies (Chapter 6), then each CIQ policy followed by its Knowledge Queries (Chapters 8-9) - 93 steps, saving the same IDs to `.env` as clicking by hand. It's safe to re-run: steps whose ID is already saved are skipped. AuthZEN evaluations and CIQ executes are *not* included - they are reads, not creations - so Chapters 7 and 10 remain yours to run, either page by page or via the app's `/chat/` story mode, which runs every CIQ execute in dependency-safe order (creates before reads, deletes last).

**Backfill `.env` - when the sandbox already exists.** If your music environment was created *outside* the app - an automated Hub sandbox, this tutorial's Postman collection, or scripts - the app's forms won't know any of the IDs. **Backfill .env** (`/api_provision/backfill`) recovers every derived ID by looking the configs up **by name** and saves them to `.env`, so the forms work against that existing sandbox. It is read-only: nothing is created or modified on the platform.

- Needs only `URL_ENDPOINTS`, `SA_TOKEN`, and `PROJECT_ID` in `.env`.
- Recognizes both the app's fixed config names and the console sandbox's random-suffixed names (`<name>-123456-0`, `app-123456`, ...).
- Tokens (`APP_TOKEN`, `USER_TOKEN`) cannot be recovered - credential secrets are only shown at creation - so set those manually.
- Hub console sandboxes include an MCP server, so `MCP_SERVER_ID` is recovered along with the rest. If backfill reports any config as *missing*, create it afterwards with the matching Getting Started step.

### What comes next

Chapter 1 introduces the music graph itself - what each node type means and which relationships connect them - so the policies and queries in later chapters land on a familiar shape.

## Chapter 1: The music graph: nodes, relationships, and scenarios

Walk through the music dataset's six node types and thirteen relationship types so the rest of the tutorial lands on a familiar shape.

## Chapter 1: The music graph

Every policy and query in this tutorial runs against the same Identity Knowledge Graph (IKG). Understanding the graph first makes the rest of the chapters self-evident.

### Why a graph?

From the [graph database guide](/guides/guide-graph-database): identity and authorization are inherently relational. "Can *this* person play *that* track at *this* venue" is a path query, not a row lookup. The IKG stores entities as nodes and the connections between them as relationships, so KBAC and ContX IQ can reason over those paths directly.

### Node types

| Type | What it represents | Key properties used by policies / queries |
| --- | --- | --- |
| `Person` | User of the music app. 12 use real `auth0\|...` external_ids (so a real IdP-issued bearer's `sub` claim resolves to a graph node); the other 74 use `person-N`. Two auth0 users are seeded with engagement relationships as recommended test subjects: **Cornelius** (`auth0\|69c3ee8cb9ed562744ff9326`) covers music-engagement queries; **Marmaduke** (`auth0\|69c4129b0ba356c7db9f91ab`) covers parent-side queries. Full table in Chapter 5. | `firstname`, `lastname`, `city`, `music_mood`, `karaoke_confidence`, `dance_skill`, `profession` |
| `Artist` | Musician or group. | `name` |
| `Album` | Released by an Artist; contains Tracks. | `title` |
| `Track` | Individual song with audio characteristics used in policies (e.g. loudness gates). | `title`, `duration`, `danceability`, `energy`, `loudness`, `popularity` |
| `Playlist` | User-created or system playlist. Has venue approvals and subscriber relationships. | `name` |
| `Venue` | Place where tracks are played. Carries thresholds policies compare against. | `name`, `min_confidence`, `min_danceability`, `max_loudness`, `max_energy` |

### Relationships

| Relationship | From → To | Used by |
| --- | --- | --- |
| `CREATED` | Artist → Track, Person → Playlist | Catalog ownership / playlist authorship |
| `PART_OF` | Track → Album | Catalog hierarchy |
| `RELEASED` | Artist → Album | Catalog ownership |
| `LIKES` | Person → Track | Same-taste matching, popular-tracks queries |
| `FOLLOWS` | Person → Artist | Same-artist-followers query |
| `SUBSCRIBED_TO` | Person → Playlist | Subscription read / share KBAC |
| `MARRIED_TO` / `PARTNERS` / `PARENT_OF` / `CO_PARENTS` | Person ↔ Person | Family-playlist KBAC, children-likes CIQ |
| `WILL_ATTEND` | Person → Venue | Concert / venue-attendees / DJ KBAC |
| `APPROVED_FOR` | Playlist → Venue | Playlist-venue-approval KBAC |
| `PLAYED_AT` | Track → Venue | Venue-playable-tracks CIQ, track-loudness KBAC |

### The scenarios you'll author

Three families of authorization questions are answered in later chapters:

1. **KBAC / AuthZEN** (Chapters 6 - 7): yes/no decisions like "can *person-52* PERFORM at *venue-1*?" or "can *track-7431* PLAY at *venue-4*?"
2. **ContX IQ - Application as subject** (Chapter 8 onwards): system-level reads/writes like "list playable tracks for venue X" run by the `_Application` identity.
3. **ContX IQ - Person as subject** (Chapter 8 onwards): user-scoped reads/writes like "my profile", "my playlists", "people with the same taste as me", scoped by `subject.external_id = $token.sub` (i.e. anchored to the bearer token's verified `sub` claim - no client-supplied identity).

### What comes next

Chapter 2 sets up the IndyKite environment that owns this graph - Project, Application, Application Agent, and credentials.

## Chapter 2: Set up the IndyKite environment

Create Project, Application, Application Agent, and credentials with the four Config API requests in the music collection.

## Chapter 2: Set up the IndyKite environment

From the [Environment guide](/guides/guide-environment): before you can use any IndyKite capability you need an **Organization → Project → Application → Application Agent** hierarchy. The collection's first four requests build that chain. Each one is auto-captured into a collection variable consumed by the next.

### Hierarchy refresher

| Level | Why it exists |
| --- | --- |
| **Organization** | Top-level account, holds Service Accounts and Projects. |
| **Project** | Isolated environment with its own IKG. |
| **Application** | Logical grouping inside a Project. Creates an `_Application` node so the application can act as a subject. |
| **Application Agent** | API authentication identity. Its credentials are sent as `X-IK-ClientKey`. |

### Variables you set yourself

- `your_sa_token` - the ServiceAccount JWT, sent as `Authorization: Bearer ...` on every request in this chapter.
- `organization_gid` - your Organization's `gid:...` identifier.

### Run these requests in order

| # | Request name | Endpoint | Captures into |
| --- | --- | --- | --- |
| 1 | `create project` | `POST /configs/v1/projects` | `project_gid` |
| 2 | `create application` | `POST /configs/v1/applications` | `application_gid` |
| 3 | `create application agent` | `POST /configs/v1/application-agents` | `app_agent_gid` |
| 4 | `create application agent credentials` | `POST /configs/v1/application-agent-credentials` | (see below) |

### Request bodies

**1. Create the Project.** Auth: `Authorization: Bearer {{your_sa_token}}`.

```json
POST /configs/v1/projects
{
  "organization_id": "{{organization_gid}}",
  "name": "eu-project",
  "display_name": "EU Project",
  "region": "europe-west1",
  "ikg_size": "2GB"
}
```

**2. Create the Application** inside that project.

```json
POST /configs/v1/applications
{
  "project_id": "{{project_gid}}",
  "name": "app-name",
  "display_name": "Application name",
  "description": "Application description"
}
```

**3. Create the Application Agent.** The `api_permissions` array is what makes this agent able to call Capture, ContX IQ, AuthZEN, etc. Drop any you don't need; a call to an API the agent is not granted fails with `401`. The chapters that follow only use `Authorization`, `Capture`, and `ContXIQ`; the payload below grants all six so the same credential also works for the optional examples on the resources pages:

- `Authorization` - the AuthZEN endpoints under `/access/v1/`: `evaluation`, `evaluations`, and the `search/action`, `search/resource`, `search/subject` discovery calls.
- `Capture` - the Capture API under `/capture/v1/`: upsert and delete nodes, relationships, properties, and metadata.
- `ContXIQ` - `POST /contx-iq/v1/execute` to run Knowledge Queries, and `GET /contx-iq/v1/whoami` to see which IKG node a user token resolves to.
- `EntityMatching` - the EntityMatching API under `/entity-matching/v1/` for identity resolution pipelines.
- `ReadAuthZConfigs` - `GET /access/v1/policies`, a read-only listing of the project's active KBAC policies as stored, with their tags. Separate from `Authorization`: deciding does not imply reading the rules, and vice versa.
- `ReadDataSchema` - `GET /data-schema/v1/`, the observed node, relationship, and property schema of the IKG (handy before writing Cypher).

```json
POST /configs/v1/application-agents
{
  "application_id": "{{application_gid}}",
  "name": "app-agent-name",
  "display_name": "App Agent name",
  "description": "App Agent description",
  "api_permissions": [
    "Authorization",
    "Capture",
    "ContXIQ",
    "EntityMatching",
    "ReadAuthZConfigs",
    "ReadDataSchema"
  ]
}
```

**4. Generate credentials** for that agent. The response is the credential JSON you'll mine for `your_agent_token`.

```json
POST /configs/v1/application-agent-credentials
{
  "application_agent_id": "{{app_agent_gid}}",
  "display_name": "AppAgent Credentials name",
  "expire_time": "2027-04-28T12:34:56Z"
}
```

### A note on credentials (step 4)

From the [Credentials guide](/guides/guide-credentials): the response of the credentials endpoint contains a downloadable JSON. Inside that JSON is the value used as `X-IK-ClientKey`. The collection's auto-capture script logs a hint when this request fires - you must **copy the X-IK-ClientKey value into `your_agent_token` manually**. Save the credentials file securely; it cannot be retrieved again.

### BYODB alternative

The collection also includes `create project BYODB` for users who want to bring their own Neo4j database. Set `db_name`, `db_password`, and `db_host` in the Variables tab before running it. Most users should use the managed-IKG `create project` path instead.

### Sanity check

After running these four requests, your collection variables tab should show non-empty values for `project_gid`, `application_gid`, `app_agent_gid`, and `your_agent_token` (the last one filled in manually from the credential JSON).

### What comes next

Chapter 3 wires Token Introspect into your environment so external IdP tokens can be validated against the IKG.

## Chapter 3: Configure Token Introspect for end-user identity

Link external IdP access tokens (Auth0) to Person nodes in the IKG so user-context CIQ executes resolve to a real graph subject.

## Chapter 3: Configure Token Introspect

From the [Token Introspect guide](/guides/guide-token-introspect): Token Introspect tells IndyKite how to validate an external access token (issued by your IdP) and which claim should be used to find the matching `Person` node. Without it, Person-subject CIQ executes have no way to know which graph node "the caller" refers to.

### Why this matters for the music collection

In Chapter 5 you will ingest 12 `Person` nodes whose `external_id` values are real Auth0 subjects (e.g. `auth0|69c3ee8cb9ed562744ff9326`). The Person-subject CIQ executes you'll run in Chapter 10 send those tokens as `Authorization: Bearer {{your_user_token}}`. Token Introspect is what makes the platform resolve the bearer token's `sub` claim to the matching `Person` node.

### Run this request

| Request | Endpoint | Captures into |
| --- | --- | --- |
| `create token introspect` | `POST /configs/v1/token-introspects` | `token_introspect_gid` |

### Auth: ServiceAccount

Like all `/configs/v1/*` requests, this one uses `{{your_sa_token}}` as `Authorization: Bearer ...`. No agent token here - this is a configuration call.

### Body

```json
POST /configs/v1/token-introspects
{
  "project_id": "{{project_gid}}",
  "name": "auth0-person-introspect",
  "display_name": "Auth0 Person Token Introspect",
  "description": "Introspect Auth0 tokens and upsert Person nodes",
  "jwt_matcher": {
    "issuer": "https://1st.eu.auth0.com",
    "audience": "N6VibJHjxIpKEvkBKSWU1xLxh6xnca55"
  },
  "ikg_node_type": "Person",
  "claims_mapping": {
    "email": {
      "selector": "email"
    }
  },
  "perform_upsert": true
}
```

Three things to notice:

- `jwt_matcher` declares which `issuer` + `audience` token to accept. The values shown here point to an Auth0 tenant IndyKite stood up specifically to exercise the platform - a test IdP whose user accounts back the 12 `auth0|...` Person nodes you ingest in Chapter 5. Keep them as-is to follow this tutorial against that test IdP, or replace them with your own Auth0 tenant's `issuer` and `audience` to wire up your own users.
- `ikg_node_type: "Person"` tells the platform that the token's `sub` claim resolves to a `Person` node. This is the binding our CIQ policies rely on via `subject.external_id = $token.sub`.
- `perform_upsert: true` means a `Person` node is auto-created the first time an unknown token sub is seen - useful in development.

At execute time the Person-subject policies in Chapter 8 enforce `subject.external_id = $token.sub`, where `$token.sub` resolves to the verified `sub` claim of the bearer token. No `subject_external_id` input param is sent by the client - the platform reads the claim from the bearer that Token Introspect just validated, and the policy filter pins the cypher subject to the matching `Person` node.

### What comes next

Chapter 4 adds an MCP Server configuration so AI agents can call IndyKite over the Model Context Protocol.

## Chapter 4: Configure the MCP Server

Stand up an MCP Server configuration so AI agents can initialize sessions and execute IndyKite tools over HTTP.

## Chapter 4: Configure the MCP Server (optional)

**Optional - skip to Chapter 5 if you don't need MCP yet.** This chapter is only required if you want an AI agent to drive IndyKite over MCP. Every later chapter (ingest, KBAC/AuthZEN, ContX IQ) works fine without it - you can come back and add MCP later by running just the requests below.

From the [MCP guide](/guides/guide-mcp): the IndyKite MCP Server exposes IndyKite capabilities (Capture, ContX IQ, AuthZEN, Token Introspect) to **Model Context Protocol** clients. AI agents that speak MCP can initialize a session, list available tools, and execute them - all against your project's IKG.

### Why include this in the tutorial

- It's the bridge between the music graph you're about to build and any LLM-driven client (Claude, GPT, custom agents) that wants to query or update it.
- The configuration call is short and depends only on values you've already captured (`project_gid`, `app_agent_gid`, `token_introspect_gid`).

### Run these requests

| Request | Endpoint | Purpose |
| --- | --- | --- |
| `create mcp server config` | `POST /configs/v1/mcp-servers` | Captures `mcp_server_gid`. |
| `read mcp server config` | `GET /configs/v1/mcp-servers/{{mcp_server_gid}}` | Optional - inspect the active config. |
| `delete mcp server config` | `DELETE /configs/v1/mcp-servers/{{mcp_server_gid}}` | Optional - tear it down. |

### Body shape

The body wires the MCP Server to the agent identity that will execute tools (`app_agent_id`) and to the Token Introspect config that resolves end-user tokens (`token_introspect_id`). Scopes and an enabled flag complete the configuration.

```json
{
  "app_agent_id": "{{app_agent_gid}}",
  "token_introspect_id": "{{token_introspect_gid}}",
  "project_id": "{{project_gid}}",
  "name": "mcp-server-test",
  "display_name": "MCP Server test",
  "description": "MCP Server configuration description",
  "enabled": true,
  "scopes_supported": [
    "email"
  ]
}
```

### What comes next

Chapter 5 ingests the music dataset itself - 16 thousand+ nodes and 31 thousand+ relationships - via two Capture API calls.

## Chapter 5: Ingest the music graph: nodes and relationships

Use the Capture API to load the entire music dataset - Artists, Albums, Tracks, Playlists, Persons, Venues, and 13 relationship types - in two requests.

## Chapter 5: Ingest the music graph

From the [Environment guide](/guides/guide-environment): the IKG is the foundation of every IndyKite product. Authorization decisions, ContX IQ queries, and contextual lookups all run against data captured here. The collection ships the music dataset inline so you can populate the graph in two requests.

### Auth changes here

Capture is data, not configuration. From this point on, requests use the **Application Agent** credential as `X-IK-ClientKey: {{your_agent_token}}` instead of the ServiceAccount Bearer.

### Run these two requests

| Request | Endpoint | Payload size |
| --- | --- | --- |
| `upsert nodes` | `POST /capture/v1/nodes/` | 15k+ nodes across 6 types |
| `upsert relationships` | `POST /capture/v1/relationships` | 31k+ relationships across 13 types |

### What gets created

Nodes by type:

- Artist: 94, Album: 1 247, Track: 14k+
- Playlist: 20, Person: 86, Venue: 24

Relationships by type:

- Catalog: `CREATED` (14k+), `PART_OF` (14k+), `RELEASED` (1k+)
- Engagement: `LIKES` (111), `FOLLOWS` (42), `SUBSCRIBED_TO` (30)
- Family: `MARRIED_TO` (15), `PARENT_OF` (55), `PARTNERS` (7), `CO_PARENTS` (4)
- Venue: `WILL_ATTEND` (86), `APPROVED_FOR` (318), `PLAYED_AT` (314)

### Body shape - upsert nodes

`POST /capture/v1/nodes/` with header `X-IK-ClientKey: {{your_agent_token}}`. Each entry has an `external_id`, a `type` (label), and a list of typed properties. Sample slice (the full payload contains 15k+ nodes):

```json
{
  "nodes": [
    {
      "external_id": "artist-2",
      "type": "Artist",
      "properties": [
        {
          "type": "name",
          "value": "ABBA"
        }
      ]
    },
    {
      "external_id": "venue-1",
      "type": "Venue",
      "properties": [
        {
          "type": "name",
          "value": "Shower-Concert-Hall"
        },
        {
          "type": "min_confidence",
          "value": 0.5
        },
        {
          "type": "max_loudness",
          "value": -3.0
        }
      ]
    },
    {
      "external_id": "auth0|69c3ee8cb9ed562744ff9326",
      "type": "Person",
      "properties": [
        {
          "type": "firstname",
          "value": "Cornelius"
        },
        {
          "type": "city",
          "value": "Ctrl-Z Canyon"
        },
        {
          "type": "music_mood",
          "value": "Acoustic Sadness"
        },
        {
          "type": "karaoke_confidence",
          "value": 0.4
        },
        {
          "type": "dance_skill",
          "value": 0.67
        }
      ]
    }
  ]
}
```

### Body shape - upsert relationships

`POST /capture/v1/relationships` with the same `X-IK-ClientKey` header. Each entry names a `source`, a `target`, and a `type`. The platform is idempotent - running the same payload twice does not create duplicates. Sample slice (the full payload contains 31k+ relationships):

```json
{
  "relationships": [
    {
      "source": {
        "type": "Artist",
        "external_id": "artist-1"
      },
      "target": {
        "type": "Track",
        "external_id": "track-1"
      },
      "type": "CREATED"
    },
    {
      "source": {
        "type": "Person",
        "external_id": "person-52"
      },
      "target": {
        "type": "Track",
        "external_id": "track-9381"
      },
      "type": "LIKES"
    },
    {
      "source": {
        "type": "Person",
        "external_id": "auth0|69c3ee8cb9ed562744ff9326"
      },
      "target": {
        "type": "Venue",
        "external_id": "venue-1"
      },
      "type": "WILL_ATTEND"
    }
  ]
}
```

### Recommended test users

The 86 Person nodes use two id schemes: 74 synthetic users with `person-N` external_ids (numbered 1-85 with a few gaps), and 12 real `auth0|...` subjects for users meant to drive end-to-end CIQ executes with a Bearer access token. The dataset is seeded so the two recommended auth0 users below cover every Person-subject query that matters:

| Auth0 sub | Person | Relationships | Use to test |
| --- | --- | --- | --- |
| `auth0\|69c3ee8cb9ed562744ff9326` | Cornelius (age 14) | 5 LIKES, 2 FOLLOWS, 2 SUBSCRIBED_TO, 5 WILL_ATTEND, 1 CREATED Playlist, plus PARENT_OF coming in | All "own data" queries (kq4-kq9), social/taste queries (kq14-kq20), venue queries (kq12, kq13, kq22), engagement (kq24). |
| `auth0\|69c4129b0ba356c7db9f91ab` | Marmaduke (parent of person-15, person-16) | PARENT_OF -> person-15 / person-16; each child has 3 LIKES. | Parent-side queries: kq11 (children-likes), kq10 (family-playlists). |

Pick the auth0 sub that matches the query you're testing - the bearer's `sub` claim is what the policy filter pins on (see Chapter 8). The other 10 auth0 users only have family relationships and will return empty for music-engagement queries.

### Verifying the ingest

A non-error 200 response on each request is sufficient for now. Chapters 6-10 will exercise the data via authorization and CIQ executes. If you need to ingest a single subset or update a property later, see the [Capture resource examples](/resources).

### What comes next

Chapter 6 introduces KBAC policies - the yes/no authorization rules - using ten concrete music-app scenarios.

## Chapter 6: KBAC policies: define what's allowed

Author ten KBAC policies covering venue performance, entry, flash mobs, track loudness gates, playlist sharing, family playlists, and DJ rights.

## Chapter 6: KBAC policies

From the [Dynamic Authorization guide](/guides/guide-dynamic-authz) and [AuthZEN guide](/guides/guide-authzen): **Knowledge-Based Access Control (KBAC)** is the rule layer. Each policy declares a `subject`, an `action`, a `resource` shape (via the cypher MATCH), and the `condition` the subject must satisfy. Chapter 7 turns these into yes/no decisions via the AuthZEN `/access/v1/evaluation` endpoint.

### The ten policies in the collection

| Request | Policy name | Subject | Action | Resource | Allows when… |
| --- | --- | --- | --- | --- | --- |
| `kbac` | concert-performer | Person | PERFORM | Venue | subject is going to the venue and karaoke_confidence ≥ venue.min_confidence |
| `kbac2` | venue-entry-by-membership | Person | ENTER | Venue | subject is going to the venue (any WILL_ATTEND) |
| `kbac3` | flash-mob-recruitment | Person | JOIN | Venue (Flash-Mob-Recruitment) | subject's dance_skill ≥ venue.min_danceability |
| `kbac4` | track-loudness-check | Track | PLAY | Venue | track is PLAYED_AT and loudness ≥ max_loudness |
| `kbac5` | dmv-endless-suffering | Track | PLAY | Venue (DMV-Waiting-Area) | track.energy ≤ venue.max_energy |
| `kbac6` | playlist-venue-approval | Playlist | FEATURE | Venue | playlist is APPROVED_FOR the venue |
| `kbac7` | share-subscribed-playlist | Person | SHARE | Playlist | subject SUBSCRIBED_TO or CREATED the playlist |
| `kbac8` | family-playlist-access | Person | VIEW | Playlist | a family member (MARRIED_TO / PARENT_OF / PARTNERS) CREATED the playlist |
| `kbac9` | corporate-no-enthusiasm | Track | PLAY | Venue (Corporate-Meeting-Room) | track.energy ≤ venue.max_energy |
| `kbac10` | dj-at-venue | Person | DJ | Venue | subject WILL_ATTEND and karaoke_confidence ≥ 0.8 |

A `2.0-kbac` policy needs a subject ingested with `is_identity: true`, and in this dataset only the people are. So the four policies whose subject is a `Track` or a `Playlist` (kbac4, kbac5, kbac6, kbac9) are created like the others but answer `false` for every evaluation; Chapter 7 evaluates the six `Person` policies.

### Anatomy of one KBAC policy

Each `kbacN` request posts to `POST /configs/v1/authorization-policies` with a stringified policy body. Stripped of envelope, the shape is:

```json
{
  "meta": {
    "policy_version": "2.0-kbac"
  },
  "subject": {
    "type": "Person"
  },
  "actions": [
    "PERFORM"
  ],
  "condition": {
    "cypher": "MATCH (subject:Person)-[:WILL_ATTEND]->(resource:Venue) MATCH (subject)-[:HAS]->(confidence:Property {type:'karaoke_confidence'}) MATCH (resource)-[:HAS]->(min_confidence:Property {type:'min_confidence'}) WHERE confidence.value >= min_confidence.value"
  }
}
```

Four things to notice:

- The cypher binds **two named nodes**: `subject` (matches the subject sent in the AuthZEN call) and `resource` (matches the resource sent in the AuthZEN call).
- The **resource type** is implied by the cypher (`resource:Venue`), so the AuthZEN evaluation must send a Venue id.
- The **action** array gates which AuthZEN calls this policy can answer (`PERFORM` here).
- A **property** is tested through its own node: match `(node)-[:HAS]->(p:Property {type:'<name>'})` and compare `p.value`. The `node.property.<name>` path belongs to ContX IQ policies; in a KBAC condition it reads nothing, the policy is still saved, and every decision is `false`.

### Three more concrete examples

**`kbac4` - Track-loudness gate (Track subject):**

```json
POST /configs/v1/authorization-policies
{
  "project_id":   "{{project_gid}}",
  "name":         "track-loudness-check",
  "display_name": "Track Loudness Venue Compatibility",
  "policy": "{
    \"meta\":      {\"policy_version\":\"2.0-kbac\"},
    \"subject\":   {\"type\":\"Track\"},
    \"actions\":   [\"PLAY\"],
    \"resource\":  {\"type\":\"Venue\"},
    \"condition\": {\"cypher\":\"MATCH (subject:Track)-[:PLAYED_AT]->(resource:Venue) MATCH (subject)-[:HAS]->(loudness:Property {type:'loudness'}) MATCH (resource)-[:HAS]->(max_loudness:Property {type:'max_loudness'}) WHERE loudness.value >= max_loudness.value\"}
  }",
  "status": "ACTIVE"
}
```

**`kbac6` - Playlist venue approval (Playlist subject, no WHERE):**

```json
policy: {
  "subject":   {"type":"Playlist"},
  "actions":   ["FEATURE"],
  "resource":  {"type":"Venue"},
  "condition": {"cypher":"MATCH (subject:Playlist)-[:APPROVED_FOR]->(resource:Venue)"}
}
```

**`kbac8` - Family playlist access (multi-relationship-type pattern):**

```json
policy: {
  "subject":   {"type":"Person"},
  "actions":   ["VIEW"],
  "resource":  {"type":"Playlist"},
  "condition": {"cypher":"MATCH (subject:Person)-[:MARRIED_TO|PARENT_OF|PARTNERS]-(family:Person)-[:CREATED]->(resource:Playlist)"}
}
```

### Auth

All ten requests use `{{your_sa_token}}` as `Authorization: Bearer ...` (Config API). The capture script writes the returned policy GID into `policy_gid`, which is overwritten each time a new policy is created.

### What comes next

Chapter 7 evaluates these policies with single AuthZEN calls and a boxcar batch.

## Chapter 7: AuthZEN evaluations: yes/no decisions on the music graph

Run thirteen single AuthZEN evaluations and one boxcar batch against the KBAC policies authored in Chapter 6.

## Chapter 7: AuthZEN evaluations

From the [AuthZEN guide](/guides/guide-authzen): AuthZEN is a standard request shape - *subject*, *resource*, *action* - that returns a yes/no decision. IndyKite implements the standard at `POST /access/v1/evaluation` for a single decision and `POST /access/v1/evaluations` for a batch (boxcar).

### Auth changes back to the agent token

Evaluations are runtime data, not configuration, so they use the Application Agent credential as `X-IK-ClientKey: {{your_agent_token}}` - same as the Capture and CIQ requests. No ServiceAccount Bearer here.

### The thirteen single evaluations

| Request | Subject | Resource | Action | Targets policy | Expected decision |
| --- | --- | --- | --- | --- | --- |
| `Evaluation` | Person/`person-52` | Venue/`venue-1` | ENTER | kbac2 (venue-entry-by-membership) | `true` |
| `Evaluation2` | Person/`person-52` | Venue/`venue-10` | ENTER | kbac2 (venue-entry-by-membership) | `true` |
| `Evaluation3` | Person/`person-44` | Playlist/`playlist-5` | VIEW | kbac8 (family-playlist-access) | `true` |
| `Evaluation4` | Person/`person-47` | Playlist/`playlist-2` | SHARE | kbac7 (share-subscribed-playlist) | `true` |
| `Evaluation5` | Person/`person-40` | Venue/`venue-3` | ENTER | kbac2 (venue-entry-by-membership) | `true` |
| `Evaluation6` | Person/`person-2` | Playlist/`playlist-1` | VIEW | kbac8 (family-playlist-access) | `true` |
| `Evaluation7` | Person/`person-44` | Playlist/`playlist-17` | SHARE | kbac7 (share-subscribed-playlist) | `true` |
| `Evaluation8` | Person/`person-1` | Playlist/`playlist-13` | VIEW | kbac8 (family-playlist-access) | `true` |
| `Evaluation9` | Person/`person-56` | Playlist/`playlist-5` | SHARE | kbac7 (share-subscribed-playlist) | `true` |
| `Evaluation10` | Person/`person-39` | Venue/`venue-21` | ENTER | kbac2 (venue-entry-by-membership) | `true` |
| `Evaluation11` | Person/`person-52` | Venue/`venue-1` | PERFORM | kbac (concert-performer) | `true`: karaoke_confidence 0.73 ≥ min_confidence 0.7 |
| `Evaluation12` | Person/`person-47` | Venue/`venue-16` | JOIN | kbac3 (flash-mob-recruitment) | `true`: dance_skill 1.0 ≥ min_danceability 0.85 |
| `Evaluation13` | Person/`person-40` | Venue/`venue-3` | DJ | kbac10 (dj-at-venue) | `true`: karaoke_confidence 0.87 ≥ 0.8 |

Every request in the collection is expected to answer `true`. To see a rule deny, change one value: `Evaluation13` with `person-52` at `venue-1` answers `false`, because that person attends the venue but has a karaoke_confidence of 0.73, below 0.8. A `false` on one of `Evaluation11` to `Evaluation13` as written means the policy does not read the property: check its condition against Chapter 6.

Every subject here is a `Person`. The four policies whose subject is a `Track` or a `Playlist` (kbac4, kbac5, kbac6, kbac9) are not evaluated in this chapter: a `2.0-kbac` policy needs a subject ingested with `is_identity: true`, and in this dataset only the people are. An evaluation with a track or a playlist as subject answers `false`.

### Single AuthZEN body shape

```json
{
  "subject": {
    "type": "Person",
    "id": "person-52"
  },
  "resource": {
    "type": "Venue",
    "id": "venue-1"
  },
  "action": {
    "name": "ENTER"
  }
}
```

The platform finds a policy whose `subject.type`, cypher `resource:<Type>`, and declared action all match, then evaluates the cypher condition against the IKG. The response is an AuthZEN decision (`decision: true|false`) plus optional context.

### Boxcar batch

From the [batch authorization resource](/resources): when a single caller needs many decisions in one round-trip, send them all to `POST /access/v1/evaluations` (note the plural). The collection's `Evaluations` request batches three sub-evaluations under a default subject of `person-52`; a sub-evaluation can also carry its own `subject`, which then replaces the default for that entry:

```json
{
  "subject": {
    "type": "Person",
    "id": "person-52"
  },
  "evaluations": [
    {
      "resource": {
        "type": "Venue",
        "id": "venue-1"
      },
      "action": {
        "name": "ENTER"
      }
    },
    {
      "resource": {
        "type": "Venue",
        "id": "venue-10"
      },
      "action": {
        "name": "ENTER"
      }
    },
    {
      "resource": {
        "type": "Playlist",
        "id": "playlist-9"
      },
      "action": {
        "name": "SHARE"
      }
    }
  ]
}
```

All three are expected to answer `true`: the two `ENTER` entries through kbac2, the `SHARE` entry through kbac7.

### More single examples

**`Evaluation13` - a rule that tests a property (kbac10 dj-at-venue):**

```json
POST /access/v1/evaluation
{
  "subject": {
    "type": "Person",
    "id": "person-40"
  },
  "resource": {
    "type": "Venue",
    "id": "venue-3"
  },
  "action": {
    "name": "DJ"
  }
}
```

**`Evaluation8` - Person subject + Playlist resource (kbac8 family-playlist):**

```json
{
  "subject": {
    "type": "Person",
    "id": "person-1"
  },
  "resource": {
    "type": "Playlist",
    "id": "playlist-13"
  },
  "action": {
    "name": "VIEW"
  }
}
```

### Response shape

Successful AuthZEN responses are minimal: a boolean decision and optional context. For example:

```json
{
  "decision": true,
  "context": {
    "reason": null
  }
}
```

For the boxcar endpoint, the response is an array of `{ decision, context }` objects in the same order as the request's `evaluations` array.

### What comes next

Chapter 8 switches to ContX IQ - data queries with policy-scoped reads and writes - by authoring 24 CIQ policies.

## Chapter 8: ContX IQ policies: context-aware data access

Author 24 CIQ policies that gate what reads, writes, and deletes are allowed against the music graph - with subject scoping for Person and Application identities.

## Chapter 8: ContX IQ policies

From the [ContX IQ guide](/guides/guide-contx-iq): ContX IQ moves authorization from "yes/no" (KBAC) to "what data can this caller actually see / change". A CIQ policy declares a `subject` type, a cypher `condition` with optional `$param` filters, and an `allowed_reads` / `allowed_upserts` / `allowed_deletes` projection over the matched graph.

### Subjects in this collection

| Subject type | Used by | Auth at execute time |
| --- | --- | --- |
| `_Application` | System-level catalog ops (venue playable tracks, artist catalog, karaoke-ready people, attendance stats). | `X-IK-ClientKey: {{your_agent_token}}` only. |
| `Person` | User-scoped reads/writes (own profile, liked tracks, playlists, family, similar taste, etc.). | `X-IK-ClientKey: {{your_agent_token}}` + `Authorization: Bearer {{your_user_token}}`. |

### Person-subject filter convention

Every Person-subject policy in this collection includes:

```json
{
  "operator": "=",
  "attribute": "subject.external_id",
  "value": "$token.sub"
}
```

Without this clause, `MATCH (subject:Person)` matches every Person in the graph - not just the caller. Anchoring it to `$token.sub` means the platform plugs in the verified `sub` claim from the bearer token at execute time. There is no client-supplied `subject_external_id` input param, so callers cannot point the query at someone else's data; the bearer is the only identity source.

### The 24 policies (grouped by domain)

| Group | Subject | Policies (request → name) |
| --- | --- | --- |
| Application catalog ops | `_Application` | `ciqpolicy` (venue-playable-tracks), `ciqpolicy2` (artist-catalog), `ciqpolicy3` (karaoke-ready-people), `ciqpolicy21` (venue-attendance-stats) |
| Person - own data | `Person` | `ciqpolicy4` (own-profile), `5` (own-liked-tracks), `6` (own-playlists), `7` (own-subscriptions), `8` (own-followed-artists), `9` (own-venues), `24` (own-playlist-engagement) |
| Person - family | `Person` | `ciqpolicy10` (family-playlists), `11` (children-likes) |
| Person - venue context | `Person` | `ciqpolicy12` (venue-other-attendees), `13` (venue-playlists), `17` (matching-venues), `18` (liked-tracks-at-venue), `22` (people-in-venue-list), `23` (eligible-venues-broad) |
| Person - social | `Person` | `ciqpolicy14` (same-taste), `15` (same-artist-followers), `16` (created-playlist-subscribers), `19` (popular-tracks-by-followed), `20` (liked-tracks-avg-energy) |

### Anatomy of one CIQ policy

Stripped of envelope, a Person-subject policy with a `$param` filter looks like:

```json
{
  "meta": {
    "policy_version": "1.0-ciq"
  },
  "subject": {
    "type": "Person"
  },
  "condition": {
    "cypher": "MATCH (subject:Person)-[:WILL_ATTEND]->(venue:Venue)<-[:WILL_ATTEND]-(other:Person)",
    "filter": [
      {
        "operator": "AND",
        "operands": [
          {
            "operator": "=",
            "attribute": "subject.external_id",
            "value": "$token.sub"
          },
          {
            "operator": "=",
            "attribute": "venue.property.name",
            "value": "$venue_name"
          }
        ]
      }
    ]
  },
  "allowed_reads": {
    "nodes": [
      "other.property.firstname",
      "other.property.city",
      "venue.property.name"
    ]
  }
}
```

Each `$param` in the filter becomes a required `input_params` key when the query that uses this policy is executed (Chapter 10). Missing one returns `HTTP 422 invalid_argument: missing or wrong input params`.

### Two real examples from the collection

**`ciqpolicy4` - simplest Person-subject policy (read/update own profile):**

```json
POST /configs/v1/authorization-policies
{
  "project_id":   "{{project_gid}}",
  "name":         "ciq-person-own-profile",
  "display_name": "Person: Read and Update Own Profile",
  "policy": "{
    \"meta\":      {\"policy_version\":\"1.0-ciq\"},
    \"subject\":   {\"type\":\"Person\"},
    \"condition\": {
      \"cypher\":  \"MATCH (subject:Person)\",
      \"filter\":  [{\"operator\":\"=\",\"attribute\":\"subject.external_id\",\"value\":\"$token.sub\"}]
    },
    \"allowed_reads\": {
      \"nodes\": [
        \"subject.property.firstname\", \"subject.property.lastname\",
        \"subject.property.email\",     \"subject.property.age\",
        \"subject.property.city\",      \"subject.property.state\",
        \"subject.property.music_mood\",\"subject.property.karaoke_confidence\",
        \"subject.property.dance_skill\",\"subject.property.profession\"
      ]
    },
    \"allowed_upserts\": { \"nodes\": { \"existing_nodes\": [\"subject\"] } }
  }",
  "status": "ACTIVE"
}
```

**`ciqpolicy14` - same-taste with COUNT aggregates and an OR clause:**

```json
policy: {
  "subject":   {"type":"Person"},
  "condition": {
    "cypher": "MATCH (subject:Person)-[:LIKES]->(track:Track)<-[:LIKES]-(other:Person)
               WHERE subject <> other
               WITH subject, other, COUNT(DISTINCT track) AS sharedTracks
               OPTIONAL MATCH (subject)-[:FOLLOWS]->(artist:Artist)<-[:FOLLOWS]-(other)
               WITH subject, other, sharedTracks,
                    COUNT(DISTINCT artist) AS sharedArtists",
    "filter": [{"operator":"AND","operands":[
       {"attribute":"subject.external_id","operator":"=", "value":"$token.sub"},
       {"attribute":"sharedTracks",       "operator":">=","value":"$min_shared_tracks"},
       {"operator":"OR","operands":[
         {"attribute":"other.property.city","operator":"=","value":"subject.property.city"},
         {"attribute":"sharedArtists",      "operator":">=","value":"$min_shared_artists"}
       ]}
    ]}]
  },
  "allowed_reads": {
    "nodes": ["other.property.firstname","other.property.lastname",
              "other.property.city",     "other.property.music_mood"],
    "aggregate_values": ["sharedTracks", "sharedArtists"]
  }
}
```

The aggregate variables produced by `WITH` become first-class `aggregate_values` the query can read - more on that in Chapter 9.

### Auth

All `ciqpolicyN` requests use the ServiceAccount Bearer (`{{your_sa_token}}`) - they are Config API calls. The capture script writes the response id into `policy_gid`, which is then consumed by the Knowledge Query immediately following.

### What comes next

Chapter 9 turns each policy into one or more Knowledge Queries that declare what to read or write.

## Chapter 9: Knowledge Queries: declare what to read or write

Author 44 Knowledge Queries against the 24 CIQ policies - read variants, write variants, and delete variants for the music graph.

## Chapter 9: Knowledge Queries

From the [ContX IQ guide](/guides/guide-contx-iq): a Knowledge Query (KQ) is a thin wrapper that **names a projection** over a CIQ policy. The policy controls what's *allowed*; the query says what subset of that to *actually fetch or write*.

### Why one policy can have multiple queries

For a single policy like `ciq-app-venue-playable-tracks` the collection ships three variants:

- `kq` - read tracks at the venue.
- `kqb` - upsert (write) Track→Venue relationships allowed by the same policy.
- `kqc` - delete those relationships.

All three reference the same `policy_id` (`{{policy_gid}}`, the most recent CIQ policy created), but their `query` JSON expresses different node/relationship subsets.

### Query body shape

```json
{
  "project_id": "{{project_gid}}",
  "name": "kq-app-venue-playable-tracks-read",
  "display_name": "App Query: Read Venue's Playable Tracks",
  "description": "Read tracks that can be played at a venue",
  "policy_id": "{{policy_gid}}",
  "query": "{\"nodes\":[\"track.property.title\",\"track.property.loudness\",...],\"relationships\":[\"r\"]}",
  "status": "ACTIVE"
}
```

The `query` field is a stringified JSON. Inside, `nodes` lists the node properties to project, and `relationships` lists relationship variables (named in the policy's cypher) to include. Aggregations are referenced via `aggregate_values` when the policy declares them.

### Mapping policy → queries in the collection

| Policy | Queries |
| --- | --- |
| `ciqpolicy` | `kq` (read), `kqb` (write), `kqc` (delete) |
| `ciqpolicy2` | `kq2`, `kq2b`, `kq2c`, `kq2d` |
| `ciqpolicy3` | `kq3` |
| `ciqpolicy4` | `kq4` (read), `kq4b` (write) |
| `ciqpolicy5` | `kq5`, `kq5b`, `kq5c` |
| `ciqpolicy6` | `kq6`, `kq6b`, `kq6c`, `kq6d` |
| `ciqpolicy7` - `ciqpolicy9` | 3 variants each (read/write/delete) |
| `ciqpolicy10` - `ciqpolicy11` | 1 read each (family / children's likes) |
| `ciqpolicy12` | `kq12` (read venue attendees) |
| `ciqpolicy13` | 3 variants (read/write/delete venue playlists) |
| `ciqpolicy14` - `ciqpolicy16` | 1 read each (social / matching) |
| `ciqpolicy17` | 2 (read, write) |
| `ciqpolicy18` - `ciqpolicy24` | 1 query each (analytics & engagement) |

Total: **44 Knowledge Queries** across the 24 policies. Run them in document order so the capture script can pair each one to its policy.

### Run-order rule

The collection is laid out so that every `ciqpolicyN` creation is immediately followed by its query (or queries). The capture script overwrites `policy_gid` on every policy create and `query_gid` on every query create. Each `ciq exec ...` request in the next chapter uses the most recent `query_gid`, so a policy → query → execute triplet always sees consistent values.

### Real KQ bodies from the collection

**`kq4` - read own profile (paired with ciqpolicy4):**

```json
POST /configs/v1/knowledge-queries
{
  "project_id":   "{{project_gid}}",
  "name":         "kq-person-own-profile-read",
  "display_name": "Person Query: Read Own Profile",
  "policy_id":    "{{policy_gid}}",
  "query": "{
     \"nodes\": [
       \"subject.property.firstname\", \"subject.property.lastname\",
       \"subject.property.email\",     \"subject.property.age\",
       \"subject.property.city\",      \"subject.property.music_mood\"
     ],
     \"relationships\": []
  }",
  "status": "ACTIVE"
}
```

**`kq14` - same-taste with aggregate values (paired with ciqpolicy14):**

```json
{
  "name": "kq-person-same-taste",
  "policy_id": "{{policy_gid}}",
  "query": "{
    \"nodes\": [
      \"other.property.firstname\", \"other.property.lastname\",
      \"other.property.city\",      \"other.property.music_mood\"
    ],
    \"aggregate_values\": [\"sharedTracks\", \"sharedArtists\"]
  }",
  "status": "ACTIVE"
}
```

**`kq22` - venue whitelist (uses `venue.property.name` projection):**

```json
{
  "name": "kq-person-people-in-venue-list",
  "policy_id": "{{policy_gid}}",
  "query": "{
    \"nodes\": [
      \"other.property.firstname\",
      \"other.property.city\",
      \"venue.property.name\"
    ]
  }",
  "status": "ACTIVE"
}
```

### Auth

All KQ creation requests use the ServiceAccount Bearer (`{{your_sa_token}}`) - same as the policies they reference.

### What comes next

Chapter 10 actually executes each Knowledge Query against the music graph using values drawn from the seeded dataset.

## Chapter 10: Execute the Knowledge Queries against the music graph

Run all 44 paired ciq exec requests, supplying the right input_params and auth headers so each query returns real music-dataset rows.

## Chapter 10: Execute the Knowledge Queries

From the [ContX IQ guide](/guides/guide-contx-iq): a CIQ execute is what actually fetches data. It posts to `POST /contx-iq/v1/execute` with the query's `id`, the values for each `$param` declared by the underlying policy, and (for Person subjects) the user's bearer token.

### One execute per query

For each `kq...` in Chapter 9 the collection ships a paired `ciq exec ...` request positioned immediately after it. Naming convention: `ciq exec kq`, `ciq exec kqb`, ..., `ciq exec kq24`. Total: **44 executes**.

### Auth differs by subject type

| Subject | Headers |
| --- | --- |
| `_Application` (9 executes) | `X-IK-ClientKey: {{your_agent_token}}` only. |
| `Person` (35 executes) | `X-IK-ClientKey: {{your_agent_token}}` **and** `Authorization: Bearer {{your_user_token}}`. |

Set `your_user_token` in the Variables tab to a real end-user access token from your IdP before running any Person-subject execute. The token's `sub` claim is what Token Introspect (Chapter 3) uses to resolve the caller to a Person node.

**The collection is optimized for one end user: Millicent Contextsworth.** The Person-subject executes are written to be run as a single caller, and the seeded `input_params` assume that caller is the Person node `Millicent Contextsworth` - `external_id: auth0|69c410bfb501d3a02bd01ea2`. So set `your_user_token` to a token *for Millicent*. The Person executes are ordered write-before-read, so running them top to bottom as Millicent first creates the referenced data (likes a track, creates/subscribes a playlist, follows an artist, attends a venue) and then the matching read/update/delete executes return it - all resolved to her via `$token.sub`.

**Mint Millicent's user token.** Use IndyKite's [toolbelt.indykite.com](https://toolbelt.indykite.com/) to issue a Person-subject user token: sign in with Millicent's **email** `millicent@contextsworth.com` and the shared **access code** below. The minted token's `sub` resolves to her Person node (`external_id: auth0|69c410bfb501d3a02bd01ea2`). The toolbelt issues tokens against the same test Auth0 tenant referenced by Chapter 3's `jwt_matcher`. All seeded Auth0 test users share one access code (intentionally public, rotated periodically): <button type="button" class="reveal-btn" data-x="SW5keSF" data-y="Sb2NrIQ==" onclick="var s=document.getElementById('test-user-pw');s.textContent=atob(this.dataset.x+this.dataset.y);s.hidden=false;this.hidden=true">Reveal code</button>``. To run as a different seeded user instead, sign in with that user's email and the same code; the bundled example values, though, are tuned for Millicent.

The **Music app** - the collection plus all the data needed to recreate the whole environment (nodes, relationships, policies, queries, executes) - can be cloned from [github.com/indykite/developer-hub/music](https://github.com/indykite/developer-hub/tree/master/music).

If you use your own IdP instead, you'll need a matching Token Introspect configuration (Chapter 3) pointing at that IdP's `issuer` + `audience`; then mint a token for one of your own users and upsert a matching `Person` node via the Capture API (with `external_id` equal to the token's `sub`) so the CIQ executes resolve to it.

### Execute body shape

After the policy tightening in Chapter 8 (`subject.external_id = $token.sub`), the only values left in `input_params` are the policy's own `$param` filters. Identity comes from the bearer token, not the body.

```json
{
  "id": "{{query_gid}}",
  "input_params": {
    "venue_name": "Shower-Concert-Hall"
  },
  "page_token": 1
}
```

### Sample defaults wired into the collection

| Param | Default value | Why this works |
| --- | --- | --- |
| Person identity (via Bearer) | `{{your_user_token}}` for an Auth0 user whose `sub` matches a seeded Person `external_id` (e.g. Cornelius `auth0\|69c3ee8cb9ed562744ff9326`). | The bearer's verified `sub` claim drives `$token.sub` in the policy filter - no body field needed. |
| `venue_name` | `Shower-Concert-Hall` | First Venue in the dataset (`venue-1`); has 50 PLAYED_AT tracks and 3 attendees. |
| `artist_name` | `ABBA` | Seeded as `artist-2`; has 9 albums and 112 tracks. |
| `venue_ids` | `["venue-1","venue-2"]` | Existing Venue external_ids. |
| `min_confidence` / `min_likes` / `min_shared_*` | `0.7` / `1` | Permissive thresholds that return rows on this dataset. |

### Real execute bodies from the collection

**Smallest possible Person execute** (`ciq exec kq4`, own-profile - the policy has no `$param` beyond identity, and identity is supplied by the bearer, so `input_params` is empty):

```json
POST /contx-iq/v1/execute
Headers:
  X-IK-ClientKey: {{your_agent_token}}
  Authorization:  Bearer {{your_user_token}}
{
  "id": "{{query_gid}}",
  "input_params": {},
  "page_token":   1
}
```

**Person execute with policy params** (`ciq exec kq14`, same-taste):

```json
{
  "id": "{{query_gid}}",
  "input_params": {
    "min_shared_tracks": 1,
    "min_shared_artists": 1
  },
  "page_token": 1
}
```

**Application-subject execute** (`ciq exec kq`, venue playable tracks - no Bearer header, only the agent key):

```json
POST /contx-iq/v1/execute
Headers:
  X-IK-ClientKey: {{your_agent_token}}
{
  "id": "{{query_gid}}",
  "input_params": {
    "venue_name": "Shower-Concert-Hall"
  },
  "page_token": 1
}
```

### Sample response (read execute)

A successful read execute returns `data`, one record per matched row, each with a `nodes` map keyed by the references the query declared (and a `relationships` map when it declares any). There is no page token in the response: a page shorter than `page_size` (default 100) is the last one. Example for `ciq exec kq4` (read own profile) when authenticated as Cornelius:

```json
{
  "data": [
    {
      "nodes": {
        "subject.property.firstname": "Cornelius",
        "subject.property.lastname": "Pickleworth",
        "subject.property.email": "cornelius@pickleworth.com",
        "subject.property.age": 14,
        "subject.property.city": "Ctrl-Z Canyon",
        "subject.property.state": "Texas",
        "subject.property.music_mood": "Acoustic Sadness",
        "subject.property.karaoke_confidence": 0.4,
        "subject.property.dance_skill": 0.67,
        "subject.property.profession": "Professional Homework Avoider"
      }
    }
  ]
}
```

### What happens at execute time

1. The platform looks up the query by `id` and resolves its policy.
2. It validates that every `$param` from the policy's filter is present in `input_params` - missing one returns `HTTP 422`.
3. For Person subjects, it introspects the bearer token, extracts the `sub` claim, and uses it as the value of `$token.sub` in the policy filter (which then pins the cypher subject to that one Person node).
4. It runs the cypher with the params plugged in, then projects only the fields listed in `allowed_reads`.
5. The result is the policy-scoped subset of the music graph matching the query's projection.

### What to expect when you run them

With the seeded dataset and the recommended test users from Chapter 5, every paired execute returns rows. Predicted row counts (auth as **Cornelius** unless noted):

| Group | Executes | Rows |
| --- | --- | --- |
| Application catalog (no bearer) | `ciq exec kq` / `kqb` / `kqc` | 50 tracks at Shower-Concert-Hall |
|  | `ciq exec kq2` / `kq2b` / `kq2c` / `kq2d` | 9 albums + 112 tracks for ABBA |
|  | `ciq exec kq3` | 3 karaoke-ready persons |
|  | `ciq exec kq21` | 3 attendees of Shower-Concert-Hall |
| Person, self-only | `kq4` / `kq4b` / `kq17` / `kq17b` / `kq23` | 1 row (the caller's own profile / properties) |
| Person, direct relationships | `kq5`/b/c (likes), `kq6`/b/c/d (playlists), `kq7`/b/c (subscriptions), `kq8`/b/c (followed artists), `kq9`/b/c (venues), `kq14-kq16`, `kq18-kq20`, `kq24` | 1 - 5 rows each (Cornelius's seeded engagement) |
| Two-hop (venue / family) | `kq10` (family playlists), `kq12`, `kq13`/b/c, `kq22` | ROWS |
| Parent-side query | `kq11` (children-likes) | EMPTY for Cornelius (he's a child); switch the bearer to **Marmaduke** (`auth0\|69c4129b0ba356c7db9f91ab`) and it returns 6 rows. |

If a Person execute returns zero rows, check (a) the bearer's `sub` claim matches a seeded Person external_id and (b) that user actually has the relationship the cypher walks. Most often the answer is "use Cornelius for music engagement, Marmaduke for parent-side queries" - see the Chapter 5 test-user table.

### Recommended order

Run each `ciqpolicyN → kqN... → ciq exec ...` triplet sequentially so `policy_gid` and `query_gid` stay in sync. The collection is already sorted that way - just hit "Run" and watch the variables rotate.

### You're done

By the end of this chapter you have run every product surface IndyKite exposes against a non-trivial music graph: environment provisioning, capture, KBAC + AuthZEN, Token Introspect, MCP, ContX IQ policies + queries + executes. Re-use these patterns against your own data: keep the variable layout, swap the dataset, adjust the policies.

### Where to go next

- [Trust Score](/guides/guide-trust-score) - assess data freshness, origin, and verification.
- [External Data Resolver](/guides/guide-external-data-resolver) - pull in external API data during a query.
- [Outbound Events](/guides/guide-outbound-events) - stream every IKG change to Kafka, Event Grid, Service Bus, or Pub/Sub.

---

Source: https://developer.indykite.com/tutorials/tutorial-music-dataset