# Blueprints

## Explanation — what & why

A **blueprint** is an app model as configuration. One file (or a root file and the
part files it includes) declares everything a Vectros app needs to exist — the record schemas, a least-privilege access
profile, a service principal, optional seed data, and optional roles — with
stable identifiers so applying it twice converges instead of duplicating (the
loader always reconciles server-side via `?upsert=true`, so re-applying the
*same* blueprint is always safe). A schema whose `typeName` is already claimed
by a **different** owner — e.g. a second blueprint modeling the same conceptual
type — must declare `basedOn` (see the schema reference below).

Blueprints exist to collapse "stand up a new app's data layer" from a sequence of
API calls into a single reviewable artifact. You write the file once; the CLI's
`bootstrap` and `blueprint-test` commands turn it into provisioned
infrastructure and a working scoped key (see [cli.md](cli.md)).

Two boundaries define what a blueprint is and is not:

- **It describes format, not trust.** The `@vectros-ai/blueprints` package owns
  the format and its structural validation only. The security boundary — the
  scope gate that limits the scopes a blueprint can mint — lives in the CLI
  binary. A blueprint is untrusted input; the binary is the trust boundary.
- **Its scopes are limited to an allowlist.** A blueprint can request scopes on
  records, schemas, search, documents, folders, inference, runs, and identity entities,
  plus a few narrow exceptions (`profiles:r`/`u`/`d`, `profiles:c:self`, a bare
  `profiles:c` only on a clause that also declares `member-lifecycle`, and
  `scripts:x:<name>`). Every other scope is rejected when the CLI applies it. See
  [cli.md](cli.md#the-scope-gate-data-plane-allowlist).

This doc is the **format reference** the blueprint walkthroughs build on. For
narrated, end-to-end builds, see the walkthroughs (getting-started,
clinical-intake, agentic-sdlc, second-brain).

## How-to

### Scaffold, validate, and apply

The full authoring loop runs through the CLI:

```bash
vectros blueprint init my-app                  # scaffold ./my-app.blueprint.yaml
vectros blueprint validate ./my-app.blueprint.yaml
vectros blueprint plan ./my-app.blueprint.yaml
vectros blueprint apply ./my-app.blueprint.yaml --tenant test   # provision it, no key (needs CLI 0.23.0+; CI: add --yes --confirm-existing-principal)
vectros bootstrap --blueprint ./my-app.blueprint.yaml           # provision it AND mint a key for your MCP client
```

If another request changes the same schema, app context, role, namespace or trigger rule at the
moment `blueprint apply` or `bootstrap` is updating it, the platform answers `409` (`VERSION_CONFLICT`)
instead of overwriting the other change, and the command stops with the platform's message. Run it again
once the other change has finished; a re-apply converges.

**What each step checks.** `validate` and `plan` check the blueprint's own text: its shape, the scope gate,
and the platform rules that depend only on what the blueprint declares (the lint errors included).
`plan --tenant test|live` also reads the tenant, as `apply` does, and stops before anything is written.
`apply` and `bootstrap` run the same lint and refuse a lint error, except two the platform does not refuse
(a lookup on an undeclared field and a seed for an undeclared type), which they print as warnings. `apply` then
checks each declared schema against the live one before the first write, and stops with every change the platform
refuses because of what is stored: an applied `asset` field removed, a field changed to or from `asset`, `assets`
or `geo`, a lookup field changed to or from `instant`, a changed `sensitive` flag or `basedOn`, an existing
lookup's `rangeEnabled` or `sortBy`, or the type of a `rangeEnabled` lookup's field or of a lookup's `sortBy`
field; on a new type, record-mode public search with `indexMode` left out; and from platform 0.51.0 an item limit
that cannot work, when it is added or changed. On a first apply, before the app context exists, nothing is live,
so `apply` checks only what a new schema cannot carry: an item limit that cannot work, and record-mode public
search with `indexMode` left out. What these checks cannot see the platform still refuses at the write: the
settings and types a lookup recorded when it was first declared (they still bind after a type change, or after
the lookup was removed), whether the type has records or documents, the owner's account settings and the
capabilities of the credential. A new `asset` field must be served by the type's public view; only the platform knows whether a field is new, so only it checks that. When an apply stops part-way, the
message says whether running it again gets past the failure or fails the same way until the blueprint or
the flags change.

**What an apply removes.** No resource, except triggers with `--prune`. A schema, script, agent, issuer,
namespace or identity left out of the blueprint stays as it is. What a declared resource holds is replaced by
what the blueprint declares: a schema's fields, lookups and render hints (a field left out of the blueprint is
removed from the schema), a role's clauses and the access profile's scopes.

You can scaffold from a bundled exemplar with `init --from <name>`. See
[cli.md](cli.md) for the lifecycle commands.

### A minimal blueprint

Blueprints are authored as YAML or JSON. A minimal one declares a context, one
schema, an access profile, and a service principal:

```yaml
name: my-app
version: 1.0.0
description: A minimal example app.
contextId: my-app
contextName: My App

schemas:
  - typeName: note
    displayName: Note
    indexMode: HYBRID          # HYBRID | SEMANTIC | TEXT | NONE
    fields:
      - { fieldId: title, fieldType: string, required: true, searchable: true }
      - { fieldId: body,  fieldType: string, searchable: true }
    lookupFields: [title]        # extra exact-match index(es). Do NOT list externalId:
                                 # it's the record's first-class id (sent top-level on
                                 # each record), with its own finder — declaring it as a
                                 # lookup is rejected, and a field of that name can never
                                 # hold a value (validate warns).

accessProfile:
  allowedActions: [records:r, records:c, records:u, search:r, schemas:r]

servicePrincipal:
  externalId: my-app
  displayName: My App
```

`indexMode`, the per-field `validation`/`renderHints`, and the schema-level
`capabilities`/`active`/ownership fields are all optional — the example stays
minimal on purpose. (Omitting `indexMode` is not the same as `HYBRID`: a record with no
resolvable mode is stored but never indexed, so declare the mode you want.) Note the deliberate absence of `records:d` in
`allowedActions`: least privilege is the authoring default.

## Reference — what a blueprint can express

### Top-level fields

| Field | Required | Meaning |
|---|---|---|
| `name` | yes | Stable blueprint id — the `--blueprint <name>` selector and idempotency key. |
| `version` | yes | Blueprint version string. |
| `description` | yes | Human-readable description. |
| `contextId` | yes | The app context the profile and key bind to. 3–31 chars; lowercase letter first, then lowercase letters/digits/dashes. |
| `contextName` | no | Human-readable context name; defaults from `name`. |
| `companyName` | no | The deploying organization's own display name, distinct from `contextName` (which is the blueprint author's fixed name for the app). Typically templated from an input per install; sent to the platform to personalize platform-sent correspondence such as invitation emails, and kept in step on a re-apply. |
| `appContext` | no | Settings of the app context itself: `description` (at most 500 characters), `readAccessLogDefault`, `meteringAxis` (`user` or `scope:<namespace>`), `principalBurstLimit`, `principalUsageCap` (each at least 1), `allowSelfErasure` and `selfErasureGraceDays` (0 to 30). A create sends each one declared. On a re-apply the first five are updated to the declared values, and a key left out keeps the stored value. `allowSelfErasure` and `selfErasureGraceDays` are set only when the apply creates the context: changing them later needs the account owner's own credential, so a re-apply that declares a different value reports it and changes nothing. |
| `schemas` | no | The record/surface schemas to provision (see below). |
| `accessProfile` | yes | The least-privilege scope the bootstrap mints for the blueprint's own key. |
| `servicePrincipal` | yes | The service principal the key is bound to. |
| `seed` | no | Deterministic seed records and documents; each entry names its `surface`. |
| `roles` | no | Reusable, multi-clause scope rules. |
| `identities` | no | Declared principals (see the glue caveat below). |
| `issuers` | no | Trusted third-party IdP issuers to register, for BYO-IdP token exchange (see below). |
| `namespaces` | no | Entity-namespace registrations to declare (see below). |
| `scripts` | no | The versioned JS source a trigger's `scriptRef` runs (see below). |
| `triggers` | no | Rules that invoke a script on a schema record's `CREATE`/`UPDATE`/`DELETE` event (see below). |
| `formatVersion` | with `agents` | The blueprint format; absent means 1. An `agents` section needs `2`. A file that declares a format newer than the tool reads is refused with a message to upgrade `@vectros-ai/cli` and `@vectros-ai/blueprints`. |
| `agents` | no | Stored agents (`/v1/agents`): a model, system prompt, tool whitelist, limits and budget per name (see below). |
| `identityProjectionClaims` | no | Which captured IdP claim names get projected, read-only, onto access profiles in this context (see *Issuers* below). |
| `inputs` | no | Install-time variables (resolved with `--set`/`--values`). |
| `include` | no | Part files that add sections to this blueprint, for a blueprint split across files (see *Splitting a blueprint* below). Root file only. |
| `stacks` | no | Named groups of the `include`d part files that `apply --stack` applies one at a time (see *Splitting a blueprint* below). Root file only. |

### Schemas

Each schema entry declares a record type:

| Field | Meaning |
|---|---|
| `typeName` | The record type name. |
| `displayName` | Human-readable label. |
| `indexMode` | `HYBRID` (keyword + semantic), `SEMANTIC`, `TEXT`, or `NONE` (store-only: persisted and readable by id and lookup, never indexed, so it never appears in a search or a grounded answer). Omitting it is not `HYBRID`: a record with no resolvable mode is stored but not indexed. |
| `fields[]` | Field definitions (see below). |
| `lookupFields[]` | Fields to index for direct lookup. Bare field name (equality), or `{ fieldName, unique?, rangeEnabled?, sortBy?, allowOverflow? }` — or, for a **composite** lookup over 2–3 fields together, `{ fieldNames: [...], sortBy?, allowOverflow? }` (see *Composite lookups* below). `rangeEnabled` adds ordered `from`/`to`/`prefix` queries (use it for dates/sequences/scores; the order is lexical, so it's wrong for ordinal enums). `sortBy` sets the order an equality lookup returns — `createdAt` (default), `lastUpdated`, or another field on the schema. You can also *range* over that sort key (`sortFrom`/`sortTo` on a `value` lookup — e.g. one session's records since a timestamp). The sorted field does **not** need to be `required`: records that carry no value for it are ordered ahead of those that do, and are never inside a bounded window. `sortBy` and the sorted field's **type** are both migration-locked, so choose them when you declare the lookup; an `array` or `object` field cannot be a `sortBy` target. Each schema has **7 fast equality slots** (range lookups use a row, not a slot; ownership ids + `externalId` ride their own); an 8th equality lookup needs `allowOverflow`. The index shape is **migration-locked** — pick it deliberately. You can add a lookup to a type that already has records; records written before it are found by it only after their next write (see *Lookup fields* in the [data-model reference](../data-model/reference.md#lookupdef)), and an existing lookup's `rangeEnabled`, `sortBy` and `sensitive` cannot be changed afterwards, nor the field type of a `rangeEnabled` lookup (an equality lookup's field can change type, but not to or from `instant`). A `sensitive` field may be an equality (blind-index) lookup, never `rangeEnabled`, and never a `sortBy` target. Up to 10. |
| `allowedSurfaces[]` | Which typed surfaces may bind the schema: `record`, `document`, `entity` (identity entities in any namespace — `org`, `client`, or one you register). Defaults to `[record]`. `user` is rejected when you validate a blueprint: a user-surfaced schema is account-global and needs a root API key, which no blueprint credential holds. Model the data as a record scoped to the user, or as an `entity` schema. |
| `capabilities.auditHistory` | Whether writes emit version history (platform default on). |
| `capabilities.ttlEligible`, `.strict`, `.validateReferences`, `.readAccessLog` | `ttlEligible` (default off): records may carry `expiresAt`. `strict` (default off): a payload key the schema does not declare is refused. `validateReferences` (default on): a reference must point at a record that exists when written. `readAccessLog`: whether reads are logged; left out, the app context's default applies. A declared `capabilities` block is laid over the live one: a capability the block leaves out keeps its live value, and declaring `false` turns one off. |
| `storageProfile` | Where a record's payload is stored: `STANDARD` (the default), `LOW_LATENCY` (always inline) or `LARGE_PAYLOAD` (always stored out of line, lifting the 400 KB limit; not with a public view in mode `record`). Left out, the stored value is kept. |
| `capabilities.triggersEnabled` | Whether records of this schema fire trigger rules. Defaults to `false`, and is the opt-in a schema must declare before a trigger may fire on it — a blueprint declaring a trigger against a schema without it is refused at `plan` time. Independent of `auditHistory`. |
| `active` | Whether the schema accepts new records. |
| `userId` / `scopes` | Schema-level ownership defaults. `scopes` is an array of `<namespace>:<value>` entries (e.g. `org:acme`), the same grammar records/entities use. |
| `basedOn` | Id of an existing schema this one **customizes**, required when a schema named `typeName` already exists in this context under a *different* owner. Omit when this is the first schema under that name (it becomes that name's shared base — root/unscoped credential only, no `userId`/`scopes`). Must point directly at the base (one hop); immutable once set. Mirrors the platform's `basedOn` schema field ([data-model/reference.md](../data-model/reference.md#schema-fields)). |
| `fileProfile`, `mediaKinds`, `maxBytes`, `contentTypes` | `fileProfile: PUBLIC_MEDIA` makes a document schema a public-media type: a document type for images (no route serves them publicly). It needs `allowedSurfaces: ['document']` and is never indexed (`indexMode` `NONE` or omitted); it cannot be a customization (`basedOn`). `mediaKinds` (only `image`), `maxBytes` (at most 10485760, 10 MiB, the default on create) and `contentTypes` (a subset of `image/jpeg`, `image/png`, `image/webp`, `image/gif`, all four by default on create) are declared with it: `validate` refuses them without `fileProfile`, even for a type already stored as public media. The profile cannot be added to a type that already has documents or variants. Leaving the profile, or any of the three settings, out of a later apply keeps the stored value; returning to a default means declaring it. Needs platform 0.50.0 or later. |
| `publicView` | Makes the type's records readable without signing in. The keys are the platform's: `mode` (`projection`, the default, or `record`), `fields` (projection only), `ownedBy`, `publishWhen`, `search`, `cacheSeconds` (0 to 86400 seconds of edge caching; 0, or omitted on a first declaration, never caches) and `purgeListsOnChange` (`publicViewVersion` is server-managed and ignored). A view declared without `cacheSeconds` or `purgeListsOnChange` keeps the live value on a re-apply, so caching set elsewhere is not reset. The two cache keys need platform 0.51.0 or later. Declared on a base schema only, with `allowedSurfaces` omitted or exactly `['record']`; projection mode only on a schema with no `userId` or `scopes`. `publishWhen.field` must be declared, not `sensitive`, of type `string`, `enum`, `number` or `boolean`, `filterable`, and a lookup of its own (in `lookupFields`, not only in a composite), and each `in` value must have its type; a view with `search` needs an `indexMode` covering each mode and a searchable field (mode `record`) or a listed string field (mode `projection`). Any change to it (adding, changing or removing it) needs the `public-publish` capability ([identity-access/reference.md](../identity-access/reference.md)), which the account owner's own login carries; publishing or widening it also needs your account's public access, which the account owner switches on with the developer portal API (a blueprint cannot). Leaving the key out of a later apply keeps the type's public view; `null` removes it. Needs platform 0.50.0 or later. |
| `publicView.geoPrecision` | `projection` mode only: for each `geo` field listed in `publicView.fields`, `'exact'` (the location as stored) or a whole number of metres from 100 to 100000, the minimum edge of the grid cell whose centre the public copy holds. Required for every listed `geo` field; refused in `record` mode. Changing it on a published type, in either direction, counts as making more data public. Needs platform 0.50.0 or later. |

Each field definition supports:

| Field key | Meaning |
|---|---|
| `fieldId` | Field name. |
| `fieldType` | Field type (e.g. `string`, `array`, `reference`; `instant` for a moment in time, an RFC 3339 date-time with an offset (up to ±18:00, years 0001 to 9999), stored in UTC at millisecond precision, finer digits refused; `array`, with `itemType` (`string`, `number`, `boolean`, `date` or `instant`, platform 0.51.0 or later) for its elements; `geo` for a location, refused until an owner of the account signs the Geocoding waiver for the tenant in the developer portal: not `sensitive`, `searchable` or an enum, never a lookup or a `sortBy`, record and document schemas only, filterable unless `filterable: false`; `asset`/`assets` for images, with `documentTypes`). A type this CLI does not know is a warning, not an error: the platform decides when it writes the schema. A filterable field may not start with `_geo_`, or be named `publicCopy` or `public_copy_owner` in any letter case: the platform keeps those for its search index. |
| `required` / `searchable` / `filterable` | Per-field flags. |
| `enumValues[]` | Allowed values for an enumerated field. |
| `validation` | Validation rules: `required`, `minLength`/`maxLength`, `min`/`max`, `pattern`, `email`/`url`/`phone`, `step`/`multipleOf`, `minItems`/`maxItems`. `minItems`/`maxItems` apply to an `array` field (`maxItems` also to `assets`). A negative limit, `minItems` above `maxItems`, or a limit on another type is a warning; from platform 0.51.0 the platform refuses it when the limit is added or changed, and `apply` stops before anything is written. A limit already stored that way is kept and has no effect. |
| `renderHints` | UI hints: `label`, `widget` (`text`/`textarea`/`select`/`date`/`checkbox`), `order`, `section`, `helpText`, `displayField` (mark the record's headline column — at most one per schema). |
| `sensitive` | Marks the field as sensitive: it is removed from version history at write time, blind-indexed for lookups, excluded from the search index, and masked on read unless a token carries the reveal scope. |
| `inline` | Keep the field on the record row when the payload is stored out of line, so it appears in list and lookup projections without `includePayload` — and so a trigger rule may project it into `input.record`. Cannot be combined with `sensitive`. |
| `targetTypeName` / `targetSurface` / `targetField` / `cardinality` | On a `reference` field, the typed link target. `targetTypeName` and `targetSurface` are **both required** — the same typeName can exist on multiple surfaces, so the surface disambiguates the lookup. `targetSurface` is `record`, `document`, `user`, or the name of an **entity-backed namespace** — `org`, `client`, or one you registered via `POST /v1/namespaces` (see [identity-access/reference.md](../identity-access/reference.md#namespaces--v1namespaces); the namespace must already be registered and entity-backed, or the schema is rejected at authoring time). `targetField` defaults to the target's `externalId` (must be a unique lookup); `cardinality` = `one` (default) / `many`. The target's existence is enforced at write by default. |
| `documentTypes` | On a field of type `asset` (one image) or `assets` (up to 20; `validation.maxItems` may set a lower limit), the public-media document types the field accepts, by `typeName`. Required on both, allowed only on them. An asset field cannot be `sensitive`, `searchable`, an enum or a reference, and is declared only on a base schema. The platform refuses removing an asset field or changing its type; the CLI leaves those checks to it. From platform 0.51.0 an asset field may be declared on any base schema: its images are public only while the record is public under a `publicView` that serves the field (in `projection` mode, listed in its `fields`), and are otherwise kept private. Setting an image that another record holds moves it, when the writer may read and update that record. Needs platform 0.50.0 or later. |
| `geocode` | On a `geo` field of a record schema, `{ from: [...] }`: the fields of the same schema that hold its address, in order (at most 10, distinct, each `string`, `enum` or `number`, never `sensitive`). `validate` checks this offline and refuses it on a schema whose `allowedSurfaces` include `document`. The platform looks up the location after each write that changes the address; a record shows the progress in `geocodeStatus` ([data-model/reference.md](../data-model/reference.md#fielddef)). Needs platform 0.50.0 or later. |

### Composite lookups

A lookup can span **2–3 fields matched together** as one index, declared with
`fieldNames` in place of `fieldName`:

```yaml
lookupFields:
  - fieldNames: [status, area]   # queried together as one exact-match index
```

- **Order is fixed at declare time.** A query can match a **leading run** of
  the declared fields — the first field alone, the first two, and so on — but
  never a later field alone; declare a separate lookup for that. Redeclaring
  the same fields in a different order creates an independent lookup that only
  sees writes made after it was declared, not the history under the old one.
- **Exact-match only.** A composite lookup can't be `unique` or `rangeEnabled`
  — declare those as a separate, single-field lookup instead.
- **Record schemas only.** `allowedSurfaces` must be exactly `['record']`;
  document, user, and entity schemas can't declare a composite lookup.
- **Each leg must be a plain, single-valued, non-range field.** A leg can't be
  an `array` or `object` field (one sort-key position holds one value), a
  `reference` field with `cardinality: many`, or a field that is itself
  declared `rangeEnabled` elsewhere on the schema — any of those would index
  only one of several values and the conjunction would silently return a
  subset while looking complete.
- **A leg cannot also be the composite's own `sortBy` target.** Within a fixed
  tuple every matching record shares the same value for that leg, so the sort
  payload would be constant and a `sortFrom`/`sortTo` window would return
  either everything or nothing, at double the sort-key cost. Sort by a
  different field, `createdAt`, or `lastUpdated` instead.
- `sortBy` and `allowOverflow` still apply otherwise: `sortBy` orders results
  **within** a group when a query supplies fewer values than the lookup
  declares (see `lookupFields[]` above).

### Access profile

```yaml
accessProfile:
  allowedActions: [records:cru, search:r, schemas:r]
  dataScope:
    "scope:org": [org_acme, null]
```

- `allowedActions` — the scopes the minted key carries. Author explicit
  `resource:op` forms; coarse verbs and `resource:*` are rejected when authored.
  Subject to the CLI scope gate.
- `roleIds` — alternative to `allowedActions`/`dataScope`: compose the profile
  from one or more roles this same blueprint declares under `roles:` (below),
  instead of an inline clause:
  ```yaml
  accessProfile:
    roleIds: [case-handler, hr-admin]
  roles:
    case-handler:
      - allowedActions: [records:r:case, records:u:case]
    hr-admin:
      - allowedActions: [records:r:hr]
  ```
  The effective grant is each named role's own clauses, concatenated in the
  order listed — never merged, so each clause keeps meaning exactly what its
  own author wrote. Mutually exclusive with `allowedActions`; a `roleIds`-
  composed profile carries no `dataScope`/`capabilities` of its own — author
  those on the referenced roles instead. Every id must resolve to a role
  declared in this same blueprint, and no id may repeat.
- `dataScope` — optional ownership binding (`userId` or `scope:<namespace>` →
  value lists; `scope:org`/`scope:client` for those reserved namespaces, or
  `scope:<namespace>` for one you registered — org/client must be registered
  too, same as any other). A `null` element is the
  documented **null sentinel**: it additively grants access to tenant-level
  (owner-less) records *in addition to* the listed owners. Omitting `null`
  restricts the key to the listed owners only — so it will not see
  tenant-level/seed records.
- `capabilities` — optional list of platform capability names (distinct from a
  schema's `capabilities.auditHistory`), e.g. `capabilities: [member-lifecycle]`.
  This package validates the *shape* only (non-blank, no duplicates, lowercase
  kebab-case, no `'*'`) — it does not itself know which names the platform
  actually grants, since that set is a platform property (eight names as of this
  release: `member-lifecycle`, `forensic-read`, `context-directory-read`,
  `delegate-mint`, `delegate-principal-stamp`, `trigger-control-plane-grant`,
  `public-publish`, `script-egress-declare` —
  see [identity-access/reference.md](../identity-access/reference.md#granted_capabilities)).
  The CLI's capability gate admits only `member-lifecycle` and
  `delegate-principal-stamp` on a blueprint it applies; any other name is rejected
  and nothing is minted. Each role clause below accepts the same field.

### Service principal, seed, roles

```yaml
servicePrincipal:
  externalId: my-app
  displayName: My App

seed:
  - surface: record                # required: `record` or `document`
    typeName: note
    externalId: seed-welcome
    fields: { title: Welcome, body: Created by the bootstrap loader. }   # externalId is the seed's top-level field above, NOT a payload field

roles:
  editor:
    - allowedActions: [records:cru, search:r]
      dataScope:
        userId: ['${{ self.userId }}']
```

- `servicePrincipal` — the principal the minted key binds to.
- `seed` — deterministic records or documents (keyed by `externalId` for idempotency). Each entry sets `surface` to `record` (with `fields`) or `document` (with a required `title` and `text`, and optional `fields`). `vectros bootstrap` writes them unless you
  pass `--no-seed`; `vectros blueprint apply` writes them only when you pass `--seed`.
- `roles` — a map of role id → ordered clauses. Each clause is an
  `(allowedActions, dataScope)` pair, evaluated per-clause at runtime. Roles are
  identity-agnostic and reusable; bind them to principals with
  `vectros access grant --principal <p> --context <c> --role <id>`. Every role clause passes the same CLI scope
  gate as `accessProfile`, so a role is not a way around it.
- `${{ self.* }}` placeholders are a **runtime per-principal** sentinel,
  resolved per-request by the platform. They are only valid inside a role
  clause's `dataScope`, a `roleAssumable` value or a `fragments` value; using one anywhere else, a trigger's grant included, is an authoring error.

**`fragments` — authoring sugar for a repeated `dataScope`.** A top-level map
of name → `dataScope`, referenced from a clause with `dataScopeRef` instead of
repeating an identical `dataScope` verbatim:

```yaml
fragments:
  ownOrg:
    "scope:org": ['${{ self.scope.org }}']
roles:
  case-handler:
    - allowedActions: [records:cru:case]
      dataScopeRef: ownOrg
    - allowedActions: [search:r]
      dataScopeRef: ownOrg
```

`dataScope` and `dataScopeRef` are mutually exclusive on the same clause. A
`dataScopeRef` is resolved to its fragment's literal `dataScope` before
anything downstream (the loader, the wire payload it sends) ever sees it — a
purely local authoring convenience, never itself provisioned.

**`roleAssumable` — which values a role's holder may become.** A top-level map
of `roleId` → grant, naming which values, per `scope:<namespace>`, a holder of
that role may assume via `POST /v1/auth/token/assume`
([identity-access/reference.md](../identity-access/reference.md#assuming-an-identity--post-v1authtokenassume)):

```yaml
roleAssumable:
  hr-admin:
    "scope:org": [org_engineering, org_sales]
roles:
  hr-admin:
    - allowedActions: [records:r]
```

Every key must resolve to a role this same blueprint declares under `roles`.
Its value grammar is narrower than a clause's `dataScope`: every key must be a
namespaced `scope:<ns>` (the principal — `userId` — can never be named here),
and no value may be `null`. `vectros blueprint plan` previews a role's
`assumable` grant alongside its clauses, since it's security-relevant — what a
holder of the role may become, not just that the role was declared.

**`assignableRoles`** — both `accessProfile` and each role clause may carry an optional roleId
allow-list restricting which named roles that clause may compose into a delegated access profile
(`roleIds` composition). Orthogonal to `allowedActions`/`dataScope`: it narrows which roles the
clause's authority may hand out, not how much data it reaches. Omitting it means no restriction; an
**empty list is rejected** rather than read as "compose nothing". At most 20 entries, duplicates
rejected. Entries are deliberately *not* resolved against this blueprint's own `roles` — a clause
may legitimately name a role that already exists in the context. Rejected on a `roleIds`-composed
`accessProfile`, which has no inline clause to carry it. **Once a clause carries the field it can
compose only the roles it names**, so name every roleId the restricted clause still needs before
adding it.

### Scripts

A blueprint may declare a top-level **`scripts`** — a map of script name → `{ source,
declaredInputContract? }` — carrying the source a trigger's `scriptRef` runs, so a blueprint that
declares a trigger can ship the code that trigger executes. Applied in-context, **before** the
triggers that reference it: a `scriptRef` is validated when the rule is *declared* rather than when
it fires, so a rule naming a script with no versions in the target context is refused outright.

```yaml
scripts:
  notify-assignee:
    source: |
      // A script is a plain (classic) script: its last expression is the result,
      // and `input` is a global. `export`, a top-level `return` and `await` are syntax errors.
      ({ notified: input.recordId });
    declaredInputContract: "{ recordId: string, record: { status: string } }"
```

- The map **key is the script's name** — what a `scriptRef.name` resolves against. 1–64 characters
  of letters, digits, `_` and `-`.
- `source` — **required**, non-blank, at most **300,000 UTF-8 bytes**. Nothing parses it, here or on
  the platform, so a syntax error stays invisible until the version first runs. It runs as a plain script, not a module: the value of its last expression is the result, and `input` is a global.
- `declaredInputContract` — optional, at most **50,000 UTF-8 bytes**, and **descriptive only**:
  it documents the input shape for a human reading the blueprint, and nothing enforces it.
- `inputSchema` — optional: the input contract the platform **enforces** on every call of the version, in the platform's small JSON Schema dialect: the root is `{ type: object }`; a node has a `type` (`string`, `number`, `integer`, `boolean`, `array`, `object`) and may have a `description` (up to 2,000 characters) and an `enum` (1 to 100 distinct values of its type); an `object` node may have `properties` (up to 100, each named 1 to 64 characters), `required` and `additionalProperties` (`false` unless set to `true`); an `array` node may have `items`; nothing else, at most 5 levels deep and 16,384 bytes. `validate` checks
  it offline with the same rules. Needs platform 0.50.0 or later.
- `optInOperations` — optional: the operation names this version declares. Which names a version may declare is the platform's
  decision, and declaring one needs the capability mapped to it, which a blueprint role cannot grant; `validate` checks that each
  entry is a non-empty string and that the list is not longer than the platform accepts. Needs platform 0.50.0 or later.
- `destinations` — optional: the destinations (by alias) this script may call. Needs platform 0.51.0 or later. Each alias is a lowercase letter followed by 1 to
  39 lowercase letters, digits or `-`, and an alias may be listed once. Not part of the version: changing the list pushes nothing.

**`destinations` is checked, never granted.** A script calls a destination only with an approval that an account owner gives
for one version, by the exact SHA-256 of its source and the operations it declares (`vectros scripts approve`, or the developer
portal). `blueprint apply` never gives one, because it would then approve the very code it had just pushed. After it applies,
it checks each declared destination against the version it converged on and, for each one that version is not approved for,
prints a warning with the exact command that approves it, for example
`vectros scripts approve send-invoice --context billing --destination crm --script-version 4`. It also reports a declared
destination the tenant does not have, or one not open to the blueprint's app context. The apply itself succeeds either way, and exits 0; pass `--require-approved` to make a declared destination that cannot be called exit 5 (the apply itself still completes). An approval also stops matching when the destination's base address or allowed methods change, and apply then reports it again.
`blueprint plan` lists the declared destinations. A new version needs its own approval, so a re-apply that pushes new code
reports the destination again.

`source`, `declaredInputContract`, `inputSchema` and `optInOperations` are all part of the version: a re-apply pushes a new version
when any of them differs from the stored one (`inputSchema` is compared in the form the platform stores, and `optInOperations` as a
set, so order and repeats do not count), and pushes nothing when none does. A blueprint that leaves `inputSchema` out does not
compare it, so a version stored with one (pushed another way) is kept while nothing else changes; a push for another reason stores a
version without one. A blueprint that leaves `optInOperations` out declares none: an absent list is the empty list, so a stored
declaration is not kept.

Both caps count UTF-8 **bytes**, not characters, matching the platform.

**There is no `path:`, deliberately.** A shipped script runs under its trigger's declared grant, so
it is live authority, and a blueprint is a bundle someone reviews before applying it — keeping the
source inside the bundle keeps what runs inside what was reviewed.

**You cannot declare a version, and a trigger on a script this blueprint ships must use
`version: latest`** — a pin is rejected at authoring time. Versions are assigned by the platform and
a stored version is immutable, so a blueprint declares only the current source for a name; a pin
would name a version the blueprint cannot know it produced, and would keep running superseded code
once the source was edited. A `scriptRef` naming a script this blueprint does **not** ship may still
pin — that is the "reference a script someone else pushed" case.

**Re-applying an unchanged blueprint pushes nothing**, and **removing a `scripts` entry does not
delete the script** — the deliberate asymmetry with `triggers` below. The stored source is the only
copy, and an unreferenced version is inert. Remove one deliberately with `vectros scripts delete`.

**Script ownership is checked before a push.** Each version a blueprint pushes records the
blueprint's `name` as its provenance. Pushing onto a script name that already exists is refused in
two cases: when the name was pushed by a **different** blueprint (there is no flag to override this;
rename one of the scripts), and when the name exists with no blueprint provenance, such as a script
you pushed by hand. For the second case the CLI refuses unless you pass `--allow-script-adoption`,
which takes that name into the blueprint's management from then on. Either refusal pushes nothing.
The reason is that an existing trigger rule on `version: latest` would otherwise start running the
blueprint's code under that rule's own, separately authored grant. The provenance is the blueprint's
self-declared `name`, not a verified identity.

### Agents

`agents` is a map of agent name to definition (`model` required; `description`, `authority`, `system`, `tools` as
`{ name, allowWrites? }`, `limits`, `budget`). It needs `formatVersion: 2`. Each entry is the **current** definition for that
name; the platform keeps every version and never edits one. `vectros blueprint apply` and `bootstrap` write each agent with
`POST /v1/agents?upsert=true` in the blueprint's context, after the roles, scripts and triggers and before any key is minted:
a new name is created at version 1, an identical definition (compared after defaults are filled in) writes nothing, and a changed
one becomes the next version. For an existing agent the CLI first makes a plain create call to see its mark and version, then the
upsert; the two versions give the exact outcome (created, unchanged, `2 -> 3`, adopted).

```yaml
formatVersion: 2
name: intake
version: 1.0.0
description: Intake records with a triage agent.
contextId: intake
schemas: []
accessProfile:
  allowedActions: [records:r, records:c]
servicePrincipal:
  externalId: intake-principal
  displayName: Intake
agents:
  intake-triage:               # the key IS the agent's name: 1-64 letters, digits, '_' and '-'
    description: Summarises a new intake record and flags missing fields.
    model: claude-sonnet-5-5
    system: You triage intake records. Be concise.
    tools:
      - { name: records_get }
      - { name: records_create, allowWrites: true }   # a tool that changes data needs allowWrites ...
    limits: { maxToolCalls: 10, maxWrites: 2 }         # ... and limits.maxWrites of at least 1
    budget: { maxInferenceCents: 100 }
```

`validate` checks the section offline: at most 50 tools, each named once; `limits.maxWrites` of at least 1 when a tool has
`allowWrites: true`; `limits.maxToolCalls`, when you set it, not `0` while tools are listed; and the name and length rules. `authority` is
checked for its shape only (an upper-case name such as `CALLER`). The platform checks the model, the tool names and the
minimum budget when the blueprint is applied. The fields, limits and defaults are in the
[agents reference](../agents-runs/reference.md).

- **Script tools.** A tool entry can instead offer a stored script: give it a `script` (`{ name, version }`, the same reference a trigger carries, `version` a version number as a string or `latest`) and, optionally, a `description` for the model (1 to 1,024 characters, on a script tool only). The script version must declare an `inputSchema`; a tool on a script the blueprint ships must use `latest` (a blueprint rule, as for triggers, because the blueprint cannot know which version number its source lands on; the platform itself also accepts a pinned version), and `validate` refuses one whose shipped entry declares no `inputSchema`. The tool's `name` is its own and must not be a catalog tool's. Saving the agent needs a credential allowed to run the script (`scripts:x`), and a run executes it under the run's caller's own credential; the platform checks both. Needs platform 0.50.0 or later.
- **Scopes.** The applying credential needs `agents:c`, and `agents:u` and `agents:r` as well when the agent already exists, even
  if nothing changed. A refusal is reported with the scopes named. `agents` is control-plane: a blueprint cannot grant it.
- **Ownership.** Each agent is marked with the blueprint's `name`, set once. Another blueprint's agent of the same name is refused;
  an agent that exists with no mark (made by hand) is refused unless the operator passes `--allow-agent-adoption`, which marks it
  and writes the declared definition as its next version if that differs. A rename of the blueprint strands the agents it made.
- **Removal.** Dropping an entry deletes nothing. A retired agent keeps its name, so a blueprint that still declares one fails its
  apply (`409`) until the agent is restored (`vectros agents version <id> --restore --file <definition>`; a purged agent cannot be restored) or the entry is removed.
- **`blueprint-test` runs a blueprint that declares agents under names of their own**: an agent keeps its name once retired, so the test applies
  a copy whose agent names carry a per-run suffix, then retires and purges exactly the agents it created (names up to 54 characters; needs `agents:d`).

### Triggers

A blueprint may declare a top-level **`triggers`** — a map of trigger name → declaration, each
naming a schema event that invokes a versioned script under an explicitly declared grant. **A
declared trigger fires:** a record write on a schema that opts in via
`capabilities.triggersEnabled` dispatches the rule's script, which runs asynchronously in a sandbox
under the grant declared here. So a trigger's `allowedActions`/`dataScope`/`capabilities`, or the
roles its `roleIds` composes, are **live authority** — author them as narrowly as any other
credential's, and review them the same way. Applied per-context, like `roles`/`accessProfile`.

```yaml
schemas:
  - typeName: intake
    displayName: Intake
    capabilities: { triggersEnabled: true }
    fields:
      - { fieldId: status, fieldType: string, inline: true }
triggers:
  on-intake-update:
    firingSource: { schemaName: intake, event: UPDATE }
    scriptRef: { name: notify-assignee, version: latest }
    fields: [status]
    allowedActions: [records:r:intake, records:u:intake]
    dataScope: { "scope:org": ["${{ input.scope.org }}"] }
    manifest: [records.get, records.update]
```

- **`fields` — required.** The record fields projected into the script's `input.record`, and on an
  `UPDATE` firing into `input.previous`. `fields: []` is the explicit "project nothing" declaration
  (the script still receives `input.recordId`); it is required rather than defaulted so that
  projecting nothing is something you state. An entry may name only a field the schema keeps
  **inline** — `inline: true`, `filterable: true`, or a lookup field (a leg or its `sortBy` target)
  — and never one marked `sensitive`. `record` and `previous` together are capped at **224 KB**
  serialised; a firing that exceeds it is not run.
- ⚠️ **A rule that declares any `fields` must be able to read what it fires on.** Its grant must hold
  a `records:r` clause covering the firing schema's type — a grant with no read at all is rejected —
  and that clause may not carry a *literal* `data_scope` constraint (a `${{ input.userId }}` or
  `${{ input.scope.<namespace> }}` placeholder is fine, since it resolves to the firing record's own
  value).
- `firingSource.schemaName` + `firingSource.event` (`CREATE` / `UPDATE` / `DELETE`) — `schemaName`
  must name a `typeName` this same blueprint declares.
- `scriptRef.name` + `scriptRef.version` — an exact integer, or the literal `"latest"`. For a script
  this blueprint ships, `latest` is the only accepted value (see *Scripts* above).
- A grant — `roleIds` (composed from this blueprint's `roles`) **or** an inline
  `allowedActions`/`dataScope` pair, mutually exclusive, the same XOR shape `accessProfile` uses.
- `manifest` (optional) — host-object verbs (e.g. `records.get`) further narrowing what the script
  may call on top of what the grant permits. Never widens it.
- `dataScope` values may use **`${{ input.<dim> }}`**, resolving to a dimension stamped on the record
  whose change fired the trigger. Valid **only** inside a trigger's `dataScope`; `${{ self.* }}`,
  `${{ under.self.* }}` and `${{ member.* }}` are rejected there, because they resolve against the
  trigger principal's identity rather than the author's.

**Removing a trigger de-provisions it, on `vectros bootstrap` and on `vectros blueprint apply --prune`.**
Triggers are the one block an apply reconciles by *absence* as well as presence: delete an entry and
re-run `vectros bootstrap`, and its rule and the access profile behind it are deleted, so a trigger
you removed cannot keep acting under a grant that outlived it. `vectros blueprint apply` deletes
nothing unless you pass `--prune`; without it a removed trigger stays live and the command says so.
Its service principal is kept, so re-adding the same trigger reattaches to one identity. Only a
trigger this blueprint created is removed: its stored `provisionedBy` marker must equal the
blueprint's `name`, and its service principal must be the one this blueprint would have created for
a trigger of that name. Triggers created outside this blueprint, another blueprint's triggers and
triggers with no marker are never touched. Both checks read stored markers, not verified identities,
and the name comes from the blueprint file, so a file that reuses another blueprint's `name` and
omits some of its triggers removes them: keep each blueprint's `name` unique. Nothing else a
blueprint declares is deleted by removing it.

### Issuers

```yaml
issuers:
  - issuerId: my-idp
    issuer: https://idp.example.com
    jwksUri: https://idp.example.com/.well-known/jwks.json
    audience: my-vectros-app
    contextId: my-context
```

A blueprint may declare top-level **`issuers`** — trusted third-party IdP issuers to
register for BYO-IdP token exchange, each `{ issuerId, issuer, jwksUri, audience,
contextId, subClaim?, emailClaim?, userinfoUri?, restrictedToDomain?, selfSignupPolicies?, capturedClaims?, acceptedIdTokenClientIds? }`. `userinfoUri` points at the IdP's
OIDC userinfo endpoint: when a presented token misses `emailClaim` (access tokens
generally don't carry `email` under OIDC unless the IdP was specifically configured to
add it), Vectros falls back to calling `userinfoUri` with that token as the bearer
credential and reads `emailClaim` from its response — omit it to leave the fallback
disabled. Unlike `schemas`/`accessProfile`/`roles` (applied
under a per-context token), issuers are applied in the loader's **bootstrap-token
phase**, alongside app-context/service-principal creation — tenant-wide provisioning
config that needs the bootstrap credential's owner-only authority. `(issuer, audience)`
must be globally unique across every tenant (an entry without `restrictedToDomain` claims its pair when it is
verified, not when it is registered), unless the entry sets `restrictedToDomain` — a
domain already verified for your account, written as a lowercase DNS name such as `acme.com`
— which scopes the uniqueness to that domain: a token then matches only when its `hd` claim
equals it (Google Workspace emits `hd` natively; other identity providers need a claims-mapping
rule that emits a claim named exactly `hd`), so scoping an issuer whose users sign in without
one locks them out.

Each entry's **`contextId` must equal the blueprint's own `contextId`** — an issuer is a
trust anchor, so a blueprint may only attach one to the context it actually provisions.
`@vectros-ai/cli` **0.16.0+** handles a blueprint whose issuers target a context other
than the bootstrap credential's own transparently: the credential re-mints itself,
pinned to the blueprint's own context, specifically to register those issuers — no extra
authoring step is needed on your part. The loader always registers (idempotent by
`issuerId`) and then reconciles: editing an already-registered issuer's
`subClaim`, `emailClaim`, `userinfoUri`, `restrictedToDomain`, `selfSignupPolicies` or `capturedClaims` and
re-running bootstrap now converges on the declared values. A `selfSignupPolicies` entry may name `additionalRoleIds`
(up to 9 more roles, none repeating `roleId`; platform 0.50.0 or later); a re-apply replaces the whole list, each
entry's `additionalRoleIds` included, so declare every additional role in the blueprint. Leaving `restrictedToDomain` out of a re-apply
keeps an existing scope; it does not clear it. **Clearing a domain scope is refused by the platform** (`400`)
unless the registration already holds the unrestricted `(issuer, audience)` pair, which a registration created
scoped to a domain does not. To get an unrestricted issuer, delete the scoped registration (`vectros issuers delete`),
declare or register a new one without `restrictedToDomain`, and verify it (`vectros issuers verify`). A context holds
one active issuer, and the delete is refused once any user has been created or matched through the old issuer; in
that case register the new issuer under a different app context. Deleting an app context retires the issuerId of an issuer whose users signed in through it. A later apply that registers it with a different issuer, jwksUri, audience or subClaim stops at the issuer step. The app context stays. ⚠️ The **trust-anchor** fields
(`issuer`, `jwksUri`, `audience`, `contextId`) stay immutable, and editing one on an
already-registered issuer now **fails the whole apply** with the platform's `400` rather
than being silently ignored as it once was. Issuer `status` is not blueprint-authorable
at all — suspend or reactivate an issuer through the API. ⚠️ **From API/SDK `0.45.0`, an issuer a
blueprint registers without `restrictedToDomain` starts `pending_verification`** and accepts no token until its registrant proves
control of the identity provider with the API's `verifyIssuer` call
([identity-access/how-to.md](../identity-access/how-to.md#register-a-trusted-external-idp-issuer-and-exchange-its-token));
an issuer that already existed is unaffected. An entry that sets `restrictedToDomain` is active at once:
the domain you verified for your account is what it proves, and it only ever matches that domain's
users. Verifying needs a real login from the IdP after a human
configures a claim rule there, so `vectros bootstrap` (or `vectros blueprint apply`) cannot finish it: it still completes and exits `0`,
says `pending verification` beside the issuer, and ends its output, on stderr, with the challenge and the exact
`vectros issuers verify` command (`@vectros-ai/cli` 0.23.0 and later). `--require-verified-issuers`
turns a pending issuer into exit `4` (a one-line notice follows the challenge) for a pipeline that must not go green over it, and an issuer whose
challenge expired while pending is reported as unverifiable, with the delete command; nothing is deleted for
you. Adding
`restrictedToDomain` to an issuer that is still awaiting verification is refused by the platform (`400`), so
the apply fails: verify the issuer first, or delete it and apply again. (Registering, reading, updating, or
deleting an issuer directly against the API, outside a blueprint, stays confined to the
calling credential's own context — see
[identity-access/reference.md](../identity-access/reference.md#trusted-issuers--v1authissuers)
for the full field grammar, every error code, and the token-exchange contract those issuers
serve; [identity-access/explanation.md](../identity-access/explanation.md#trusted-issuer-federation-byo-idp-token-exchange)
for the concept and the flow end to end.)

**`acceptedIdTokenClientIds`** lists other client ids an ID token from this identity provider may be addressed to, for an app's in-app account deletion (`/v1/me/erasure`) when the registration's `audience` is an API rather than the app (Auth0, for example): up to 10, each non-blank, at most 255 characters, each once. Leaving it out of a later apply keeps the stored list; an empty list keeps only `audience`. Needs platform 0.50.0 or later.

**`capturedClaims`** names additional OIDC claim names — beyond `emailClaim`, which keeps its own
field — to read from that issuer's tokens on every successful exchange and store as your tenant's
golden identity-provider-asserted copy for the signed-in user. Not a fixed set: name whatever your
provider actually asserts. Each is read from the verified token first, falling back to `userinfoUri`
(when configured) only for names still missing. Omit to capture nothing beyond email — unchanged
behaviour for every existing blueprint. At most 20 entries of at most 64 characters each; a
duplicate is rejected rather than deduplicated.

The top-level **`identityProjectionClaims`** is the other half: it declares which of those captured
names are projected, read-only, onto access profiles in this blueprint's app context, where they
surface as `identityProjection` on the profile. Capture and projection are separate opt-ins —
capturing stores a claim against the user, projecting exposes it on a profile — and declaring a
name no issuer captures simply never fills. A profile's projection fills **once**, the first time a
sign-in for that principal can supply a value (for an invited member, not until they accept and sign
in), and never updates again; editing the list therefore affects only profiles not yet filled.

⚠️ **It takes effect when the app context is CREATED.** Re-applying a blueprint against a context
that already exists does not change the declaration in either direction — a declared list is not
applied, and an empty list does not disable. Change an existing context's declaration through the
platform API. Like `issuers`, it applies in the **bootstrap-token phase**, because setting it needs
the platform provisioning capability only that phase's credential carries.

### Namespaces

```yaml
namespaces:
  - namespace: team
    entityBacked: true
    specificityRank: 10
```

A blueprint may also declare top-level **`namespaces`** — entity-namespace
registrations, each `{ namespace, specificityRank, entityBacked?, tenantWide?, membershipRecordType?,
membershipTargetField?, membershipLevelField?, membershipLevels? }`. Like `issuers`,
these are applied in the loader's **bootstrap-token phase**. **By default, a declared
namespace is owned by the blueprint's own `contextId`** — it applies with a context-bound
credential, and the platform's namespace registration confines a context-bound caller to
its own context. An entry may add `tenantWide: true` to request a tenant-wide
registration instead (visible to every app context). That is a deliberate, narrow opt-in
with two conditions: the applying credential must hold a platform capability granted only
to the account owner, and the CLI must be run with `--allow-tenant-wide-namespaces`;
without the flag the CLI refuses the blueprint (exit `2`) and a tenant-wide entry that
collides with an existing registration fails the apply rather than adopting it. A registration records no owner, so a
re-apply of the blueprint that registered it fails the same way, unless the run names the namespace with
`--adopt-tenant-wide-namespace <namespace>`: the registration is then used if it is tenant-wide and every
setting the entry declares matches it, and the run stops otherwise. A tenant-wide entry that declares
membership is registered with the blueprint's own context as the context its membership records live in.

- `namespace` — 2-32 chars, a lowercase letter first, then lowercase letters/digits/
  `_`/`-`. A closed set of words is rejected as reserved (`user`, `record`, `document`,
  `entity`, `self`, `tenant`, `context`, `scope`, `versions`, `lookup`) — `org`/`client`
  are NOT in that set: they're reserved namespace names, not built-ins, registered the
  same way as any other (see
  [identity-access/reference.md](../identity-access/reference.md#namespaces--v1namespaces)
  for the platform endpoint this mirrors). Signup does not register them: an account has `org` and
  `client` only once it registers them (for example by declaring them here). Accounts created before
  that change may still hold the rows signup made for them, at `specificityRank` 1000 (`org`) and 2000
  (`client`); a rank must be unique across the account, so a registration of yours needs a different
  rank wherever those rows exist. A context-owned registration shadows a tenant-wide one of the same
  name for this context's own callers.
- `specificityRank` — an integer `0..1_000_000`, this namespace's position in the
  account's specificity order. Must be unique among this blueprint's own namespaces —
  a collision with the rest of the account's registrations (including `org`=1000 and
  `client`=2000) surfaces at apply time.
- `entityBacked` (optional) — when `true`, every value in this namespace must resolve
  to an existing identity entity; when `false`/omitted, values are free-form strings
  validated by grammar only.
- `membershipRecordType` + `membershipTargetField` — optional, declared together (or
  both omitted): which record type + field hold grants of this namespace's values.
  `membershipRecordType` must name a `typeName` **this same blueprint** declares under
  `schemas:`. Declaring this grants nobody anything on its own; a role opts in
  explicitly with `${{ member.scope.<namespace> }}` in its `dataScope`.
- `membershipLevelField` + `membershipLevels` — optional, declared together: the field
  naming a grant's level, and the complete set of level labels allowed.

Registration is **not idempotent server-side**: a re-apply whose declaration matches
what's already registered converges silently, but one that disagrees with the live
registration fails the apply rather than silently overwriting it.

### Inputs (install-time variables)

A blueprint may declare an `inputs:` block and reference values with
`${{ inputs.<name> }}` (plus the built-ins `${{ vectros.context }}` /
`${{ vectros.suffix }}`). Supply values at validate/plan/apply time with `--set`
or `--values`. Inputs apply to **file** blueprints only.

### Splitting a blueprint across files and stacks

A real app's blueprint grows to dozens of schemas and roles. You can split it into a **root file**
and **part files**, and group the parts into **stacks** that can be applied one at a time.

**Parts.** The root file lists its parts under `include:`. Each entry is a path relative to the root
file's directory, and may use `*` to match within one path segment (`schemas/*.part.yaml`); each
pattern's matches are taken in lexical order, and the patterns in the order written. A part file is
named `*.part.yaml`, `*.part.yml` or `*.part.json`, so no tool mistakes it for a whole blueprint, and
it may declare only these sections: `schemas`, `roles`, `roleAssumable`, `fragments`, `identities`,
`issuers`, `namespaces`, `scripts`, `triggers`, `agents` and `seed`. The blueprint's identity and its
own grant stay in the root file: `name`, `version`, `description`, `contextId`, `contextName`,
`companyName`, `servicePrincipal`, `accessProfile`, `identityProjectionClaims`, `formatVersion`,
`inputs`, `include` and `stacks` are refused in a part.

**Nothing is overridden.** The parts are composed into one blueprint: lists are concatenated (the
root's entries first, then each part's), maps are combined, and a name declared twice (a schema
`typeName`, a role id, a trigger name, a fragment, and so on) is refused with both files and lines.
So a role, schema or trigger is always written in exactly one file, and reading that file is reading
all of it. A field that names a resource or refers to one (a schema `typeName`, an `issuerId`, a
trigger's `schemaName`, `scriptRef.name` or `roleIds`, a seed's `typeName` and `externalId`, and the
like) must be written out, not taken from `${{ inputs.* }}`, because duplicates and stacks are decided
by those names before inputs are resolved.

**Confinement.** A part must live inside the root file's directory: an absolute path, a path that
climbs out with `..`, a URL, and a symbolic link that resolves outside the directory are all refused.
The directory is the bundle you review.

**Errors name the file.** Every command reads the root file and composes the whole blueprint first.
A structural or input problem is reported with the file and line it comes from, and `validate` and
`plan` add the file and line to a lint finding or gate refusal that names a resource:

```text
  ✖ Malformed blueprint:
  • catalog/products.part.yaml:11: schemas[4].fields[1].fieldType: Invalid input: expected string, received undefined
```

`inputs:` is declared in the root and resolved after composition, so `${{ inputs.<name> }}` works in
any part. `vectros blueprint flatten <root>` prints the composed blueprint as one document (inputs
left unresolved), which validates and applies exactly as the split files do.

**Stacks.** The root file may group its parts into named `stacks:`. Every included file belongs to
exactly one stack, and `root` is reserved for what the root file itself declares (including the
access profile). A stack is a deploy unit inside one blueprint, not a separate blueprint: it shares
the blueprint's `name`, service principal and access profile, and moving a part from one stack to
another changes nothing about who owns what it declares. A fragment must be in the same stack as every
role that uses it, and a `roleAssumable` entry in the same stack as its role: both are written as part
of the role, so declaring them elsewhere would make their own stack's apply change nothing.

```yaml
# my-app.blueprint.yaml (the root, abridged)
name: my-app
version: "1.0.0"
description: An app split across part files.
contextId: my-app
servicePrincipal: { externalId: my-app-loader, displayName: My App loader }
accessProfile:
  allowedActions: [records:r:product, records:r:order]
include:
  - identity/*.part.yaml
  - catalog/*.part.yaml
  - orders/*.part.yaml
stacks:
  identity: [identity/*.part.yaml]
  catalog: [catalog/*.part.yaml]
  orders: [orders/*.part.yaml]
```

`vectros blueprint apply <root> --stack orders --tenant test` validates and gates the **whole**
blueprint, then writes only the orders stack's resources. The service principal, the context and the
declared identities are ensured on every apply; the access profile is written only when `root` is
selected (or by an apply without `--stack`), so a stack apply without `root` does not ask to confirm
an existing service principal. An apply that includes `root` rewrites the access profile and asks, as
a whole apply does: in a pipeline pass `--confirm-existing-principal`, or it exits 3. Exit 3 is also an apply with
`--yes` that publishes more than is public now without `--confirm-public-fields` (see [cli](cli.md)): before its
confirmation, `apply` lists per schema the fields that become public, stop being public or stay public, compared with
the live schemas. Repeat `--stack` to apply several. What a selected stack needs from
another stack must already be live, and is checked before anything is written; the apply is refused,
naming the stack to apply first. That covers a trigger's schema, script and roles; a schema's
reference-field targets, including a target surface that is an entity namespace; the roles a role's
`assignableRoles` or an issuer's self-signup policy name; every namespace a selected role, trigger,
schema or seed scopes by, and the namespace of every declared identity; with `--seed`, each seed's
schema; and, with `root`, the access profile's roles and the namespaces its `dataScope` and
`identityOverrides` name. A namespace counts as live only when it is registered where the blueprint
declares it (this context, or tenant-wide for a `tenantWide` one). A role's actions naming another
stack's schema (`records:r:<type>`) are not checked, as in a whole apply. This is a check of the
references the blueprint names, not a guarantee that an apply cannot fail part-way: the platform can
still refuse a write for a reason no name shows. It also confirms that a resource exists, not that it
matches its file: apply the stack that declares it after you change it.

Apply a split blueprint whole the first time (no `--stack`), so every stack and the access profile
exist; after that, apply one stack at a time as its files change. To build one up stack by stack
instead, apply them in dependency order and include `root` last (in the sketch above: `identity`, `catalog`,
`orders`, then `root`). `vectros blueprint plan <root> --stack <name>` previews the same, listing what
the stack assumes is already applied, and names any role the access profile is composed from that the
stack rewrites (that changes the service principal's grant).

A stack apply never deletes anything, and `--stack` cannot be combined with `--prune`: a trigger
removed from its file no longer belongs to any stack, so removing it is done by an apply of the whole
blueprint with `--prune`. Stacks limit what an apply writes, not who may apply it: the credential that
applies one stack could apply them all.

### Bundled blueprints

Four blueprints ship with the library:

| Name | What it provisions |
|---|---|
| `task-management` | Structured task tracking, shareable across sessions, agents, and users. The authoring exemplar. |
| `agentic-sdlc` | A whole-SDLC system of record for an AI development team — decisions, designs, references, runbooks, and post-mortems as documents, plus controls, conventions, gotchas, and a glossary as records, cross-linked and recalled by meaning. |
| `second-brain` | A personal knowledge base — capture notes, ideas, and links, then ask them anything. |
| `clinical-intake` | A clinical intake data model (synthetic/illustrative). |

List them with `vectros blueprint list`; apply one with
`vectros bootstrap --blueprint <name>` (which also mints a key for your MCP client) or
`vectros blueprint apply <name> --tenant test|live` (which mints none).

## Notes & limits — glue caveats

- **`bootstrap` needs a sign-in.** Applying a blueprint with `bootstrap` uses your stored
  `vectros login` session (run it once; later runs reuse it) or, with none, a bridge token
  from the developer portal.
- **`identities:` blocks are resolved at apply time.** Each entry declares a `kind`
  (`user`, or an entity namespace — `org`, `client`, or one you registered) plus an
  `externalId`; the loader resolves it through the ordinary identity API — `createUser`
  for `kind: user`, `createEntity({ namespace: kind, ... })` for anything else — using the
  bridge token's own authority, and the resolved id becomes available to the rest of the
  blueprint as `${{ identities.<name> }}`. The CLI **fails closed** on a blueprint that
  declares an entity namespace that hasn't been registered, rather than applying it
  partially.
- **`reference` fields enforce the target at write.** A blueprint can declare a
  typed reference between record types; by default the platform requires the
  referenced record to exist when the referencing record is written — so if a seed
  record references another, seed the target **first**. (To opt out for an
  order-independent bulk load, set `capabilities.validateReferences: false` on the
  referencing schema.) There is no reverse-reference
  query on this surface; to ask "which records reference X", declare the reference
  field as an equality lookup.
- **Most control-plane scopes are rejected.** A blueprint cannot request scopes on keys,
  app contexts, users, billing, admin, `agents`, the namespace registry, or most of `profiles`
  and `scripts` — the CLI scope gate rejects them, mints nothing, and exits non-zero.
  The gate's allowlist does include `entities` (creating and managing identity entities,
  including `org`/`client`, ownership-gated like records) and the narrow exceptions
  listed in [cli.md](cli.md#the-scope-gate-data-plane-allowlist). Declaring principals
  via `identities:` (above) is a separate mechanism — the loader resolves them itself at
  apply time, which is what lets seed records reference them, rather than minting an
  `entities` scope for the bootstrapped key.

## Where to go next

- [cli.md](cli.md) — `init`, `validate`, `plan`, `bootstrap`, and
  `blueprint-test` operate on these files.
- [mcp.md](mcp.md) — the scoped key a blueprint mints is what an MCP agent runs
  on.
- [sdk.md](sdk.md) — the operations a blueprint's schemas and scopes govern.
- The blueprint walkthroughs — narrated, end-to-end builds on top of this format.
