From da0d0aba5b5b09b9cb0af0a56754762d4079b897 Mon Sep 17 00:00:00 2001
From: yyyyaaa
Date: Sat, 28 Nov 2026 21:05:44 +0700
Subject: [PATCH 01/10] feat(node-type-registry): sync the registry from
constructive-db, and keep it synced
constructive-db owns the registry; this package publishes a copy of its src/.
- scripts/sync-registry.mjs (pnpm sync:registry ) copies src/ from a
constructive-db checkout, except the files each repository keeps for
itself. With --check it lists each file that differs and exits 1, so the
integration tests can check their pinned pair.
- The copy now has what the backend has: ProcessCustom, the auth:byo and
b2b:saas presets, the module dependency model (findMissingModuleDependencies,
withRequiredModules), the content presets, and the schema fixes of
constructive-db#4504 (relation and table targets, required policy data,
a nonempty join).
- blocks-schema is a dependency: the content preset types use its document type.
- The README example is a valid blueprint, and the module-types tests follow
the registry and check presets with its dependency model.
---
packages/node-type-registry/README.md | 19 +-
.../__tests__/blueprint-schema.test.ts | 55 ++
.../__tests__/module-types.test.ts | 59 +-
.../__tests__/sync-registry.test.ts | 61 ++
packages/node-type-registry/package.json | 8 +-
.../scripts/sync-registry.mjs | 97 ++++
.../src/authz/authz-database-claim.ts | 2 +-
.../src/authz/authz-entity-membership.ts | 2 +-
.../authz/authz-related-entity-membership.ts | 2 +-
.../src/authz/authz-related-member-owner.ts | 2 +-
.../src/authz/authz-value-exists.ts | 1 +
.../src/authz/authz-value-match.ts | 1 +
.../src/blueprint-schema.generated.ts | 3 +-
.../src/blueprint-types.generated.ts | 150 +++--
.../src/codegen/generate-types.ts | 214 ++++++-
.../src/content-presets/agent.ts | 47 ++
.../src/content-presets/approvals.ts | 27 +
.../src/content-presets/index.ts | 55 +-
.../src/content-presets/layouts.ts | 91 +++
.../src/content-presets/legal.ts | 34 ++
.../src/content-presets/mantra-standalone.ts | 28 +
.../src/content-presets/mantra.ts | 72 +++
.../src/content-presets/principals.ts | 87 +++
.../src/content-presets/robots.ts | 72 +++
.../src/content-presets/sso.ts | 32 ++
.../src/content-presets/types.ts | 226 +++++++-
.../src/data/check-owned-relation.ts | 5 +
.../src/data/data-capabilities.ts | 15 +-
.../src/data/data-inherit-from-parent.ts | 2 +-
.../node-type-registry/src/job/trigger.ts | 5 +
.../src/limit/enforce-feature.ts | 19 +-
.../src/limit/track-usage.ts | 6 +
.../src/module-presets/auth-byo.ts | 53 ++
.../src/module-presets/b2b-saas.ts | 63 +++
.../src/module-presets/b2b-storage.ts | 11 +-
.../src/module-presets/dependencies.ts | 524 ++++++++++++++++++
.../src/module-presets/index.ts | 52 +-
.../src/module-presets/types.ts | 33 +-
.../src/module-types/index.ts | 13 +-
.../node-type-registry/src/process/chunks.ts | 9 +
.../node-type-registry/src/process/custom.ts | 105 ++++
.../src/process/extraction.ts | 53 +-
.../src/process/file-embedding.ts | 45 +-
.../src/process/image-embedding.ts | 72 +--
.../src/process/image-versions.ts | 68 ++-
.../node-type-registry/src/process/index.ts | 1 +
.../src/relation/relation-belongs-to.ts | 8 +
pnpm-lock.yaml | 21 +
48 files changed, 2385 insertions(+), 245 deletions(-)
create mode 100644 packages/node-type-registry/__tests__/sync-registry.test.ts
create mode 100644 packages/node-type-registry/scripts/sync-registry.mjs
create mode 100644 packages/node-type-registry/src/content-presets/agent.ts
create mode 100644 packages/node-type-registry/src/content-presets/approvals.ts
create mode 100644 packages/node-type-registry/src/content-presets/layouts.ts
create mode 100644 packages/node-type-registry/src/content-presets/legal.ts
create mode 100644 packages/node-type-registry/src/content-presets/mantra-standalone.ts
create mode 100644 packages/node-type-registry/src/content-presets/mantra.ts
create mode 100644 packages/node-type-registry/src/content-presets/principals.ts
create mode 100644 packages/node-type-registry/src/content-presets/robots.ts
create mode 100644 packages/node-type-registry/src/content-presets/sso.ts
create mode 100644 packages/node-type-registry/src/module-presets/auth-byo.ts
create mode 100644 packages/node-type-registry/src/module-presets/b2b-saas.ts
create mode 100644 packages/node-type-registry/src/module-presets/dependencies.ts
create mode 100644 packages/node-type-registry/src/process/custom.ts
diff --git a/packages/node-type-registry/README.md b/packages/node-type-registry/README.md
index 32631f6201..b4b47ab12c 100644
--- a/packages/node-type-registry/README.md
+++ b/packages/node-type-registry/README.md
@@ -12,7 +12,7 @@
-Node type definitions for the Constructive blueprint system. Single source of truth for all Authz*, Data*, Relation*, View*, and Table* node types.
+Node type definitions for the Constructive blueprint system: every Authz*, Data*, Relation*, View* and Table* node type, with the module presets and content presets.
## Usage
@@ -23,7 +23,7 @@ import { allNodeTypes, AuthzDirectOwner, DataId } from 'node-type-registry';
console.log(AuthzDirectOwner.parameter_schema);
// Get all node types as a flat array
-console.log(allNodeTypes.length); // 52
+console.log(allNodeTypes.length);
```
## Blueprint Types (generated)
@@ -50,10 +50,10 @@ const definition: BlueprintDefinition = {
{ $type: 'DataDirectOwner', data: { include_id: false } },
],
fields: [
- { name: 'title', type: 'text', is_not_null: true },
- { name: 'description', type: 'text' },
+ { name: 'title', type: { name: 'text' }, is_not_null: true },
+ { name: 'description', type: { name: 'text' } },
],
- policies: [{ $type: 'AuthzDirectOwner' }],
+ policies: [{ $type: 'AuthzDirectOwner', data: { entity_field: 'owner_id' } }],
},
],
relations: [
@@ -73,16 +73,15 @@ const definition: BlueprintDefinition = {
};
```
-### Regenerating types
+### Where the source lives
-When node type definitions are added or modified, regenerate with:
+`src/` is a copy of the registry that the backend deploys, generated files included. Change a node type or a preset there, then copy it here from a checkout of the backend's repository:
```bash
-cd graphql/node-type-registry && pnpm generate:types
+pnpm sync:registry # copies src/
+pnpm sync:registry --check # lists the files that differ, and exits 1 if one does
```
-This produces `src/blueprint-types.generated.ts` from the TS node type source of truth.
-
## Authz nodes: plain words and closed parameters
Every `Authz*` node carries plain words, so a person or an agent can tell who a policy lets in without reading SQL: `summary` (one sentence), and `use_when`, `avoid_when` and `risks`.
diff --git a/packages/node-type-registry/__tests__/blueprint-schema.test.ts b/packages/node-type-registry/__tests__/blueprint-schema.test.ts
index e9432c7cea..69193c220a 100644
--- a/packages/node-type-registry/__tests__/blueprint-schema.test.ts
+++ b/packages/node-type-registry/__tests__/blueprint-schema.test.ts
@@ -44,6 +44,61 @@ describe('the blueprint definition JSON Schema', () => {
expect(errors(table({ policies: [{ ...TEAM, $type: 'AuthzNoSuchNode' }] }))).toContain('/tables/0/policies/0/$type must be equal to one of the allowed values');
});
+ test('only policies with required caller inputs need data', () => {
+ expect(errors(table({ policies: [{ $type: 'AuthzEntityMembership' }] }))).toContain("/tables/0/policies/0 must have required property 'data'");
+ expect(errors(table({ policies: [{ $type: 'AuthzAllowAll' }] }))).toEqual([]);
+ expect(errors(table({ policies: [{ $type: 'AuthzAllowAll', privileges: ['update'], with_check: { $type: 'AuthzEntityMembership' } }] }))).toContain(
+ "/tables/0/policies/0/with_check must have required property 'data'"
+ );
+ });
+
+ test('each relation end names a table or a module table, not both', () => {
+ const module = { type: 'agent', scope: 'org', table: 'message' };
+ const relates = (ends: Record) => ({
+ ...table(),
+ relations: [{ $type: 'RelationBelongsTo', delete_action: 'r', ...ends }]
+ });
+ expect(errors(relates({}))).not.toEqual([]);
+ expect(errors(relates({ source_table: 'projects' }))).not.toEqual([]);
+ expect(errors(relates({ source_table: 'projects', target_module: module }))).toEqual([]);
+ expect(errors(relates({ source_table: 'projects', target_module: module, delete_action: undefined }))).toContain(
+ "/relations/0 must have required property 'delete_action'"
+ );
+ expect(errors(relates({ source_table: 'projects', target_schema: 'app_public', target_module: module }))).not.toEqual([]);
+ expect(errors(relates({ source_table: 'projects', target_table: 'messages', target_module: module }))).not.toEqual([]);
+ });
+
+ test('each table has one target and nodes that require data cannot use shorthand', () => {
+ const module = { type: 'agent', scope: 'org', table: 'message' };
+ expect(errors({ tables: [{}] })).not.toEqual([]);
+ expect(errors({ tables: [{ module }] })).toEqual([]);
+ expect(errors(table({ module }))).not.toEqual([]);
+ const install = { type: 'agent', scope: 'org' };
+ const provisions = { message: { policies: [TEAM] } };
+ expect(errors({ tables: [{ module: install, provisions }] })).toEqual([]);
+ expect(errors({ tables: [{ module: install }] })).not.toEqual([]);
+ expect(errors({ tables: [{ module, provisions }] })).not.toEqual([]);
+ expect(errors({ tables: [{ module: install, provisions, policies: [TEAM] }] })).not.toEqual([]);
+ expect(errors(table({ nodes: ['DataId'] }))).toEqual([]);
+ expect(errors(table({ nodes: ['AuthzColumnSecurity'] }))).not.toEqual([]);
+ });
+
+ test.each(['AuthzValueExists', 'AuthzValueMatch'])('%s requires a nonempty join', ($type) => {
+ expect(errors(table({ policies: [{ $type, data: { ref_schema: 'app_public', ref_table: 'teams', join: [] } }] }))).toContain(
+ '/tables/0/policies/0/data/join must NOT have fewer than 1 items'
+ );
+ });
+
+ test('junction policies use the same validation as table policies', () => {
+ const junction = (policy: Record) => ({
+ ...table(),
+ relations: [{ $type: 'RelationManyToMany', source_table: 'projects', target_table: 'labels', policies: [policy] }]
+ });
+ expect(errors(junction(TEAM))).toEqual([]);
+ expect(errors(junction({ $type: 'AuthzNoSuchNode' }))).not.toEqual([]);
+ expect(errors(junction({ $type: 'AuthzEntityMembership' }))).toContain("/relations/0/policies/0 must have required property 'data'");
+ });
+
test('a with_check override is for update only', () => {
const check = { $type: 'AuthzValueAllowed', data: { column: 'role', allowed: ['member'], operator: 'in' } };
expect(errors(table({ policies: [{ ...TEAM, privileges: ['update'], with_check: check }] }))).toEqual([]);
diff --git a/packages/node-type-registry/__tests__/module-types.test.ts b/packages/node-type-registry/__tests__/module-types.test.ts
index e4460a8b5b..f228e1cc44 100644
--- a/packages/node-type-registry/__tests__/module-types.test.ts
+++ b/packages/node-type-registry/__tests__/module-types.test.ts
@@ -1,5 +1,6 @@
import {
allModulePresets,
+ findMissingModuleDependencies,
type ModuleEntry,
type ModulePreset,
publicModulePresets,
@@ -11,26 +12,6 @@ import {
publicModuleTypes
} from '../src/module-types';
-function moduleEntries(
- preset: (typeof allModulePresets)[number]
-): Array<[string, Record]> {
- return preset.modules.map((entry) => {
- if (typeof entry === 'string') return [entry, {}];
- return entry;
- });
-}
-
-function hasModule(
- entries: Array<[string, Record]>,
- name: string,
- scope?: string
-): boolean {
- return entries.some(
- ([entryName, options]) =>
- entryName === name && (scope === undefined || options.scope === scope)
- );
-}
-
describe('module type registry', () => {
test('matches the complete module registry', () => {
expect(allModuleTypes.map(({ name }) => name)).toEqual([
@@ -48,6 +29,7 @@ describe('module type registry', () => {
'database_settings_module',
'db_preset_module',
'db_usage_module',
+ 'refusal_log_module',
'devices_module',
'domain_module',
'email_sender_module',
@@ -83,6 +65,7 @@ describe('module type registry', () => {
'phone_numbers_module',
'plans_module',
'principal_auth_module',
+ 'principals_module',
'profiles_module',
'rate_limit_meters_module',
'rate_limits_module',
@@ -122,6 +105,7 @@ describe('module type registry', () => {
'content_preset_module',
'database_settings_module',
'db_preset_module',
+ 'refusal_log_module',
'domain_module',
'infra_config_module',
'infra_module',
@@ -166,7 +150,9 @@ describe('module type registry', () => {
'minimal',
'auth:hardened',
'b2b:storage',
- 'full'
+ 'full',
+ 'b2b:saas',
+ 'auth:byo'
]);
});
@@ -235,36 +221,9 @@ describe('module type registry', () => {
expect(full?.modules).toContainEqual(['function_module', { scope: 'app' }]);
});
- test('all presets satisfy the provisioning dependency checks', () => {
+ test('every preset installs the modules its modules depend on', () => {
for (const preset of allModulePresets) {
- const entries = moduleEntries(preset);
- expect(hasModule(entries, 'users_module')).toBe(true);
- expect(hasModule(entries, 'sessions_module')).toBe(true);
- expect(hasModule(entries, 'rls_module')).toBe(true);
-
- if (hasModule(entries, 'session_secrets_module')) {
- expect(hasModule(entries, 'sessions_module')).toBe(true);
- }
- if (hasModule(entries, 'user_auth_module')) {
- expect(hasModule(entries, 'sessions_module')).toBe(true);
- }
- if (hasModule(entries, 'identity_providers_module')) {
- expect(hasModule(entries, 'connected_accounts_module')).toBe(true);
- expect(hasModule(entries, 'internal_secrets_module', 'app')).toBe(true);
- }
- if (hasModule(entries, 'webauthn_auth_module')) {
- expect(hasModule(entries, 'user_auth_module')).toBe(true);
- expect(hasModule(entries, 'session_secrets_module')).toBe(true);
- expect(hasModule(entries, 'webauthn_credentials_module')).toBe(true);
- }
- if (hasModule(entries, 'hierarchy_module', 'org')) {
- expect(hasModule(entries, 'memberships_module', 'org')).toBe(true);
- }
- for (const scope of ['app', 'org']) {
- if (hasModule(entries, 'invites_module', scope)) {
- expect(hasModule(entries, 'memberships_module', scope)).toBe(true);
- }
- }
+ expect({ preset: preset.name, missing: findMissingModuleDependencies(preset.modules) }).toEqual({ preset: preset.name, missing: [] });
}
});
});
diff --git a/packages/node-type-registry/__tests__/sync-registry.test.ts b/packages/node-type-registry/__tests__/sync-registry.test.ts
new file mode 100644
index 0000000000..55d88e6f2c
--- /dev/null
+++ b/packages/node-type-registry/__tests__/sync-registry.test.ts
@@ -0,0 +1,61 @@
+import { execFileSync, spawnSync } from 'child_process';
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+
+const SCRIPT = join(__dirname, '..', 'scripts', 'sync-registry.mjs');
+
+/** A git repository at `root` with `files` committed. */
+function repo(root: string, files: Record): void {
+ for (const [file, text] of Object.entries(files)) {
+ mkdirSync(dirname(join(root, file)), { recursive: true });
+ writeFileSync(join(root, file), text);
+ }
+ const git = (...args: string[]) => execFileSync('git', ['-c', 'user.email=test@example.com', '-c', 'user.name=test', ...args], { cwd: root, stdio: 'ignore' });
+ git('init', '-q');
+ git('add', '-A');
+ git('commit', '-q', '-m', 'files');
+}
+
+describe('sync-registry', () => {
+ let dir: string;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'sync-registry-'));
+ });
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('removes nothing and stops when a file under src/ that git does not track would be removed', () => {
+ const upstream = join(dir, 'db');
+ repo(upstream, { 'packages/node-type-registry/src/index.ts': 'export {};\n' });
+ const here = join(dir, 'here');
+ repo(here, { 'src/index.ts': 'export {};\n', 'src/gone.ts': 'export {};\n' });
+ mkdirSync(join(here, 'scripts'));
+ copyFileSync(SCRIPT, join(here, 'scripts', 'sync-registry.mjs'));
+ writeFileSync(join(here, 'src', 'local.ts'), '// a file of the person, not committed\n');
+
+ const run = spawnSync('node', [join(here, 'scripts', 'sync-registry.mjs'), upstream], { encoding: 'utf8' });
+
+ expect(run.status).not.toBe(0);
+ expect(run.stderr).toContain('src/local.ts');
+ expect(existsSync(join(here, 'src', 'local.ts'))).toBe(true);
+ expect(existsSync(join(here, 'src', 'gone.ts'))).toBe(true);
+ });
+
+ it('replaces nothing and stops when upstream has a file that is here but untracked, with other text', () => {
+ const upstream = join(dir, 'db');
+ repo(upstream, { 'packages/node-type-registry/src/index.ts': 'export {};\n', 'packages/node-type-registry/src/new.ts': 'export const a = 1;\n' });
+ const here = join(dir, 'here');
+ repo(here, { 'src/index.ts': 'export {};\n' });
+ mkdirSync(join(here, 'scripts'));
+ copyFileSync(SCRIPT, join(here, 'scripts', 'sync-registry.mjs'));
+ writeFileSync(join(here, 'src', 'new.ts'), '// the person\'s own work\n');
+
+ const run = spawnSync('node', [join(here, 'scripts', 'sync-registry.mjs'), upstream], { encoding: 'utf8' });
+
+ expect(run.status).not.toBe(0);
+ expect(run.stderr).toContain('src/new.ts');
+ expect(readFileSync(join(here, 'src', 'new.ts'), 'utf8')).toBe("// the person's own work\n");
+ });
+});
diff --git a/packages/node-type-registry/package.json b/packages/node-type-registry/package.json
index f4a3405f3e..0749c167c0 100644
--- a/packages/node-type-registry/package.json
+++ b/packages/node-type-registry/package.json
@@ -1,7 +1,7 @@
{
"name": "node-type-registry",
"version": "1.24.1",
- "description": "Node type definitions for the Constructive blueprint system. Single source of truth for all Authz*, Data*, Relation*, and View* node types.",
+ "description": "Node type definitions for the Constructive blueprint system: every Authz*, Data*, Relation* and View* node type, with the module presets and content presets.",
"author": "Constructive ",
"main": "index.js",
"module": "esm/index.js",
@@ -29,7 +29,11 @@
"test:watch": "jest --watch",
"generate:types": "ts-node src/codegen/generate-types.ts",
"generate:json": "ts-node src/codegen/generate-json.ts --outdir dist",
- "generate:reference": "ts-node src/codegen/generate-reference.ts"
+ "generate:reference": "ts-node src/codegen/generate-reference.ts",
+ "sync:registry": "node scripts/sync-registry.mjs"
+ },
+ "dependencies": {
+ "blocks-schema": "^0.5.4"
},
"devDependencies": {
"@babel/generator": "^7.29.0",
diff --git a/packages/node-type-registry/scripts/sync-registry.mjs b/packages/node-type-registry/scripts/sync-registry.mjs
new file mode 100644
index 0000000000..0a6d94105b
--- /dev/null
+++ b/packages/node-type-registry/scripts/sync-registry.mjs
@@ -0,0 +1,97 @@
+#!/usr/bin/env node
+// constructive-db owns the registry source; this package publishes a copy of it. This script copies src/ from a
+// constructive-db checkout. With --check it changes nothing, lists each file that differs, and exits 1 if one does.
+//
+// node scripts/sync-registry.mjs [--check]
+
+import { execFileSync } from 'node:child_process';
+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// The files under src/ that only one repository has: constructive-db's seed SQL generator and audit, and this
+// package's generators of its JSON files and reference pages. Each repository keeps its own tests.
+const OWN = {
+ 'constructive-db': ['src/audit/', 'src/generate.ts'],
+ constructive: ['src/codegen/generate-json.ts', 'src/codegen/generate-reference.ts']
+};
+
+const args = process.argv.slice(2);
+const check = args.includes('--check');
+const [checkout, ...extra] = args.filter((arg) => arg !== '--check');
+if (!checkout || extra.length) fail('Usage: node scripts/sync-registry.mjs [--check] ');
+
+const here = join(dirname(fileURLToPath(import.meta.url)), '..');
+const upstream = join(checkout, 'packages', 'node-type-registry');
+if (!existsSync(join(upstream, 'src', 'index.ts'))) {
+ fail(`${upstream} has no registry source (src/index.ts). Give the path of a constructive-db checkout.`);
+}
+
+const owned = (repo, file) => OWN[repo].some((path) => (path.endsWith('/') ? file.startsWith(path) : file === path));
+
+// The files under src/ as git lists them, so nothing git does not keep (an editor's or a system's file) is copied or
+// compared: what constructive-db tracks, and here also the files a sync just copied and git does not ignore.
+function files(root, { untracked }) {
+ try {
+ const listed = execFileSync('git', ['ls-files', '-z', ...(untracked ? ['--cached', '--others', '--exclude-standard'] : []), '--', 'src'], { cwd: root, encoding: 'utf8' });
+ return [...new Set(listed.split('\0').filter(Boolean))].filter((file) => existsSync(join(root, file))).sort();
+ } catch (err) {
+ fail(`git could not list the files of ${root} (${err.message.split('\n')[0]}). Give the path of a git checkout of constructive-db, and run this in a git checkout of constructive.`);
+ }
+}
+
+const shared = files(upstream, { untracked: false }).filter((file) => !owned('constructive-db', file));
+const clash = shared.filter((file) => owned('constructive', file));
+if (clash.length) {
+ fail(`constructive-db now has ${clash.join(', ')}, which this package keeps as its own. Rename one of them, or take it out of OWN.`);
+}
+const kept = new Set(shared);
+const changes = [
+ ...shared.filter((file) => !existsSync(join(here, file))).map((file) => ({ kind: 'missing', file })),
+ ...shared
+ .filter((file) => existsSync(join(here, file)) && !readFileSync(join(here, file)).equals(readFileSync(join(upstream, file))))
+ .map((file) => ({ kind: 'changed', file })),
+ ...files(here, { untracked: true }).filter((file) => !owned('constructive', file) && !kept.has(file)).map((file) => ({ kind: 'extra', file }))
+];
+
+if (check) {
+ if (!changes.length) {
+ console.log(`The registry source matches ${upstream}.`);
+ process.exit(0);
+ }
+ for (const { kind, file } of changes) console.log(`${kind.padEnd(7)} ${file}`);
+ console.error(
+ `\nThe registry source differs from ${upstream} in ${changes.length} file(s). ` +
+ 'Make the change in constructive-db, then run node scripts/sync-registry.mjs here.'
+ );
+ process.exit(1);
+}
+
+// git can restore a tracked file a sync removes or replaces, but not an untracked one, so the sync stops before it
+// changes anything. A missing file is only added, so it is not one of them.
+const tracked = new Set(files(here, { untracked: false }));
+const untracked = changes.filter(({ kind, file }) => kind !== 'missing' && !tracked.has(file)).map(({ file }) => file);
+if (untracked.length) {
+ fail(
+ `The sync would remove or replace ${untracked.join(', ')}, which git does not track, so nothing was changed. ` +
+ 'Move those files out of src/, commit them, or add them to OWN in this script, then run it again.'
+ );
+}
+
+for (const { kind, file } of changes) {
+ if (kind === 'extra') rmSync(join(here, file));
+ else {
+ mkdirSync(dirname(join(here, file)), { recursive: true });
+ copyFileSync(join(upstream, file), join(here, file));
+ }
+ console.log(`${kind === 'extra' ? 'removed' : 'copied '} ${file}`);
+}
+console.log(
+ `\n${changes.length} file(s) synced. Build and test this package, then check the skills pages: ` +
+ 'ts-node src/codegen/generate-reference.ts --check --outdir /.agents/skills'
+);
+
+function fail(message) {
+ console.error(message);
+ process.exit(2);
+}
diff --git a/packages/node-type-registry/src/authz/authz-database-claim.ts b/packages/node-type-registry/src/authz/authz-database-claim.ts
index a28a6519c4..1a35aeb1ef 100644
--- a/packages/node-type-registry/src/authz/authz-database-claim.ts
+++ b/packages/node-type-registry/src/authz/authz-database-claim.ts
@@ -42,6 +42,6 @@ export const AuthzDatabaseClaim: NodeTypeDefinition = {
'Rows people reach through the API: use a membership policy.'
],
risks: [
- 'Every session the platform binds to that database passes, including an API key used through the database connection proxy.'
+ 'By default, every session the platform binds to that database passes, including an API key used through the database connection proxy. You can require the platform to attest the connection instead.'
]
};
diff --git a/packages/node-type-registry/src/authz/authz-entity-membership.ts b/packages/node-type-registry/src/authz/authz-entity-membership.ts
index be1276997e..a6cab6deb4 100644
--- a/packages/node-type-registry/src/authz/authz-entity-membership.ts
+++ b/packages/node-type-registry/src/authz/authz-entity-membership.ts
@@ -44,7 +44,7 @@ export const AuthzEntityMembership: NodeTypeDefinition = {
format: 'column-ref',
'x-column-scope': 'local',
description:
- 'Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capability/capabilities — both are ANDed.',
+ 'Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capabilities — both checks must pass.',
},
is_admin: {
type: 'boolean',
diff --git a/packages/node-type-registry/src/authz/authz-related-entity-membership.ts b/packages/node-type-registry/src/authz/authz-related-entity-membership.ts
index 2334578f38..1ca02a864b 100644
--- a/packages/node-type-registry/src/authz/authz-related-entity-membership.ts
+++ b/packages/node-type-registry/src/authz/authz-related-entity-membership.ts
@@ -99,7 +99,7 @@ export const AuthzRelatedEntityMembership: NodeTypeDefinition = {
'Rows that name their team directly: use AuthzEntityMembership.'
],
risks: [
- 'The registry does not list sel_obj. The backend\'s own policies set sel_obj to true and sel_field to id; without them the row\'s column is compared with the team id itself, not with the related row.',
+ 'To compare the row\'s column with the related row\'s id rather than the team id, set sel_obj to true and sel_field to id.',
ACTIVE_MEMBER_RISK,
OTHER_TABLE_RISK
]
diff --git a/packages/node-type-registry/src/authz/authz-related-member-owner.ts b/packages/node-type-registry/src/authz/authz-related-member-owner.ts
index 936537cb86..fc909ef907 100644
--- a/packages/node-type-registry/src/authz/authz-related-member-owner.ts
+++ b/packages/node-type-registry/src/authz/authz-related-member-owner.ts
@@ -101,7 +101,7 @@ export const AuthzRelatedMemberOwner: NodeTypeDefinition = {
'Rows that name their team directly: use AuthzMemberOwner.'
],
risks: [
- 'The registry does not list sel_obj. The backend\'s own policies set sel_obj to true and sel_field to id; without them the row\'s column is compared with the team id itself, not with the related row.',
+ 'To compare the row\'s column with the related row\'s id rather than the team id, set sel_obj to true and sel_field to id.',
ACTIVE_MEMBER_RISK,
AGENT_IDENTITY_RISK,
OTHER_TABLE_RISK
diff --git a/packages/node-type-registry/src/authz/authz-value-exists.ts b/packages/node-type-registry/src/authz/authz-value-exists.ts
index acadd496e2..c6d2338a92 100644
--- a/packages/node-type-registry/src/authz/authz-value-exists.ts
+++ b/packages/node-type-registry/src/authz/authz-value-exists.ts
@@ -38,6 +38,7 @@ export const AuthzValueExists: NodeTypeDefinition = {
},
join: {
type: 'array',
+ minItems: 1,
description: 'Join conditions between the protected row and the referenced table',
items: {
type: 'object',
diff --git a/packages/node-type-registry/src/authz/authz-value-match.ts b/packages/node-type-registry/src/authz/authz-value-match.ts
index 8cb6682a0a..5c38bb2069 100644
--- a/packages/node-type-registry/src/authz/authz-value-match.ts
+++ b/packages/node-type-registry/src/authz/authz-value-match.ts
@@ -38,6 +38,7 @@ export const AuthzValueMatch: NodeTypeDefinition = {
},
join: {
type: 'array',
+ minItems: 1,
description: 'Join conditions between the protected row and the referenced table',
items: {
type: 'object',
diff --git a/packages/node-type-registry/src/blueprint-schema.generated.ts b/packages/node-type-registry/src/blueprint-schema.generated.ts
index 2d729771dc..27dbb3dfa3 100644
--- a/packages/node-type-registry/src/blueprint-schema.generated.ts
+++ b/packages/node-type-registry/src/blueprint-schema.generated.ts
@@ -3,7 +3,8 @@
// Regenerate with:
// cd packages/node-type-registry && pnpm generate:types
+/* eslint-disable */
import type { JSONSchema } from './types';
/** JSON Schema (draft-07) of a blueprint definition: the shapes construct_blueprint() reads, with each node's data checked against its parameter_schema in the form a caller writes it. */
-export const blueprintDefinitionJsonSchema: JSONSchema = {"$schema":"http://json-schema.org/draft-07/schema#","title":"BlueprintDefinition","description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint().","allOf":[{"$ref":"#/$defs/BlueprintDefinition"}],"$defs":{"AuthzAllowAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Allows all access. Generates TRUE expression."},"AuthzAppMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must hold an app membership (hardcoded membership_type=1). App-level analog of AuthzMemberOwner for global scopes with no entity key — authorship never survives losing app membership."},"AuthzAppMembershipParams":{"type":"object","properties":{"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":[],"additionalProperties":false,"description":"Checks whether the user is a member of the app. You can also require a specific permission."},"AuthzColumnSecurityParams":{"type":"object","properties":{"columns":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Guarded columns that share the same rule and authorization (e.g. [\"is_shared\"])."},"rule":{"type":"string","enum":["set_true","set_false","set_values","not_values","writable_when","transition","immutable"],"description":"Write pattern that arms the guard: set_true/set_false (column set to that boolean), set_values (column set to one of values), not_values (column set to a non-NULL value outside values), writable_when (column written/changed at all), transition (OLD->NEW pairs in allowed), immutable (delegates to DataImmutableFields).","default":"writable_when"},"authz":{"$ref":"#/$defs/AuthzExpression","description":"An Authz expression (one node such as {\"AuthzAppMembership\": {...}}, or AND, OR or NOT over nodes) that must be satisfied to perform the guarded write. Required for all rules except immutable."},"values":{"type":"array","items":{"type":"string"},"description":"For rule=set_values: the protected values that arm the guard. For rule=not_values: the allowed values; any non-NULL value outside them arms the guard."},"allowed":{"type":"array","items":{"type":"string"},"description":"For rule=transition: allowed guarded transitions expressed as \"from->to\" (e.g. [\"member->admin\"])."},"allow_system":{"type":"boolean","description":"When true, the system role (AuthzSystemOnly) bypasses the guard so provisioning/seed paths without a JWT principal can write freely.","default":false},"error_code":{"type":"string","description":"Machine-readable code prefixed onto the raised error message (e.g. MANAGED_DOMAIN_PUBLISH_FORBIDDEN)."},"error_message":{"type":"string","description":"Human-readable message raised when the guard denies the write."},"conditions":{"type":["object","array"],"items":{"type":"object"},"description":"Conditions on the row being written; the guard arms only when the write matches the rule and the row meets them."}},"required":["columns","rule"],"allOf":[{"if":{"properties":{"rule":{"not":{"const":"immutable"}}}},"then":{"required":["authz"]}},{"if":{"properties":{"rule":{"enum":["set_values","not_values"]}}},"then":{"required":["values"],"properties":{"values":{"minItems":1}}}},{"if":{"properties":{"rule":{"const":"transition"}}},"then":{"required":["allowed"],"properties":{"allowed":{"minItems":1}}}}],"additionalProperties":false,"description":"Column-level write authorization. Generates BEFORE INSERT/UPDATE triggers that enforce an authorization node whenever a guarded column is written to a protected value or transitions. The write-time counterpart to RLS SELECT/WITH CHECK policies: any table can declare \"only an actor satisfying may set column X\". The nested authz value is a normal Authz node compiled by the standard RLS pipeline; row-referencing nodes have their protected-table column references rebound to NEW. The immutable rule delegates to the native DataImmutableFields generator."},"AuthzCompositeParams":{"$ref":"#/$defs/AuthzExpression","description":"Composite authorization policy that combines multiple authorization nodes using boolean logic (AND/OR). The data field contains a JSONB AST with nested authorization nodes."},"AuthzDatabaseClaimParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column carrying the row's database id","default":"database_id"},"schema_id":{"type":"string","format":"uuid","description":"A schema whose database must be the claimed one, in place of a column; the rule then reads no column."},"lane_attested":{"type":"boolean","description":"Only connections the platform attests for the claimed database pass.","default":false}},"additionalProperties":false,"description":"Passes when the row's database column equals the session's pinned database claim (jwt.claims.database_id). Consults no principal, membership or entity, so it admits a connection whose identity the platform sets — such as a cloud function's database connection, whose claim comes from the connection and cannot widen it — to exactly the database that connection is bound to. A session with no claim fails loudly rather than reading nothing."},"AuthzDenyAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Denies all access. Generates FALSE expression."},"AuthzDirectOwnerAnyParams":{"type":"object","properties":{"entity_fields":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Array of column names to check for ownership"}},"required":["entity_fields"],"additionalProperties":false,"description":"OR logic for multiple ownership fields. Checks if current user matches any of the specified fields."},"AuthzDirectOwnerParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)"}},"required":["entity_field"],"additionalProperties":false,"description":"Direct equality comparison between a table column and the current user ID. Simplest authorization pattern with no subqueries."},"AuthzEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"mask_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capability/capabilities — both are ANDed."},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"},"check_function_name":{"type":"string","description":"A function that checks the membership instead of the member list; it is called with the row's team column."},"check_function_schema":{"type":"string","description":"The schema of that function."}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Checks whether the user belongs to the organization or group linked to this record."},"AuthzExpression":{"type":"object","description":"One Authz node as {\"AuthzEntityMembership\": {...}}, or AND or OR with a list of expressions, or NOT with one expression.","minProperties":1,"maxProperties":1,"properties":{"AND":{"$ref":"#/$defs/shared-040cc005ef"},"OR":{"$ref":"#/$defs/shared-040cc005ef"},"NOT":{"$ref":"#/$defs/AuthzExpression"},"AuthzAllowAll":{"$ref":"#/$defs/AuthzAllowAllParams"},"AuthzAppMemberOwner":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"},"AuthzAppMembership":{"$ref":"#/$defs/AuthzAppMembershipParams"},"AuthzDatabaseClaim":{"$ref":"#/$defs/AuthzDatabaseClaimParams"},"AuthzDenyAll":{"$ref":"#/$defs/AuthzDenyAllParams"},"AuthzDirectOwner":{"$ref":"#/$defs/AuthzDirectOwnerParams"},"AuthzDirectOwnerAny":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"},"AuthzEntityMembership":{"$ref":"#/$defs/AuthzEntityMembershipParams"},"AuthzFilePath":{"$ref":"#/$defs/AuthzFilePathParams"},"AuthzHumanOnly":{"$ref":"#/$defs/AuthzHumanOnlyParams"},"AuthzMemberList":{"$ref":"#/$defs/AuthzMemberListParams"},"AuthzMemberOwner":{"$ref":"#/$defs/AuthzMemberOwnerParams"},"AuthzOrgHierarchy":{"$ref":"#/$defs/AuthzOrgHierarchyParams"},"AuthzPeerOwnership":{"$ref":"#/$defs/AuthzPeerOwnershipParams"},"AuthzPublishable":{"$ref":"#/$defs/AuthzPublishableParams"},"AuthzRelatedEntityMembership":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"},"AuthzRelatedMemberList":{"$ref":"#/$defs/AuthzRelatedMemberListParams"},"AuthzRelatedMemberOwner":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"},"AuthzRelatedPeerOwnership":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"},"AuthzSystemOnly":{"$ref":"#/$defs/AuthzSystemOnlyParams"},"AuthzTemporal":{"$ref":"#/$defs/AuthzTemporalParams"},"AuthzValueAllowed":{"$ref":"#/$defs/AuthzValueAllowedParams"},"AuthzValueExists":{"$ref":"#/$defs/AuthzValueExistsParams"},"AuthzValueMatch":{"$ref":"#/$defs/AuthzValueMatchParams"}},"additionalProperties":false},"AuthzFilePathParams":{"type":"object","properties":{"shares_table_id":{"type":"string","format":"uuid","description":"UUID of the path_shares table (alternative to shares_schema/shares_table)"},"shares_schema":{"type":"string","description":"Schema of the path_shares table (or use shares_table_id)"},"shares_table":{"type":"string","description":"Name of the path_shares table (or use shares_table_id)"},"files_table_id":{"type":"string","format":"uuid","description":"UUID of the files table (alternative to files_schema/files_table)"},"files_schema":{"type":"string","description":"Schema of the files table (or use files_table_id)"},"files_table":{"type":"string","description":"Name of the files table (or use files_table_id)"},"capability_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Boolean column on the path_shares table that grants the required permission (e.g. can_read, can_write)"},"bucket_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the files table referencing the bucket","default":"bucket_id"},"path_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Ltree column on the files table representing the file path","default":"path"}},"required":["capability_field"],"allOf":[{"anyOf":[{"required":["shares_table_id"]},{"required":["shares_schema","shares_table"]}]},{"anyOf":[{"required":["files_table_id"]},{"required":["files_schema","files_table"]}]}],"additionalProperties":false,"description":"Path-scoped file sharing via ltree containment. Grants access when a path_shares row matches the current user, bucket, and an ancestor path with the required permission."},"AuthzHumanOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Passes only for human sessions: compares the session's principal claim to its user claim, so service principals (API keys, agents) are excluded. Typically applied as a restrictive policy alongside a permissive membership policy."},"AuthzMemberListParams":{"type":"object","properties":{"array_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the array of user IDs"}},"required":["array_field"],"additionalProperties":false,"description":"Check if current user is in an array column on the same row."},"AuthzMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id)","default":"entity_id"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must be a member of the entity referenced by entity_field. Combines direct ownership with entity membership — the actor can only access rows they own within entities they belong to."},"AuthzNotReadOnlyParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Blocks changes by users marked read-only in the member list. Pair it with AuthzEntityMembership to check that the user is a member in the first place."},"AuthzOrgHierarchyParams":{"type":"object","properties":{"direction":{"type":"string","enum":["up","down"],"description":"down=manager sees subordinates, up=subordinate sees managers"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the org entity","default":"entity_id"},"anchor_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the user (e.g., owner_id)"},"max_depth":{"type":"integer","description":"Optional max depth to limit visibility"}},"required":["direction","anchor_field"],"additionalProperties":false,"description":"Organizational hierarchy visibility using closure table. Managers can see subordinate data or subordinates can see manager data."},"AuthzPeerOwnershipParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the owning user (e.g., owner_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Peer visibility through shared entity membership. Authorizes access to user-owned rows when the owner and current user are both members of the same entity."},"AuthzPublishableParams":{"type":"object","properties":{"is_published_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Boolean field indicating published state","default":"is_published"},"published_at_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Timestamp field for publish time","default":"published_at"},"require_published_at":{"type":"boolean","description":"Require published_at to be non-null and <= now()","default":true}},"additionalProperties":false,"description":"Published state access control. Restricts access to records that are published."},"AuthzRelatedEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Choose the column on the linked table that identifies the organization, group, or other membership target."},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Checks membership through a linked table, such as whether the user belongs to the organization linked there."},"AuthzRelatedMemberListParams":{"type":"object","properties":{"owned_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to owned_schema/owned_table)"},"owned_schema":{"type":"string","description":"Schema of the related table (or use owned_table_id)"},"owned_table":{"type":"string","description":"Name of the related table (or use owned_table_id)"},"owned_table_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Array column in related table"},"owned_table_ref_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"FK column in related table"},"this_object_key":{"type":"string","format":"column-ref","x-column-scope":"local","description":"PK column in protected table"}},"required":["owned_table_key","owned_table_ref_key","this_object_key"],"anyOf":[{"required":["owned_table_id"]},{"required":["owned_schema","owned_table"]}],"additionalProperties":false,"description":"Array membership check in a related table."},"AuthzRelatedMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the related table to match to the entity ID in the member list"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access only when the current user owns the row and belongs to the entity referenced by a related row. If the user loses membership, owning the row no longer gives them access."},"AuthzRelatedPeerOwnershipParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the related table (e.g., message_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to obj_schema/obj_table)"},"obj_schema":{"type":"string","description":"Schema of the related table (or use obj_table_id)"},"obj_table":{"type":"string","description":"Name of the related table (or use obj_table_id)"},"obj_field_id":{"type":"string","format":"uuid","description":"UUID of field on related table containing the owner user ID (alternative to obj_field)"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field name on related table containing the owner user ID (e.g., sender_id)"},"obj_ref_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field on related table to select for matching entity_field","default":"id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access when the current user and the owner are members of the same entity. Unlike AuthzPeerOwnership, it looks up the owner on a related row."},"AuthzSystemOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Restricts access to system-initiated operations (triggers, background jobs). Checks jwt.claims.role_type = \"system\". Normal API requests default to \"user\" and are denied. Use for INSERT policies on append-only event/audit/usage tables."},"AuthzTemporalParams":{"type":"object","properties":{"valid_from_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for start time (at least one of valid_from_field or valid_until_field required)"},"valid_until_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for end time (at least one of valid_from_field or valid_until_field required)"},"valid_from_inclusive":{"type":"boolean","description":"Include start boundary","default":true},"valid_until_inclusive":{"type":"boolean","description":"Include end boundary","default":false}},"anyOf":[{"required":["valid_from_field"]},{"required":["valid_until_field"]}],"additionalProperties":false,"description":"Time-window based access control. Restricts access based on valid_from and/or valid_until timestamps. At least one of valid_from_field or valid_until_field must be provided."},"AuthzValueAllowedParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table to check"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the value check"}},"required":["column","allowed","operator"],"additionalProperties":false,"description":"Check the protected row's own column against an allowed set of values."},"AuthzValueExistsParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-1ca2c9bd61"},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with optional additional conditions."},"AuthzValueMatchParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-1ca2c9bd61"},"match":{"type":"object","description":"Value match on a referenced column","properties":{"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table to match"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the match"}},"required":["ref_column","allowed","operator"],"additionalProperties":false},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["match","join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with a value/array match on a referenced column and optional additional conditions."},"BlueprintAchievement":{"type":"object","properties":{"name":{"type":"string","description":"Unique name for the achievement level."},"description":{"type":"string","description":"Human-readable description of this achievement."},"priority":{"type":"number","description":"Display ordering priority; lower values appear first. Defaults to 100."},"requirements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementRequirement"},"description":"Requirements that must be met to earn this achievement."},"rewards":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementReward"},"description":"Rewards granted when the achievement is earned."},"entity_prefix":{"type":"string","description":"Entity prefix to scope this achievement to (e.g., \"org\", \"app\"). Used to resolve the correct events_module. Defaults to \"app\"."}},"required":["name","requirements"],"description":"An achievement entry for the blueprint achievements[] section. Creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"BlueprintAchievementRequirement":{"type":"object","properties":{"event_name":{"type":"string","description":"Name identifier matching an event_type or step name."},"count":{"type":"number","description":"Number of events needed to satisfy this requirement."},"description":{"type":"string","description":"Human-readable description of what this requirement entails."}},"required":["event_name","count"],"description":"A requirement entry within a blueprint achievement. Defines what events must occur to earn the achievement."},"BlueprintAchievementReward":{"type":"object","properties":{"reward_type":{"enum":["limit_credit","meter_credit"],"description":"Type of reward: limit_credit (grants limit credits) or meter_credit (grants meter credits)."},"target_name":{"type":"string","description":"Target limit name or meter slug for the credit grant."},"amount":{"type":"number","description":"Number of credits to grant."},"credit_type":{"type":"string","description":"Credit type: permanent, expiring, etc. Defaults to \"permanent\"."}},"required":["reward_type","target_name","amount"],"description":"A reward entry within a blueprint achievement. Defines credits granted when the achievement is earned."},"BlueprintAgentConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Agent scope. \"app\" (default) creates app-level agent tables (membership_type = NULL). \"org\" creates per-org agent tables. Only used at the top level of a blueprint definition — entity-scoped agents inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module agents. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_agent_thread."},"api_name":{"type":"string","description":"API name for the agent module. Used in GraphQL naming. Defaults to \"agent\"."},"has_plans":{"type":"boolean","description":"Whether to provision the agent_plan table for workflow plans with ordered tasks and approval gates. When true, tasks belong to plans (plan_id NOT NULL) instead of directly to threads. Defaults to false."},"has_resources":{"type":"boolean","description":"Whether to provision the unified agent_resource table (skills + knowledge with slug, kind, search, embedding). Standalone flag — also auto-enabled by has_agents. Defaults to false."},"has_agents":{"type":"boolean","description":"Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false."},"has_runs":{"type":"boolean","description":"Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false."},"resources":{"type":"array","items":{"type":"object","properties":{"dimensions":{"type":"number"},"chunk_size":{"type":"number"},"chunk_overlap":{"type":"number"},"chunk_strategy":{"enum":["paragraph","sentence","token"]},"embedding_model":{"type":"string"},"embedding_provider":{"type":"string"},"search_indexes":{"type":"array","items":{"type":"string"}}}},"description":"Resource configuration array. First element configures the agent_resource table: vector dimensions (default 768), chunk_size (default 1000), chunk_strategy (default \"paragraph\"), chunk_overlap (default 200), embedding_model, embedding_provider, search_indexes (default [\"bm25\"])."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the agent tables. NULL = apply defaults from apply_agent_security()."},"provisions":{"type":"object","properties":{"thread":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"message":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"task":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"prompt":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"plan":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"resource":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"agent":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"persona":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"run":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"event":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"workspace":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for agent tables. Each key targets a specific table (thread, message, task, prompt, plan, resource, agent, persona, run, event, workspace) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision. Overriding `event` replaces the append-only default, so a grant list there can make the transcript mutable; overriding `workspace` replaces its no-delete default."}},"description":"Agent module configuration. When used at the top level of a blueprint, the scope field controls whether agents are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions thread, message, task, prompt tables. has_resources adds unified agent_resource (skills + knowledge). has_agents adds agent registry + personas (implies has_resources)."},"BlueprintBucketSeed":{"type":"object","properties":{"name":{"type":"string","description":"Bucket key name (e.g., \"avatars\", \"documents\"). Becomes the key column value."},"description":{"type":"string","description":"Human-readable description of this bucket."},"is_public":{"type":"boolean","description":"Whether the bucket is publicly readable. Defaults to false."},"allowed_mime_types":{"type":"array","items":{"type":"string"},"description":"MIME type allowlist (e.g., [\"image/png\", \"image/jpeg\"]). NULL means all types allowed."},"max_file_size":{"type":"number","description":"Maximum file size in bytes for this bucket. NULL means no limit."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for this bucket."}},"required":["name"],"description":"A bucket seed entry for storage.buckets[]. Creates an initial bucket row in the {prefix}_buckets table during entity type provisioning. Only used for app-level storage (not entity-scoped)."},"BlueprintCheckConstraint":{"allOf":[{"$ref":"#/$defs/BlueprintTableCheckConstraint"},{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this CHECK constraint belongs to."}},"required":["table_name"]}],"description":"A CHECK constraint definition within a blueprint (top-level, requires table_name)."},"BlueprintDefinition":{"type":"object","properties":{"tables":{"type":"array","items":{"$ref":"#/$defs/BlueprintTable"},"description":"Tables to create."},"relations":{"type":"array","items":{"$ref":"#/$defs/BlueprintRelation"},"description":"Relations between tables."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintIndex"},"description":"Indexes on table columns."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintFullTextSearch"},"description":"Full-text search configurations."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintUniqueConstraint"},"description":"Unique constraints on table columns."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintCheckConstraint"},"description":"CHECK constraints on table columns."},"entity_types":{"type":"array","items":{"$ref":"#/$defs/BlueprintEntityType"},"description":"Entity types to provision in Phase 0 (before tables). Each entry creates an entity table with membership modules and security."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Top-level storage configuration array. Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates storage_module with membership_type = NULL. Org-scoped creates per-org/user storage with owner_id and AFTER INSERT bucket seeding. When infra is installed, a private \"functions\" bucket is auto-injected into org-scoped entries. For child entity type storage, use entity_types[].storage instead."},"achievements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievement"},"description":"Achievement definitions. Each entry creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Top-level namespace configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates namespace_module with membership_type = NULL. Org-scoped creates per-org namespaces. For entity-scoped namespaces, use entity_types[].namespaces instead."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Top-level function configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates function_module with membership_type = NULL. Org-scoped creates per-org functions. For entity-scoped functions, use entity_types[].functions instead."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Top-level agent configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates agent_module with membership_type = NULL. Org-scoped creates per-org agents. For entity-scoped agents, use entity_types[].agents instead."}},"required":["tables"],"description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint()."},"BlueprintEntityTableProvision":{"type":"object","properties":{"use_rls":{"type":"boolean","description":"Whether to enable RLS on the entity table. Forwarded to secure_table_provision. Defaults to true."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Node objects applied to the entity table for field creation (e.g., DataTimestamps, DataPeoplestamps). Forwarded to secure_table_provision as-is."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the entity table. Forwarded to secure_table_provision as-is."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects for the entity table. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples. Forwarded to secure_table_provision as-is. Defaults to []."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for the entity table. When present, these policies fully replace the five default entity-table policies (is_visible becomes a no-op)."}},"description":"Override object for the entity table created by a BlueprintEntityType. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, policies[] replaces the default entity-table policies entirely."},"BlueprintEntityType":{"type":"object","properties":{"name":{"type":"string","description":"Entity type name (e.g., \"data_room\", \"channel\", \"department\"). Required when creating a new entity type. Omit when extending an existing entity type (e.g., prefix: \"org\") — the entry will add storage/config to the existing type without creating a new one."},"prefix":{"type":"string","description":"Short prefix for generated objects (e.g., \"dr\", \"ch\", \"dept\"). Used in table/trigger naming."},"description":{"type":"string","description":"Human-readable description of this entity type."},"parent_entity":{"type":"string","description":"Parent entity type name. Defaults to \"org\"."},"table_name":{"type":"string","description":"Custom table name for the entity table. Defaults to name-derived convention."},"is_visible":{"type":"boolean","description":"Whether parent-entity members can see child entities via the default parent_member SELECT policy. Gates one of the five default policies. No-op when table_provision is supplied. Defaults to true."},"has_limits":{"type":"boolean","description":"Whether to provision a limits module for this entity type. Defaults to false."},"has_profiles":{"type":"boolean","description":"Whether to provision a profiles module for this entity type. Defaults to false. A membership may hold any number of profiles: the {prefix}_membership_profiles assignment table holds every profile it holds and the membership mask is granted | bit_or(held profile masks)."},"has_levels":{"type":"boolean","description":"Whether to provision a levels module for this entity type. Defaults to false."},"has_invites":{"type":"boolean","description":"Whether to provision entity-scoped invite tables ({prefix}_invites, {prefix}_claimed_invites) and a submit_{prefix}_invite_code() function. Defaults to false."},"has_invite_achievements":{"type":"boolean","description":"Whether to auto-attach an EventTracker to the claimed_invites table for invite-based achievements. Requires has_invites=true AND has_levels=true. When true, records 'invite_claimed' events credited to the sender (inviter) on each claimed invite. Defaults to false."},"skip_entity_policies":{"type":"boolean","description":"Escape hatch: when true AND table_provision is NULL, zero policies are provisioned on the entity table. Defaults to false."},"table_provision":{"$ref":"#/$defs/BlueprintEntityTableProvision","description":"Override for the entity table. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, its policies[] replaces the five default entity-table policies; is_visible becomes a no-op. When NULL (default), the five default policies are applied (gated by is_visible)."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Storage module configuration array. Presence triggers provisioning (same inference model as namespaces, functions, agents). Each entry provisions a separate storage module with its own tables, RLS, and settings. Each entry may specify a key for multi-module support (defaults to \"default\")."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Namespace module configuration array. Presence triggers provisioning. Each entry provisions a namespace_module with its own tables, computed-name proxy, and entity-scoped RLS. Registers manage_namespaces capability bit. \"[{}]\" = provision one default namespace module."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Function module configuration array. Presence triggers provisioning. Each entry provisions function_definitions, function_invocations (partitioned), and function_execution_logs tables. Registers manage_functions + invoke_functions capability bits. \"[{}]\" = provision one default function module."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Agent module configuration array. Presence triggers provisioning. Each entry provisions thread, message, task, prompt tables (and optionally knowledge with vector embeddings). \"[{}]\" = provision one default agent module."},"graphs":{"type":"array","items":{"$ref":"#/$defs/BlueprintGraphConfig"},"description":"Graph module configuration array. Presence triggers capability registration (manage_graphs, execute_graphs). Graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here. \"[{}]\" = register default graph capabilities."}},"required":["prefix"],"description":"An entity type entry for Phase 0 of construct_blueprint(). When name is provided, provisions a new entity type with its own entity table, membership modules, and security policies via entity_type_provision. When name is omitted and only prefix is given, extends an existing entity type (e.g., the built-in \"org\") with additional capabilities like storage — without creating a new entity type."},"BlueprintField":{"type":"object","properties":{"name":{"type":"string","description":"The column name."},"type":{"$ref":"#/$defs/FieldType","description":"The structured PostgreSQL type (e.g., { name: \"text\" })."},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint."},"default":{"$ref":"#/$defs/FieldDefault","description":"The structured default (e.g., { value: \"pending\" })."},"min":{"type":"number"},"max":{"type":"number"},"regexp":{"type":"string"},"index":{"enum":["btree","gin","gist","brin","hash"]},"description":{"type":"string","description":"Comment/description for this field."}},"required":["name","type"],"description":"A custom field (column) to add to a blueprint table."},"BlueprintFtsSource":{"type":"object","properties":{"field":{"type":"string","description":"Column name of the source field."},"weight":{"type":"string","description":"TSVector weight: \"A\", \"B\", \"C\", or \"D\"."},"lang":{"type":"string","description":"Language for text search. Defaults to \"english\"."}},"required":["field","weight"],"description":"A source field contributing to a full-text search tsvector column."},"BlueprintFullTextSearch":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this full-text search belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"}},"required":["table_name","field","sources"],"description":"A full-text search configuration for a blueprint table (top-level, requires table_name)."},"BlueprintFunctionConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Function scope. \"app\" (default) creates app-level functions (membership_type = NULL). \"org\" creates per-org functions. Only used at the top level of a blueprint definition — entity-scoped functions inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module functions. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_function_definitions."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the function tables. NULL = apply defaults from apply_function_security()."},"provisions":{"type":"object","properties":{"definitions":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"invocations":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"execution_logs":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for function tables. Each key targets a specific table (definitions, invocations, execution_logs) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Function module configuration. When used at the top level of a blueprint, the scope field controls whether functions are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions function_definitions, function_invocations (partitioned, 12-month retention), and function_execution_logs tables."},"BlueprintGraphConfig":{"type":"object","properties":{"key":{"type":"string","description":"Module discriminator for multi-module graphs. Defaults to \"default\"."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the graph tables. NULL = apply defaults from apply_graph_security()."}},"description":"Graph module configuration. Presence triggers capability registration (manage_graphs, execute_graphs). The graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here — the graph module itself must be provisioned separately."},"BlueprintIndex":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this index belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"}},"required":["table_name","access_method"],"description":"An index definition within a blueprint (top-level, requires table_name)."},"BlueprintModuleInstallRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type of the install, e.g. \"image\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type"],"description":"A reference to an installed module, naming no table of its own. Used by a table entry whose provisions map supplies the table keys."},"BlueprintModuleTableRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type owning the table. Currently \"agent\"."},"table":{"type":"string","description":"Logical table key within the module, not a table name. Agent: \"thread\", \"message\", \"task\", \"prompt\", \"plan\", \"agent\", \"persona\", \"resource\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type","table"],"description":"A reference from a blueprint table entry to a table generated by an installed module. Resolved through the module row's recorded table ids; a reference that matches no module instance or no provisioned table fails construction rather than creating a table."},"BlueprintNamespaceConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Namespace scope. \"app\" (default) creates app-level namespaces (membership_type = NULL). \"org\" creates per-org namespaces. Only used at the top level of a blueprint definition — entity-scoped namespaces inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module namespaces. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_namespaces."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the namespaces table. NULL = apply defaults from apply_namespace_security()."},"provisions":{"type":"object","properties":{"namespaces":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"namespace_events":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for namespace tables. Each key targets a specific table (namespaces, namespace_events) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Namespace module configuration. When used at the top level of a blueprint, the scope field controls whether namespaces are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions a namespaces table with computed-name proxy, rename trigger, and entity-scoped RLS."},"BlueprintNode":{"anyOf":[{"$ref":"#/$defs/BlueprintNodeShorthand"},{"$ref":"#/$defs/BlueprintNodeObject"}],"description":"A node entry in a blueprint table. Either a string shorthand or a typed object."},"BlueprintNodeObject":{"type":"object","properties":{"data":{"type":"object"},"$type":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzColumnSecurity","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch","CheckGreaterThan","CheckLessThan","CheckNotEqual","CheckOneOf","CheckOwnedRelation","DataArchivable","DataBulk","DataCapabilities","DataCompositeField","DataDenormalized","DataDirectOwner","DataEntityMembership","DataFileRef","DataForceCurrentUser","DataGenerated","DataHistory","DataI18n","DataId","DataIdentity","DataImmutableFields","DataInflection","DataInheritFromParent","DataJsonb","DataLock","DataMemberOwner","DataOwnedFields","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchBm25","SearchFullText","SearchSpatial","SearchSpatialAggregate","SearchTrgm","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","EventReferral","EventTracker","GuardStepUp","JobTrigger","LimitEnforceAggregate","LimitEnforceCounter","LimitEnforceFeature","LimitEnforceRate","LimitTrackUsage","LimitWarningAggregate","LimitWarningCounter","LimitWarningRate","ProcessChunks","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"]}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"if":{"$ref":"#/$defs/shared-49ec07b1f5"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-21a1ba9587"},{"if":{"properties":{"$type":{"const":"AuthzColumnSecurity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzColumnSecurityParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"if":{"$ref":"#/$defs/shared-47ab73adbe"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-34021cf1ff"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-15602a740a"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzEntityMembershipParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-5f5453df14"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzFilePathParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-aced6572ca"},{"if":{"$ref":"#/$defs/shared-eff5f86cd2"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberListParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-d91c021eee"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberOwnerParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-2c17992067"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzNotReadOnlyParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-97d5c3be03"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzOrgHierarchyParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-b1dc7b2e4f"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPeerOwnershipParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"if":{"$ref":"#/$defs/shared-f93f3b8ac9"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-584ca266e8"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberListParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-433a283165"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-5192cb016d"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"if":{"$ref":"#/$defs/shared-57b27779bd"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueAllowedParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-e23bde2ba6"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueExistsParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-3245b618eb"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueMatchParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckGreaterThanParams"}}}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckLessThanParams"}}}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckNotEqualParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOneOfParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"CheckOwnedRelation"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOwnedRelationParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataArchivable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataArchivableParams"}}}},{"if":{"properties":{"$type":{"const":"DataBulk"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataBulkParams"}}}},{"if":{"properties":{"$type":{"const":"DataCapabilities"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCapabilitiesParams"}}}},{"if":{"properties":{"$type":{"const":"DataCompositeField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCompositeFieldParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDenormalized"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDenormalizedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDirectOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataEntityMembershipParams"}}}},{"if":{"properties":{"$type":{"const":"DataFileRef"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataFileRefParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataForceCurrentUser"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataForceCurrentUserParams"}}}},{"if":{"properties":{"$type":{"const":"DataGenerated"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataGeneratedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataHistory"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataHistoryParams"}}}},{"if":{"properties":{"$type":{"const":"DataI18n"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataI18nParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataId"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdParams"}}}},{"if":{"properties":{"$type":{"const":"DataIdentity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdentityParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataImmutableFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataImmutableFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInflection"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInflectionParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInheritFromParent"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInheritFromParentParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataJsonb"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataJsonbParams"}}}},{"if":{"properties":{"$type":{"const":"DataLock"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataLockParams"}}}},{"if":{"properties":{"$type":{"const":"DataMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataMemberOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataOwnedFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnedFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataOwnershipInEntity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnershipInEntityParams"}}}},{"if":{"properties":{"$type":{"const":"DataPeoplestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPeoplestampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPrincipalstamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPrincipalstampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPublishableParams"}}}},{"if":{"properties":{"$type":{"const":"DataRealtime"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataRealtimeParams"}}}},{"if":{"properties":{"$type":{"const":"DataSlug"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSlugParams"}}}},{"if":{"properties":{"$type":{"const":"DataSoftDelete"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSoftDeleteParams"}}}},{"if":{"properties":{"$type":{"const":"DataStatusField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataStatusFieldParams"}}}},{"if":{"properties":{"$type":{"const":"DataTags"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTagsParams"}}}},{"if":{"properties":{"$type":{"const":"DataTimestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTimestampsParams"}}}},{"if":{"properties":{"$type":{"const":"SearchBm25"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchBm25Params"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchFullText"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchFullTextParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchSpatial"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialParams"}}}},{"if":{"properties":{"$type":{"const":"SearchSpatialAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchTrgm"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchTrgmParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchUnified"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchUnifiedParams"}}}},{"if":{"properties":{"$type":{"const":"SearchVector"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchVectorParams"}}}},{"if":{"properties":{"$type":{"const":"TableOrganizationSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableOrganizationSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserProfiles"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserProfilesParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"EventReferral"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventReferralParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"EventTracker"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventTrackerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"GuardStepUp"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/GuardStepUpParams"}}}},{"if":{"properties":{"$type":{"const":"JobTrigger"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/JobTriggerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceFeature"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceFeatureParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitTrackUsage"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitTrackUsageParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"ProcessChunks"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessChunksParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessExtraction"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessExtractionParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessFileEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessFileEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageVersions"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageVersionsParams"}},"required":["data"]}}],"description":"Object form -- { $type, data } with typed parameters."},"BlueprintNodeShorthand":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzColumnSecurity","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch","CheckGreaterThan","CheckLessThan","CheckNotEqual","CheckOneOf","CheckOwnedRelation","DataArchivable","DataBulk","DataCapabilities","DataCompositeField","DataDenormalized","DataDirectOwner","DataEntityMembership","DataFileRef","DataForceCurrentUser","DataGenerated","DataHistory","DataI18n","DataId","DataIdentity","DataImmutableFields","DataInflection","DataInheritFromParent","DataJsonb","DataLock","DataMemberOwner","DataOwnedFields","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchBm25","SearchFullText","SearchSpatial","SearchSpatialAggregate","SearchTrgm","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","EventReferral","EventTracker","GuardStepUp","JobTrigger","LimitEnforceAggregate","LimitEnforceCounter","LimitEnforceFeature","LimitEnforceRate","LimitTrackUsage","LimitWarningAggregate","LimitWarningCounter","LimitWarningRate","ProcessChunks","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"],"description":"String shorthand -- just the node type name."},"BlueprintPolicy":{"type":"object","properties":{"privileges":{"type":"array","minItems":1,"items":{"type":"string","pattern":"^([Ss][Ee][Ll][Ee][Cc][Tt]|[Ii][Nn][Ss][Ee][Rr][Tt]|[Uu][Pp][Dd][Aa][Tt][Ee]|[Dd][Ee][Ll][Ee][Tt][Ee])$"}},"permissive":{"type":"boolean"},"policy_role":{"type":"string"},"policy_name":{"type":"string"},"data":{"type":"object"},"with_check":{"$ref":"#/$defs/BlueprintPolicyWithCheck"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-c893ee8510"},{"$ref":"#/$defs/shared-a2c45e97d1"},{"$ref":"#/$defs/shared-85b2c2543e"},{"$ref":"#/$defs/shared-e3e4ac8f48"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-11809f0714"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-8e6e495eb6"},{"$ref":"#/$defs/shared-c2c61348f0"},{"$ref":"#/$defs/shared-4f25156f61"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-33013a269d"},{"$ref":"#/$defs/shared-0596961db6"},{"$ref":"#/$defs/shared-89ec3722aa"},{"$ref":"#/$defs/shared-1a97ddc6fb"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-c88c54a5c5"},{"$ref":"#/$defs/shared-3fc6945ad1"},{"$ref":"#/$defs/shared-c1527c6159"}],"description":"An RLS policy entry for a blueprint table. A with_check override applies to UPDATE only.","if":{"required":["with_check"]},"then":{"required":["privileges"],"properties":{"privileges":{"items":{"type":"string","pattern":"^[Uu][Pp][Dd][Aa][Tt][Ee]$"}}}}},"BlueprintPolicyWithCheck":{"type":"object","properties":{"data":{"type":"object"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-c893ee8510"},{"$ref":"#/$defs/shared-a2c45e97d1"},{"$ref":"#/$defs/shared-85b2c2543e"},{"$ref":"#/$defs/shared-e3e4ac8f48"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-11809f0714"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-8e6e495eb6"},{"$ref":"#/$defs/shared-c2c61348f0"},{"$ref":"#/$defs/shared-4f25156f61"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-33013a269d"},{"$ref":"#/$defs/shared-0596961db6"},{"$ref":"#/$defs/shared-89ec3722aa"},{"$ref":"#/$defs/shared-1a97ddc6fb"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-c88c54a5c5"},{"$ref":"#/$defs/shared-3fc6945ad1"},{"$ref":"#/$defs/shared-c1527c6159"}]},"BlueprintRelation":{"type":"object","description":"A relation entry in a blueprint definition.","properties":{"source_table":{"type":"string"},"target_table":{"type":"string"},"source_schema":{"type":"string"},"target_schema":{"type":"string"},"source_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"target_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"$type":{"enum":["RelationBelongsTo","RelationHasMany","RelationHasOne","RelationManyToMany","RelationSpatial"]}},"required":["$type"],"allOf":[{"if":{"properties":{"$type":{"const":"RelationBelongsTo"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field added"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., projects → project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}}}},{"if":{"properties":{"$type":{"const":"RelationHasMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Parent table being referenced by the FK (e.g., projects in projects has many tasks)"},"target_table_id":{"type":"string","format":"uuid","description":"Child table that receives the FK field (e.g., tasks in projects has many tasks)"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the target table. Auto-derived from source table name if omitted (e.g., projects derives project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}}}},{"if":{"properties":{"$type":{"const":"RelationHasOne"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field and unique constraint"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., users → user_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}}}},{"if":{"properties":{"$type":{"const":"RelationManyToMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"First table in the M:N relationship"},"target_table_id":{"type":"string","format":"uuid","description":"Second table in the M:N relationship"},"junction_table_id":{"type":"string","format":"uuid","description":"Existing junction table to use. If uuid_nil(), a new bare table is created"},"junction_table_name":{"type":"string","description":"Junction table name. Auto-derived from both table names if omitted (e.g., projects + tags derives project_tags)"},"source_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for source table. Auto-derived if omitted (e.g., projects derives project_id)"},"target_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for target table. Auto-derived if omitted (e.g., tags derives tag_id)"},"use_composite_key":{"type":"boolean","description":"When true, creates a composite PK from the two FK fields. When false, no PK is created by the trigger (use nodes with DataId for UUID PK). Mutually exclusive with nodes containing DataId.","default":false},"nodes":{"type":"array","items":{"type":"object"},"description":"Array of node objects for field creation on junction table. Each object has a $type key (e.g. DataId, DataEntityMembership) and optional data keys. Forwarded to secure_table_provision as-is. Empty array means no additional fields."},"grants":{"type":"array","items":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{"type":"array","items":{"type":"string"}}}},"required":["roles","privileges"]},"description":"Unified grant objects for the junction table. Each entry is { roles: string[], privileges: string[][] }. Forwarded to secure_table_provision as-is. Default: []"},"policies":{"type":"array","items":{"type":"object","properties":{"$type":{"type":"string"},"data":{"type":"object"},"privileges":{"type":"array","items":{"type":"string"}},"policy_role":{"type":"string"},"permissive":{"type":"boolean"},"policy_name":{"type":"string"}},"required":["$type"]},"description":"RLS policy objects for the junction table. Each entry has $type (Authz* generator), optional data, privileges, policy_role, permissive, policy_name. Forwarded to secure_table_provision as-is. Default: []"}}}},{"if":{"properties":{"$type":{"const":"RelationSpatial"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that owns the relation (the @spatialRelation tag is emitted on the owner column of this table)"},"source_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on source_table that carries the @spatialRelation smart tag"},"target_table_id":{"type":"string","format":"uuid","description":"Table being referenced by the spatial predicate"},"target_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on target_table that the predicate is evaluated against"},"name":{"type":"string","description":"Relation name (stable, snake_case). Becomes the generated filter field name in GraphQL (e.g. nearby_clinic). Unique per (source_table_id, name) — idempotency key."},"operator":{"type":"string","enum":["st_contains","st_within","st_intersects","st_covers","st_coveredby","st_overlaps","st_touches","st_dwithin"],"description":"PostGIS spatial predicate. One of the 8 whitelisted operators. st_dwithin requires param_name."},"param_name":{"type":"string","description":"Parameter name for parametric operators (currently only st_dwithin, which needs a distance argument). Must be NULL for all other operators. Enforced by table CHECK."},"source_field":{"type":"string"},"target_field":{"type":"string"}},"required":["source_field","target_field"]}}]},"BlueprintStorageConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Storage scope. \"app\" (default) creates app-level storage (no owner_id). \"org\" creates per-org/user storage (owner_id = org entity id, buckets seeded per-entity via AFTER INSERT trigger). Only \"app\" and \"org\" are allowed — child entity types get storage via entity_types[].storage."},"key":{"type":"string","description":"Module key discriminator. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case."},"storage_key":{"type":"string","description":"@deprecated Use `key` instead. Kept for backward compatibility."},"buckets":{"type":"array","items":{"$ref":"#/$defs/BlueprintBucketSeed"},"description":"Initial bucket seed entries. Each creates a row in {prefix}_buckets during provisioning."},"upload_url_expiry_seconds":{"type":"number","description":"Override for presigned upload URL expiry time in seconds."},"download_url_expiry_seconds":{"type":"number","description":"Override for presigned download URL expiry time in seconds."},"default_max_file_size":{"type":"number","description":"Default maximum file size in bytes for the storage module."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for the storage module."},"confirm_upload_delay":{"type":"string","description":"Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. \"30 seconds\"). Defaults to \"30 seconds\"."},"staging":{"type":"boolean","description":"Provision a temporary staging bucket (type temp, tagged default-temp) that stages for the private default bucket, so uploads land there and are promoted into their destination on confirmation. Setting staging_ttl implies this. Defaults to false."},"staging_ttl":{"type":"string","description":"How long an unpromoted staged file survives before it is eligible for expiry (PostgreSQL interval string, e.g. \"24 hours\"). Implies staging. Defaults to \"24 hours\"."},"provisions":{"type":"object","properties":{"files":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"buckets":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for storage tables. Each key targets a specific storage table (files, buckets) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision targeting the corresponding table. When a key includes policies[], those REPLACE the default storage policies for that table; tables without a key still get defaults."}},"description":"Storage configuration with optional scope. When used at the top level of a blueprint, the scope field controls whether storage is app-level (\"app\", default) or org-level (\"org\"). Seeds initial buckets, overrides module-level settings (expiry times, file size limits, CORS), and provides per-table provisioning overrides via provisions."},"BlueprintTable":{"type":"object","properties":{"table_name":{"type":"string","description":"The PostgreSQL table name to create. Required unless the entry carries a module reference instead."},"schema_name":{"type":"string","description":"Optional schema name (falls back to top-level default)."},"module":{"anyOf":[{"$ref":"#/$defs/BlueprintModuleTableRef"},{"$ref":"#/$defs/BlueprintModuleInstallRef"}],"description":"Attach this entry to a table an installed module generated instead of naming one, e.g. { type: \"agent\", scope: \"org\", table: \"message\" }. Mutually exclusive with table_name/schema_name. An entry carrying provisions names the install alone and leaves out table, since the provisions keys name the tables."},"provisions":{"type":"object","additionalProperties":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"description":"Provision security onto the tables the referenced module generated, keyed by the module's own table keys (e.g. { registries: { policies: [...] } } for an image module). Requires a module reference without \"table\", since the keys name the tables. Each entry takes ownership of the security it declares: the grants/policies given become that table's whole set, replacing what the module installed — unlike this entry's own policies[]/grants[], which layer onto one table."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Array of node type entries that define the table's behavior. Omitted by an entry that only carries provisions or only attaches policies to a module table."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the table."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for this table."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples (e.g. [[\"select\",\"*\"]]). Enables per-role targeting. Defaults to []."},"use_rls":{"type":"boolean","description":"Whether to enable RLS on this table. Defaults to true."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableIndex"},"description":"Table-level indexes (table_name inherited from parent)."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableFullTextSearch"},"description":"Table-level full-text search configurations (table_name inherited from parent)."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableUniqueConstraint"},"description":"Table-level unique constraints (table_name inherited from parent)."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableCheckConstraint"},"description":"Table-level CHECK constraints (table_name inherited from parent)."}},"description":"A table definition within a blueprint."},"BlueprintTableCheckConstraint":{"type":"object","properties":{"$type":{"enum":["CheckOneOf","CheckGreaterThan","CheckLessThan","CheckNotEqual"]}},"required":["$type"],"allOf":[{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"type":"object","properties":{"$type":{"const":"CheckOneOf"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckOneOfParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"type":"object","properties":{"$type":{"const":"CheckGreaterThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckGreaterThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"type":"object","properties":{"$type":{"const":"CheckLessThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckLessThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"type":"object","properties":{"$type":{"const":"CheckNotEqual"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckNotEqualParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}}],"description":"A CHECK constraint nested inside a table definition (table_name not required)."},"BlueprintTableFullTextSearch":{"type":"object","properties":{"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["field","sources"],"description":"A full-text search configuration nested inside a table definition (table_name not required)."},"BlueprintTableIndex":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["access_method"],"description":"An index definition nested inside a table definition (table_name not required)."},"BlueprintTableUniqueConstraint":{"type":"object","properties":{"columns":{"$ref":"#/$defs/shared-a0bfcadf85"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["columns"],"description":"A unique constraint nested inside a table definition (table_name not required)."},"BlueprintUniqueConstraint":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this unique constraint belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"columns":{"$ref":"#/$defs/shared-a0bfcadf85"}},"required":["table_name","columns"],"description":"A unique constraint definition within a blueprint (top-level, requires table_name)."},"CheckGreaterThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column > value)","default":0},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] > columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is greater than a threshold (single-column: column > value) or that one column is greater than another (cross-column: columns[0] > columns[1]). Compiled via AST helpers."},"CheckLessThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column < value)"},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] < columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is less than a threshold (single-column: column < value) or that one column is less than another (cross-column: columns[0] < columns[1]). Compiled via AST helpers."},"CheckNotEqualParams":{"type":"object","properties":{"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns that must not be equal","minItems":2,"maxItems":2}},"required":["columns"],"description":"Adds a CHECK constraint that validates two columns are not equal (columns[0] != columns[1]). Useful for preventing self-referencing rows. Compiled via AST helpers."},"CheckOneOfParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","description":"Column to validate against the allowed values"},"values":{"type":"array","items":{"type":"string"},"description":"Array of allowed values for the column"}},"required":["column","values"],"description":"Adds a CHECK constraint that validates a column value is one of an allowed set (e.g. tier IN ('free', 'paid', 'custom')). Compiled to column = ANY(ARRAY[...]) via AST helpers."},"CheckOwnedRelationParams":{"type":"object","properties":{"link_schema_name":{"type":"string","description":"Schema holding the link tables the ownership is proven through"},"owner_scope":{"type":"string","description":"Scope that owns the referencing rows; matched against the link row's owner_scope (e.g. database, platform)"},"owner_key_field_name":{"type":"string","format":"column-ref","description":"Column on the referencing table carrying its scope key, matched against the link row's owner_key. NULL for a global scope, whose owner key is NULL by construction"},"pointers":{"type":"array","description":"Typed pointer columns to guard, each resolved through its own link table","items":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Pointer column on the referencing table"},"link_table_name":{"type":"string","description":"Link table in link_schema_name whose ids this column points at"},"target_type_field_name":{"type":"string","description":"Optional link column additionally restricted regardless of ownership (e.g. a bucket type)"},"target_type_value":{"type":"string","description":"Value target_type_field_name must equal"},"allow_owner_tier":{"type":"boolean","description":"Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database","default":false}},"required":["field_name","link_table_name"]}},"arity":{"type":"string","enum":["exactly_one","all","any"],"description":"How many pointers a row must set: exactly_one for a polymorphic target (route → api OR site OR bucket), all for a junction/join row of a has-and-belongs-to-many relation (and for a mandatory belongs-to), any for optional pointers that are only checked when set","default":"exactly_one"},"required_error":{"type":"string","description":"Error code raised when the arity rule over the pointers is violated","default":"OWNED_RELATION_TARGET_REQUIRED"},"denied_error":{"type":"string","description":"Error code raised when the target is not owned by the referencing row owner","default":"OWNED_RELATION_TARGET_NOT_OWNED"},"trigger_function_schema":{"type":"string","description":"Schema the guard trigger function is created in; defaults to the table schema"},"trigger_function_name":{"type":"string","description":"Guard trigger function name; defaults to tg_
_owned_relation_guard"},"trigger_name":{"type":"string","description":"Guard trigger name; defaults to
_owned_relation_guard"}},"required":["link_schema_name","owner_scope","pointers"],"description":"Declares that typed pointer columns may only reference rows owned by the same scope owner as the referencing row, proven through a link table that carries the owner (owner_scope, owner_key) — typically a catalog projection that must never be referenced structurally. Creates one BEFORE INSERT OR UPDATE trigger enforcing the declared arity over the pointers and requiring every pointer that is set to resolve to a same-owner row, so it covers belongs-to / has-one / has-many (key on the row being written) and has-and-belongs-to-many (both keys on the junction row, arity all). Visibility/publication flags are never an authorization input."},"DataArchivableParams":{"type":"object","properties":{"is_archived_field":{"type":"string","format":"column-ref","description":"Column name for the archive boolean flag","default":"is_archived"},"archived_at_field":{"type":"string","format":"column-ref","description":"Column name for the archive timestamp","default":"archived_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds user-reversible archive support with is_archived boolean and archived_at timestamp, plus a partial index for efficient active-row queries."},"DataBulkParams":{"type":"object","properties":{"insert":{"type":"boolean","description":"Enable bulk insert (+bulkInsert)","default":true},"upsert":{"type":"boolean","description":"Enable bulk upsert (+bulkUpsert)","default":false},"update":{"type":"boolean","description":"Enable bulk update (+bulkUpdate)","default":false},"delete":{"type":"boolean","description":"Enable bulk delete (+bulkDelete)","default":false}},"description":"Enables bulk mutation smart tags on a table. When provisioned, adds @behavior tags for the selected bulk operations (insert, upsert, update, delete). Requires the graphile-bulk-mutations plugin."},"DataCapabilitiesParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the bit(n) mask column to create on this table.","default":"required_capabilities"},"capabilities":{"type":"string","description":"Selects the capabilities module whose bit numbering the mask is measured in, by scope (e.g. \"app\", \"org\") or by table prefix. Required only when the database has more than one; several with no selector raises naming the candidates."},"default":{"type":"array","items":{"type":"string"},"description":"Capability names every row requires unless told otherwise, resolved to a literal mask and baked into the column default. Omitted means a zero mask: requires nothing."},"mode":{"type":"string","enum":["direct","derived"],"description":"Who writes the mask: \"direct\" the writer, bounded by the subset guard; \"derived\" the mapping row named by from_column, stamped by generated triggers and hidden from mutations.","default":"direct"},"from_column":{"type":"string","format":"column-ref","description":"Derived mode only: the column on this table naming the mapping row to copy the mask from (e.g. classification_id)."},"mapping_table":{"type":"string","description":"Derived mode only: table holding one mask per class (e.g. document_classifications)."},"mapping_key":{"type":"string","format":"column-ref","description":"Derived mode only: column on the mapping table that from_column matches.","default":"id"},"mapping_column":{"type":"string","format":"column-ref","description":"Derived mode only: the mapping table's own bit(n) mask column. Created when absent, so a classification table needs no DataCapabilities declaration of its own. Defaults to the same name as field."},"subset_guard":{"type":"boolean","description":"Direct mode only: refuse a write requiring bits the writer does not hold, so nobody can lock a row away from everyone including themselves. Off is for trusted-writer tables only.","default":true},"entity_field":{"type":"string","format":"column-ref","description":"Direct mode only: the entity column the subset guard's membership check reads.","default":"entity_id"}},"description":"Per-row required permissions. A profile compiles a person to bits so no policy joins a profiles table; this compiles a row to bits so no policy joins a grant table either — the row stores which permissions are required, and an AuthzEntityMembership policy with mask_column checks that the user has all of them. The mask only narrows: it takes access away from someone membership already lets in, and never grants access to a non-member. Zero requires nothing, which is what an unclassified row defaults to. In direct mode the writer sets the mask and the subset guard bounds it to bits the writer holds; in derived mode it is copied from a mapping row (classification -> mask) by generated triggers, so authors edit one classification instead of every document."},"DataCompositeFieldParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the derived text field to create","default":"embedding_text"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names to concatenate into the target field"},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format: 'labeled' (field_name: value) or 'plain' (values only)","default":"labeled"}},"required":["source_fields"],"description":"Creates a derived text field that automatically concatenates multiple source fields via BEFORE INSERT/UPDATE triggers. Used to produce a unified text representation (e.g., embedding_text) from multiple columns on a table. The trigger fires with '_000' prefix to run before Search* triggers alphabetically."},"DataDenormalizedParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"FK field on this table that references the parent row (e.g. view_id)"},"set_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on this table to be populated from the parent (e.g. [\"database_id\"])"},"ref_field":{"type":"string","format":"column-ref","description":"Field on the parent table that is the FK target (e.g. id)"},"ref_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the parent table to copy from (e.g. [\"database_id\"])"},"use_updates":{"type":"boolean","description":"If true, also creates an UPDATE trigger so changes to the FK re-copy values","default":true},"update_defaults":{"type":"boolean","description":"If true, sets the default value of set_fields to uuid_nil() so they are populated by the trigger","default":true},"func_name":{"type":"string","description":"Custom function name suffix (defaults to the FK field name)"},"func_order":{"type":"integer","description":"Trigger ordering (0-padded). Lower numbers fire first","default":0}},"required":["field","set_fields","ref_field","ref_fields"],"description":"Creates INSERT and UPDATE triggers that copy field values from a referenced (parent) table into the current table whenever the FK changes. Used to denormalize frequently-read columns (e.g. database_id on junction tables) so that RLS and queries can filter locally without joining."},"DataDirectOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for owner ID","default":"owner_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from owner_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the owner column","default":true}},"description":"Adds ownership column for direct user ownership. Enables AuthzDirectOwner authorization."},"DataEntityMembershipParams":{"type":"object","properties":{"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for entity ID","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the entity column","default":true}},"description":"Adds entity reference for organization/group scoping. Enables AuthzEntityMembership, AuthzMembership, AuthzOrgHierarchy authorization."},"DataFileRefParams":{"type":"object","required":["field"],"properties":{"field":{"type":"string","format":"column-ref","pattern":"\\S","description":"The upload, image or attachment column to register"},"storage":{"type":"object","description":"The storage module the file lives in, selected by its scope and/or key; every key given must match exactly one module. When omitted, the table's scope column decides, and a table with no scope column uses the app's storage.","properties":{"scope":{"type":"string","pattern":"\\S","description":"Scope of the storage module, e.g. \"app\", \"org\" or an entity type's scope"},"key":{"type":"string","pattern":"\\S","description":"Key of the storage module, for a scope with more than one"}},"minProperties":1,"additionalProperties":false},"bucket":{"type":"string","pattern":"\\S","description":"Key of the bucket an upload resolves to. Set this or bucket_tags, not both."},"bucket_tags":{"type":"array","items":{"type":"string"},"description":"Tags of the bucket an upload resolves to. Set this or bucket, not both."},"is_public":{"type":"boolean","description":"With no bucket named, picks the default public (true) or private (false) bucket; with a bucket named, asserts that bucket is public or private. Omitted, the bucket alone decides."},"enforce_fk":{"type":"boolean","description":"Strict mode: a real foreign key beside the column. Not implemented yet, so the backend refuses true.","default":false}},"not":{"required":["bucket","bucket_tags"]},"description":"Registers an existing upload, image or attachment column as a managed reference to a files row: it records which storage module the file lives in and which bucket an upload resolves to, and the backend generates the sync trigger and the GC index from that. The column must be declared in fields[] first; the node creates no column."},"DataForceCurrentUserParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to force to current_user_id()","default":"actor_id"}},"description":"BEFORE INSERT trigger that forces a field to the value of jwt_public.current_user_id(). Prevents clients from spoofing the actor/uploader identity. The field value is always overwritten regardless of what the client provides."},"DataGeneratedParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the generated column to create"},"type":{"type":"object","description":"FieldType for the generated column (default: text)","default":{"name":"text"}},"kind":{"type":"string","enum":["expression","concat","slug","object_name","hash"],"description":"Preset for building the generation expression","default":"expression"},"generation_type":{"type":"string","enum":["stored","virtual"],"description":"Whether the column is STORED (persisted on write) or VIRTUAL (computed on read, PostgreSQL 18+)","default":"stored"},"source_field":{"type":"string","format":"column-ref","description":"Single source field for expression/slug/object_name presets"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names for concat/hash presets"},"expression":{"type":"object","description":"Raw FieldGeneration DSL or AST (used when kind is expression)"},"separator":{"type":"string","description":"Separator used by concat preset","default":" "},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format for concat preset: 'labeled' (field_name: value) or 'plain' (values only)","default":"plain"},"prefix":{"type":"string","description":"Optional prefix for object_name preset"},"suffix":{"type":"string","description":"Optional suffix for object_name preset"},"algorithm":{"type":"string","description":"Hash algorithm for hash preset (e.g. sha256, md5)","default":"sha256"},"is_required":{"type":"boolean","description":"Whether the generated column is NOT NULL","default":false}},"required":["target"],"description":"Creates a native PostgreSQL GENERATED ALWAYS AS (expr) column (STORED or VIRTUAL) from a source field expression, preset, or raw AST. The column is read-only for clients and computed automatically by PostgreSQL."},"DataHistoryParams":{"type":"object","properties":{"table_suffix":{"type":"string","description":"Suffix for the history table name","default":"_history"},"recorded_at_field":{"type":"string","format":"column-ref","description":"Column name for the version timestamp (also the partition key when partitioned)","default":"recorded_at"},"operation_field":{"type":"string","format":"column-ref","description":"Column name recording the operation ('INSERT' | 'UPDATE' | 'DELETE')","default":"history_op"},"exclude_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Source columns to omit from the history table (e.g. large jsonb or vector columns). Excluded columns are never created on the history table and never written by the trigger.","default":[]},"copy_mutation_policies":{"type":"boolean","description":"Whether to also clone INSERT/UPDATE/DELETE policies (not just SELECT). Default false — the history table is written only by the trigger and exposed read-only through GraphQL.","default":false},"partitioned":{"type":"boolean","description":"When true, range-partition the history table by recorded_at via pg_partman so old partitions can be dropped per the retention window.","default":false},"partition_interval":{"type":"string","description":"pg_partman partition interval (when partitioned)","default":"1 month"},"retention":{"type":"string","description":"pg_partman retention window; partitions older than this are dropped by run_maintenance (when partitioned). Empty keeps forever.","default":"12 months"},"premake":{"type":"integer","description":"Number of future partitions pg_partman pre-creates","default":2}},"description":"Creates a companion
_history table that records a new version row on every INSERT/UPDATE/DELETE via an AFTER trigger. The history table copies the source columns as plain nullable columns with NO keys or constraints, plus a recorded_at timestamp and a history_op column (NEW-append: INSERT/UPDATE store the new row, DELETE stores a tombstone). SELECT policies are cloned from the base table. Optionally range-partitions the history table by recorded_at (pg_partman) with a retention window so history is kept for a while but not forever. Adds an @history smart comment so the Graphile history plugin can expose version queries and restore mutations."},"DataI18nParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the base table to make translatable. Each field is duplicated on the translation table with the same type."},"table_suffix":{"type":"string","description":"Suffix for the translation table name","default":"_translations"},"lang_code_type":{"type":"string","enum":["citext","text"],"description":"Type for the lang_code column","default":"citext"},"copy_mutation_policies":{"type":"boolean","description":"Whether to also copy INSERT/UPDATE/DELETE policies (not just SELECT). Default true — translations should be editable by the same users who can edit the base row.","default":true},"search":{"type":"object","description":"SearchFullText configuration for the translations table. When provided, creates a tsvector column on the translations table with lang_column=lang_code for dynamic per-row language stemming.","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column on the translations table","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the translatable source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"}},"required":["field"]},"description":"Translatable columns that feed the tsvector. Language is determined dynamically from the lang_code column of each row."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"]}},"required":["fields"],"description":"Creates a companion _translations table with lang_code + translatable fields. Copies SELECT policies and column-ref fields from the base table. Adds @i18n smart comment so the Graphile i18n plugin discovers it. Requires i18n_module to be provisioned for the database."},"DataIdParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the primary key","default":"id"}},"description":"Adds a UUID primary key column with auto-generation default (uuidv7). This is the standard primary key pattern for all tables."},"DataIdentityParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the identity column to create"},"type":{"type":"object","description":"FieldType for the identity column (default: bigint)","default":{"name":"bigint"}},"generation":{"type":"string","enum":["always","by_default"],"description":"'always' for GENERATED ALWAYS AS IDENTITY, 'by_default' for GENERATED BY DEFAULT AS IDENTITY","default":"by_default"},"sequence":{"type":"object","description":"Optional sequence tuning for the backing identity sequence","properties":{"start":{"type":"integer","description":"START WITH value"},"increment":{"type":"integer","description":"INCREMENT BY value"},"min":{"type":["integer","null"],"description":"MINVALUE (null uses the default)"},"max":{"type":["integer","null"],"description":"MAXVALUE (null uses the default)"},"cache":{"type":"integer","description":"CACHE value"},"cycle":{"type":"boolean","description":"Whether the sequence cycles (CYCLE / NO CYCLE)"}}},"is_required":{"type":"boolean","description":"Whether the identity column is NOT NULL (identity columns are implicitly NOT NULL)","default":false}},"required":["target"],"description":"Creates a native PostgreSQL identity column (GENERATED ALWAYS / BY DEFAULT AS IDENTITY) backed by an implicit sequence. The database assigns values automatically; ALWAYS identity columns are not writable by clients."},"DataImmutableFieldsParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names that cannot be modified after INSERT (e.g. [\"key\", \"bucket_id\", \"owner_id\"])"}},"required":["fields"],"description":"BEFORE UPDATE trigger that prevents changes to a list of specified fields after INSERT. Raises an exception if any of the listed fields have changed. Unlike FieldImmutable (single-field), this handles multiple fields in a single trigger for efficiency."},"DataInflectionParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to transform"},"ops":{"type":"array","items":{"type":"string","enum":["plural","singular","camel","pascal","dashed","slugify","underscore","lower","upper"]},"description":"Inflection operations to apply in order"}},"required":["field_name","ops"],"description":"Transforms field values using inflection operations (snake_case, camelCase, slugify, plural, singular, etc). Attaches BEFORE INSERT and BEFORE UPDATE triggers. References fields by name in data jsonb."},"DataInheritFromParentParams":{"type":"object","properties":{"parent_fk_field":{"type":"string","format":"column-ref","description":"Name of the FK field on this table that references the parent (e.g. bucket_id)"},"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to copy from the parent row (e.g. [\"owner_id\", \"is_public\"])"},"parent_table":{"type":"string","description":"Parent table name (optional fallback if FK not yet registered in metaschema)"},"parent_schema":{"type":"string","description":"Parent table schema (optional, defaults to same schema as child table)"}},"required":["parent_fk_field","fields"],"description":"BEFORE INSERT trigger that copies specified fields from a parent table via a foreign key. The parent row is looked up through RLS (SECURITY INVOKER), so the insert fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files."},"DataJsonbParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the JSONB field","default":"metadata"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false},"create_index":{"type":"boolean","description":"Whether to create a GIN index","default":true}},"description":"Adds a JSONB column with optional GIN index for containment queries (@>, ?, ?|, ?&). Standard pattern for semi-structured metadata."},"DataLockParams":{"type":"object","properties":{"lock_field":{"type":"string","format":"column-ref","description":"Boolean column holding the lock state","default":"locked"},"events":{"type":"array","items":{"type":"string","enum":["UPDATE","DELETE"]},"description":"Which DML events are guarded while the row is locked. INSERT is not lockable — a row cannot be locked before it exists.","default":["DELETE"]},"enforcement":{"type":"string","enum":["step_up","block"],"description":"How a guarded verb is stopped while locked. step_up requires recent strong verification (needs a provisioned user_auth_module); block refuses the verb outright with ROW_LOCKED until unlocked.","default":"step_up"},"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Verification method satisfying the step-up requirement, for the guarded verbs in step_up mode and for clearing the lock","default":"fresh_auth"},"guard_unlock":{"type":"boolean","description":"Require step-up to change the lock column itself, so a locked row cannot be quietly unlocked and then deleted. Redundant (and therefore skipped) in step_up mode when UPDATE is already guarded.","default":true},"protect_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For a guarded UPDATE, restrict the guard to changes touching these columns. Empty guards the whole row.","default":[]},"default_locked":{"type":"boolean","description":"Initial value of the lock column for new rows","default":false},"min_age":{"type":"string","description":"Optional interval (e.g. \"24 hours\"); in step_up mode the guard only fires for rows older than this, so freshly created rows stay easy to clean up. Empty guards rows of any age.","default":""}},"description":"Adds a boolean lock column and guards mutations while a row is locked, so infrastructure rows other things depend on (a bucket a function needs, a route, a resource) are not deleted or edited by accident. Two enforcement modes: step_up requires recent strong verification (via GuardStepUp / require_step_up) for the guarded verbs, while block refuses them outright until the row is unlocked. Clearing the lock is itself step-up guarded, so unlocking is a deliberate, re-authenticated step rather than a silent prelude to deletion."},"DataMemberOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true},"entity_type":{"type":"string","description":"Membership scope (e.g. 'org', 'room'). Resolved to a membership type via the database's membership_types_module. This is the authoring form — use it instead of membership_type."},"membership_type":{"type":"integer","description":"Membership type resolved from the scope. Internal: prefer entity_type. Cannot be combined with entity_type.","default":null}},"description":"Adds owner_id and entity_id columns with a compound AuthzMemberOwner policy. The current user must own the row and be a member of the entity it belongs to. Use for private data within an entity scope — e.g., personal chat threads that belong to the company but only the author can see."},"DataOwnedFieldsParams":{"type":"object","properties":{"role_key_field_name":{"type":"string","format":"column-ref","description":"Name of the field identifying the owner (e.g. sender_id)"},"protected_field_names":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Names of fields only this owner can modify"}},"required":["role_key_field_name","protected_field_names"],"description":"Restricts which user can modify specific columns in shared objects. Creates an AFTER UPDATE trigger that throws OWNED_PROPS when a non-owner tries to change protected fields. References fields by name in data jsonb."},"DataOwnershipInEntityParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true}},"description":"Combines direct ownership with entity scoping. Adds both owner_id and entity_id columns. Enables AuthzDirectOwner, AuthzEntityMembership, and AuthzOrgHierarchy authorization. Particularly useful for OrgHierarchy where a user owns a row (owner_id) within an entity (entity_id), and managers above can see subordinate-owned records via the hierarchy closure table."},"DataPeoplestampsParams":{"type":"object","properties":{"created_by_field":{"type":"string","format":"column-ref","description":"Column name for the creating user reference","default":"created_by"},"updated_by_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating user reference","default":"updated_by"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from created_by and updated_by to the users table","default":false},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the peoplestamp columns","default":true}},"description":"Adds human actor tracking for creates/updates: created_by/updated_by record the human user (jwt_public.current_user_id())."},"DataPrincipalstampsParams":{"type":"object","properties":{"created_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the creating principal reference (agent, API key, or user)","default":"created_by_principal"},"updated_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating principal reference (agent, API key, or user)","default":"updated_by_principal"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the principalstamp columns","default":true}},"description":"Adds acting-principal tracking for creates/updates: created_by_principal/updated_by_principal record the acting principal — agent, API key, service identity, or the user itself (jwt_public.current_principal_id())."},"DataPublishableParams":{"type":"object","properties":{"is_published_field_name":{"type":"string","format":"column-ref","description":"Column name for the published boolean flag","default":"is_published"},"published_at_field_name":{"type":"string","format":"column-ref","description":"Column name for the publish timestamp","default":"published_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds publish state columns (is_published, published_at) for content visibility. Enables AuthzPublishable and AuthzTemporal authorization."},"DataRealtimeParams":{"type":"object","properties":{"operations":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML operations to track with emit_change triggers","default":["INSERT","UPDATE","DELETE"]},"subscriber_table_name":{"type":"string","description":"Custom name for the subscriber table (defaults to {source_table}_subscriber)"},"ephemeral":{"type":"boolean","description":"When true, events are delivered via pg_notify only without writing to change_log. Ideal for high-frequency ephemeral signals (e.g. cursor positions, live indicators) where persistence is unnecessary. Subscriber table and RLS policies are still created for access control.","default":false}},"description":"Creates per-table subscriber tables in subscriptions_public with RLS policies derived from source table SELECT policies. Attaches statement-level triggers to emit changes to subscribers."},"DataSlugParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to slugify","default":"slug"},"source_field_name":{"type":"string","format":"column-ref","description":"Optional source field name (defaults to field_name)"}},"required":[],"description":"Auto-generates URL-friendly slugs from field values on insert/update. Attaches BEFORE INSERT and BEFORE UPDATE triggers that call inflection.slugify() on the target field. References fields by name in data jsonb."},"DataSoftDeleteParams":{"type":"object","properties":{"deleted_at_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete timestamp","default":"deleted_at"},"is_deleted_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete boolean flag","default":"is_deleted"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds soft delete support with deleted_at and is_deleted columns."},"DataStatusFieldParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the status field","default":"status"},"type":{"$ref":"#/$defs/FieldType","description":"Column type as a FieldType object"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object (e.g., { value: \"active\" })"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":true},"allowed_values":{"type":"array","items":{"type":"string"},"description":"If provided, creates a CHECK constraint restricting the column to these values"}},"description":"Adds a status column with B-tree index for efficient equality filtering and sorting. Optionally constrains values via CHECK constraint when allowed_values is provided."},"DataTagsParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the tags array","default":"tags"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false}},"description":"Adds a citext[] tags column with GIN index for efficient array containment queries (@>, &&). Standard tagging pattern for categorization and filtering."},"DataTimestampsParams":{"type":"object","properties":{"created_at_field":{"type":"string","format":"column-ref","description":"Column name for the creation timestamp","default":"created_at"},"updated_at_field":{"type":"string","format":"column-ref","description":"Column name for the last-updated timestamp","default":"updated_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds automatic timestamp tracking with created_at and updated_at columns."},"EventReferralParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record for the referrer (e.g., \"invitee_uploaded_avatar\", \"invitee_completed_onboarding\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the invitee (actor) ID on the source table — used to look up the referrer via claimed_invites.receiver_id","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped referral events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"max_depth":{"type":"integer","description":"Maximum depth to walk up the invite chain. Default 1 (direct inviter only). Set 2–10 to enable multi-level referral rewards. App-level only — must not be combined with entity_field.","default":1,"minimum":1,"maximum":10},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events for the referrer (inviter) when their invitees perform actions on a watched table. Resolves the referrer automatically via the invites module's claimed_invites table using the membership_type context. Supports the same compound condition system as EventTracker. Use with achievements to unlock levels and grant credits based on invitee activity."},"EventTrackerParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record (e.g., \"avatar_uploaded\", \"order_completed\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"count":{"type":"integer","description":"Number of events to record per trigger fire","default":1},"toggle":{"type":"boolean","description":"Toggle mode: records event when condition is met, removes when condition is unmet","default":false},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the actor (user) ID to attribute the event to","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events via the events module when table rows change. Supports the same compound condition system as JobTrigger (condition_field, watch_fields, or full AND/OR/NOT conditions). Events are recorded to app_events and aggregated automatically. Use with achievements (blueprint-level) to unlock levels and grant credits based on event accumulation."},"FieldDefault":{"type":"object","description":"A structured default expression, e.g. { value: false }, { function: \"now\" } or { value: {}, cast: { name: \"jsonb\" } }.","properties":{"value":{"description":"Literal value."},"function":{"type":"string","description":"Function name."},"schema":{"type":"string","description":"Schema qualifier of the function."},"args":{"type":"array","items":{"anyOf":[{"type":["string","number","boolean","null"]},{"$ref":"#/$defs/FieldDefault"}]},"description":"Function arguments."},"cast":{"$ref":"#/$defs/FieldType"},"operator":{"type":"string","description":"Binary operator, e.g. \"+\"."},"left":{"$ref":"#/$defs/FieldDefault"},"right":{"$ref":"#/$defs/FieldDefault"},"sql_keyword":{"type":"string","description":"SQL keyword, e.g. \"CURRENT_TIMESTAMP\"."}}},"FieldType":{"type":"object","description":"A structured PostgreSQL type, e.g. { name: \"text\" } or { name: \"numeric\", args: [10, 2] }.","properties":{"name":{"type":"string","description":"Type name."},"schema":{"type":"string","description":"Schema qualifier."},"args":{"type":"array","items":{"type":["string","number","boolean"]},"description":"Type arguments."},"array_dimensions":{"type":"integer","description":"Number of array dimensions: 1 is text[]."},"range":{"type":"array","items":{"type":"string"},"maxItems":2,"description":"Interval field range, e.g. [\"day\", \"second\"]."}},"required":["name"]},"GuardStepUpParams":{"type":"object","properties":{"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Which recent proof satisfies the step-up requirement: password (password re-entry), mfa (second factor), password_or_mfa (either factor; an SSO sign-in alone does not count), or fresh_auth (any recent sign-in or re-verification, including SSO, magic link and OTP)","default":"fresh_auth"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML events require step-up verification","default":["UPDATE","DELETE"]},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":[],"description":"Attaches a BEFORE trigger that calls require_step_up() to enforce recent strong verification (password, MFA, or identity-provider assertion) before allowing mutations. Requires a provisioned sessions_module (with app_settings_auth) for the target database. The step_up_window is read from app_settings_auth at runtime (default 30 minutes). Supports compound conditions (AND/OR/NOT), watch_fields (fire only when specific fields change), and simple condition_field/condition_value leaf conditions."},"JobTriggerParams":{"type":"object","properties":{"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier passed to add_job (e.g., process_invoice, sync_to_stripe). Must match a registered function definition when function_module is installed."},"payload_strategy":{"type":"string","enum":["row","row_id","fields","custom"],"description":"How to build the job payload: row (full NEW/OLD), row_id (just id), fields (selected columns), custom (mapped columns)","default":"row_id"},"payload_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names to include in payload (only for fields strategy)"},"payload_custom":{"type":"object","additionalProperties":{"type":"string","format":"column-ref"},"description":"Key-to-column mapping for custom payload (e.g., {\"invoice_id\": \"id\", \"total\": \"amount\"})"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Trigger events to create","default":["INSERT","UPDATE"]},"include_old":{"type":"boolean","description":"Include OLD row in payload (for UPDATE triggers)","default":false},"include_meta":{"type":"boolean","description":"Include table/schema metadata in payload","default":false},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"$ref":"#/$defs/shared-6b829f5502"},"obj_schema":{"$ref":"#/$defs/shared-11a9ffe32a"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"job_key":{"type":"string","description":"Static job key for upsert semantics (prevents duplicate jobs)"},"queue_name":{"type":"string","description":"Job queue name for routing to specific workers"},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0},"run_at_delay":{"type":"string","description":"Delay before job runs as PostgreSQL interval (e.g., 30 seconds, 5 minutes)"},"max_attempts":{"type":"integer","description":"Maximum retry attempts for the job","default":25}},"required":["task_identifier"],"description":"Dynamically creates PostgreSQL triggers that enqueue jobs via app_jobs.add_job() when table rows are inserted, updated, or deleted. Supports configurable payload strategies (full row, row ID, selected fields, or custom mapping), conditional firing via WHEN clauses, watched field changes, and extended job options (queue, priority, delay, max attempts)."},"LimitEnforceAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to track (must match a default_limits entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches aggregate limit-tracking triggers to a table. On INSERT the named limit is incremented per entity; on DELETE it is decremented. Uses org_limit_aggregates_inc/dec for per-entity (org-level) aggregate limits rather than per-user limits. Requires a provisioned limits_module for the target database."},"LimitEnforceCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to track (must match a default_limits entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor or entity id used for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for entity context resolution. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches limit-tracking triggers to a table. On INSERT the named limit is incremented; on DELETE it is decremented. Requires a provisioned limits_module for the target scope."},"LimitEnforceFeatureParams":{"type":"object","properties":{"feature_name":{"type":"string","description":"Cap name representing this feature (must match a limit_caps_defaults entry with max=0 or max=1)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for per-entity cap lookups (only used for org scope). For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["feature_name"],"description":"Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE INSERT trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0)."},"LimitEnforceRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry, e.g. \"messaging\", \"inference\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limiting. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id (user) for rate limiting","default":"owner_id"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Which DML events to enforce rate limits on (DELETE is excluded since it reduces load)","default":["INSERT"]}},"required":["meter_slug"],"description":"Attaches a BEFORE trigger that calls check_rate_limit() to enforce sliding-window rate limits before allowing mutations. The function checks all three scopes (entity, actor-in-entity, actor) in a single call; which scopes are actually enforced is controlled by what rows exist in rate_window_limits (plan-based config). Requires a provisioned meter_rate_limits_module and billing_module for the target database."},"LimitTrackUsageParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to record usage against (must match a meters table entry, e.g. \"databases\", \"seats\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for billing. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"quantity":{"type":"integer","description":"Units to record per event (default 1)","default":1},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["meter_slug"],"description":"Declaratively attaches billing usage-recording triggers to a table. On INSERT the named meter is incremented via record_usage; on DELETE it is decremented (reversal). On UPDATE, if the entity_field changes, the old entity is decremented and the new entity is incremented. Requires a provisioned billing_module for the target database."},"LimitWarningAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to watch (must match a limit_warnings.name entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the entity's aggregate usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor/entity triple. Requires a provisioned limits_module with limit_warnings and aggregate limits enabled."},"LimitWarningCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to watch (must match a limit_warnings.name entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id. When provided, entity_id is included in the job payload and dedup state. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires a provisioned limits_module with limit_warnings enabled."},"LimitWarningRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use for warnings and warning_state tables. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for rate limit lookup","default":"owner_id"}},"required":["meter_slug"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current request count in the active sliding window has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires both a limits_module with limit_warnings enabled and a rate_limit_meters_module."},"ProcessChunksParams":{"type":"object","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"dimensions":{"type":"integer","description":"Vector dimensions for per-chunk embeddings","default":768},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric for the HNSW index on chunk embeddings","default":"cosine"},"embedding_model":{"type":"string","description":"Embedding model identifier for per-chunk embeddings. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"chunks_table_name":{"type":"string","description":"Override the chunks table name. Defaults to {parent_table}_chunks."},"metadata_fields":{"type":"array","items":{"type":"string"},"description":"Field names from the parent table to copy into chunk metadata"},"search_indexes":{"type":"array","items":{"$ref":"#/$defs/shared-5492e6a87c"},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override (e.g. [\"fulltext\", \"bm25\"])."},"entity_field":{"type":"string","format":"column-ref","description":"Column on the parent table that holds (or references) the entity_id for billing scope. Forwarded to the chunking job trigger."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the chunking job trigger.","properties":{"obj_table":{"$ref":"#/$defs/shared-462d3d2412"},"obj_schema":{"$ref":"#/$defs/shared-3d0fa23a34"},"obj_field":{"$ref":"#/$defs/shared-d4553f7be9"}},"required":["obj_table","obj_field"]},"enqueue_chunking_job":{"type":"boolean","description":"Whether to create a job trigger that auto-enqueues chunking on parent INSERT/UPDATE","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}},"description":"Creates a chunked-embedding child table for any parent table. Provisions the chunks table with content, chunk_index, embedding vector, metadata, HNSW index, inherited RLS, and optional job trigger for automatic text splitting. Composed internally by ProcessFileEmbedding (enabled by default in extract mode) but can also be used standalone."},"ProcessExtractionParams":{"type":"object","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"extraction_model":{"type":"string","description":"Extraction model identifier (e.g. a vision model for OCR, an LLM for structured extraction). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config."},"extraction_provider":{"type":"string","description":"Extraction provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%'].","default":["application/pdf","text/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the extraction worker","default":"document:extract_file_text"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for extraction tasks","default":"extraction"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates extraction output fields and a job trigger for file text extraction. Fires when a file is uploaded (status = 'uploaded') or on INSERT. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks."},"ProcessFileEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 512 for CLIP, 768 for nomic, 1536 for ada-002)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\", \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%'].","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the worker. In direct mode this is the embedding worker; in extract mode this is the extraction worker.","default":"embedding:process_file_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"source_bucket":{"type":"object","description":"Typed bucket reference ({\"$ref\":\"bucket\",\"tags\":[...],\"type\":...}) for the bucket the source files live in, when it is not the record's own bucket_id (which payload_custom already carries). Stamped into the trigger payload at attach time and resolved to coordinates at dispatch.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"variants_bucket":{"type":"object","description":"Typed bucket reference for where derived outputs (thumbnails, resized variants, extracted assets) are written. Stamped into the trigger payload at attach time and resolved to coordinates at dispatch, so the function never selects a bucket.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"type":"object","description":"Text extraction configuration. When present, the generator creates extraction output fields on the table and configures SearchVector with source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction).","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"}}},"include_chunks":{"type":"boolean","description":"Whether to create a chunks table via ProcessChunks. Defaults to true when extraction is provided, false in direct mode. Set explicitly to override."},"chunks":{"type":"object","description":"Chunking configuration passed through to ProcessChunks. When include_chunks is true (or defaults to true in extract mode), these params configure the chunks table, embedding dimensions, strategy, etc.","default":{},"properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"metadata_fields":{"type":"array","items":{"type":"string"},"description":"Field names from parent to copy into chunk metadata"},"search_indexes":{"type":"array","items":{"$ref":"#/$defs/shared-5492e6a87c"},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override."},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}},"description":"Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies."},"ProcessImageEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (default 512 for CLIP-style image embeddings)","default":512},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image embedding worker","default":"embedding:process_image_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"type":"object","description":"Text extraction configuration. Forwarded to ProcessFileEmbedding. When present, enables extract mode (e.g., OCR for images).","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata","default":"extracted_metadata"}}},"chunks":{"type":"object","description":"Chunking configuration. Forwarded to ProcessFileEmbedding. Only meaningful when extraction is also provided.","properties":{"content_field_name":{"type":"string","format":"column-ref","default":"content"},"chunk_size":{"type":"integer","default":1000},"chunk_overlap":{"type":"integer","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"default":"paragraph"},"metadata_fields":{"type":"object"},"enqueue_chunking_job":{"type":"boolean","default":true},"chunking_task_name":{"type":"string","format":"function-ref","default":"embedding:chunk_record"}}}},"description":"Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_image_embedding', direct mode (no extraction). Accepts all ProcessFileEmbedding parameters — any overrides are forwarded through."},"ProcessImageVersionsParams":{"type":"object","required":["versions"],"properties":{"versions":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","description":"Version identifier (e.g., \"thumb\", \"preview\", \"hero\")"},"width":{"type":"integer","description":"Target width in pixels"},"height":{"type":"integer","description":"Target height in pixels"},"fit":{"type":"string","enum":["cover","contain","fill","inside","outside"],"description":"Resize fitting strategy","default":"cover"},"format":{"type":"string","enum":["jpeg","png","webp","avif"],"description":"Output image format","default":"webp"},"quality":{"type":"integer","description":"Output quality (1-100)","default":80}},"required":["name"]},"description":"Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Required — the blueprint must explicitly define what variants to generate.","minItems":1},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Defaults to all image types.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image processing worker","default":"image:process_image_versions"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for image processing tasks","default":"image_processing"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates a job trigger for image variant generation. Fires when an image file is uploaded (status = 'uploaded') or on INSERT. The external worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.) and stores them as new file records linked to the source image."},"SearchBm25Params":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of existing text column to index with BM25"},"text_config":{"type":"string","description":"PostgreSQL text search configuration for BM25","default":"english"},"k1":{"type":"number","description":"BM25 k1 parameter: term frequency saturation (typical: 1.2-2.0)","default":null},"b":{"type":"number","description":"BM25 b parameter: document length normalization (0=none, 1=full, typical: 0.75)","default":null},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["field_name"],"description":"Creates a BM25 index on an existing text column using pg_textsearch. Enables statistical relevance ranking with configurable k1 and b parameters. The BM25 index is auto-detected by graphile-search."},"SearchFullTextParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"},"lang":{"type":"string","description":"PostgreSQL text search configuration","default":"english"}},"required":["field"]},"description":"Source columns that feed the tsvector. Each has a field name, weight (A-D), and language config."},"lang_column":{"type":"string","format":"column-ref","description":"Column name whose value determines the text search configuration per row. When set, the tsvector trigger uses NEW.::regconfig instead of a static language, enabling dynamic per-row language stemming. The per-field lang values in source_fields are used as fallback defaults for the langs array but the trigger reads from this column at runtime."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"],"description":"Adds a tsvector column with GIN index and automatic trigger population from source fields. Enables PostgreSQL full-text search with configurable weights and language support. Leverages the existing metaschema full_text_search infrastructure."},"SearchSpatialAggregateParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the aggregate geometry column on the parent table","default":"geom_aggregate"},"source_table_id":{"type":"string","format":"uuid","description":"UUID of the source (child) table containing individual geometries"},"source_geom_field":{"type":"string","format":"column-ref","description":"Name of the geometry column on the source table","default":"geom"},"source_fk_field":{"type":"string","format":"column-ref","description":"Name of the foreign key column on the source table pointing to the parent"},"aggregate_function":{"type":"string","enum":["union","collect","convex_hull","concave_hull"],"description":"PostGIS aggregation function: union (ST_Union, merges overlapping), collect (ST_Collect, groups without merging), convex_hull (smallest convex polygon), concave_hull (tighter boundary)","default":"union"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"Output geometry type constraint for the aggregate field","default":"MultiPolygon"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method for the aggregate field","default":"gist"}},"required":["source_table_id","source_fk_field"],"description":"Creates a derived/materialized geometry field on the parent table that automatically aggregates geometries from a source (child) table via triggers. When child rows are inserted/updated/deleted, the parent aggregate field is recalculated using the specified PostGIS aggregation function (ST_Union, ST_Collect, ST_ConvexHull, ST_ConcaveHull). Useful for materializing spatial boundaries from collections of points or polygons."},"SearchSpatialParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the geometry/geography column","default":"geom"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"PostGIS geometry type constraint","default":"Point"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry (for geodetic calculations on the sphere)","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method","default":"gist"}},"description":"Adds a PostGIS geometry or geography column with a spatial index (GiST or SP-GiST). Supports configurable geometry types (Point, Polygon, etc.), SRID, and dimensionality. The graphile-postgis plugin auto-detects geometry/geography columns by codec type for spatial filtering (ST_Contains, ST_DWithin, bbox operators)."},"SearchTrgmParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to create trigram indexes on (fields must already exist on the table)"}},"required":["fields"],"description":"Creates GIN trigram indexes (gin_trgm_ops) on specified text/citext fields for fuzzy LIKE/ILIKE/similarity search. Adds @trgmSearch smart tag for PostGraphile integration. Fields must already exist on the table."},"SearchUnifiedParams":{"type":"object","properties":{"full_text_search":{"type":"object","description":"SearchFullText parameters. Omit to skip FTS setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"weight":{"type":"string","enum":["A","B","C","D"]},"lang":{"type":"string"}},"required":["field"]}},"search_score_weight":{"type":"number","default":1}}},"bm25":{"type":"object","description":"SearchBm25 parameters. Omit to skip BM25 setup.","properties":{"field_name":{"type":"string","format":"column-ref"},"text_config":{"type":"string","default":"english"},"k1":{"type":"number"},"b":{"type":"number"},"search_score_weight":{"type":"number","default":1}}},"embedding":{"type":"object","description":"SearchVector parameters. Omit to skip embedding setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"embedding"},"dimensions":{"type":"integer","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"]},"metric":{"type":"string","enum":["cosine","l2","ip"]},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"}},"embedding_model":{"type":"string","description":"Embedding model identifier. When null, the worker falls back to runtime config."},"embedding_provider":{"type":"string","description":"Embedding provider name. When null, the worker falls back to runtime config."},"search_score_weight":{"type":"number","default":1},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}}},"embedding_text_field":{"type":"string","format":"column-ref","description":"Name of the composite text field created for embedding input","default":"embedding_text"},"composite_format":{"type":"string","enum":["labeled","plain"],"description":"Output format for the composite text field","default":"labeled"},"trgm_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to tag with @trgmSearch for fuzzy/typo-tolerant matching"},"search_config":{"type":"object","description":"Unified search score configuration written to @searchConfig smart tag","properties":{"weights":{"type":"object","description":"Per-algorithm weights: {tsv: 1.5, bm25: 1.0, pgvector: 0.8, trgm: 0.3}"},"normalization":{"type":"string","enum":["linear","sigmoid"],"description":"Score normalization strategy","default":"linear"},"boost_recent":{"type":"boolean","description":"Enable recency boost for search results","default":false},"boost_recency_field":{"type":"string","format":"column-ref","description":"Timestamp field for recency boost (e.g. created_at, updated_at)"},"boost_recency_decay":{"type":"number","description":"Decay rate for recency boost (0-1, lower = faster decay)","default":0.5}}}},"description":"Composite node type that orchestrates multiple search modalities (full-text search, BM25, embeddings, trigram) on a single table. Configures per-table search score weights, normalization strategy, and recency boost via the @searchConfig smart tag."},"SearchVectorParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 384, 768, 1536, 3072)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric (cosine, l2, ip)","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names that feed the embedding. Used by stale trigger to detect content changes."},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"enqueue_job":{"type":"boolean","description":"Auto-create trigger that enqueues embedding generation jobs","default":true},"job_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the job queue. Must match a registered function definition when function_module is installed.","default":"embedding:embed_record"},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue. Must match a registered function definition when function_module is installed.","default":"embedding:chunk_record"}}}},"description":"Adds a vector embedding column with HNSW or IVFFlat index for similarity search. Supports configurable dimensions, distance metrics (cosine, l2, ip), per-field {field_name}_updated_at timestamp tracking (read-only in GraphQL), and automatic job enqueue triggers for embedding generation."},"TableOrganizationSettingsParams":{"type":"object","properties":{},"description":"Creates an organization settings table with standard business fields (legal_name, address fields). Uses AuthzEntityMembership for access control."},"TableUserProfilesParams":{"type":"object","properties":{},"description":"Creates a user profiles table with standard profile fields (profile_picture, bio, first_name, last_name, tags, desired). Uses AuthzDirectOwner for edit access and AuthzAllowAll for select."},"TableUserSettingsParams":{"type":"object","properties":{},"description":"Creates a user settings table for user-specific configuration. Uses AuthzDirectOwner for access control."},"TriggerCondition":{"type":"object","properties":{"field":{"type":"string","description":"Column name (validated against the table)."},"op":{"enum":["=","!=",">","<",">=","<=","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS DISTINCT FROM"],"description":"Comparison operator."},"value":{"description":"Comparison value. Type is resolved from the column definition."},"row":{"enum":["NEW","OLD"],"description":"Row reference (default: NEW)."},"ref":{"type":"object","properties":{"field":{"type":"string"},"row":{"enum":["NEW","OLD"]}},"description":"Column reference for field-to-field comparison (alternative to value)."},"AND":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with AND."},"OR":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with OR."},"NOT":{"$ref":"#/$defs/TriggerCondition","description":"Negated condition."}},"description":"Recursive condition type for compound trigger WHEN clauses. Leaf conditions specify {field, op, value?, row?, ref?}. Combinators nest via AND, OR, NOT."},"shared-001d8d7cd3":{"anyOf":[{"required":["obj_table_id"]},{"required":["obj_schema","obj_table"]}]},"shared-0165627a32":{"type":"array","items":{"type":"string"},"description":"Capability names of any kind (capability, level, ...) merged into the same mask"},"shared-040cc005ef":{"type":"array","minItems":1,"items":{"$ref":"#/$defs/AuthzExpression"}},"shared-0596961db6":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberListParams"}}}},"shared-066977ff2f":{"anyOf":[{"required":["obj_field"]},{"required":["obj_field_id"]}]},"shared-078ee82414":{"properties":{"$type":{"const":"CheckOneOf"}},"required":["$type"]},"shared-0968d06284":{"type":"string","description":"Schema of the join table (or use obj_table_id)"},"shared-0a22d2c3f6":{"type":"string","description":"Single column name for the index."},"shared-11809f0714":{"if":{"properties":{"$type":{"const":"AuthzMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberListParams"}}}},"shared-11a9ffe32a":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"shared-13aff2afe8":{"type":"string","description":"The member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-152f619c56":{"if":{"properties":{"$type":{"const":"AuthzDenyAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDenyAllParams"}}}},"shared-15602a740a":{"properties":{"$type":{"const":"AuthzEntityMembership"}},"required":["$type"]},"shared-1a317ed066":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger."},"shared-1a97ddc6fb":{"if":{"properties":{"$type":{"const":"AuthzRelatedPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"}}}},"shared-1c8d46d43b":{"properties":{"$type":{"const":"CheckNotEqual"}},"required":["$type"]},"shared-1ca2c9bd61":{"type":"array","description":"Join conditions between the protected row and the referenced table","items":{"type":"object","properties":{"local_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table"},"ref_column":{"$ref":"#/$defs/shared-7539b204c0"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"shared-21a1ba9587":{"if":{"properties":{"$type":{"const":"AuthzAppMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMembershipParams"}}}},"shared-22f38cc906":{"type":"array","items":{"type":"string"},"description":"Operator classes for the index columns."},"shared-230094622e":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"obj_field":{"type":"string","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"shared-2997c2f821":{"if":{"properties":{"$type":{"const":"AuthzSystemOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzSystemOnlyParams"}}}},"shared-2a834ba4ff":{"type":"string","description":"Index access method (e.g., \"BTREE\", \"GIN\", \"GIST\", \"HNSW\", \"BM25\")."},"shared-2c17992067":{"properties":{"$type":{"const":"AuthzNotReadOnly"}},"required":["$type"]},"shared-2c20767ba3":{"properties":{"$type":{"const":"CheckGreaterThan"}},"required":["$type"]},"shared-3245b618eb":{"properties":{"$type":{"const":"AuthzValueMatch"}},"required":["$type"]},"shared-33013a269d":{"if":{"properties":{"$type":{"const":"AuthzRelatedEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"}}}},"shared-33af0ede37":{"type":"string","format":"column-ref","description":"Single column to compare against value (mutually exclusive with columns)"},"shared-34021cf1ff":{"properties":{"$type":{"const":"AuthzDirectOwnerAny"}},"required":["$type"]},"shared-36ea8e912e":{"if":{"properties":{"$type":{"const":"AuthzDatabaseClaim"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDatabaseClaimParams"}}}},"shared-39f66ad592":{"if":{"properties":{"$type":{"const":"AuthzAllowAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAllowAllParams"}}}},"shared-3a33134347":{"type":"object","description":"Metadata fields from parent to copy into chunks"},"shared-3d0fa23a34":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"shared-3fc6945ad1":{"if":{"properties":{"$type":{"const":"AuthzValueExists"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueExistsParams"}}}},"shared-411f8ee76d":{"type":"string","description":"Schema of the referenced table (or use ref_table_id)"},"shared-433a283165":{"properties":{"$type":{"const":"AuthzRelatedMemberOwner"}},"required":["$type"]},"shared-462d3d2412":{"type":"string","description":"Name of the related table to look up entity_id from"},"shared-47ab73adbe":{"properties":{"$type":{"const":"AuthzDirectOwner"}},"required":["$type"]},"shared-48649a3a43":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"}},"shared-49ec07b1f5":{"properties":{"$type":{"const":"AuthzAppMemberOwner"}},"required":["$type"]},"shared-4f25156f61":{"if":{"properties":{"$type":{"const":"AuthzPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPeerOwnershipParams"}}}},"shared-5192cb016d":{"properties":{"$type":{"const":"AuthzRelatedPeerOwnership"}},"required":["$type"]},"shared-51c1d9a5f0":{"type":"string","minLength":1,"not":{"const":"app"},"description":"Entity type prefix (e.g. 'org', 'channel', 'department'), resolved to its membership_type; use it instead of membership_type for readability."},"shared-5492e6a87c":{"type":"string","enum":["fulltext","bm25","trigram"]},"shared-55595a36d2":{"type":["array","object"],"items":{"type":"object"},"description":"Optional higher-level condition JSON applied to the referenced table (row alias d)"},"shared-57b27779bd":{"properties":{"$type":{"const":"AuthzValueAllowed"}},"required":["$type"]},"shared-584ca266e8":{"properties":{"$type":{"const":"AuthzRelatedMemberList"}},"required":["$type"]},"shared-5a2832df1c":{"type":"array","items":{"type":"string"},"description":"Array of column names for a multi-column index."},"shared-5e11bfeb01":{"type":"boolean","description":"If true, require is_owner flag on current user membership"},"shared-5f5453df14":{"properties":{"$type":{"const":"AuthzFilePath"}},"required":["$type"]},"shared-626b0c3c0b":{"type":"array","items":{"$ref":"#/$defs/BlueprintFtsSource"},"description":"Source fields that feed into this tsvector."},"shared-637ef72440":{"type":"string","pattern":"^[01]+$","description":"Capability bits a member must hold, as a bit string. Capabilities or levels, when given, replace it."},"shared-6639e33d04":{"if":{"properties":{"$type":{"const":"AuthzComposite"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzCompositeParams"}}}},"shared-698b2fd59a":{"type":"integer","minimum":2,"maximum":2147483647,"description":"The team kind: 2=org, 3+=dynamic entity types."},"shared-6adc1df48e":{"type":"string","description":"Optional schema name for disambiguation (falls back to top-level default)."},"shared-6b829f5502":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"shared-6dbc2f5a83":{"if":{"properties":{"$type":{"const":"AuthzPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPublishableParams"}}}},"shared-6eb30390ff":{"type":"string","enum":["INSERT","DELETE","UPDATE"]},"shared-7539b204c0":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table"},"shared-757c15800e":{"type":"string","description":"Name of the CHECK constraint."},"shared-787b8adf81":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Additional compound conditions beyond auto-generated filtering. Merged with the auto-generated conditions via AND."},"shared-7a53e1103e":{"type":"boolean","description":"Select sel_field from the related row instead of the team id; the platform's own related policies set it with sel_field \"id\"."},"shared-7edb884d72":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from"},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"}},"required":["obj_table","obj_field"]},"shared-7f50b0e5b7":{"type":"string","description":"Name of the referenced table (or use ref_table_id)"},"shared-8358853df2":{"properties":{"$type":{"const":"CheckLessThan"}},"required":["$type"]},"shared-85b2c2543e":{"if":{"properties":{"$type":{"const":"AuthzEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzEntityMembershipParams"}}}},"shared-8763e18b77":{"anyOf":[{"required":["membership_type"]},{"required":["entity_type"]},{"required":["sprt_schema","sprt_table"]}]},"shared-88656ecafa":{"type":"string","format":"column-ref","description":"Column name for conditional WHEN clause (fires only when field equals condition_value)"},"shared-8881b94a41":{"if":{"properties":{"$type":{"const":"AuthzTemporal"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzTemporalParams"}}}},"shared-89ec3722aa":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"}}}},"shared-8cc6b29877":{"type":"string","format":"uuid","description":"UUID of the referenced table (alternative to ref_schema/ref_table)"},"shared-8cef65cfda":{"type":"object","additionalProperties":{"oneOf":[{"type":"string","format":"column-ref"},{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"path":{"type":"array","items":{"type":"string"},"minItems":1}},"required":["field","path"]}]},"description":"Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({\"field\": \"upload\", \"path\": [\"key\"]}). Defaults to the four file columns, or to the file_field document when file_field is set."},"shared-8e6e495eb6":{"if":{"properties":{"$type":{"const":"AuthzNotReadOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzNotReadOnlyParams"}}}},"shared-9146e81ef6":{"type":"string","format":"uuid","description":"UUID of the join table (alternative to obj_schema/obj_table)"},"shared-927486214a":{"type":"boolean","description":"If true, require is_admin flag"},"shared-9572999fa8":{"type":"string","description":"The schema of the member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-97d5c3be03":{"properties":{"$type":{"const":"AuthzOrgHierarchy"}},"required":["$type"]},"shared-9af2f9702a":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'."},"shared-9d6147637c":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id, org_id)"},"shared-a0bfcadf85":{"type":"array","items":{"type":"string"},"description":"Column names that form the unique constraint."},"shared-a2c45e97d1":{"if":{"properties":{"$type":{"const":"AuthzDirectOwnerAny"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"}}}},"shared-a9d73b8ba7":{"if":{"properties":{"$type":{"const":"AuthzMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberOwnerParams"}}}},"shared-ab071ec2f8":{"type":"boolean","description":"If true, require is_owner flag"},"shared-ab15ceab40":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations."},"shared-ac9a0977fa":{"type":"string","description":"Embedding provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"shared-aced6572ca":{"if":{"properties":{"$type":{"const":"AuthzHumanOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzHumanOnlyParams"}}}},"shared-ad437cb66f":{"type":"string","format":"column-ref","x-column-scope":"local"},"shared-ad8f69741a":{"type":"string","description":"Optional schema name override."},"shared-af38a22089":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch"]},"shared-b0876b5627":{"type":"array","items":{"type":"string"},"description":"Achievement level names to require (kind=level catalog rows, merged into the same mask)"},"shared-b1944d8f7b":{"description":"Allowed values as a constant list, or a local column name containing the allowed values","anyOf":[{"type":"string","format":"column-ref","x-column-scope":"local","description":"Local column name containing allowed values"},{"type":"array","items":{"type":["string","boolean","number","null"]},"description":"Constant list of allowed values. Element JSON type is preserved: booleans/numbers emit typed constants (e.g. [true] -> TRUE, [5] -> 5), strings emit text literals."}]},"shared-b1dc7b2e4f":{"properties":{"$type":{"const":"AuthzPeerOwnership"}},"required":["$type"]},"shared-b68f53d1ed":{"type":"integer","description":"The width the mask is padded to; by default the length of the mask."},"shared-bb55f34041":{"type":"boolean","description":"Whether this is a unique index."},"shared-bc381c03de":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{}}},"required":["roles","privileges"]},"shared-c1527c6159":{"if":{"properties":{"$type":{"const":"AuthzValueMatch"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueMatchParams"}}}},"shared-c2c61348f0":{"if":{"properties":{"$type":{"const":"AuthzOrgHierarchy"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzOrgHierarchyParams"}}}},"shared-c5c620bfe3":{"type":"string","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. A zero mask requires nothing."},"shared-c88c54a5c5":{"if":{"properties":{"$type":{"const":"AuthzValueAllowed"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueAllowedParams"}}}},"shared-c893ee8510":{"if":{"properties":{"$type":{"const":"AuthzDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerParams"}}}},"shared-cc52e308f2":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Compound conditions for the trigger WHEN clause. Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema. Cannot be combined with condition_field or watch_fields."},"shared-cd4dc6cdf6":{"type":"string","description":"Name of the join table (or use obj_table_id)"},"shared-d3e6ac0b5d":{"type":"boolean","description":"If true, require is_admin flag on current user membership"},"shared-d4553f7be9":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"},"shared-d85a10e177":{"type":"object","description":"Reference to a table an installed module generated, resolved during blueprint construction (alternative to ref_table_id / ref_schema + ref_table)","properties":{"type":{"type":"string","description":"Module type owning the table, e.g. \"agent\""},"table":{"type":"string","description":"Logical table key within the module, e.g. \"thread\""},"scope":{"type":"string","description":"Scope of the module instance, e.g. \"app\" or \"org\""},"prefix":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations"}},"required":["type","table"]},"shared-d8e76848ea":{"type":"string","format":"uuid","description":"UUID of field on join table (alternative to obj_field)"},"shared-d91c021eee":{"properties":{"$type":{"const":"AuthzMemberOwner"}},"required":["$type"]},"shared-db0e2e6361":{"type":"string","format":"uuid","description":"Table being referenced by the FK"},"shared-dfbaf50fc6":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the join table"},"shared-e1125a4a5e":{"type":"string","description":"Scope of the module instance (e.g. \"app\", \"org\"). Required when the database installs the module at more than one scope."},"shared-e23bde2ba6":{"properties":{"$type":{"const":"AuthzValueExists"}},"required":["$type"]},"shared-e3e4ac8f48":{"if":{"properties":{"$type":{"const":"AuthzFilePath"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzFilePathParams"}}}},"shared-e6dbbbcd8d":{"type":"string","enum":["c","r","n","d","a"],"description":"FK delete action: c=CASCADE, r=RESTRICT, n=SET NULL, d=SET DEFAULT, a=NO ACTION. Required."},"shared-e772a2f2a5":{"type":"object","additionalProperties":{},"description":"Additional index-specific options."},"shared-eb6d498d14":{"if":{"properties":{"$type":{"const":"AuthzAppMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"}}}},"shared-eb860e1011":{"type":"string","enum":["INSERT","UPDATE","DELETE"]},"shared-ee69c55731":{"type":"string","description":"Name of the tsvector field on the table."},"shared-eff5f86cd2":{"properties":{"$type":{"const":"AuthzMemberList"}},"required":["$type"]},"shared-effacc6003":{"type":"object","description":"A further row that must exist in a third table, joined to the referenced row (alias b unless ref_alias says otherwise).","properties":{"ref_table_id":{"type":"string","format":"uuid","description":"UUID of the third table (alternative to ref_schema/ref_table)"},"ref_schema":{"type":"string","description":"Schema of the third table (or use ref_table_id)"},"ref_table":{"type":"string","description":"Name of the third table (or use ref_table_id)"},"ref_alias":{"type":"string","description":"Alias of the third table in the join","default":"b"},"join":{"type":"array","description":"Join conditions between the referenced row and the third table","items":{"type":"object","properties":{"local_column":{"$ref":"#/$defs/shared-7539b204c0"},"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the third table"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"conditions":{"type":["array","object"],"items":{"type":"object"},"description":"Optional condition JSON applied to the third table"}},"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]}],"additionalProperties":false},"shared-f35a015b21":{"type":"string","description":"Optional custom name for the index."},"shared-f4262069e5":{"type":"string","enum":["public","private","temp"]},"shared-f7ad90b1e2":{"type":"string","description":"Value to compare against condition_field in WHEN clause"},"shared-f93f3b8ac9":{"properties":{"$type":{"const":"AuthzRelatedEntityMembership"}},"required":["$type"]},"shared-fe3f452ee5":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For UPDATE triggers, only fire when these fields change (uses DISTINCT FROM)"}}};
+export const blueprintDefinitionJsonSchema: JSONSchema = {"$schema":"http://json-schema.org/draft-07/schema#","title":"BlueprintDefinition","description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint().","allOf":[{"$ref":"#/$defs/BlueprintDefinition"}],"$defs":{"AuthzAllowAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Allows all access. Generates TRUE expression."},"AuthzAppMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must hold an app membership (hardcoded membership_type=1). App-level analog of AuthzMemberOwner for global scopes with no entity key — authorship never survives losing app membership."},"AuthzAppMembershipParams":{"type":"object","properties":{"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":[],"additionalProperties":false,"description":"Checks whether the user is a member of the app. You can also require a specific permission."},"AuthzColumnSecurityParams":{"type":"object","properties":{"columns":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Guarded columns that share the same rule and authorization (e.g. [\"is_shared\"])."},"rule":{"type":"string","enum":["set_true","set_false","set_values","not_values","writable_when","transition","immutable"],"description":"Write pattern that arms the guard: set_true/set_false (column set to that boolean), set_values (column set to one of values), not_values (column set to a non-NULL value outside values), writable_when (column written/changed at all), transition (OLD->NEW pairs in allowed), immutable (delegates to DataImmutableFields).","default":"writable_when"},"authz":{"$ref":"#/$defs/AuthzExpression","description":"An Authz expression (one node such as {\"AuthzAppMembership\": {...}}, or AND, OR or NOT over nodes) that must be satisfied to perform the guarded write. Required for all rules except immutable."},"values":{"type":"array","items":{"type":"string"},"description":"For rule=set_values: the protected values that arm the guard. For rule=not_values: the allowed values; any non-NULL value outside them arms the guard."},"allowed":{"type":"array","items":{"type":"string"},"description":"For rule=transition: allowed guarded transitions expressed as \"from->to\" (e.g. [\"member->admin\"])."},"allow_system":{"type":"boolean","description":"When true, the system role (AuthzSystemOnly) bypasses the guard so provisioning/seed paths without a JWT principal can write freely.","default":false},"error_code":{"type":"string","description":"Machine-readable code prefixed onto the raised error message (e.g. MANAGED_DOMAIN_PUBLISH_FORBIDDEN)."},"error_message":{"type":"string","description":"Human-readable message raised when the guard denies the write."},"conditions":{"type":["object","array"],"items":{"type":"object"},"description":"Conditions on the row being written; the guard arms only when the write matches the rule and the row meets them."}},"required":["columns","rule"],"allOf":[{"if":{"properties":{"rule":{"not":{"const":"immutable"}}}},"then":{"required":["authz"]}},{"if":{"properties":{"rule":{"enum":["set_values","not_values"]}}},"then":{"required":["values"],"properties":{"values":{"minItems":1}}}},{"if":{"properties":{"rule":{"const":"transition"}}},"then":{"required":["allowed"],"properties":{"allowed":{"minItems":1}}}}],"additionalProperties":false,"description":"Column-level write authorization. Generates BEFORE INSERT/UPDATE triggers that enforce an authorization node whenever a guarded column is written to a protected value or transitions. The write-time counterpart to RLS SELECT/WITH CHECK policies: any table can declare \"only an actor satisfying may set column X\". The nested authz value is a normal Authz node compiled by the standard RLS pipeline; row-referencing nodes have their protected-table column references rebound to NEW. The immutable rule delegates to the native DataImmutableFields generator."},"AuthzCompositeParams":{"$ref":"#/$defs/AuthzExpression","description":"Composite authorization policy that combines multiple authorization nodes using boolean logic (AND/OR). The data field contains a JSONB AST with nested authorization nodes."},"AuthzDatabaseClaimParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column carrying the row's database id","default":"database_id"},"schema_id":{"type":"string","format":"uuid","description":"A schema whose database must be the claimed one, in place of a column; the rule then reads no column."},"lane_attested":{"type":"boolean","description":"Only connections the platform attests for the claimed database pass.","default":false}},"additionalProperties":false,"description":"Passes when the row's database column equals the session's pinned database claim (jwt.claims.database_id). Consults no principal, membership or entity, so it admits a connection whose identity the platform sets — such as a cloud function's database connection, whose claim comes from the connection and cannot widen it — to exactly the database that connection is bound to. A session with no claim fails loudly rather than reading nothing."},"AuthzDenyAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Denies all access. Generates FALSE expression."},"AuthzDirectOwnerAnyParams":{"type":"object","properties":{"entity_fields":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Array of column names to check for ownership"}},"required":["entity_fields"],"additionalProperties":false,"description":"OR logic for multiple ownership fields. Checks if current user matches any of the specified fields."},"AuthzDirectOwnerParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)"}},"required":["entity_field"],"additionalProperties":false,"description":"Direct equality comparison between a table column and the current user ID. Simplest authorization pattern with no subqueries."},"AuthzEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"mask_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capabilities — both checks must pass."},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"},"check_function_name":{"type":"string","description":"A function that checks the membership instead of the member list; it is called with the row's team column."},"check_function_schema":{"type":"string","description":"The schema of that function."}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Checks whether the user belongs to the organization or group linked to this record."},"AuthzExpression":{"type":"object","description":"One Authz node as {\"AuthzEntityMembership\": {...}}, or AND or OR with a list of expressions, or NOT with one expression.","minProperties":1,"maxProperties":1,"properties":{"AND":{"$ref":"#/$defs/shared-040cc005ef"},"OR":{"$ref":"#/$defs/shared-040cc005ef"},"NOT":{"$ref":"#/$defs/AuthzExpression"},"AuthzAllowAll":{"$ref":"#/$defs/AuthzAllowAllParams"},"AuthzAppMemberOwner":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"},"AuthzAppMembership":{"$ref":"#/$defs/AuthzAppMembershipParams"},"AuthzDatabaseClaim":{"$ref":"#/$defs/AuthzDatabaseClaimParams"},"AuthzDenyAll":{"$ref":"#/$defs/AuthzDenyAllParams"},"AuthzDirectOwner":{"$ref":"#/$defs/AuthzDirectOwnerParams"},"AuthzDirectOwnerAny":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"},"AuthzEntityMembership":{"$ref":"#/$defs/AuthzEntityMembershipParams"},"AuthzFilePath":{"$ref":"#/$defs/AuthzFilePathParams"},"AuthzHumanOnly":{"$ref":"#/$defs/AuthzHumanOnlyParams"},"AuthzMemberList":{"$ref":"#/$defs/AuthzMemberListParams"},"AuthzMemberOwner":{"$ref":"#/$defs/AuthzMemberOwnerParams"},"AuthzOrgHierarchy":{"$ref":"#/$defs/AuthzOrgHierarchyParams"},"AuthzPeerOwnership":{"$ref":"#/$defs/AuthzPeerOwnershipParams"},"AuthzPublishable":{"$ref":"#/$defs/AuthzPublishableParams"},"AuthzRelatedEntityMembership":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"},"AuthzRelatedMemberList":{"$ref":"#/$defs/AuthzRelatedMemberListParams"},"AuthzRelatedMemberOwner":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"},"AuthzRelatedPeerOwnership":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"},"AuthzSystemOnly":{"$ref":"#/$defs/AuthzSystemOnlyParams"},"AuthzTemporal":{"$ref":"#/$defs/AuthzTemporalParams"},"AuthzValueAllowed":{"$ref":"#/$defs/AuthzValueAllowedParams"},"AuthzValueExists":{"$ref":"#/$defs/AuthzValueExistsParams"},"AuthzValueMatch":{"$ref":"#/$defs/AuthzValueMatchParams"}},"additionalProperties":false},"AuthzFilePathParams":{"type":"object","properties":{"shares_table_id":{"type":"string","format":"uuid","description":"UUID of the path_shares table (alternative to shares_schema/shares_table)"},"shares_schema":{"type":"string","description":"Schema of the path_shares table (or use shares_table_id)"},"shares_table":{"type":"string","description":"Name of the path_shares table (or use shares_table_id)"},"files_table_id":{"type":"string","format":"uuid","description":"UUID of the files table (alternative to files_schema/files_table)"},"files_schema":{"type":"string","description":"Schema of the files table (or use files_table_id)"},"files_table":{"type":"string","description":"Name of the files table (or use files_table_id)"},"capability_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Boolean column on the path_shares table that grants the required permission (e.g. can_read, can_write)"},"bucket_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the files table referencing the bucket","default":"bucket_id"},"path_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Ltree column on the files table representing the file path","default":"path"}},"required":["capability_field"],"allOf":[{"anyOf":[{"required":["shares_table_id"]},{"required":["shares_schema","shares_table"]}]},{"anyOf":[{"required":["files_table_id"]},{"required":["files_schema","files_table"]}]}],"additionalProperties":false,"description":"Path-scoped file sharing via ltree containment. Grants access when a path_shares row matches the current user, bucket, and an ancestor path with the required permission."},"AuthzHumanOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Passes only for human sessions: compares the session's principal claim to its user claim, so service principals (API keys, agents) are excluded. Typically applied as a restrictive policy alongside a permissive membership policy."},"AuthzMemberListParams":{"type":"object","properties":{"array_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the array of user IDs"}},"required":["array_field"],"additionalProperties":false,"description":"Check if current user is in an array column on the same row."},"AuthzMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id)","default":"entity_id"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must be a member of the entity referenced by entity_field. Combines direct ownership with entity membership — the actor can only access rows they own within entities they belong to."},"AuthzNotReadOnlyParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Blocks changes by users marked read-only in the member list. Pair it with AuthzEntityMembership to check that the user is a member in the first place."},"AuthzOrgHierarchyParams":{"type":"object","properties":{"direction":{"type":"string","enum":["up","down"],"description":"down=manager sees subordinates, up=subordinate sees managers"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the org entity","default":"entity_id"},"anchor_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the user (e.g., owner_id)"},"max_depth":{"type":"integer","description":"Optional max depth to limit visibility"}},"required":["direction","anchor_field"],"additionalProperties":false,"description":"Organizational hierarchy visibility using closure table. Managers can see subordinate data or subordinates can see manager data."},"AuthzPeerOwnershipParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the owning user (e.g., owner_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Peer visibility through shared entity membership. Authorizes access to user-owned rows when the owner and current user are both members of the same entity."},"AuthzPublishableParams":{"type":"object","properties":{"is_published_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Boolean field indicating published state","default":"is_published"},"published_at_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Timestamp field for publish time","default":"published_at"},"require_published_at":{"type":"boolean","description":"Require published_at to be non-null and <= now()","default":true}},"additionalProperties":false,"description":"Published state access control. Restricts access to records that are published."},"AuthzRelatedEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Choose the column on the linked table that identifies the organization, group, or other membership target."},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Checks membership through a linked table, such as whether the user belongs to the organization linked there."},"AuthzRelatedMemberListParams":{"type":"object","properties":{"owned_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to owned_schema/owned_table)"},"owned_schema":{"type":"string","description":"Schema of the related table (or use owned_table_id)"},"owned_table":{"type":"string","description":"Name of the related table (or use owned_table_id)"},"owned_table_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Array column in related table"},"owned_table_ref_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"FK column in related table"},"this_object_key":{"type":"string","format":"column-ref","x-column-scope":"local","description":"PK column in protected table"}},"required":["owned_table_key","owned_table_ref_key","this_object_key"],"anyOf":[{"required":["owned_table_id"]},{"required":["owned_schema","owned_table"]}],"additionalProperties":false,"description":"Array membership check in a related table."},"AuthzRelatedMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the related table to match to the entity ID in the member list"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access only when the current user owns the row and belongs to the entity referenced by a related row. If the user loses membership, owning the row no longer gives them access."},"AuthzRelatedPeerOwnershipParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the related table (e.g., message_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to obj_schema/obj_table)"},"obj_schema":{"type":"string","description":"Schema of the related table (or use obj_table_id)"},"obj_table":{"type":"string","description":"Name of the related table (or use obj_table_id)"},"obj_field_id":{"type":"string","format":"uuid","description":"UUID of field on related table containing the owner user ID (alternative to obj_field)"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field name on related table containing the owner user ID (e.g., sender_id)"},"obj_ref_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field on related table to select for matching entity_field","default":"id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access when the current user and the owner are members of the same entity. Unlike AuthzPeerOwnership, it looks up the owner on a related row."},"AuthzSystemOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Restricts access to system-initiated operations (triggers, background jobs). Checks jwt.claims.role_type = \"system\". Normal API requests default to \"user\" and are denied. Use for INSERT policies on append-only event/audit/usage tables."},"AuthzTemporalParams":{"type":"object","properties":{"valid_from_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for start time (at least one of valid_from_field or valid_until_field required)"},"valid_until_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for end time (at least one of valid_from_field or valid_until_field required)"},"valid_from_inclusive":{"type":"boolean","description":"Include start boundary","default":true},"valid_until_inclusive":{"type":"boolean","description":"Include end boundary","default":false}},"anyOf":[{"required":["valid_from_field"]},{"required":["valid_until_field"]}],"additionalProperties":false,"description":"Time-window based access control. Restricts access based on valid_from and/or valid_until timestamps. At least one of valid_from_field or valid_until_field must be provided."},"AuthzValueAllowedParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table to check"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the value check"}},"required":["column","allowed","operator"],"additionalProperties":false,"description":"Check the protected row's own column against an allowed set of values."},"AuthzValueExistsParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-6ea79cf84b"},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with optional additional conditions."},"AuthzValueMatchParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-6ea79cf84b"},"match":{"type":"object","description":"Value match on a referenced column","properties":{"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table to match"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the match"}},"required":["ref_column","allowed","operator"],"additionalProperties":false},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["match","join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with a value/array match on a referenced column and optional additional conditions."},"BlueprintAchievement":{"type":"object","properties":{"name":{"type":"string","description":"Unique name for the achievement level."},"description":{"type":"string","description":"Human-readable description of this achievement."},"priority":{"type":"number","description":"Display ordering priority; lower values appear first. Defaults to 100."},"requirements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementRequirement"},"description":"Requirements that must be met to earn this achievement."},"rewards":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementReward"},"description":"Rewards granted when the achievement is earned."},"entity_prefix":{"type":"string","description":"Entity prefix to scope this achievement to (e.g., \"org\", \"app\"). Used to resolve the correct events_module. Defaults to \"app\"."}},"required":["name","requirements"],"description":"An achievement entry for the blueprint achievements[] section. Creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"BlueprintAchievementRequirement":{"type":"object","properties":{"event_name":{"type":"string","description":"Name identifier matching an event_type or step name."},"count":{"type":"number","description":"Number of events needed to satisfy this requirement."},"description":{"type":"string","description":"Human-readable description of what this requirement entails."}},"required":["event_name","count"],"description":"A requirement entry within a blueprint achievement. Defines what events must occur to earn the achievement."},"BlueprintAchievementReward":{"type":"object","properties":{"reward_type":{"enum":["limit_credit","meter_credit"],"description":"Type of reward: limit_credit (grants limit credits) or meter_credit (grants meter credits)."},"target_name":{"type":"string","description":"Target limit name or meter slug for the credit grant."},"amount":{"type":"number","description":"Number of credits to grant."},"credit_type":{"type":"string","description":"Credit type: permanent, expiring, etc. Defaults to \"permanent\"."}},"required":["reward_type","target_name","amount"],"description":"A reward entry within a blueprint achievement. Defines credits granted when the achievement is earned."},"BlueprintAgentConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Agent scope. \"app\" (default) creates app-level agent tables (membership_type = NULL). \"org\" creates per-org agent tables. Only used at the top level of a blueprint definition — entity-scoped agents inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module agents. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_agent_thread."},"api_name":{"type":"string","description":"API name for the agent module. Used in GraphQL naming. Defaults to \"agent\"."},"has_plans":{"type":"boolean","description":"Whether to provision the agent_plan table for workflow plans with ordered tasks and approval gates. When true, tasks belong to plans (plan_id NOT NULL) instead of directly to threads. Defaults to false."},"has_resources":{"type":"boolean","description":"Whether to provision the unified agent_resource table (skills + knowledge with slug, kind, search, embedding). Standalone flag — also auto-enabled by has_agents. Defaults to false."},"has_agents":{"type":"boolean","description":"Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false."},"has_repository_resources":{"type":"boolean","description":"Whether to attach resources to the repositories they apply to, through an agent_resource_repository junction (resource_id, repository_id, priority). Requires resources and a repository module at this same scope — with no repository catalog to point at, the junction is not created. Defaults to false."},"has_runs":{"type":"boolean","description":"Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false."},"resources":{"type":"array","items":{"type":"object","properties":{"dimensions":{"type":"number"},"chunk_size":{"type":"number"},"chunk_overlap":{"type":"number"},"chunk_strategy":{"enum":["paragraph","sentence","token"]},"embedding_model":{"type":"string"},"embedding_provider":{"type":"string"},"search_indexes":{"type":"array","items":{"type":"string"}}}},"description":"Resource configuration array. First element configures the agent_resource table: vector dimensions (default 768), chunk_size (default 1000), chunk_strategy (default \"paragraph\"), chunk_overlap (default 200), embedding_model, embedding_provider, search_indexes (default [\"bm25\"])."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the agent tables. NULL = apply defaults from apply_agent_security()."},"provisions":{"type":"object","properties":{"thread":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"message":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"task":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"prompt":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"plan":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"resource":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"agent":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"persona":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"run":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"event":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"workspace":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for agent tables. Each key targets a specific table (thread, message, task, prompt, plan, resource, agent, persona, run, event, workspace) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision. Overriding `event` replaces the append-only default, so a grant list there can make the transcript mutable; overriding `workspace` replaces its no-delete default."}},"description":"Agent module configuration. When used at the top level of a blueprint, the scope field controls whether agents are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions thread, message, task, prompt tables. has_resources adds unified agent_resource (skills + knowledge). has_agents adds agent registry + personas (implies has_resources)."},"BlueprintBucketSeed":{"type":"object","properties":{"name":{"type":"string","description":"Bucket key name (e.g., \"avatars\", \"documents\"). Becomes the key column value."},"description":{"type":"string","description":"Human-readable description of this bucket."},"type":{"enum":["public","private","temp"],"description":"Bucket access type. Defaults to public when is_public is true and private otherwise."},"is_public":{"type":"boolean","description":"Whether the bucket is publicly readable. Must agree with type when both are supplied."},"destination":{"type":"string","description":"Destination bucket key for a temporary bucket."},"staging_ttl":{"type":"string","description":"Maximum staging time for a temporary bucket as a PostgreSQL interval."},"allowed_mime_types":{"type":"array","items":{"type":"string"},"description":"MIME type allowlist (e.g., [\"image/png\", \"image/jpeg\"]). NULL means all types allowed."},"max_file_size":{"type":"number","description":"Maximum file size in bytes for this bucket. NULL means no limit."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for this bucket."}},"required":["name"],"description":"A bucket seed entry for storage.buckets[]. Creates an initial bucket row in the {prefix}_buckets table during entity type provisioning. Only used for app-level storage (not entity-scoped)."},"BlueprintCheckConstraint":{"allOf":[{"$ref":"#/$defs/BlueprintTableCheckConstraint"},{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this CHECK constraint belongs to."}},"required":["table_name"]}],"description":"A CHECK constraint definition within a blueprint (top-level, requires table_name)."},"BlueprintDefinition":{"type":"object","properties":{"tables":{"type":"array","items":{"$ref":"#/$defs/BlueprintTable"},"description":"Tables to create."},"relations":{"type":"array","items":{"$ref":"#/$defs/BlueprintRelation"},"description":"Relations between tables."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintIndex"},"description":"Indexes on table columns."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintFullTextSearch"},"description":"Full-text search configurations."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintUniqueConstraint"},"description":"Unique constraints on table columns."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintCheckConstraint"},"description":"CHECK constraints on table columns."},"entity_types":{"type":"array","items":{"$ref":"#/$defs/BlueprintEntityType"},"description":"Entity types to provision in Phase 0 (before tables). Each entry creates an entity table with membership modules and security."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Top-level storage configuration array. Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates storage_module with membership_type = NULL. Org-scoped creates per-org/user storage with owner_id and AFTER INSERT bucket seeding. When infra is installed, a private \"functions\" bucket is auto-injected into org-scoped entries. For child entity type storage, use entity_types[].storage instead."},"achievements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievement"},"description":"Achievement definitions. Each entry creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Top-level namespace configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates namespace_module with membership_type = NULL. Org-scoped creates per-org namespaces. For entity-scoped namespaces, use entity_types[].namespaces instead."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Top-level function configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates function_module with membership_type = NULL. Org-scoped creates per-org functions. For entity-scoped functions, use entity_types[].functions instead."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Top-level agent configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates agent_module with membership_type = NULL. Org-scoped creates per-org agents. For entity-scoped agents, use entity_types[].agents instead."}},"required":["tables"],"description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint()."},"BlueprintEntityTableProvision":{"type":"object","properties":{"use_rls":{"type":"boolean","description":"Whether to enable RLS on the entity table. Forwarded to secure_table_provision. Defaults to true."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Node objects applied to the entity table for field creation (e.g., DataTimestamps, DataPeoplestamps). Forwarded to secure_table_provision as-is."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the entity table. Forwarded to secure_table_provision as-is."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects for the entity table. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples. Forwarded to secure_table_provision as-is. Defaults to []."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for the entity table. When present, these policies fully replace the five default entity-table policies (is_visible becomes a no-op)."}},"description":"Override object for the entity table created by a BlueprintEntityType. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, policies[] replaces the default entity-table policies entirely."},"BlueprintEntityType":{"type":"object","properties":{"name":{"type":"string","description":"Entity type name (e.g., \"data_room\", \"channel\", \"department\"). Required when creating a new entity type. Omit when extending an existing entity type (e.g., prefix: \"org\") — the entry will add storage/config to the existing type without creating a new one."},"prefix":{"type":"string","description":"Short prefix for generated objects (e.g., \"dr\", \"ch\", \"dept\"). Used in table/trigger naming."},"description":{"type":"string","description":"Human-readable description of this entity type."},"parent_entity":{"type":"string","description":"Parent entity type name. Defaults to \"org\"."},"table_name":{"type":"string","description":"Custom table name for the entity table. Defaults to name-derived convention."},"is_visible":{"type":"boolean","description":"Whether parent-entity members can see child entities via the default parent_member SELECT policy. Gates one of the five default policies. No-op when table_provision is supplied. Defaults to true."},"has_limits":{"type":"boolean","description":"Whether to provision a limits module for this entity type. Defaults to false."},"has_profiles":{"type":"boolean","description":"Whether to provision a profiles module for this entity type. Defaults to false. A membership may hold any number of profiles: the {prefix}_membership_profiles assignment table holds every profile it holds and the membership mask is granted | bit_or(held profile masks)."},"has_levels":{"type":"boolean","description":"Whether to provision a levels module for this entity type. Defaults to false."},"has_invites":{"type":"boolean","description":"Whether to provision entity-scoped invite tables ({prefix}_invites, {prefix}_claimed_invites) and a submit_{prefix}_invite_code() function. Defaults to false."},"has_invite_achievements":{"type":"boolean","description":"Whether to auto-attach an EventTracker to the claimed_invites table for invite-based achievements. Requires has_invites=true AND has_levels=true. When true, records 'invite_claimed' events credited to the sender (inviter) on each claimed invite. Defaults to false."},"skip_entity_policies":{"type":"boolean","description":"Escape hatch: when true AND table_provision is NULL, zero policies are provisioned on the entity table. Defaults to false."},"table_provision":{"$ref":"#/$defs/BlueprintEntityTableProvision","description":"Override for the entity table. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, its policies[] replaces the five default entity-table policies; is_visible becomes a no-op. When NULL (default), the five default policies are applied (gated by is_visible)."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Storage module configuration array. Presence triggers provisioning (same inference model as namespaces, functions, agents). Each entry provisions a separate storage module with its own tables, RLS, and settings. Each entry may specify a key for multi-module support (defaults to \"default\")."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Namespace module configuration array. Presence triggers provisioning. Each entry provisions a namespace_module with its own tables, computed-name proxy, and entity-scoped RLS. Registers manage_namespaces capability bit. \"[{}]\" = provision one default namespace module."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Function module configuration array. Presence triggers provisioning. Each entry provisions function_definitions, function_invocations (partitioned), and function_execution_logs tables. Registers manage_functions + invoke_functions capability bits. \"[{}]\" = provision one default function module."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Agent module configuration array. Presence triggers provisioning. Each entry provisions thread, message, task, prompt tables (and optionally knowledge with vector embeddings). \"[{}]\" = provision one default agent module."},"graphs":{"type":"array","items":{"$ref":"#/$defs/BlueprintGraphConfig"},"description":"Graph module configuration array. Presence triggers capability registration (manage_graphs, execute_graphs). Graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here. \"[{}]\" = register default graph capabilities."}},"required":["prefix"],"description":"An entity type entry for Phase 0 of construct_blueprint(). When name is provided, provisions a new entity type with its own entity table, membership modules, and security policies via entity_type_provision. When name is omitted and only prefix is given, extends an existing entity type (e.g., the built-in \"org\") with additional capabilities like storage — without creating a new entity type."},"BlueprintField":{"type":"object","properties":{"name":{"type":"string","description":"The column name."},"type":{"$ref":"#/$defs/FieldType","description":"The structured PostgreSQL type (e.g., { name: \"text\" })."},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint."},"default":{"$ref":"#/$defs/FieldDefault","description":"The structured default (e.g., { value: \"pending\" })."},"min":{"type":"number"},"max":{"type":"number"},"regexp":{"type":"string"},"index":{"enum":["btree","gin","gist","brin","hash"]},"description":{"type":"string","description":"Comment/description for this field."},"processing":{"anyOf":[{"const":false},{"$ref":"#/$defs/BlueprintFieldProcessing"}],"description":"Upload and image fields only. The processing lanes that run on the field's files. Omitted, an image field newly added by the blueprint renders the default versions and nothing else runs; false runs nothing."}},"required":["name","type"],"description":"A custom field (column) to add to a blueprint table."},"BlueprintFieldProcessing":{"type":"object","properties":{"versions":{"anyOf":[{"type":"boolean"},{"$ref":"#/$defs/shared-1232a5e8ca"},{"type":"object","properties":{"versions":{"$ref":"#/$defs/shared-1232a5e8ca"},"versions_field":{"type":"string","format":"column-ref","description":"Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document.","default":"image_versions"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image processing worker","default":"image:process_image_versions"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for image processing tasks","default":"image_processing"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}}}],"description":"Image fields. Resized versions of the image, written into the image document as `versions`. On by default with the default set of sizes; a list states the versions instead, an object any ProcessImageVersions parameter, false turns it off."},"embedding":{"anyOf":[{"type":"boolean"},{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (default 512 for CLIP-style image embeddings)","default":512},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-0d918e14b9"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image embedding worker. The payload is the file row (file_id, key, mime_type, bucket_id), so the task must be a record worker that reads the object itself — not embedding:process_image_embedding, which embeds an image_url it is handed.","default":"embedding:process_file_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"}}},{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 512 for CLIP, 768 for nomic, 1536 for ada-002)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-c9b32dbf00"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"$ref":"#/$defs/shared-cf7316ac6e"},"task_identifier":{"$ref":"#/$defs/shared-f90494132b"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"source_bucket":{"$ref":"#/$defs/shared-41591dfcf8"},"variants_bucket":{"$ref":"#/$defs/shared-8aa6c03738"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"$ref":"#/$defs/shared-a0d2b7ccf1"},"include_chunks":{"$ref":"#/$defs/shared-347ff05f99"},"chunks":{"type":"object","description":"Chunking configuration passed through to ProcessChunks. When include_chunks is true (or defaults to true in extract mode), these params configure the chunks table, embedding dimensions, strategy, etc.","default":{},"properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"metadata_fields":{"$ref":"#/$defs/shared-6119be8d95"},"search_indexes":{"$ref":"#/$defs/shared-0ed784651d"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}}}],"description":"Image and upload fields. A vector embedding of the file. Off by default; true takes the node defaults, an object any ProcessImageEmbedding (image) or ProcessFileEmbedding (upload) parameter. The vector column is `_embedding` unless `field_name` names it."},"extraction":{"anyOf":[{"type":"boolean"},{"type":"object","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"extraction_model":{"$ref":"#/$defs/shared-f862b57bdc"},"extraction_provider":{"$ref":"#/$defs/shared-82428b2411"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%'].","default":["application/pdf","text/%"]},"routes":{"$ref":"#/$defs/shared-9649b5119d"},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the extraction worker","default":"document:extract_file_text"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for extraction tasks","default":"extraction"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}}}],"description":"Upload fields. Text and metadata extracted from the file. Off by default; true takes the node defaults, an object any ProcessExtraction parameter. The columns are `_text` and `_metadata` unless `text_field` / `metadata_field` name them."}},"description":"What runs on the files of an upload or image field. Each key is a lane and provisions the same node an entry in nodes[] would, with file_field filled in; naming the field in such a node instead leaves that lane to the node."},"BlueprintFtsSource":{"type":"object","properties":{"field":{"type":"string","description":"Column name of the source field."},"weight":{"type":"string","description":"TSVector weight: \"A\", \"B\", \"C\", or \"D\"."},"lang":{"type":"string","description":"Language for text search. Defaults to \"english\"."}},"required":["field","weight"],"description":"A source field contributing to a full-text search tsvector column."},"BlueprintFullTextSearch":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this full-text search belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"}},"required":["table_name","field","sources"],"description":"A full-text search configuration for a blueprint table (top-level, requires table_name)."},"BlueprintFunctionConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Function scope. \"app\" (default) creates app-level functions (membership_type = NULL). \"org\" creates per-org functions. Only used at the top level of a blueprint definition — entity-scoped functions inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module functions. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_function_definitions."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the function tables. NULL = apply defaults from apply_function_security()."},"provisions":{"type":"object","properties":{"definitions":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"invocations":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"execution_logs":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for function tables. Each key targets a specific table (definitions, invocations, execution_logs) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Function module configuration. When used at the top level of a blueprint, the scope field controls whether functions are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions function_definitions, function_invocations (partitioned, 12-month retention), and function_execution_logs tables."},"BlueprintGraphConfig":{"type":"object","properties":{"key":{"type":"string","description":"Module discriminator for multi-module graphs. Defaults to \"default\"."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the graph tables. NULL = apply defaults from apply_graph_security()."}},"description":"Graph module configuration. Presence triggers capability registration (manage_graphs, execute_graphs). The graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here — the graph module itself must be provisioned separately."},"BlueprintIndex":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this index belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"}},"required":["table_name","access_method"],"description":"An index definition within a blueprint (top-level, requires table_name)."},"BlueprintModuleInstallRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type of the install, e.g. \"image\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type"],"description":"A reference to an installed module, naming no table of its own. Used by a table entry whose provisions map supplies the table keys."},"BlueprintModuleTableRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type owning the table. Currently \"agent\"."},"table":{"type":"string","description":"Logical table key within the module, not a table name. Agent: \"thread\", \"message\", \"task\", \"prompt\", \"plan\", \"agent\", \"persona\", \"resource\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type","table"],"description":"A reference from a blueprint table entry to a table generated by an installed module. Resolved through the module row's recorded table ids; a reference that matches no module instance or no provisioned table fails construction rather than creating a table."},"BlueprintNamespaceConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Namespace scope. \"app\" (default) creates app-level namespaces (membership_type = NULL). \"org\" creates per-org namespaces. Only used at the top level of a blueprint definition — entity-scoped namespaces inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module namespaces. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_namespaces."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the namespaces table. NULL = apply defaults from apply_namespace_security()."},"provisions":{"type":"object","properties":{"namespaces":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"namespace_events":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for namespace tables. Each key targets a specific table (namespaces, namespace_events) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Namespace module configuration. When used at the top level of a blueprint, the scope field controls whether namespaces are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions a namespaces table with computed-name proxy, rename trigger, and entity-scoped RLS."},"BlueprintNode":{"anyOf":[{"$ref":"#/$defs/BlueprintNodeShorthand"},{"$ref":"#/$defs/BlueprintNodeObject"}],"description":"A node entry in a blueprint table. Either a string shorthand or a typed object."},"BlueprintNodeObject":{"type":"object","properties":{"data":{"type":"object"},"$type":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzColumnSecurity","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch","CheckGreaterThan","CheckLessThan","CheckNotEqual","CheckOneOf","CheckOwnedRelation","DataArchivable","DataBulk","DataCapabilities","DataCompositeField","DataDenormalized","DataDirectOwner","DataEntityMembership","DataFileRef","DataForceCurrentUser","DataGenerated","DataHistory","DataI18n","DataId","DataIdentity","DataImmutableFields","DataInflection","DataInheritFromParent","DataJsonb","DataLock","DataMemberOwner","DataOwnedFields","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchBm25","SearchFullText","SearchSpatial","SearchSpatialAggregate","SearchTrgm","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","EventReferral","EventTracker","GuardStepUp","JobTrigger","LimitEnforceAggregate","LimitEnforceCounter","LimitEnforceFeature","LimitEnforceRate","LimitTrackUsage","LimitWarningAggregate","LimitWarningCounter","LimitWarningRate","ProcessChunks","ProcessCustom","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"]}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"if":{"properties":{"$type":{"const":"AuthzColumnSecurity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzColumnSecurityParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-6ac44ac2ba"},{"$ref":"#/$defs/shared-0379afb669"},{"$ref":"#/$defs/shared-ca5d04c28d"},{"$ref":"#/$defs/shared-ff315e2ff3"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-5a2b860e32"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-1afc3ee393"},{"$ref":"#/$defs/shared-968a890679"},{"$ref":"#/$defs/shared-35954fc61d"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-7756a0ed5a"},{"$ref":"#/$defs/shared-a5a04dd84a"},{"$ref":"#/$defs/shared-f5f12fa8f6"},{"$ref":"#/$defs/shared-b297346d46"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-0022037ad5"},{"$ref":"#/$defs/shared-1d336e787f"},{"$ref":"#/$defs/shared-693097b0e5"},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckGreaterThanParams"}}}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckLessThanParams"}}}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckNotEqualParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOneOfParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"CheckOwnedRelation"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOwnedRelationParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataArchivable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataArchivableParams"}}}},{"if":{"properties":{"$type":{"const":"DataBulk"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataBulkParams"}}}},{"if":{"properties":{"$type":{"const":"DataCapabilities"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCapabilitiesParams"}}}},{"if":{"properties":{"$type":{"const":"DataCompositeField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCompositeFieldParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDenormalized"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDenormalizedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDirectOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataEntityMembershipParams"}}}},{"if":{"properties":{"$type":{"const":"DataFileRef"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataFileRefParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataForceCurrentUser"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataForceCurrentUserParams"}}}},{"if":{"properties":{"$type":{"const":"DataGenerated"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataGeneratedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataHistory"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataHistoryParams"}}}},{"if":{"properties":{"$type":{"const":"DataI18n"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataI18nParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataId"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdParams"}}}},{"if":{"properties":{"$type":{"const":"DataIdentity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdentityParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataImmutableFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataImmutableFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInflection"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInflectionParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInheritFromParent"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInheritFromParentParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataJsonb"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataJsonbParams"}}}},{"if":{"properties":{"$type":{"const":"DataLock"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataLockParams"}}}},{"if":{"properties":{"$type":{"const":"DataMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataMemberOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataOwnedFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnedFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataOwnershipInEntity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnershipInEntityParams"}}}},{"if":{"properties":{"$type":{"const":"DataPeoplestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPeoplestampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPrincipalstamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPrincipalstampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPublishableParams"}}}},{"if":{"properties":{"$type":{"const":"DataRealtime"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataRealtimeParams"}}}},{"if":{"properties":{"$type":{"const":"DataSlug"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSlugParams"}}}},{"if":{"properties":{"$type":{"const":"DataSoftDelete"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSoftDeleteParams"}}}},{"if":{"properties":{"$type":{"const":"DataStatusField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataStatusFieldParams"}}}},{"if":{"properties":{"$type":{"const":"DataTags"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTagsParams"}}}},{"if":{"properties":{"$type":{"const":"DataTimestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTimestampsParams"}}}},{"if":{"properties":{"$type":{"const":"SearchBm25"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchBm25Params"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchFullText"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchFullTextParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchSpatial"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialParams"}}}},{"if":{"properties":{"$type":{"const":"SearchSpatialAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchTrgm"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchTrgmParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchUnified"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchUnifiedParams"}}}},{"if":{"properties":{"$type":{"const":"SearchVector"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchVectorParams"}}}},{"if":{"properties":{"$type":{"const":"TableOrganizationSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableOrganizationSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserProfiles"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserProfilesParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"EventReferral"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventReferralParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"EventTracker"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventTrackerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"GuardStepUp"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/GuardStepUpParams"}}}},{"if":{"properties":{"$type":{"const":"JobTrigger"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/JobTriggerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceFeature"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceFeatureParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitTrackUsage"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitTrackUsageParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"ProcessChunks"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessChunksParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessCustom"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessCustomParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"ProcessExtraction"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessExtractionParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessFileEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessFileEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageVersions"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageVersionsParams"}}}}],"description":"Object form -- { $type, data } with typed parameters."},"BlueprintNodeShorthand":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzHumanOnly","AuthzMemberOwner","AuthzPublishable","AuthzSystemOnly","AuthzTemporal","CheckGreaterThan","CheckLessThan","DataArchivable","DataBulk","DataCapabilities","DataDirectOwner","DataEntityMembership","DataForceCurrentUser","DataHistory","DataId","DataJsonb","DataLock","DataMemberOwner","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchSpatial","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","GuardStepUp","ProcessChunks","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"],"description":"String shorthand -- just the node type name."},"BlueprintPolicy":{"type":"object","properties":{"privileges":{"type":"array","minItems":1,"items":{"type":"string","pattern":"^([Ss][Ee][Ll][Ee][Cc][Tt]|[Ii][Nn][Ss][Ee][Rr][Tt]|[Uu][Pp][Dd][Aa][Tt][Ee]|[Dd][Ee][Ll][Ee][Tt][Ee])$"}},"permissive":{"type":"boolean"},"policy_role":{"type":"string"},"policy_name":{"type":"string"},"data":{"type":"object"},"with_check":{"$ref":"#/$defs/BlueprintPolicyWithCheck"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-6ac44ac2ba"},{"$ref":"#/$defs/shared-0379afb669"},{"$ref":"#/$defs/shared-ca5d04c28d"},{"$ref":"#/$defs/shared-ff315e2ff3"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-5a2b860e32"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-1afc3ee393"},{"$ref":"#/$defs/shared-968a890679"},{"$ref":"#/$defs/shared-35954fc61d"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-7756a0ed5a"},{"$ref":"#/$defs/shared-a5a04dd84a"},{"$ref":"#/$defs/shared-f5f12fa8f6"},{"$ref":"#/$defs/shared-b297346d46"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-0022037ad5"},{"$ref":"#/$defs/shared-1d336e787f"},{"$ref":"#/$defs/shared-693097b0e5"}],"description":"An RLS policy entry for a blueprint table. A with_check override applies to UPDATE only.","if":{"required":["with_check"]},"then":{"required":["privileges"],"properties":{"privileges":{"items":{"type":"string","pattern":"^[Uu][Pp][Dd][Aa][Tt][Ee]$"}}}}},"BlueprintPolicyWithCheck":{"type":"object","properties":{"data":{"type":"object"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-6ac44ac2ba"},{"$ref":"#/$defs/shared-0379afb669"},{"$ref":"#/$defs/shared-ca5d04c28d"},{"$ref":"#/$defs/shared-ff315e2ff3"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-5a2b860e32"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-1afc3ee393"},{"$ref":"#/$defs/shared-968a890679"},{"$ref":"#/$defs/shared-35954fc61d"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-7756a0ed5a"},{"$ref":"#/$defs/shared-a5a04dd84a"},{"$ref":"#/$defs/shared-f5f12fa8f6"},{"$ref":"#/$defs/shared-b297346d46"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-0022037ad5"},{"$ref":"#/$defs/shared-1d336e787f"},{"$ref":"#/$defs/shared-693097b0e5"}]},"BlueprintRelation":{"type":"object","description":"A relation entry in a blueprint definition.","properties":{"source_table":{"type":"string"},"target_table":{"type":"string"},"source_schema":{"type":"string"},"target_schema":{"type":"string"},"source_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"target_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"$type":{"enum":["RelationBelongsTo","RelationHasMany","RelationHasOne","RelationManyToMany","RelationSpatial"]}},"allOf":[{"oneOf":[{"required":["source_table"],"not":{"required":["source_module"]}},{"required":["source_module"],"not":{"anyOf":[{"required":["source_table"]},{"required":["source_schema"]}]}}]},{"oneOf":[{"required":["target_table"],"not":{"required":["target_module"]}},{"required":["target_module"],"not":{"anyOf":[{"required":["target_table"]},{"required":["target_schema"]}]}}]},{"if":{"properties":{"$type":{"const":"RelationBelongsTo"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field added"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., projects → project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true},"scope_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Columns both tables carry that the referenced row must share with the referencing row (e.g. [\"entity_id\"], or [\"project_id\"] for a stage of the same project). Adds a hidden composite FK (field_name, ...scope_fields) -> target (id, ...scope_fields) plus the target unique key it needs, so a row cannot point at another scope's row even when it knows the id."}},"required":["delete_action"]}},{"if":{"properties":{"$type":{"const":"RelationHasMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Parent table being referenced by the FK (e.g., projects in projects has many tasks)"},"target_table_id":{"type":"string","format":"uuid","description":"Child table that receives the FK field (e.g., tasks in projects has many tasks)"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the target table. Auto-derived from source table name if omitted (e.g., projects derives project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}},"required":["delete_action"]}},{"if":{"properties":{"$type":{"const":"RelationHasOne"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field and unique constraint"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., users → user_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}},"required":["delete_action"]}},{"if":{"properties":{"$type":{"const":"RelationManyToMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"First table in the M:N relationship"},"target_table_id":{"type":"string","format":"uuid","description":"Second table in the M:N relationship"},"junction_table_id":{"type":"string","format":"uuid","description":"Existing junction table to use. If uuid_nil(), a new bare table is created"},"junction_table_name":{"type":"string","description":"Junction table name. Auto-derived from both table names if omitted (e.g., projects + tags derives project_tags)"},"source_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for source table. Auto-derived if omitted (e.g., projects derives project_id)"},"target_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for target table. Auto-derived if omitted (e.g., tags derives tag_id)"},"use_composite_key":{"type":"boolean","description":"When true, creates a composite PK from the two FK fields. When false, no PK is created by the trigger (use nodes with DataId for UUID PK). Mutually exclusive with nodes containing DataId.","default":false},"nodes":{"type":"array","items":{"type":"object"},"description":"Array of node objects for field creation on junction table. Each object has a $type key (e.g. DataId, DataEntityMembership) and optional data keys. Forwarded to secure_table_provision as-is. Empty array means no additional fields."},"grants":{"type":"array","items":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{"type":"array","items":{"type":"string"}}}},"required":["roles","privileges"]},"description":"Unified grant objects for the junction table. Each entry is { roles: string[], privileges: string[][] }. Forwarded to secure_table_provision as-is. Default: []"},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"}}}}},{"if":{"properties":{"$type":{"const":"RelationSpatial"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that owns the relation (the @spatialRelation tag is emitted on the owner column of this table)"},"source_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on source_table that carries the @spatialRelation smart tag"},"target_table_id":{"type":"string","format":"uuid","description":"Table being referenced by the spatial predicate"},"target_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on target_table that the predicate is evaluated against"},"name":{"type":"string","description":"Relation name (stable, snake_case). Becomes the generated filter field name in GraphQL (e.g. nearby_clinic). Unique per (source_table_id, name) — idempotency key."},"operator":{"type":"string","enum":["st_contains","st_within","st_intersects","st_covers","st_coveredby","st_overlaps","st_touches","st_dwithin"],"description":"PostGIS spatial predicate. One of the 8 whitelisted operators. st_dwithin requires param_name."},"param_name":{"type":"string","description":"Parameter name for parametric operators (currently only st_dwithin, which needs a distance argument). Must be NULL for all other operators. Enforced by table CHECK."},"source_field":{"type":"string"},"target_field":{"type":"string"}},"required":["name","operator","source_field","target_field"]}}],"required":["$type"]},"BlueprintStorageConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Storage scope. \"app\" (default) creates app-level storage (no owner_id). \"org\" creates per-org/user storage (owner_id = org entity id, buckets seeded per-entity via AFTER INSERT trigger). Only \"app\" and \"org\" are allowed — child entity types get storage via entity_types[].storage."},"key":{"type":"string","description":"Module key discriminator. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case."},"buckets":{"type":"array","items":{"$ref":"#/$defs/BlueprintBucketSeed"},"description":"Initial bucket seed entries. Each creates a row in {prefix}_buckets during provisioning."},"upload_url_expiry_seconds":{"type":"number","description":"Override for presigned upload URL expiry time in seconds."},"download_url_expiry_seconds":{"type":"number","description":"Override for presigned download URL expiry time in seconds."},"default_max_file_size":{"type":"number","description":"Default maximum file size in bytes for the storage module."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for the storage module."},"confirm_upload_delay":{"type":"string","description":"Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. \"30 seconds\"). Every files table runs the confirm loop: the AFTER INSERT trigger enqueues a storage:confirm_upload job that verifies the object exists in S3 before moving status from requested to uploaded, and expires a requested row whose bytes never arrived within upload_url_expiry_seconds. Defaults to \"30 seconds\"."},"staging":{"type":"boolean","description":"Provision a temporary staging bucket (type temp, tagged default-temp) that stages for the private default bucket, so uploads land there and are promoted into their destination on confirmation. Setting staging_ttl implies this. Defaults to false."},"staging_ttl":{"type":"string","description":"How long an unpromoted staged file survives before it is eligible for expiry (PostgreSQL interval string, e.g. \"24 hours\"). Implies staging. Defaults to \"24 hours\"."},"provisions":{"type":"object","properties":{"files":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"buckets":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for storage tables. Each key targets a specific storage table (files, buckets) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision targeting the corresponding table. When a key includes policies[], those REPLACE the default storage policies for that table; tables without a key still get defaults."}},"description":"Storage configuration with optional scope. When used at the top level of a blueprint, the scope field controls whether storage is app-level (\"app\", default) or org-level (\"org\"). Seeds initial buckets, overrides module-level settings (expiry times, file size limits, CORS), and provides per-table provisioning overrides via provisions."},"BlueprintTable":{"type":"object","properties":{"table_name":{"type":"string","description":"The PostgreSQL table name to create. Required unless the entry carries a module reference instead."},"schema_name":{"type":"string","description":"Optional schema name (falls back to top-level default)."},"module":{"anyOf":[{"$ref":"#/$defs/BlueprintModuleTableRef"},{"$ref":"#/$defs/BlueprintModuleInstallRef"}],"description":"Attach this entry to a table an installed module generated instead of naming one, e.g. { type: \"agent\", scope: \"org\", table: \"message\" }. Mutually exclusive with table_name/schema_name. An entry carrying provisions names the install alone and leaves out table, since the provisions keys name the tables."},"provisions":{"type":"object","additionalProperties":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"description":"Provision security onto the tables the referenced module generated, keyed by the module's own table keys (e.g. { registries: { policies: [...] } } for an image module). Requires a module reference without \"table\", since the keys name the tables. Each entry takes ownership of the security it declares: the grants/policies given become that table's whole set, replacing what the module installed — unlike this entry's own policies[]/grants[], which layer onto one table."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Array of node type entries that define the table's behavior. Omitted by an entry that only carries provisions or only attaches policies to a module table."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the table."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for this table."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples (e.g. [[\"select\",\"*\"]]). Enables per-role targeting. Defaults to []."},"use_rls":{"type":"boolean","description":"Whether to enable RLS on this table. Defaults to true."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableIndex"},"description":"Table-level indexes (table_name inherited from parent)."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableFullTextSearch"},"description":"Table-level full-text search configurations (table_name inherited from parent)."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableUniqueConstraint"},"description":"Table-level unique constraints (table_name inherited from parent)."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableCheckConstraint"},"description":"Table-level CHECK constraints (table_name inherited from parent)."}},"description":"A table definition within a blueprint.","oneOf":[{"required":["table_name"],"not":{"required":["module"]}},{"required":["module"],"not":{"anyOf":[{"required":["table_name"]},{"required":["schema_name"]}]}}],"if":{"required":["provisions"]},"then":{"required":["module"],"not":{"anyOf":[{"required":["policies"]},{"required":["grants"]},{"required":["nodes"]},{"required":["fields"]}]},"properties":{"module":{"not":{"required":["table"]}},"provisions":{"minProperties":1}}},"else":{"properties":{"module":{"$ref":"#/$defs/BlueprintModuleTableRef"}}}},"BlueprintTableCheckConstraint":{"type":"object","properties":{"$type":{"enum":["CheckOneOf","CheckGreaterThan","CheckLessThan","CheckNotEqual"]}},"required":["$type"],"allOf":[{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"type":"object","properties":{"$type":{"const":"CheckOneOf"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckOneOfParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"type":"object","properties":{"$type":{"const":"CheckGreaterThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckGreaterThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"type":"object","properties":{"$type":{"const":"CheckLessThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckLessThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"type":"object","properties":{"$type":{"const":"CheckNotEqual"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckNotEqualParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}}],"description":"A CHECK constraint nested inside a table definition (table_name not required)."},"BlueprintTableFullTextSearch":{"type":"object","properties":{"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["field","sources"],"description":"A full-text search configuration nested inside a table definition (table_name not required)."},"BlueprintTableIndex":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["access_method"],"description":"An index definition nested inside a table definition (table_name not required)."},"BlueprintTableUniqueConstraint":{"type":"object","properties":{"columns":{"$ref":"#/$defs/shared-a0bfcadf85"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["columns"],"description":"A unique constraint nested inside a table definition (table_name not required)."},"BlueprintUniqueConstraint":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this unique constraint belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"columns":{"$ref":"#/$defs/shared-a0bfcadf85"}},"required":["table_name","columns"],"description":"A unique constraint definition within a blueprint (top-level, requires table_name)."},"CheckGreaterThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column > value)","default":0},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] > columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is greater than a threshold (single-column: column > value) or that one column is greater than another (cross-column: columns[0] > columns[1]). Compiled via AST helpers."},"CheckLessThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column < value)"},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] < columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is less than a threshold (single-column: column < value) or that one column is less than another (cross-column: columns[0] < columns[1]). Compiled via AST helpers."},"CheckNotEqualParams":{"type":"object","properties":{"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns that must not be equal","minItems":2,"maxItems":2}},"required":["columns"],"description":"Adds a CHECK constraint that validates two columns are not equal (columns[0] != columns[1]). Useful for preventing self-referencing rows. Compiled via AST helpers."},"CheckOneOfParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","description":"Column to validate against the allowed values"},"values":{"type":"array","items":{"type":"string"},"description":"Array of allowed values for the column"}},"required":["column","values"],"description":"Adds a CHECK constraint that validates a column value is one of an allowed set (e.g. tier IN ('free', 'paid', 'custom')). Compiled to column = ANY(ARRAY[...]) via AST helpers."},"CheckOwnedRelationParams":{"type":"object","properties":{"link_schema_name":{"type":"string","description":"Schema holding the link tables the ownership is proven through"},"owner_scope":{"type":"string","description":"Scope that owns the referencing rows; matched against the link row's owner_scope (e.g. database, platform)"},"owner_key_field_name":{"type":"string","format":"column-ref","description":"Column on the referencing table carrying its scope key, matched against the link row's owner_key. NULL for a global scope, whose owner key is NULL by construction"},"pointers":{"type":"array","description":"Typed pointer columns to guard, each resolved through its own link table","items":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Pointer column on the referencing table"},"link_table_name":{"type":"string","description":"Link table in link_schema_name whose ids this column points at"},"target_type_field_name":{"type":"string","description":"Optional link column additionally restricted regardless of ownership (e.g. a bucket type)"},"target_type_value":{"type":"string","description":"Value target_type_field_name must equal"},"allow_owner_tier":{"type":"boolean","description":"Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database","default":false},"allow_frame_chain":{"type":"boolean","description":"Admit rows owned by any frame on the referencing row's own scope-frame chain (its own scopes, then the platform database's chain) for this column, for pointers naming a definition published UP the hierarchy — the shared platform function image a tenant route targets. Ancestry only: a peer or another keyed owner is on no chain. Requires owner_key_field_name","default":false}},"required":["field_name","link_table_name"]}},"arity":{"type":"string","enum":["exactly_one","all","any"],"description":"How many pointers a row must set: exactly_one for a polymorphic target (route → api OR site OR bucket), all for a junction/join row of a has-and-belongs-to-many relation (and for a mandatory belongs-to), any for optional pointers that are only checked when set","default":"exactly_one"},"required_error":{"type":"string","description":"Error code raised when the arity rule over the pointers is violated","default":"OWNED_RELATION_TARGET_REQUIRED"},"denied_error":{"type":"string","description":"Error code raised when the target is not owned by the referencing row owner","default":"OWNED_RELATION_TARGET_NOT_OWNED"},"trigger_function_schema":{"type":"string","description":"Schema the guard trigger function is created in; defaults to the table schema"},"trigger_function_name":{"type":"string","description":"Guard trigger function name; defaults to tg_
_owned_relation_guard"},"trigger_name":{"type":"string","description":"Guard trigger name; defaults to
_owned_relation_guard"}},"required":["link_schema_name","owner_scope","pointers"],"description":"Declares that typed pointer columns may only reference rows owned by the same scope owner as the referencing row, proven through a link table that carries the owner (owner_scope, owner_key) — typically a catalog projection that must never be referenced structurally. Creates one BEFORE INSERT OR UPDATE trigger enforcing the declared arity over the pointers and requiring every pointer that is set to resolve to a same-owner row, so it covers belongs-to / has-one / has-many (key on the row being written) and has-and-belongs-to-many (both keys on the junction row, arity all). Visibility/publication flags are never an authorization input."},"DataArchivableParams":{"type":"object","properties":{"is_archived_field":{"type":"string","format":"column-ref","description":"Column name for the archive boolean flag","default":"is_archived"},"archived_at_field":{"type":"string","format":"column-ref","description":"Column name for the archive timestamp","default":"archived_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds user-reversible archive support with is_archived boolean and archived_at timestamp, plus a partial index for efficient active-row queries."},"DataBulkParams":{"type":"object","properties":{"insert":{"type":"boolean","description":"Enable bulk insert (+bulkInsert)","default":true},"upsert":{"type":"boolean","description":"Enable bulk upsert (+bulkUpsert)","default":false},"update":{"type":"boolean","description":"Enable bulk update (+bulkUpdate)","default":false},"delete":{"type":"boolean","description":"Enable bulk delete (+bulkDelete)","default":false}},"description":"Enables bulk mutation smart tags on a table. When provisioned, adds @behavior tags for the selected bulk operations (insert, upsert, update, delete). Requires the graphile-bulk-mutations plugin."},"DataCapabilitiesParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the bit(n) mask column to create on this table.","default":"required_capabilities"},"capabilities":{"type":"object","description":"Selector for the capabilities module whose bit numbering the mask is measured in, e.g. {\"scope\": \"org\"}. Every key given must match exactly one module; none or several raises naming the candidates. Required only when the database has more than one.","properties":{"scope":{"type":"string","description":"Scope the module is installed at (\"app\", \"org\", or an entity type prefix)."},"prefix":{"type":"string","description":"Table prefix of the module instance; rarely needed since prefix follows scope."}},"additionalProperties":false},"default":{"type":"array","items":{"type":"string"},"description":"Capability names every row requires unless told otherwise, resolved to a literal mask and baked into the column default. Omitted means a zero mask: requires nothing."},"mode":{"type":"string","enum":["direct","derived"],"description":"Who writes the mask: \"direct\" the writer, bounded by the subset guard; \"derived\" the mapping row named by from_column, stamped by generated triggers and hidden from mutations.","default":"direct"},"from_column":{"type":"string","format":"column-ref","description":"Derived mode only: the column on this table naming the mapping row to copy the mask from (e.g. classification_id)."},"mapping_table":{"type":"string","description":"Derived mode only: table holding one mask per class (e.g. document_classifications)."},"mapping_key":{"type":"string","format":"column-ref","description":"Derived mode only: column on the mapping table that from_column matches.","default":"id"},"mapping_column":{"type":"string","format":"column-ref","description":"Derived mode only: the mapping table's own bit(n) mask column. Created when absent, so a classification table needs no DataCapabilities declaration of its own. Defaults to the same name as field."},"subset_guard":{"type":"boolean","description":"Direct mode only: refuse a write requiring bits the writer does not hold, so nobody can lock a row away from everyone including themselves. Off is for trusted-writer tables only.","default":true},"entity_field":{"type":"string","format":"column-ref","description":"Direct mode only: the entity column the subset guard's membership check reads.","default":"entity_id"}},"description":"Per-row required permissions. A profile compiles a person to bits so no policy joins a profiles table; this compiles a row to bits so no policy joins a grant table either — the row stores which permissions are required, and an AuthzEntityMembership policy with mask_column checks that the user has all of them. The mask only narrows: it takes access away from someone membership already lets in, and never grants access to a non-member. Zero requires nothing, which is what an unclassified row defaults to. In direct mode the writer sets the mask and the subset guard bounds it to bits the writer holds; in derived mode it is copied from a mapping row (classification -> mask) by generated triggers, so authors edit one classification instead of every document."},"DataCompositeFieldParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the derived text field to create","default":"embedding_text"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names to concatenate into the target field"},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format: 'labeled' (field_name: value) or 'plain' (values only)","default":"labeled"}},"required":["source_fields"],"description":"Creates a derived text field that automatically concatenates multiple source fields via BEFORE INSERT/UPDATE triggers. Used to produce a unified text representation (e.g., embedding_text) from multiple columns on a table. The trigger fires with '_000' prefix to run before Search* triggers alphabetically."},"DataDenormalizedParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"FK field on this table that references the parent row (e.g. view_id)"},"set_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on this table to be populated from the parent (e.g. [\"database_id\"])"},"ref_field":{"type":"string","format":"column-ref","description":"Field on the parent table that is the FK target (e.g. id)"},"ref_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the parent table to copy from (e.g. [\"database_id\"])"},"use_updates":{"type":"boolean","description":"If true, also creates an UPDATE trigger so changes to the FK re-copy values","default":true},"update_defaults":{"type":"boolean","description":"If true, sets the default value of set_fields to uuid_nil() so they are populated by the trigger","default":true},"func_name":{"type":"string","description":"Custom function name suffix (defaults to the FK field name)"},"func_order":{"type":"integer","description":"Trigger ordering (0-padded). Lower numbers fire first","default":0}},"required":["field","set_fields","ref_field","ref_fields"],"description":"Creates INSERT and UPDATE triggers that copy field values from a referenced (parent) table into the current table whenever the FK changes. Used to denormalize frequently-read columns (e.g. database_id on junction tables) so that RLS and queries can filter locally without joining."},"DataDirectOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for owner ID","default":"owner_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from owner_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the owner column","default":true}},"description":"Adds ownership column for direct user ownership. Enables AuthzDirectOwner authorization."},"DataEntityMembershipParams":{"type":"object","properties":{"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for entity ID","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the entity column","default":true}},"description":"Adds entity reference for organization/group scoping. Enables AuthzEntityMembership, AuthzMembership, AuthzOrgHierarchy authorization."},"DataFileRefParams":{"type":"object","required":["field"],"properties":{"field":{"type":"string","format":"column-ref","pattern":"\\S","description":"The upload, image or attachment column to register"},"storage":{"type":"object","description":"The storage module the file lives in, selected by its scope and/or key; every key given must match exactly one module. When omitted, the table's scope column decides, and a table with no scope column uses the app's storage.","properties":{"scope":{"type":"string","pattern":"\\S","description":"Scope of the storage module, e.g. \"app\", \"org\" or an entity type's scope"},"key":{"type":"string","pattern":"\\S","description":"Key of the storage module, for a scope with more than one"}},"minProperties":1,"additionalProperties":false},"bucket":{"type":"string","pattern":"\\S","description":"Key of the bucket an upload resolves to. Set this or bucket_tags, not both."},"bucket_tags":{"type":"array","items":{"type":"string"},"description":"Tags of the bucket an upload resolves to. Set this or bucket, not both."},"is_public":{"type":"boolean","description":"With no bucket named, picks the default public (true) or private (false) bucket; with a bucket named, asserts that bucket is public or private. Omitted, the bucket alone decides."},"enforce_fk":{"type":"boolean","description":"Strict mode: a real foreign key beside the column. Not implemented yet, so the backend refuses true.","default":false}},"not":{"required":["bucket","bucket_tags"]},"description":"Registers an existing upload, image or attachment column as a managed reference to a files row: it records which storage module the file lives in and which bucket an upload resolves to, and the backend generates the sync trigger and the GC index from that. The column must be declared in fields[] first; the node creates no column."},"DataForceCurrentUserParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to force to current_user_id()","default":"actor_id"}},"description":"BEFORE INSERT trigger that forces a field to the value of jwt_public.current_user_id(). Prevents clients from spoofing the actor/uploader identity. The field value is always overwritten regardless of what the client provides."},"DataGeneratedParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the generated column to create"},"type":{"type":"object","description":"FieldType for the generated column (default: text)","default":{"name":"text"}},"kind":{"type":"string","enum":["expression","concat","slug","object_name","hash"],"description":"Preset for building the generation expression","default":"expression"},"generation_type":{"type":"string","enum":["stored","virtual"],"description":"Whether the column is STORED (persisted on write) or VIRTUAL (computed on read, PostgreSQL 18+)","default":"stored"},"source_field":{"type":"string","format":"column-ref","description":"Single source field for expression/slug/object_name presets"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names for concat/hash presets"},"expression":{"type":"object","description":"Raw FieldGeneration DSL or AST (used when kind is expression)"},"separator":{"type":"string","description":"Separator used by concat preset","default":" "},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format for concat preset: 'labeled' (field_name: value) or 'plain' (values only)","default":"plain"},"prefix":{"type":"string","description":"Optional prefix for object_name preset"},"suffix":{"type":"string","description":"Optional suffix for object_name preset"},"algorithm":{"type":"string","description":"Hash algorithm for hash preset (e.g. sha256, md5)","default":"sha256"},"is_required":{"type":"boolean","description":"Whether the generated column is NOT NULL","default":false}},"required":["target"],"description":"Creates a native PostgreSQL GENERATED ALWAYS AS (expr) column (STORED or VIRTUAL) from a source field expression, preset, or raw AST. The column is read-only for clients and computed automatically by PostgreSQL."},"DataHistoryParams":{"type":"object","properties":{"table_suffix":{"type":"string","description":"Suffix for the history table name","default":"_history"},"recorded_at_field":{"type":"string","format":"column-ref","description":"Column name for the version timestamp (also the partition key when partitioned)","default":"recorded_at"},"operation_field":{"type":"string","format":"column-ref","description":"Column name recording the operation ('INSERT' | 'UPDATE' | 'DELETE')","default":"history_op"},"exclude_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Source columns to omit from the history table (e.g. large jsonb or vector columns). Excluded columns are never created on the history table and never written by the trigger.","default":[]},"copy_mutation_policies":{"type":"boolean","description":"Whether to also clone INSERT/UPDATE/DELETE policies (not just SELECT). Default false — the history table is written only by the trigger and exposed read-only through GraphQL.","default":false},"partitioned":{"type":"boolean","description":"When true, range-partition the history table by recorded_at via pg_partman so old partitions can be dropped per the retention window.","default":false},"partition_interval":{"type":"string","description":"pg_partman partition interval (when partitioned)","default":"1 month"},"retention":{"type":"string","description":"pg_partman retention window; partitions older than this are dropped by run_maintenance (when partitioned). Empty keeps forever.","default":"12 months"},"premake":{"type":"integer","description":"Number of future partitions pg_partman pre-creates","default":2}},"description":"Creates a companion
_history table that records a new version row on every INSERT/UPDATE/DELETE via an AFTER trigger. The history table copies the source columns as plain nullable columns with NO keys or constraints, plus a recorded_at timestamp and a history_op column (NEW-append: INSERT/UPDATE store the new row, DELETE stores a tombstone). SELECT policies are cloned from the base table. Optionally range-partitions the history table by recorded_at (pg_partman) with a retention window so history is kept for a while but not forever. Adds an @history smart comment so the Graphile history plugin can expose version queries and restore mutations."},"DataI18nParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the base table to make translatable. Each field is duplicated on the translation table with the same type."},"table_suffix":{"type":"string","description":"Suffix for the translation table name","default":"_translations"},"lang_code_type":{"type":"string","enum":["citext","text"],"description":"Type for the lang_code column","default":"citext"},"copy_mutation_policies":{"type":"boolean","description":"Whether to also copy INSERT/UPDATE/DELETE policies (not just SELECT). Default true — translations should be editable by the same users who can edit the base row.","default":true},"search":{"type":"object","description":"SearchFullText configuration for the translations table. When provided, creates a tsvector column on the translations table with lang_column=lang_code for dynamic per-row language stemming.","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column on the translations table","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the translatable source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"}},"required":["field"]},"description":"Translatable columns that feed the tsvector. Language is determined dynamically from the lang_code column of each row."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"]}},"required":["fields"],"description":"Creates a companion _translations table with lang_code + translatable fields. Copies SELECT policies and column-ref fields from the base table. Adds @i18n smart comment so the Graphile i18n plugin discovers it. Requires i18n_module to be provisioned for the database."},"DataIdParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the primary key","default":"id"}},"description":"Adds a UUID primary key column with auto-generation default (uuidv7). This is the standard primary key pattern for all tables."},"DataIdentityParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the identity column to create"},"type":{"type":"object","description":"FieldType for the identity column (default: bigint)","default":{"name":"bigint"}},"generation":{"type":"string","enum":["always","by_default"],"description":"'always' for GENERATED ALWAYS AS IDENTITY, 'by_default' for GENERATED BY DEFAULT AS IDENTITY","default":"by_default"},"sequence":{"type":"object","description":"Optional sequence tuning for the backing identity sequence","properties":{"start":{"type":"integer","description":"START WITH value"},"increment":{"type":"integer","description":"INCREMENT BY value"},"min":{"type":["integer","null"],"description":"MINVALUE (null uses the default)"},"max":{"type":["integer","null"],"description":"MAXVALUE (null uses the default)"},"cache":{"type":"integer","description":"CACHE value"},"cycle":{"type":"boolean","description":"Whether the sequence cycles (CYCLE / NO CYCLE)"}}},"is_required":{"type":"boolean","description":"Whether the identity column is NOT NULL (identity columns are implicitly NOT NULL)","default":false}},"required":["target"],"description":"Creates a native PostgreSQL identity column (GENERATED ALWAYS / BY DEFAULT AS IDENTITY) backed by an implicit sequence. The database assigns values automatically; ALWAYS identity columns are not writable by clients."},"DataImmutableFieldsParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names that cannot be modified after INSERT (e.g. [\"key\", \"bucket_id\", \"owner_id\"])"}},"required":["fields"],"description":"BEFORE UPDATE trigger that prevents changes to a list of specified fields after INSERT. Raises an exception if any of the listed fields have changed. Unlike FieldImmutable (single-field), this handles multiple fields in a single trigger for efficiency."},"DataInflectionParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to transform"},"ops":{"type":"array","items":{"type":"string","enum":["plural","singular","camel","pascal","dashed","slugify","underscore","lower","upper"]},"description":"Inflection operations to apply in order"}},"required":["field_name","ops"],"description":"Transforms field values using inflection operations (snake_case, camelCase, slugify, plural, singular, etc). Attaches BEFORE INSERT and BEFORE UPDATE triggers. References fields by name in data jsonb."},"DataInheritFromParentParams":{"type":"object","properties":{"parent_fk_field":{"type":"string","format":"column-ref","description":"Name of the FK field on this table that references the parent (e.g. bucket_id)"},"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to copy from the parent row (e.g. [\"owner_id\", \"is_public\"])"},"parent_table":{"type":"string","description":"Parent table name (optional fallback if FK not yet registered in metaschema)"},"parent_schema":{"type":"string","description":"Parent table schema (optional, defaults to same schema as child table)"}},"required":["parent_fk_field","fields"],"description":"BEFORE INSERT OR UPDATE trigger that copies specified fields from a parent table via a foreign key; on UPDATE the fields are re-copied only when the parent FK changes. The parent row is looked up through RLS (SECURITY INVOKER), so the insert or update fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files."},"DataJsonbParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the JSONB field","default":"metadata"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false},"create_index":{"type":"boolean","description":"Whether to create a GIN index","default":true}},"description":"Adds a JSONB column with optional GIN index for containment queries (@>, ?, ?|, ?&). Standard pattern for semi-structured metadata."},"DataLockParams":{"type":"object","properties":{"lock_field":{"type":"string","format":"column-ref","description":"Boolean column holding the lock state","default":"locked"},"events":{"type":"array","items":{"type":"string","enum":["UPDATE","DELETE"]},"description":"Which DML events are guarded while the row is locked. INSERT is not lockable — a row cannot be locked before it exists.","default":["DELETE"]},"enforcement":{"type":"string","enum":["step_up","block"],"description":"How a guarded verb is stopped while locked. step_up requires recent strong verification (needs a provisioned user_auth_module); block refuses the verb outright with ROW_LOCKED until unlocked.","default":"step_up"},"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Verification method satisfying the step-up requirement, for the guarded verbs in step_up mode and for clearing the lock","default":"fresh_auth"},"guard_unlock":{"type":"boolean","description":"Require step-up to change the lock column itself, so a locked row cannot be quietly unlocked and then deleted. Redundant (and therefore skipped) in step_up mode when UPDATE is already guarded.","default":true},"protect_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For a guarded UPDATE, restrict the guard to changes touching these columns. Empty guards the whole row.","default":[]},"default_locked":{"type":"boolean","description":"Initial value of the lock column for new rows","default":false},"min_age":{"type":"string","description":"Optional interval (e.g. \"24 hours\"); in step_up mode the guard only fires for rows older than this, so freshly created rows stay easy to clean up. Empty guards rows of any age.","default":""}},"description":"Adds a boolean lock column and guards mutations while a row is locked, so infrastructure rows other things depend on (a bucket a function needs, a route, a resource) are not deleted or edited by accident. Two enforcement modes: step_up requires recent strong verification (via GuardStepUp / require_step_up) for the guarded verbs, while block refuses them outright until the row is unlocked. Clearing the lock is itself step-up guarded, so unlocking is a deliberate, re-authenticated step rather than a silent prelude to deletion."},"DataMemberOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true},"entity_type":{"type":"string","description":"Membership scope (e.g. 'org', 'room'). Resolved to a membership type via the database's membership_types_module. This is the authoring form — use it instead of membership_type."},"membership_type":{"type":"integer","description":"Membership type resolved from the scope. Internal: prefer entity_type. Cannot be combined with entity_type.","default":null}},"description":"Adds owner_id and entity_id columns with a compound AuthzMemberOwner policy. The current user must own the row and be a member of the entity it belongs to. Use for private data within an entity scope — e.g., personal chat threads that belong to the company but only the author can see."},"DataOwnedFieldsParams":{"type":"object","properties":{"role_key_field_name":{"type":"string","format":"column-ref","description":"Name of the field identifying the owner (e.g. sender_id)"},"protected_field_names":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Names of fields only this owner can modify"}},"required":["role_key_field_name","protected_field_names"],"description":"Restricts which user can modify specific columns in shared objects. Creates an AFTER UPDATE trigger that throws OWNED_PROPS when a non-owner tries to change protected fields. References fields by name in data jsonb."},"DataOwnershipInEntityParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true}},"description":"Combines direct ownership with entity scoping. Adds both owner_id and entity_id columns. Enables AuthzDirectOwner, AuthzEntityMembership, and AuthzOrgHierarchy authorization. Particularly useful for OrgHierarchy where a user owns a row (owner_id) within an entity (entity_id), and managers above can see subordinate-owned records via the hierarchy closure table."},"DataPeoplestampsParams":{"type":"object","properties":{"created_by_field":{"type":"string","format":"column-ref","description":"Column name for the creating user reference","default":"created_by"},"updated_by_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating user reference","default":"updated_by"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from created_by and updated_by to the users table","default":false},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the peoplestamp columns","default":true}},"description":"Adds human actor tracking for creates/updates: created_by/updated_by record the human user (jwt_public.current_user_id())."},"DataPrincipalstampsParams":{"type":"object","properties":{"created_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the creating principal reference (agent, API key, or user)","default":"created_by_principal"},"updated_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating principal reference (agent, API key, or user)","default":"updated_by_principal"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the principalstamp columns","default":true}},"description":"Adds acting-principal tracking for creates/updates: created_by_principal/updated_by_principal record the acting principal — agent, API key, service identity, or the user itself (jwt_public.current_principal_id())."},"DataPublishableParams":{"type":"object","properties":{"is_published_field_name":{"type":"string","format":"column-ref","description":"Column name for the published boolean flag","default":"is_published"},"published_at_field_name":{"type":"string","format":"column-ref","description":"Column name for the publish timestamp","default":"published_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds publish state columns (is_published, published_at) for content visibility. Enables AuthzPublishable and AuthzTemporal authorization."},"DataRealtimeParams":{"type":"object","properties":{"operations":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML operations to track with emit_change triggers","default":["INSERT","UPDATE","DELETE"]},"subscriber_table_name":{"type":"string","description":"Custom name for the subscriber table (defaults to {source_table}_subscriber)"},"ephemeral":{"type":"boolean","description":"When true, events are delivered via pg_notify only without writing to change_log. Ideal for high-frequency ephemeral signals (e.g. cursor positions, live indicators) where persistence is unnecessary. Subscriber table and RLS policies are still created for access control.","default":false}},"description":"Creates per-table subscriber tables in subscriptions_public with RLS policies derived from source table SELECT policies. Attaches statement-level triggers to emit changes to subscribers."},"DataSlugParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to slugify","default":"slug"},"source_field_name":{"type":"string","format":"column-ref","description":"Optional source field name (defaults to field_name)"}},"required":[],"description":"Auto-generates URL-friendly slugs from field values on insert/update. Attaches BEFORE INSERT and BEFORE UPDATE triggers that call inflection.slugify() on the target field. References fields by name in data jsonb."},"DataSoftDeleteParams":{"type":"object","properties":{"deleted_at_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete timestamp","default":"deleted_at"},"is_deleted_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete boolean flag","default":"is_deleted"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds soft delete support with deleted_at and is_deleted columns."},"DataStatusFieldParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the status field","default":"status"},"type":{"$ref":"#/$defs/FieldType","description":"Column type as a FieldType object"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object (e.g., { value: \"active\" })"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":true},"allowed_values":{"type":"array","items":{"type":"string"},"description":"If provided, creates a CHECK constraint restricting the column to these values"}},"description":"Adds a status column with B-tree index for efficient equality filtering and sorting. Optionally constrains values via CHECK constraint when allowed_values is provided."},"DataTagsParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the tags array","default":"tags"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false}},"description":"Adds a citext[] tags column with GIN index for efficient array containment queries (@>, &&). Standard tagging pattern for categorization and filtering."},"DataTimestampsParams":{"type":"object","properties":{"created_at_field":{"type":"string","format":"column-ref","description":"Column name for the creation timestamp","default":"created_at"},"updated_at_field":{"type":"string","format":"column-ref","description":"Column name for the last-updated timestamp","default":"updated_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds automatic timestamp tracking with created_at and updated_at columns."},"EventReferralParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record for the referrer (e.g., \"invitee_uploaded_avatar\", \"invitee_completed_onboarding\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the invitee (actor) ID on the source table — used to look up the referrer via claimed_invites.receiver_id","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped referral events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"max_depth":{"type":"integer","description":"Maximum depth to walk up the invite chain. Default 1 (direct inviter only). Set 2–10 to enable multi-level referral rewards. App-level only — must not be combined with entity_field.","default":1,"minimum":1,"maximum":10},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events for the referrer (inviter) when their invitees perform actions on a watched table. Resolves the referrer automatically via the invites module's claimed_invites table using the membership_type context. Supports the same compound condition system as EventTracker. Use with achievements to unlock levels and grant credits based on invitee activity."},"EventTrackerParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record (e.g., \"avatar_uploaded\", \"order_completed\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"count":{"type":"integer","description":"Number of events to record per trigger fire","default":1},"toggle":{"type":"boolean","description":"Toggle mode: records event when condition is met, removes when condition is unmet","default":false},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the actor (user) ID to attribute the event to","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events via the events module when table rows change. Supports the same compound condition system as JobTrigger (condition_field, watch_fields, or full AND/OR/NOT conditions). Events are recorded to app_events and aggregated automatically. Use with achievements (blueprint-level) to unlock levels and grant credits based on event accumulation."},"FieldDefault":{"type":"object","description":"A structured default expression, e.g. { value: false }, { function: \"now\" } or { value: {}, cast: { name: \"jsonb\" } }.","properties":{"value":{"description":"Literal value."},"function":{"type":"string","description":"Function name."},"schema":{"type":"string","description":"Schema qualifier of the function."},"args":{"type":"array","items":{"anyOf":[{"type":["string","number","boolean","null"]},{"$ref":"#/$defs/FieldDefault"}]},"description":"Function arguments."},"cast":{"$ref":"#/$defs/FieldType"},"operator":{"type":"string","description":"Binary operator, e.g. \"+\"."},"left":{"$ref":"#/$defs/FieldDefault"},"right":{"$ref":"#/$defs/FieldDefault"},"sql_keyword":{"type":"string","description":"SQL keyword, e.g. \"CURRENT_TIMESTAMP\"."}}},"FieldType":{"type":"object","description":"A structured PostgreSQL type, e.g. { name: \"text\" } or { name: \"numeric\", args: [10, 2] }.","properties":{"name":{"type":"string","description":"Type name."},"schema":{"type":"string","description":"Schema qualifier."},"args":{"type":"array","items":{"type":["string","number","boolean"]},"description":"Type arguments."},"array_dimensions":{"type":"integer","description":"Number of array dimensions: 1 is text[]."},"range":{"type":"array","items":{"type":"string"},"maxItems":2,"description":"Interval field range, e.g. [\"day\", \"second\"]."}},"required":["name"]},"GuardStepUpParams":{"type":"object","properties":{"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Which recent proof satisfies the step-up requirement: password (password re-entry), mfa (second factor), password_or_mfa (either factor; an SSO sign-in alone does not count), or fresh_auth (any recent sign-in or re-verification, including SSO, magic link and OTP)","default":"fresh_auth"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML events require step-up verification","default":["UPDATE","DELETE"]},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":[],"description":"Attaches a BEFORE trigger that calls require_step_up() to enforce recent strong verification (password, MFA, or identity-provider assertion) before allowing mutations. Requires a provisioned sessions_module (with app_settings_auth) for the target database. The step_up_window is read from app_settings_auth at runtime (default 30 minutes). Supports compound conditions (AND/OR/NOT), watch_fields (fire only when specific fields change), and simple condition_field/condition_value leaf conditions."},"JobTriggerParams":{"type":"object","properties":{"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier passed to add_job (e.g., process_invoice, sync_to_stripe). Must match a registered function definition when function_module is installed."},"payload_strategy":{"type":"string","enum":["row","row_id","fields","custom"],"description":"How to build the job payload: row (full NEW/OLD), row_id (just id), fields (selected columns), custom (mapped columns)","default":"row_id"},"payload_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names to include in payload (only for fields strategy)"},"payload_custom":{"type":"object","additionalProperties":{"type":"string","format":"column-ref"},"description":"Key-to-column mapping for custom payload (e.g., {\"invoice_id\": \"id\", \"total\": \"amount\"})"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Trigger events to create","default":["INSERT","UPDATE"]},"include_old":{"type":"boolean","description":"Include OLD row in payload (for UPDATE triggers)","default":false},"include_meta":{"type":"boolean","description":"Include table/schema metadata in payload","default":false},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"$ref":"#/$defs/shared-6b829f5502"},"obj_schema":{"$ref":"#/$defs/shared-11a9ffe32a"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"job_key":{"type":"string","description":"Static job key for upsert semantics (prevents duplicate jobs)"},"queue_name":{"type":"string","description":"Job queue name for routing to specific workers"},"queue_key_field":{"type":"string","format":"column-ref","description":"Column whose value keys the job queue, so the queue name becomes \":\". A named queue is held for the whole job, so a shared literal queue serializes every job that uses it; keying on the work's subject keeps same-subject jobs ordered while unrelated subjects run in parallel."},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0},"run_at_delay":{"type":"string","description":"Delay before job runs as PostgreSQL interval (e.g., 30 seconds, 5 minutes)"},"max_attempts":{"type":"integer","description":"Maximum retry attempts for the job","default":25}},"required":["task_identifier"],"description":"Dynamically creates PostgreSQL triggers that enqueue jobs via app_jobs.add_job() when table rows are inserted, updated, or deleted. Supports configurable payload strategies (full row, row ID, selected fields, or custom mapping), conditional firing via WHEN clauses, watched field changes, and extended job options (queue, priority, delay, max attempts)."},"LimitEnforceAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to track (must match a default_limits entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches aggregate limit-tracking triggers to a table. On INSERT the named limit is incremented per entity; on DELETE it is decremented. Uses org_limit_aggregates_inc/dec for per-entity (org-level) aggregate limits rather than per-user limits. Requires a provisioned limits_module for the target database."},"LimitEnforceCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to track (must match a default_limits entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor or entity id used for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for entity context resolution. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches limit-tracking triggers to a table. On INSERT the named limit is incremented; on DELETE it is decremented. Requires a provisioned limits_module for the target scope."},"LimitEnforceFeatureParams":{"type":"object","properties":{"feature_name":{"type":"string","description":"Cap name representing this feature (must match a limit_caps_defaults entry with max=0 or max=1)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for per-entity cap lookups (only used for org scope). For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Which DML events the cap gates. UPDATE is required when a row can reach the gated state after creation (e.g. a discriminator flipped from an ungated value to a gated one). DELETE is not supported: a cap answers whether a row may exist.","default":["INSERT"]},"conditions":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Compound conditions for the trigger WHEN clause, so the cap gates a subset of rows rather than the whole table (e.g. only the rows a customer authors on a table the platform also writes). Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema."}},"required":["feature_name"],"description":"Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). Gate INSERT and UPDATE when a row can reach the gated state after creation, and narrow the gate with conditions when only some of the table's rows are the gated feature."},"LimitEnforceRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry, e.g. \"messaging\", \"inference\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limiting. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id (user) for rate limiting","default":"owner_id"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Which DML events to enforce rate limits on (DELETE is excluded since it reduces load)","default":["INSERT"]}},"required":["meter_slug"],"description":"Attaches a BEFORE trigger that calls check_rate_limit() to enforce sliding-window rate limits before allowing mutations. The function checks all three scopes (entity, actor-in-entity, actor) in a single call; which scopes are actually enforced is controlled by what rows exist in rate_window_limits (plan-based config). Requires a provisioned meter_rate_limits_module and billing_module for the target database."},"LimitTrackUsageParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to record usage against (must match a meters table entry, e.g. \"databases\", \"seats\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for billing. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"quantity":{"type":"integer","description":"Units to record per event (default 1)","default":1},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]},"enforce":{"type":"boolean","description":"With INSERT tracked, also attach a BEFORE INSERT gate on check_billing_quota that refuses a row past the allowance (BILLING_QUOTA_EXCEEDED), like the invocation quota gate. Off (default), rows past the allowance are inserted and their charge is refused. A slug with no meter row is never refused.","default":false}},"required":["meter_slug"],"description":"Declaratively attaches billing usage-recording triggers to a table. On INSERT the named meter is incremented via record_usage; on DELETE it is decremented (reversal). On UPDATE, if the entity_field changes, the old entity is decremented and the new entity is incremented. Requires a provisioned billing_module for the target database."},"LimitWarningAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to watch (must match a limit_warnings.name entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the entity's aggregate usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor/entity triple. Requires a provisioned limits_module with limit_warnings and aggregate limits enabled."},"LimitWarningCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to watch (must match a limit_warnings.name entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id. When provided, entity_id is included in the job payload and dedup state. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires a provisioned limits_module with limit_warnings enabled."},"LimitWarningRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use for warnings and warning_state tables. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for rate limit lookup","default":"owner_id"}},"required":["meter_slug"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current request count in the active sliding window has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires both a limits_module with limit_warnings enabled and a rate_limit_meters_module."},"ProcessChunksParams":{"type":"object","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Parent columns the chunks are cut from. When set, the enqueue triggers fire only once one of them is populated (INSERT) or changed (UPDATE), and the worker chunks exactly those columns. Omit to chunk every readable content column on every write."},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"dimensions":{"type":"integer","description":"Vector dimensions for per-chunk embeddings","default":768},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric for the HNSW index on chunk embeddings","default":"cosine"},"embedding_model":{"type":"string","description":"Embedding model identifier for per-chunk embeddings. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"chunks_table_name":{"type":"string","description":"Override the chunks table name. Defaults to {parent_table}_chunks."},"metadata_fields":{"type":"array","items":{"type":"string"},"description":"Field names from the parent table to copy into chunk metadata"},"search_indexes":{"type":"array","items":{"$ref":"#/$defs/shared-5492e6a87c"},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override (e.g. [\"fulltext\", \"bm25\"])."},"entity_field":{"type":"string","format":"column-ref","description":"Column on the parent table that holds (or references) the entity_id for billing scope. Forwarded to the chunking job trigger."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the chunking job trigger.","properties":{"obj_table":{"$ref":"#/$defs/shared-462d3d2412"},"obj_schema":{"$ref":"#/$defs/shared-3d0fa23a34"},"obj_field":{"$ref":"#/$defs/shared-d4553f7be9"}},"required":["obj_table","obj_field"]},"enqueue_chunking_job":{"type":"boolean","description":"Whether to create a job trigger that auto-enqueues chunking on parent INSERT/UPDATE","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}},"description":"Creates a chunked-embedding child table for any parent table. Provisions the chunks table with content, chunk_index, embedding vector, metadata, HNSW index, inherited RLS, and optional job trigger for automatic text splitting. Composed internally by ProcessFileEmbedding (enabled by default in extract mode) but can also be used standalone."},"ProcessCustomParams":{"type":"object","required":["task_identifier"],"properties":{"task_identifier":{"type":"string","format":"function-ref","description":"Task identifier of the tenant-registered function (namespace:name). Must resolve through the function registry for this database at provisioning time."},"result_field":{"type":"string","format":"column-ref","description":"Optional jsonb field on the files table that receives the result the task hands to the generated writer. When omitted the writer only records the uploaded → processed transition."},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"Optional MIME type LIKE patterns to match. Multiple patterns are OR'd together. When omitted every uploaded file is processed."},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the files table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger."},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for the task","default":"process_custom"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Enqueues a tenant-registered task when a file on a storage files table reaches status = 'uploaded' and generates the result writer the task calls back over the function lane. The task must already be registered for the database (register_function with scope database); the node is refused otherwise."},"ProcessExtractionParams":{"type":"object","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"extraction_model":{"$ref":"#/$defs/shared-f862b57bdc"},"extraction_provider":{"$ref":"#/$defs/shared-82428b2411"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%'].","default":["application/pdf","text/%"]},"routes":{"$ref":"#/$defs/shared-9649b5119d"},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the extraction worker","default":"document:extract_file_text"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and text_field (created as jsonb) and metadata_field hold one entry per element, as jsonb objects keyed by the element's object key."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for extraction tasks","default":"extraction"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates extraction output fields and a job trigger for file text extraction. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks."},"ProcessFileEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 512 for CLIP, 768 for nomic, 1536 for ada-002)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-c9b32dbf00"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"$ref":"#/$defs/shared-cf7316ac6e"},"task_identifier":{"$ref":"#/$defs/shared-f90494132b"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_FILE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"source_bucket":{"$ref":"#/$defs/shared-41591dfcf8"},"variants_bucket":{"$ref":"#/$defs/shared-8aa6c03738"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"$ref":"#/$defs/shared-a0d2b7ccf1"},"include_chunks":{"$ref":"#/$defs/shared-347ff05f99"},"chunks":{"type":"object","description":"Chunking configuration passed through to ProcessChunks. When include_chunks is true (or defaults to true in extract mode), these params configure the chunks table, embedding dimensions, strategy, etc.","default":{},"properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"metadata_fields":{"$ref":"#/$defs/shared-6119be8d95"},"search_indexes":{"$ref":"#/$defs/shared-0ed784651d"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}},"description":"Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided; extract mode composes ProcessExtraction for the text (its task, MIME rule, queue and, on a storage files table, its result writer). On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies."},"ProcessImageEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (default 512 for CLIP-style image embeddings)","default":512},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-0d918e14b9"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image embedding worker. The payload is the file row (file_id, key, mime_type, bucket_id), so the task must be a record worker that reads the object itself — not embedding:process_image_embedding, which embeds an image_url it is handed.","default":"embedding:process_file_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_IMAGE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"}},"description":"Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_file_embedding', direct mode only: there is no image extraction (OCR) worker, so extraction is refused. Every other parameter is forwarded through."},"ProcessImageVersionsParams":{"type":"object","properties":{"versions":{"$ref":"#/$defs/shared-1232a5e8ca"},"versions_field":{"type":"string","format":"column-ref","description":"Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document.","default":"image_versions"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image processing worker","default":"image:process_image_versions"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and each element carries its own manifest in its versions member."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for image processing tasks","default":"image_processing"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates a job trigger for image variant generation. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The image worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.), stores them beside the source object in the file's own bucket, and records each variant's name, key, format, dimensions and size: inside the file column's own document (its versions member) on a business table, in the manifest column on a storage files table. With no versions given the worker uses the default ladder (thumbnail, small, medium, large, xlarge), resolved when the job runs, and skips any version larger than the source."},"SearchBm25Params":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of existing text column to index with BM25"},"text_config":{"type":"string","description":"PostgreSQL text search configuration for BM25","default":"english"},"k1":{"type":"number","description":"BM25 k1 parameter: term frequency saturation (typical: 1.2-2.0)","default":null},"b":{"type":"number","description":"BM25 b parameter: document length normalization (0=none, 1=full, typical: 0.75)","default":null},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["field_name"],"description":"Creates a BM25 index on an existing text column using pg_textsearch. Enables statistical relevance ranking with configurable k1 and b parameters. The BM25 index is auto-detected by graphile-search."},"SearchFullTextParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"},"lang":{"type":"string","description":"PostgreSQL text search configuration","default":"english"}},"required":["field"]},"description":"Source columns that feed the tsvector. Each has a field name, weight (A-D), and language config."},"lang_column":{"type":"string","format":"column-ref","description":"Column name whose value determines the text search configuration per row. When set, the tsvector trigger uses NEW.::regconfig instead of a static language, enabling dynamic per-row language stemming. The per-field lang values in source_fields are used as fallback defaults for the langs array but the trigger reads from this column at runtime."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"],"description":"Adds a tsvector column with GIN index and automatic trigger population from source fields. Enables PostgreSQL full-text search with configurable weights and language support. Leverages the existing metaschema full_text_search infrastructure."},"SearchSpatialAggregateParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the aggregate geometry column on the parent table","default":"geom_aggregate"},"source_table_id":{"type":"string","format":"uuid","description":"UUID of the source (child) table containing individual geometries"},"source_geom_field":{"type":"string","format":"column-ref","description":"Name of the geometry column on the source table","default":"geom"},"source_fk_field":{"type":"string","format":"column-ref","description":"Name of the foreign key column on the source table pointing to the parent"},"aggregate_function":{"type":"string","enum":["union","collect","convex_hull","concave_hull"],"description":"PostGIS aggregation function: union (ST_Union, merges overlapping), collect (ST_Collect, groups without merging), convex_hull (smallest convex polygon), concave_hull (tighter boundary)","default":"union"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"Output geometry type constraint for the aggregate field","default":"MultiPolygon"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method for the aggregate field","default":"gist"}},"required":["source_table_id","source_fk_field"],"description":"Creates a derived/materialized geometry field on the parent table that automatically aggregates geometries from a source (child) table via triggers. When child rows are inserted/updated/deleted, the parent aggregate field is recalculated using the specified PostGIS aggregation function (ST_Union, ST_Collect, ST_ConvexHull, ST_ConcaveHull). Useful for materializing spatial boundaries from collections of points or polygons."},"SearchSpatialParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the geometry/geography column","default":"geom"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"PostGIS geometry type constraint","default":"Point"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry (for geodetic calculations on the sphere)","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method","default":"gist"}},"description":"Adds a PostGIS geometry or geography column with a spatial index (GiST or SP-GiST). Supports configurable geometry types (Point, Polygon, etc.), SRID, and dimensionality. The graphile-postgis plugin auto-detects geometry/geography columns by codec type for spatial filtering (ST_Contains, ST_DWithin, bbox operators)."},"SearchTrgmParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to create trigram indexes on (fields must already exist on the table)"}},"required":["fields"],"description":"Creates GIN trigram indexes (gin_trgm_ops) on specified text/citext fields for fuzzy LIKE/ILIKE/similarity search. Adds @trgmSearch smart tag for PostGraphile integration. Fields must already exist on the table."},"SearchUnifiedParams":{"type":"object","properties":{"full_text_search":{"type":"object","description":"SearchFullText parameters. Omit to skip FTS setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"weight":{"type":"string","enum":["A","B","C","D"]},"lang":{"type":"string"}},"required":["field"]}},"search_score_weight":{"type":"number","default":1}}},"bm25":{"type":"object","description":"SearchBm25 parameters. Omit to skip BM25 setup.","properties":{"field_name":{"type":"string","format":"column-ref"},"text_config":{"type":"string","default":"english"},"k1":{"type":"number"},"b":{"type":"number"},"search_score_weight":{"type":"number","default":1}}},"embedding":{"type":"object","description":"SearchVector parameters. Omit to skip embedding setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"embedding"},"dimensions":{"type":"integer","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"]},"metric":{"type":"string","enum":["cosine","l2","ip"]},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"}},"embedding_model":{"type":"string","description":"Embedding model identifier. When null, the worker falls back to runtime config."},"embedding_provider":{"type":"string","description":"Embedding provider name. When null, the worker falls back to runtime config."},"search_score_weight":{"type":"number","default":1},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}}},"embedding_text_field":{"type":"string","format":"column-ref","description":"Name of the composite text field created for embedding input","default":"embedding_text"},"composite_format":{"type":"string","enum":["labeled","plain"],"description":"Output format for the composite text field","default":"labeled"},"trgm_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to tag with @trgmSearch for fuzzy/typo-tolerant matching"},"search_config":{"type":"object","description":"Unified search score configuration written to @searchConfig smart tag","properties":{"weights":{"type":"object","description":"Per-algorithm weights: {tsv: 1.5, bm25: 1.0, pgvector: 0.8, trgm: 0.3}"},"normalization":{"type":"string","enum":["linear","sigmoid"],"description":"Score normalization strategy","default":"linear"},"boost_recent":{"type":"boolean","description":"Enable recency boost for search results","default":false},"boost_recency_field":{"type":"string","format":"column-ref","description":"Timestamp field for recency boost (e.g. created_at, updated_at)"},"boost_recency_decay":{"type":"number","description":"Decay rate for recency boost (0-1, lower = faster decay)","default":0.5}}}},"description":"Composite node type that orchestrates multiple search modalities (full-text search, BM25, embeddings, trigram) on a single table. Configures per-table search score weights, normalization strategy, and recency boost via the @searchConfig smart tag."},"SearchVectorParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 384, 768, 1536, 3072)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric (cosine, l2, ip)","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names that feed the embedding. Used by stale trigger to detect content changes."},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"enqueue_job":{"type":"boolean","description":"Auto-create trigger that enqueues embedding generation jobs","default":true},"job_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the job queue. Must match a registered function definition when function_module is installed.","default":"embedding:embed_record"},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue. Must match a registered function definition when function_module is installed.","default":"embedding:chunk_record"}}}},"description":"Adds a vector embedding column with HNSW or IVFFlat index for similarity search. Supports configurable dimensions, distance metrics (cosine, l2, ip), per-field {field_name}_updated_at timestamp tracking (read-only in GraphQL), and automatic job enqueue triggers for embedding generation."},"TableOrganizationSettingsParams":{"type":"object","properties":{},"description":"Creates an organization settings table with standard business fields (legal_name, address fields). Uses AuthzEntityMembership for access control."},"TableUserProfilesParams":{"type":"object","properties":{},"description":"Creates a user profiles table with standard profile fields (profile_picture, bio, first_name, last_name, tags, desired). Uses AuthzDirectOwner for edit access and AuthzAllowAll for select."},"TableUserSettingsParams":{"type":"object","properties":{},"description":"Creates a user settings table for user-specific configuration. Uses AuthzDirectOwner for access control."},"TriggerCondition":{"type":"object","properties":{"field":{"type":"string","description":"Column name (validated against the table)."},"op":{"enum":["=","!=",">","<",">=","<=","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS DISTINCT FROM"],"description":"Comparison operator."},"value":{"description":"Comparison value. Type is resolved from the column definition."},"row":{"enum":["NEW","OLD"],"description":"Row reference (default: NEW)."},"ref":{"type":"object","properties":{"field":{"type":"string"},"row":{"enum":["NEW","OLD"]}},"description":"Column reference for field-to-field comparison (alternative to value)."},"AND":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with AND."},"OR":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with OR."},"NOT":{"$ref":"#/$defs/TriggerCondition","description":"Negated condition."}},"description":"Recursive condition type for compound trigger WHEN clauses. Leaf conditions specify {field, op, value?, row?, ref?}. Combinators nest via AND, OR, NOT."},"shared-001d8d7cd3":{"anyOf":[{"required":["obj_table_id"]},{"required":["obj_schema","obj_table"]}]},"shared-0022037ad5":{"if":{"properties":{"$type":{"const":"AuthzValueAllowed"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueAllowedParams"}},"required":["data"]}},"shared-0165627a32":{"type":"array","items":{"type":"string"},"description":"Capability names of any kind (capability, level, ...) merged into the same mask"},"shared-0379afb669":{"if":{"properties":{"$type":{"const":"AuthzDirectOwnerAny"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"}},"required":["data"]}},"shared-040cc005ef":{"type":"array","minItems":1,"items":{"$ref":"#/$defs/AuthzExpression"}},"shared-066977ff2f":{"anyOf":[{"required":["obj_field"]},{"required":["obj_field_id"]}]},"shared-078ee82414":{"properties":{"$type":{"const":"CheckOneOf"}},"required":["$type"]},"shared-0968d06284":{"type":"string","description":"Schema of the join table (or use obj_table_id)"},"shared-0a22d2c3f6":{"type":"string","description":"Single column name for the index."},"shared-0d918e14b9":{"type":"string","description":"Embedding model identifier (e.g. \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"shared-0ed784651d":{"type":"array","items":{"type":"string","enum":["fulltext","bm25","trigram"]},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override."},"shared-11a9ffe32a":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"shared-1232a5e8ca":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","description":"Version identifier (e.g., \"thumb\", \"preview\", \"hero\")"},"width":{"type":"integer","description":"Target width in pixels"},"height":{"type":"integer","description":"Target height in pixels"},"fit":{"type":"string","enum":["cover","contain","fill","inside","outside"],"description":"Resize fitting strategy","default":"cover"},"format":{"type":"string","enum":["jpeg","png","webp","avif"],"description":"Output image format","default":"webp"},"quality":{"type":"integer","description":"Output quality (1-100)","default":80}},"required":["name"]},"description":"Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Optional: when omitted the worker resolves the default ladder at job time (thumbnail 160x160 cover, then small 320, medium 640, large 1280 and xlarge 1920 wide, WebP quality 80), so a later change to the default reaches tables already provisioned. A version larger than the source is skipped rather than upscaled.","minItems":1},"shared-13aff2afe8":{"type":"string","description":"The member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-152f619c56":{"if":{"properties":{"$type":{"const":"AuthzDenyAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDenyAllParams"}}}},"shared-1a317ed066":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger."},"shared-1afc3ee393":{"if":{"properties":{"$type":{"const":"AuthzNotReadOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzNotReadOnlyParams"}},"required":["data"]}},"shared-1c8d46d43b":{"properties":{"$type":{"const":"CheckNotEqual"}},"required":["$type"]},"shared-1d336e787f":{"if":{"properties":{"$type":{"const":"AuthzValueExists"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueExistsParams"}},"required":["data"]}},"shared-21a1ba9587":{"if":{"properties":{"$type":{"const":"AuthzAppMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMembershipParams"}}}},"shared-22f38cc906":{"type":"array","items":{"type":"string"},"description":"Operator classes for the index columns."},"shared-230094622e":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"obj_field":{"type":"string","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"shared-2997c2f821":{"if":{"properties":{"$type":{"const":"AuthzSystemOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzSystemOnlyParams"}}}},"shared-2a834ba4ff":{"type":"string","description":"Index access method (e.g., \"BTREE\", \"GIN\", \"GIST\", \"HNSW\", \"BM25\")."},"shared-2c20767ba3":{"properties":{"$type":{"const":"CheckGreaterThan"}},"required":["$type"]},"shared-33af0ede37":{"type":"string","format":"column-ref","description":"Single column to compare against value (mutually exclusive with columns)"},"shared-347ff05f99":{"type":"boolean","description":"Whether to create a chunks table via ProcessChunks. Defaults to true when extraction is provided, false in direct mode. Set explicitly to override."},"shared-35954fc61d":{"if":{"properties":{"$type":{"const":"AuthzPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPeerOwnershipParams"}},"required":["data"]}},"shared-36ea8e912e":{"if":{"properties":{"$type":{"const":"AuthzDatabaseClaim"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDatabaseClaimParams"}}}},"shared-39f66ad592":{"if":{"properties":{"$type":{"const":"AuthzAllowAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAllowAllParams"}}}},"shared-3a33134347":{"type":"object","description":"Metadata fields from parent to copy into chunks"},"shared-3d0fa23a34":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"shared-411f8ee76d":{"type":"string","description":"Schema of the referenced table (or use ref_table_id)"},"shared-41591dfcf8":{"type":"object","description":"Typed bucket reference ({\"$ref\":\"bucket\",\"tags\":[...],\"type\":...}) for the bucket the source files live in, when it is not the record's own bucket_id (which payload_custom already carries). Stamped into the trigger payload at attach time and resolved to coordinates at dispatch.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"shared-462d3d2412":{"type":"string","description":"Name of the related table to look up entity_id from"},"shared-48649a3a43":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"}},"shared-51c1d9a5f0":{"type":"string","minLength":1,"not":{"const":"app"},"description":"Entity type prefix (e.g. 'org', 'channel', 'department'), resolved to its membership_type; use it instead of membership_type for readability."},"shared-5492e6a87c":{"type":"string","enum":["fulltext","bm25","trigram"]},"shared-55595a36d2":{"type":["array","object"],"items":{"type":"object"},"description":"Optional higher-level condition JSON applied to the referenced table (row alias d)"},"shared-5a2832df1c":{"type":"array","items":{"type":"string"},"description":"Array of column names for a multi-column index."},"shared-5a2b860e32":{"if":{"properties":{"$type":{"const":"AuthzMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberListParams"}},"required":["data"]}},"shared-5e11bfeb01":{"type":"boolean","description":"If true, require is_owner flag on current user membership"},"shared-6119be8d95":{"type":"array","items":{"type":"string"},"description":"Field names from parent to copy into chunk metadata"},"shared-626b0c3c0b":{"type":"array","items":{"$ref":"#/$defs/BlueprintFtsSource"},"description":"Source fields that feed into this tsvector."},"shared-637ef72440":{"type":"string","pattern":"^[01]+$","description":"Capability bits a member must hold, as a bit string. Capabilities or levels, when given, replace it."},"shared-6639e33d04":{"if":{"properties":{"$type":{"const":"AuthzComposite"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzCompositeParams"}}}},"shared-693097b0e5":{"if":{"properties":{"$type":{"const":"AuthzValueMatch"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueMatchParams"}},"required":["data"]}},"shared-698b2fd59a":{"type":"integer","minimum":2,"maximum":2147483647,"description":"The team kind: 2=org, 3+=dynamic entity types."},"shared-6ac44ac2ba":{"if":{"properties":{"$type":{"const":"AuthzDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerParams"}},"required":["data"]}},"shared-6adc1df48e":{"type":"string","description":"Optional schema name for disambiguation (falls back to top-level default)."},"shared-6b829f5502":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"shared-6dbc2f5a83":{"if":{"properties":{"$type":{"const":"AuthzPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPublishableParams"}}}},"shared-6ea79cf84b":{"type":"array","minItems":1,"description":"Join conditions between the protected row and the referenced table","items":{"type":"object","properties":{"local_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table"},"ref_column":{"$ref":"#/$defs/shared-7539b204c0"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"shared-6eb30390ff":{"type":"string","enum":["INSERT","DELETE","UPDATE"]},"shared-7539b204c0":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table"},"shared-757c15800e":{"type":"string","description":"Name of the CHECK constraint."},"shared-7756a0ed5a":{"if":{"properties":{"$type":{"const":"AuthzRelatedEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"}},"required":["data"]}},"shared-787b8adf81":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Additional compound conditions beyond auto-generated filtering. Merged with the auto-generated conditions via AND."},"shared-7a53e1103e":{"type":"boolean","description":"Select sel_field from the related row instead of the team id; the platform's own related policies set it with sel_field \"id\"."},"shared-7edb884d72":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from"},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"}},"required":["obj_table","obj_field"]},"shared-7f50b0e5b7":{"type":"string","description":"Name of the referenced table (or use ref_table_id)"},"shared-82428b2411":{"type":"string","description":"Extraction provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"shared-8358853df2":{"properties":{"$type":{"const":"CheckLessThan"}},"required":["$type"]},"shared-8763e18b77":{"anyOf":[{"required":["membership_type"]},{"required":["entity_type"]},{"required":["sprt_schema","sprt_table"]}]},"shared-88656ecafa":{"type":"string","format":"column-ref","description":"Column name for conditional WHEN clause (fires only when field equals condition_value)"},"shared-8881b94a41":{"if":{"properties":{"$type":{"const":"AuthzTemporal"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzTemporalParams"}}}},"shared-8aa6c03738":{"type":"object","description":"Typed bucket reference for where derived outputs (thumbnails, resized variants, extracted assets) are written. Stamped into the trigger payload at attach time and resolved to coordinates at dispatch, so the function never selects a bucket.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"shared-8cc6b29877":{"type":"string","format":"uuid","description":"UUID of the referenced table (alternative to ref_schema/ref_table)"},"shared-8cef65cfda":{"type":"object","additionalProperties":{"oneOf":[{"type":"string","format":"column-ref"},{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"path":{"$ref":"#/$defs/shared-9b5e4c440f"}},"required":["field","path"]}]},"description":"Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({\"field\": \"upload\", \"path\": [\"key\"]}). Defaults to the four file columns, or to the file_field document when file_field is set."},"shared-9146e81ef6":{"type":"string","format":"uuid","description":"UUID of the join table (alternative to obj_schema/obj_table)"},"shared-927486214a":{"type":"boolean","description":"If true, require is_admin flag"},"shared-9572999fa8":{"type":"string","description":"The schema of the member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-9649b5119d":{"type":"array","items":{"type":"object","properties":{"mime_patterns":{"type":"array","items":{"type":"string"},"minItems":1,"description":"MIME type LIKE patterns this route takes, e.g. ['application/vnd.openxmlformats-officedocument.%']."},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier of the function that extracts these MIME types"},"extraction_model":{"type":"string","description":"Extraction model for this route; the node's when omitted"},"extraction_provider":{"type":"string","description":"Extraction provider for this route; the node's when omitted"},"queue_name":{"type":"string","description":"Job queue name for this route; the node's when omitted"},"max_attempts":{"type":"integer","description":"Maximum retry attempts for this route; the node's when omitted"},"priority":{"type":"integer","description":"Job priority for this route; the node's when omitted"}},"required":["mime_patterns","task_identifier"]},"description":"MIME types sent to another extraction function. A file runs the first route whose mime_patterns match it; the node's own mime_patterns and task_identifier take only the files no route matched, so one file never runs two functions. Every route writes the node's text_field and metadata_field, and shares its file_field, events, trigger_conditions and billing scope. A task is named once across the node and its routes (PROCESS_EXTRACTION_DUPLICATE_ROUTE_TASK). Example: [{\"mime_patterns\": [\"application/vnd.openxmlformats-officedocument.%\"], \"task_identifier\": \"office:extract_text\"}]."},"shared-968a890679":{"if":{"properties":{"$type":{"const":"AuthzOrgHierarchy"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzOrgHierarchyParams"}},"required":["data"]}},"shared-9b5e4c440f":{"type":"array","items":{"type":"string"},"minItems":1},"shared-9d6147637c":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id, org_id)"},"shared-a0bfcadf85":{"type":"array","items":{"type":"string"},"description":"Column names that form the unique constraint."},"shared-a0d2b7ccf1":{"type":"object","description":"Text extraction configuration. When present, the node composes ProcessExtraction (output fields, MIME-conditional trigger on queue extraction with 5 attempts, and on a storage files table the _write_extraction writer) and configures SearchVector with the text field as source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction).","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"routes":{"type":"array","items":{"type":"object","properties":{"mime_patterns":{"$ref":"#/$defs/shared-9b5e4c440f"},"task_identifier":{"type":"string","format":"function-ref"}},"required":["mime_patterns","task_identifier"]},"description":"MIME types sent to another extraction function, as ProcessExtraction.routes: the first matching route takes a file, and the node's own mime_patterns and task take the rest."}}},"shared-a5a04dd84a":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberListParams"}},"required":["data"]}},"shared-a9d73b8ba7":{"if":{"properties":{"$type":{"const":"AuthzMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberOwnerParams"}}}},"shared-ab071ec2f8":{"type":"boolean","description":"If true, require is_owner flag"},"shared-ab15ceab40":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations."},"shared-ac9a0977fa":{"type":"string","description":"Embedding provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"shared-aced6572ca":{"if":{"properties":{"$type":{"const":"AuthzHumanOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzHumanOnlyParams"}}}},"shared-ad437cb66f":{"type":"string","format":"column-ref","x-column-scope":"local"},"shared-ad8f69741a":{"type":"string","description":"Optional schema name override."},"shared-af38a22089":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch"]},"shared-b0876b5627":{"type":"array","items":{"type":"string"},"description":"Achievement level names to require (kind=level catalog rows, merged into the same mask)"},"shared-b1944d8f7b":{"description":"Allowed values as a constant list, or a local column name containing the allowed values","anyOf":[{"type":"string","format":"column-ref","x-column-scope":"local","description":"Local column name containing allowed values"},{"type":"array","items":{"type":["string","boolean","number","null"]},"description":"Constant list of allowed values. Element JSON type is preserved: booleans/numbers emit typed constants (e.g. [true] -> TRUE, [5] -> 5), strings emit text literals."}]},"shared-b297346d46":{"if":{"properties":{"$type":{"const":"AuthzRelatedPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"}},"required":["data"]}},"shared-b68f53d1ed":{"type":"integer","description":"The width the mask is padded to; by default the length of the mask."},"shared-bb55f34041":{"type":"boolean","description":"Whether this is a unique index."},"shared-bc381c03de":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{}}},"required":["roles","privileges"]},"shared-c5c620bfe3":{"type":"string","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. A zero mask requires nothing."},"shared-c9b32dbf00":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\", \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"shared-ca5d04c28d":{"if":{"properties":{"$type":{"const":"AuthzEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzEntityMembershipParams"}},"required":["data"]}},"shared-cc52e308f2":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Compound conditions for the trigger WHEN clause. Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema. Cannot be combined with condition_field or watch_fields."},"shared-cd4dc6cdf6":{"type":"string","description":"Name of the join table (or use obj_table_id)"},"shared-cf7316ac6e":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%']. Defaults to ['image/%'] in direct mode and to ['application/pdf', 'text/%'] in extract mode."},"shared-d3e6ac0b5d":{"type":"boolean","description":"If true, require is_admin flag on current user membership"},"shared-d4553f7be9":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"},"shared-d85a10e177":{"type":"object","description":"Reference to a table an installed module generated, resolved during blueprint construction (alternative to ref_table_id / ref_schema + ref_table)","properties":{"type":{"type":"string","description":"Module type owning the table, e.g. \"agent\""},"table":{"type":"string","description":"Logical table key within the module, e.g. \"thread\""},"scope":{"type":"string","description":"Scope of the module instance, e.g. \"app\" or \"org\""},"prefix":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations"}},"required":["type","table"]},"shared-d8e76848ea":{"type":"string","format":"uuid","description":"UUID of field on join table (alternative to obj_field)"},"shared-db0e2e6361":{"type":"string","format":"uuid","description":"Table being referenced by the FK"},"shared-dfbaf50fc6":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the join table"},"shared-e1125a4a5e":{"type":"string","description":"Scope of the module instance (e.g. \"app\", \"org\"). Required when the database installs the module at more than one scope."},"shared-e6dbbbcd8d":{"type":"string","enum":["c","r","n","d","a"],"description":"FK delete action: c=CASCADE, r=RESTRICT, n=SET NULL, d=SET DEFAULT, a=NO ACTION. Required."},"shared-e772a2f2a5":{"type":"object","additionalProperties":{},"description":"Additional index-specific options."},"shared-eb6d498d14":{"if":{"properties":{"$type":{"const":"AuthzAppMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"}}}},"shared-eb860e1011":{"type":"string","enum":["INSERT","UPDATE","DELETE"]},"shared-ee69c55731":{"type":"string","description":"Name of the tsvector field on the table."},"shared-effacc6003":{"type":"object","description":"A further row that must exist in a third table, joined to the referenced row (alias b unless ref_alias says otherwise).","properties":{"ref_table_id":{"type":"string","format":"uuid","description":"UUID of the third table (alternative to ref_schema/ref_table)"},"ref_schema":{"type":"string","description":"Schema of the third table (or use ref_table_id)"},"ref_table":{"type":"string","description":"Name of the third table (or use ref_table_id)"},"ref_alias":{"type":"string","description":"Alias of the third table in the join","default":"b"},"join":{"type":"array","description":"Join conditions between the referenced row and the third table","items":{"type":"object","properties":{"local_column":{"$ref":"#/$defs/shared-7539b204c0"},"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the third table"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"conditions":{"type":["array","object"],"items":{"type":"object"},"description":"Optional condition JSON applied to the third table"}},"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]}],"additionalProperties":false},"shared-f35a015b21":{"type":"string","description":"Optional custom name for the index."},"shared-f4262069e5":{"type":"string","enum":["public","private","temp"]},"shared-f5f12fa8f6":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"}},"required":["data"]}},"shared-f7ad90b1e2":{"type":"string","description":"Value to compare against condition_field in WHEN clause"},"shared-f862b57bdc":{"type":"string","description":"Extraction model identifier (e.g. a vision model for OCR, an LLM for structured extraction). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config."},"shared-f90494132b":{"type":"string","format":"function-ref","description":"Job task identifier for the worker. In direct mode this is the embedding worker (default embedding:process_file_embedding); in extract mode this is the extraction worker (default document:extract_file_text)."},"shared-fe3f452ee5":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For UPDATE triggers, only fire when these fields change (uses DISTINCT FROM)"},"shared-ff315e2ff3":{"if":{"properties":{"$type":{"const":"AuthzFilePath"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzFilePathParams"}},"required":["data"]}}}};
diff --git a/packages/node-type-registry/src/blueprint-types.generated.ts b/packages/node-type-registry/src/blueprint-types.generated.ts
index 318a01db09..ef846ea548 100644
--- a/packages/node-type-registry/src/blueprint-types.generated.ts
+++ b/packages/node-type-registry/src/blueprint-types.generated.ts
@@ -87,6 +87,7 @@ export interface CheckOwnedRelationParams {
/* Optional link column additionally restricted regardless of ownership (e.g. a bucket type) */target_type_field_name?: string;
/* Value target_type_field_name must equal */target_type_value?: string;
/* Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database */allow_owner_tier?: boolean;
+ /* Admit rows owned by any frame on the referencing row's own scope-frame chain (its own scopes, then the platform database's chain) for this column, for pointers naming a definition published UP the hierarchy — the shared platform function image a tenant route targets. Ancestry only: a peer or another keyed owner is on no chain. Requires owner_key_field_name */allow_frame_chain?: boolean;
}[];
/* How many pointers a row must set: exactly_one for a polymorphic target (route → api OR site OR bucket), all for a junction/join row of a has-and-belongs-to-many relation (and for a mandatory belongs-to), any for optional pointers that are only checked when set */
arity?: 'exactly_one' | 'all' | 'any';
@@ -131,8 +132,11 @@ export interface DataBulkParams {
export interface DataCapabilitiesParams {
/* Name of the bit(n) mask column to create on this table. */
field?: string;
- /* Selects the capabilities module whose bit numbering the mask is measured in, by scope (e.g. "app", "org") or by table prefix. Required only when the database has more than one; several with no selector raises naming the candidates. */
- capabilities?: string;
+ /* Selector for the capabilities module whose bit numbering the mask is measured in, e.g. {"scope": "org"}. Every key given must match exactly one module; none or several raises naming the candidates. Required only when the database has more than one. */
+ capabilities?: {
+ /* Scope the module is installed at ("app", "org", or an entity type prefix). */scope?: string;
+ /* Table prefix of the module instance; rarely needed since prefix follows scope. */prefix?: string;
+ };
/* Capability names every row requires unless told otherwise, resolved to a literal mask and baked into the column default. Omitted means a zero mask: requires nothing. */
default?: string[];
/* Who writes the mask: "direct" the writer, bounded by the subset guard; "derived" the mapping row named by from_column, stamped by generated triggers and hidden from mutations. */
@@ -336,7 +340,7 @@ export interface DataInflectionParams {
/* Inflection operations to apply in order */
ops: ('plural' | 'singular' | 'camel' | 'pascal' | 'dashed' | 'slugify' | 'underscore' | 'lower' | 'upper')[];
}
-/** BEFORE INSERT trigger that copies specified fields from a parent table via a foreign key. The parent row is looked up through RLS (SECURITY INVOKER), so the insert fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files. */
+/** BEFORE INSERT OR UPDATE trigger that copies specified fields from a parent table via a foreign key; on UPDATE the fields are re-copied only when the parent FK changes. The parent row is looked up through RLS (SECURITY INVOKER), so the insert or update fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files. */
export interface DataInheritFromParentParams {
/* Name of the FK field on this table that references the parent (e.g. bucket_id) */
parent_fk_field: string;
@@ -638,7 +642,7 @@ export interface LimitEnforceCounterParams {
/* Which DML events to attach triggers for */
events?: ('INSERT' | 'DELETE' | 'UPDATE')[];
}
-/** Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE INSERT trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). */
+/** Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). Gate INSERT and UPDATE when a row can reach the gated state after creation, and narrow the gate with conditions when only some of the table's rows are the gated feature. */
export interface LimitEnforceFeatureParams {
/* Cap name representing this feature (must match a limit_caps_defaults entry with max=0 or max=1) */
feature_name: string;
@@ -652,6 +656,10 @@ export interface LimitEnforceFeatureParams {
/* Schema of the related table (user-facing name, e.g., "public"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous). */obj_schema?: string;
/* Column on the related table that holds the entity_id (e.g., "entity_id"). Required. */obj_field: string;
};
+ /* Which DML events the cap gates. UPDATE is required when a row can reach the gated state after creation (e.g. a discriminator flipped from an ungated value to a gated one). DELETE is not supported: a cap answers whether a row may exist. */
+ events?: ('INSERT' | 'UPDATE')[];
+ /* Compound conditions for the trigger WHEN clause, so the cap gates a subset of rows rather than the whole table (e.g. only the rows a customer authors on a table the platform also writes). Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema. */
+ conditions?: TriggerCondition | TriggerCondition[];
}
/** Attaches a BEFORE trigger that calls check_rate_limit() to enforce sliding-window rate limits before allowing mutations. The function checks all three scopes (entity, actor-in-entity, actor) in a single call; which scopes are actually enforced is controlled by what rows exist in rate_window_limits (plan-based config). Requires a provisioned meter_rate_limits_module and billing_module for the target database. */
export interface LimitEnforceRateParams {
@@ -692,6 +700,8 @@ export interface LimitTrackUsageParams {
quantity?: number;
/* Which DML events to attach triggers for */
events?: ('INSERT' | 'DELETE' | 'UPDATE')[];
+ /* With INSERT tracked, also attach a BEFORE INSERT gate on check_billing_quota that refuses a row past the allowance (BILLING_QUOTA_EXCEEDED), like the invocation quota gate. Off (default), rows past the allowance are inserted and their charge is refused. A slug with no meter row is never refused. */
+ enforce?: boolean;
}
/**
* ===========================================================================
@@ -965,6 +975,8 @@ export interface JobTriggerParams {
job_key?: string;
/* Job queue name for routing to specific workers */
queue_name?: string;
+ /* Column whose value keys the job queue, so the queue name becomes ":". A named queue is held for the whole job, so a shared literal queue serializes every job that uses it; keying on the work's subject keeps same-subject jobs ordered while unrelated subjects run in parallel. */
+ queue_key_field?: string;
/* Job priority (lower = higher priority) */
priority?: number;
/* Delay before job runs as PostgreSQL interval (e.g., 30 seconds, 5 minutes) */
@@ -982,6 +994,8 @@ export interface JobTriggerParams {
export interface ProcessChunksParams {
/* Name of the text content column in the chunks table */
content_field_name?: string;
+ /* Parent columns the chunks are cut from. When set, the enqueue triggers fire only once one of them is populated (INSERT) or changed (UPDATE), and the worker chunks exactly those columns. Omit to chunk every readable content column on every write. */
+ source_fields?: string[];
/* Maximum number of characters per chunk */
chunk_size?: number;
/* Number of overlapping characters between consecutive chunks */
@@ -1015,7 +1029,32 @@ export interface ProcessChunksParams {
/* Task identifier for the chunking job queue */
chunking_task_name?: string;
}
-/** Creates extraction output fields and a job trigger for file text extraction. Fires when a file is uploaded (status = 'uploaded') or on INSERT. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks. */
+/** Enqueues a tenant-registered task when a file on a storage files table reaches status = 'uploaded' and generates the result writer the task calls back over the function lane. The task must already be registered for the database (register_function with scope database); the node is refused otherwise. */
+export interface ProcessCustomParams {
+ /* Task identifier of the tenant-registered function (namespace:name). Must resolve through the function registry for this database at provisioning time. */
+ task_identifier: string;
+ /* Optional jsonb field on the files table that receives the result the task hands to the generated writer. When omitted the writer only records the uploaded → processed transition. */
+ result_field?: string;
+ /* Optional MIME type LIKE patterns to match. Multiple patterns are OR'd together. When omitted every uploaded file is processed. */
+ mime_patterns?: string[];
+ /* Additional compound conditions beyond auto-generated filtering. Merged with the auto-generated conditions via AND. */
+ trigger_conditions?: TriggerCondition | TriggerCondition[];
+ /* Column on the files table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger. */
+ entity_field?: string;
+ /* FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger. */
+ entity_lookup?: {
+ /* Name of the related table to look up entity_id from */obj_table: string;
+ /* Schema of the related table (user-facing name, optional) */obj_schema?: string;
+ /* Column on the related table that holds the entity_id */obj_field: string;
+ };
+ /* Job queue name for the task */
+ queue_name?: string;
+ /* Maximum number of retry attempts */
+ max_attempts?: number;
+ /* Job priority (lower = higher priority) */
+ priority?: number;
+}
+/** Creates extraction output fields and a job trigger for file text extraction. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks. */
export interface ProcessExtractionParams {
/* Field to store extracted text/markdown */
text_field?: string;
@@ -1027,11 +1066,21 @@ export interface ProcessExtractionParams {
extraction_provider?: string;
/* MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%']. */
mime_patterns?: string[];
+ /* MIME types sent to another extraction function. A file runs the first route whose mime_patterns match it; the node's own mime_patterns and task_identifier take only the files no route matched, so one file never runs two functions. Every route writes the node's text_field and metadata_field, and shares its file_field, events, trigger_conditions and billing scope. A task is named once across the node and its routes (PROCESS_EXTRACTION_DUPLICATE_ROUTE_TASK). Example: [{"mime_patterns": ["application/vnd.openxmlformats-officedocument.%"], "task_identifier": "office:extract_text"}]. */
+ routes?: {
+ /* MIME type LIKE patterns this route takes, e.g. ['application/vnd.openxmlformats-officedocument.%']. */mime_patterns: string[];
+ /* Job task identifier of the function that extracts these MIME types */task_identifier: string;
+ /* Extraction model for this route; the node's when omitted */extraction_model?: string;
+ /* Extraction provider for this route; the node's when omitted */extraction_provider?: string;
+ /* Job queue name for this route; the node's when omitted */queue_name?: string;
+ /* Maximum retry attempts for this route; the node's when omitted */max_attempts?: number;
+ /* Job priority for this route; the node's when omitted */priority?: number;
+ }[];
/* Job task identifier for the extraction worker */
task_identifier?: string;
- /* Trigger events that fire the job */
+ /* Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested). */
events?: ('INSERT' | 'UPDATE')[];
- /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */
+ /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and text_field (created as jsonb) and metadata_field hold one entry per element, as jsonb objects keyed by the element's object key. */
file_field?: string;
/* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */
payload_custom?: {
@@ -1054,7 +1103,7 @@ export interface ProcessExtractionParams {
/* Job priority (lower = higher priority) */
priority?: number;
}
-/** Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies. */
+/** Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided; extract mode composes ProcessExtraction for the text (its task, MIME rule, queue and, on a storage files table, its result writer). On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies. */
export interface ProcessFileEmbeddingParams {
/* Name of the vector embedding column */
field_name?: string;
@@ -1072,13 +1121,13 @@ export interface ProcessFileEmbeddingParams {
embedding_model?: string;
/* Embedding provider name (e.g. "ollama", "openai"). When null, the worker falls back to runtime config. */
embedding_provider?: string;
- /* MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%']. */
+ /* MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%']. Defaults to ['image/%'] in direct mode and to ['application/pdf', 'text/%'] in extract mode. */
mime_patterns?: string[];
- /* Job task identifier for the worker. In direct mode this is the embedding worker; in extract mode this is the extraction worker. */
+ /* Job task identifier for the worker. In direct mode this is the embedding worker (default embedding:process_file_embedding); in extract mode this is the extraction worker (default document:extract_file_text). */
task_identifier?: string;
- /* Trigger events that fire the job */
+ /* Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested). */
events?: ('INSERT' | 'UPDATE')[];
- /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */
+ /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_FILE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element. */
file_field?: string;
/* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */
payload_custom?: {
@@ -1108,10 +1157,14 @@ export interface ProcessFileEmbeddingParams {
/* Schema of the related table (user-facing name, optional) */obj_schema?: string;
/* Column on the related table that holds the entity_id */obj_field: string;
};
- /* Text extraction configuration. When present, the generator creates extraction output fields on the table and configures SearchVector with source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction). */
+ /* Text extraction configuration. When present, the node composes ProcessExtraction (output fields, MIME-conditional trigger on queue extraction with 5 attempts, and on a storage files table the _write_extraction writer) and configures SearchVector with the text field as source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction). */
extraction?: {
/* Field to store extracted text/markdown */text_field?: string;
/* JSONB field for extraction metadata (page count, language, etc.) */metadata_field?: string;
+ /* MIME types sent to another extraction function, as ProcessExtraction.routes: the first matching route takes a file, and the node's own mime_patterns and task take the rest. */routes?: {
+ mime_patterns: string[];
+ task_identifier: string;
+ }[];
};
/* Whether to create a chunks table via ProcessChunks. Defaults to true when extraction is provided, false in direct mode. Set explicitly to override. */
include_chunks?: boolean;
@@ -1127,7 +1180,7 @@ export interface ProcessFileEmbeddingParams {
/* Task identifier for the chunking job queue */chunking_task_name?: string;
};
}
-/** Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_image_embedding', direct mode (no extraction). Accepts all ProcessFileEmbedding parameters — any overrides are forwarded through. */
+/** Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_file_embedding', direct mode only: there is no image extraction (OCR) worker, so extraction is refused. Every other parameter is forwarded through. */
export interface ProcessImageEmbeddingParams {
/* Name of the vector embedding column */
field_name?: string;
@@ -1147,11 +1200,11 @@ export interface ProcessImageEmbeddingParams {
embedding_provider?: string;
/* MIME type LIKE patterns to match. Multiple patterns are OR'd together. */
mime_patterns?: string[];
- /* Job task identifier for the image embedding worker */
+ /* Job task identifier for the image embedding worker. The payload is the file row (file_id, key, mime_type, bucket_id), so the task must be a record worker that reads the object itself — not embedding:process_image_embedding, which embeds an image_url it is handed. */
task_identifier?: string;
/* Trigger events that fire the job */
events?: ('INSERT' | 'UPDATE')[];
- /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */
+ /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_IMAGE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element. */
file_field?: string;
/* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */
payload_custom?: {
@@ -1167,28 +1220,11 @@ export interface ProcessImageEmbeddingParams {
/* Schema of the related table (user-facing name, optional) */obj_schema?: string;
/* Column on the related table that holds the entity_id */obj_field: string;
};
- /* Text extraction configuration. Forwarded to ProcessFileEmbedding. When present, enables extract mode (e.g., OCR for images). */
- extraction?: {
- /* Field to store extracted text */text_field?: string;
- /* JSONB field for extraction metadata */metadata_field?: string;
- };
- /* Chunking configuration. Forwarded to ProcessFileEmbedding. Only meaningful when extraction is also provided. */
- chunks?: {
- content_field_name?: string;
- chunk_size?: number;
- chunk_overlap?: number;
- chunk_strategy?: 'fixed' | 'sentence' | 'paragraph' | 'semantic';
- metadata_fields?: {
- [key: string]: unknown;
- };
- enqueue_chunking_job?: boolean;
- chunking_task_name?: string;
- };
}
-/** Creates a job trigger for image variant generation. Fires when an image file is uploaded (status = 'uploaded') or on INSERT. The external worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.) and stores them as new file records linked to the source image. */
+/** Creates a job trigger for image variant generation. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The image worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.), stores them beside the source object in the file's own bucket, and records each variant's name, key, format, dimensions and size: inside the file column's own document (its versions member) on a business table, in the manifest column on a storage files table. With no versions given the worker uses the default ladder (thumbnail, small, medium, large, xlarge), resolved when the job runs, and skips any version larger than the source. */
export interface ProcessImageVersionsParams {
- /* Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Required — the blueprint must explicitly define what variants to generate. */
- versions: {
+ /* Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Optional: when omitted the worker resolves the default ladder at job time (thumbnail 160x160 cover, then small 320, medium 640, large 1280 and xlarge 1920 wide, WebP quality 80), so a later change to the default reaches tables already provisioned. A version larger than the source is skipped rather than upscaled. */
+ versions?: {
/* Version identifier (e.g., "thumb", "preview", "hero") */name: string;
/* Target width in pixels */width?: number;
/* Target height in pixels */height?: number;
@@ -1196,13 +1232,15 @@ export interface ProcessImageVersionsParams {
/* Output image format */format?: 'jpeg' | 'png' | 'webp' | 'avif';
/* Output quality (1-100) */quality?: number;
}[];
- /* MIME type LIKE patterns to match. Defaults to all image types. */
+ /* Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document. */
+ versions_field?: string;
+ /* MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it. */
mime_patterns?: string[];
/* Job task identifier for the image processing worker */
task_identifier?: string;
- /* Trigger events that fire the job */
+ /* Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested). */
events?: ('INSERT' | 'UPDATE')[];
- /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */
+ /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and each element carries its own manifest in its versions member. */
file_field?: string;
/* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */
payload_custom?: {
@@ -1346,7 +1384,7 @@ export interface AuthzEntityMembershipParams {
levels?: string[];
/* Capability names of any kind (capability, level, ...) merged into the same mask */
capabilities?: string[];
- /* Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capability/capabilities — both are ANDed. */
+ /* Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capabilities — both checks must pass. */
mask_column?: string;
/* If true, require is_admin flag */
is_admin?: boolean;
@@ -1762,6 +1800,8 @@ export interface RelationBelongsToParams {
delete_action: 'c' | 'r' | 'n' | 'd' | 'a';
/* Whether the FK field is NOT NULL */
is_required?: boolean;
+ /* Columns both tables carry that the referenced row must share with the referencing row (e.g. ["entity_id"], or ["project_id"] for a stage of the same project). Adds a hidden composite FK (field_name, ...scope_fields) -> target (id, ...scope_fields) plus the target unique key it needs, so a row cannot point at another scope's row even when it knows the id. */
+ scope_fields?: string[];
}
/** Creates a foreign key field on the target table referencing the source table. Inverse of RelationBelongsTo — same FK, different perspective. "projects has many tasks" creates tasks.project_id. Auto-derives the FK field name from the source table name using inflection. delete_action is required and must be explicitly provided by the caller. */
export interface RelationHasManyParams {
@@ -1916,6 +1956,15 @@ export interface ViewTableProjectionParams {
* ===========================================================================
*/
;
+/** What runs on the files of an upload or image field. Each key is a lane and provisions the same node an entry in nodes[] would, with file_field filled in; naming the field in such a node instead leaves that lane to the node. */
+export interface BlueprintFieldProcessing {
+ /** Image fields. Resized versions of the image, written into the image document as `versions`. On by default with the default set of sizes; a list states the versions instead, an object any ProcessImageVersions parameter, false turns it off. */
+ versions?: boolean | NonNullable | Omit;
+ /** Image and upload fields. A vector embedding of the file. Off by default; true takes the node defaults, an object any ProcessImageEmbedding (image) or ProcessFileEmbedding (upload) parameter. The vector column is `_embedding` unless `field_name` names it. */
+ embedding?: boolean | Omit | Omit;
+ /** Upload fields. Text and metadata extracted from the file. Off by default; true takes the node defaults, an object any ProcessExtraction parameter. The columns are `_text` and `_metadata` unless `text_field` / `metadata_field` name them. */
+ extraction?: boolean | Omit;
+}
/** A custom field (column) to add to a blueprint table. */
export interface BlueprintField {
/** The column name. */
@@ -1932,6 +1981,8 @@ export interface BlueprintField {
index?: 'btree' | 'gin' | 'gist' | 'brin' | 'hash';
/** Comment/description for this field. */
description?: string;
+ /** Upload and image fields only. The processing lanes that run on the field's files. Omitted, an image field newly added by the blueprint renders the default versions and nothing else runs; false runs nothing. */
+ processing?: false | BlueprintFieldProcessing;
}
/** A WITH CHECK override node for an UPDATE policy. Its expression governs the resulting row while the main policy node governs the targeted row. */
export interface BlueprintPolicyWithCheck {
@@ -2094,8 +2145,14 @@ export interface BlueprintBucketSeed {
name: string;
/** Human-readable description of this bucket. */
description?: string;
- /** Whether the bucket is publicly readable. Defaults to false. */
+ /** Bucket access type. Defaults to public when is_public is true and private otherwise. */
+ type?: 'public' | 'private' | 'temp';
+ /** Whether the bucket is publicly readable. Must agree with type when both are supplied. */
is_public?: boolean;
+ /** Destination bucket key for a temporary bucket. */
+ destination?: string;
+ /** Maximum staging time for a temporary bucket as a PostgreSQL interval. */
+ staging_ttl?: string;
/** MIME type allowlist (e.g., ["image/png", "image/jpeg"]). NULL means all types allowed. */
allowed_mime_types?: string[];
/** Maximum file size in bytes for this bucket. NULL means no limit. */
@@ -2109,8 +2166,6 @@ export interface BlueprintStorageConfig {
scope?: 'app' | 'org';
/** Module key discriminator. Defaults to "default" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case. */
key?: string;
- /** @deprecated Use `key` instead. Kept for backward compatibility. */
- storage_key?: string;
/** Initial bucket seed entries. Each creates a row in {prefix}_buckets during provisioning. */
buckets?: BlueprintBucketSeed[];
/** Override for presigned upload URL expiry time in seconds. */
@@ -2121,7 +2176,7 @@ export interface BlueprintStorageConfig {
default_max_file_size?: number;
/** CORS allowed origins for the storage module. */
allowed_origins?: string[];
- /** Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Defaults to "30 seconds". */
+ /** Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Every files table runs the confirm loop: the AFTER INSERT trigger enqueues a storage:confirm_upload job that verifies the object exists in S3 before moving status from requested to uploaded, and expires a requested row whose bytes never arrived within upload_url_expiry_seconds. Defaults to "30 seconds". */
confirm_upload_delay?: string;
/** Provision a temporary staging bucket (type temp, tagged default-temp) that stages for the private default bucket, so uploads land there and are promoted into their destination on confirmation. Setting staging_ttl implies this. Defaults to false. */
staging?: boolean;
@@ -2211,6 +2266,8 @@ export interface BlueprintAgentConfig {
has_resources?: boolean;
/** Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false. */
has_agents?: boolean;
+ /** Whether to attach resources to the repositories they apply to, through an agent_resource_repository junction (resource_id, repository_id, priority). Requires resources and a repository module at this same scope — with no repository catalog to point at, the junction is not created. Defaults to false. */
+ has_repository_resources?: boolean;
/** Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false. */
has_runs?: boolean;
/** Resource configuration array. First element configures the agent_resource table: vector dimensions (default 768), chunk_size (default 1000), chunk_strategy (default "paragraph"), chunk_overlap (default 200), embedding_model, embedding_provider, search_indexes (default ["bm25"]). */
@@ -2309,7 +2366,7 @@ export interface BlueprintEntityType {
*/
;
/** String shorthand -- just the node type name. */
-export type BlueprintNodeShorthand = 'AuthzAllowAll' | 'AuthzAppMemberOwner' | 'AuthzAppMembership' | 'AuthzColumnSecurity' | 'AuthzComposite' | 'AuthzDatabaseClaim' | 'AuthzDenyAll' | 'AuthzDirectOwner' | 'AuthzDirectOwnerAny' | 'AuthzEntityMembership' | 'AuthzFilePath' | 'AuthzHumanOnly' | 'AuthzMemberList' | 'AuthzMemberOwner' | 'AuthzNotReadOnly' | 'AuthzOrgHierarchy' | 'AuthzPeerOwnership' | 'AuthzPublishable' | 'AuthzRelatedEntityMembership' | 'AuthzRelatedMemberList' | 'AuthzRelatedMemberOwner' | 'AuthzRelatedPeerOwnership' | 'AuthzSystemOnly' | 'AuthzTemporal' | 'AuthzValueAllowed' | 'AuthzValueExists' | 'AuthzValueMatch' | 'CheckGreaterThan' | 'CheckLessThan' | 'CheckNotEqual' | 'CheckOneOf' | 'CheckOwnedRelation' | 'DataArchivable' | 'DataBulk' | 'DataCapabilities' | 'DataCompositeField' | 'DataDenormalized' | 'DataDirectOwner' | 'DataEntityMembership' | 'DataFileRef' | 'DataForceCurrentUser' | 'DataGenerated' | 'DataHistory' | 'DataI18n' | 'DataId' | 'DataIdentity' | 'DataImmutableFields' | 'DataInflection' | 'DataInheritFromParent' | 'DataJsonb' | 'DataLock' | 'DataMemberOwner' | 'DataOwnedFields' | 'DataOwnershipInEntity' | 'DataPeoplestamps' | 'DataPrincipalstamps' | 'DataPublishable' | 'DataRealtime' | 'DataSlug' | 'DataSoftDelete' | 'DataStatusField' | 'DataTags' | 'DataTimestamps' | 'SearchBm25' | 'SearchFullText' | 'SearchSpatial' | 'SearchSpatialAggregate' | 'SearchTrgm' | 'SearchUnified' | 'SearchVector' | 'TableOrganizationSettings' | 'TableUserProfiles' | 'TableUserSettings' | 'EventReferral' | 'EventTracker' | 'GuardStepUp' | 'JobTrigger' | 'LimitEnforceAggregate' | 'LimitEnforceCounter' | 'LimitEnforceFeature' | 'LimitEnforceRate' | 'LimitTrackUsage' | 'LimitWarningAggregate' | 'LimitWarningCounter' | 'LimitWarningRate' | 'ProcessChunks' | 'ProcessExtraction' | 'ProcessFileEmbedding' | 'ProcessImageEmbedding' | 'ProcessImageVersions';
+export type BlueprintNodeShorthand = 'AuthzAllowAll' | 'AuthzAppMemberOwner' | 'AuthzAppMembership' | 'AuthzComposite' | 'AuthzDatabaseClaim' | 'AuthzDenyAll' | 'AuthzHumanOnly' | 'AuthzMemberOwner' | 'AuthzPublishable' | 'AuthzSystemOnly' | 'AuthzTemporal' | 'CheckGreaterThan' | 'CheckLessThan' | 'DataArchivable' | 'DataBulk' | 'DataCapabilities' | 'DataDirectOwner' | 'DataEntityMembership' | 'DataForceCurrentUser' | 'DataHistory' | 'DataId' | 'DataJsonb' | 'DataLock' | 'DataMemberOwner' | 'DataOwnershipInEntity' | 'DataPeoplestamps' | 'DataPrincipalstamps' | 'DataPublishable' | 'DataRealtime' | 'DataSlug' | 'DataSoftDelete' | 'DataStatusField' | 'DataTags' | 'DataTimestamps' | 'SearchSpatial' | 'SearchUnified' | 'SearchVector' | 'TableOrganizationSettings' | 'TableUserProfiles' | 'TableUserSettings' | 'GuardStepUp' | 'ProcessChunks' | 'ProcessExtraction' | 'ProcessFileEmbedding' | 'ProcessImageEmbedding' | 'ProcessImageVersions';
/** Object form -- { $type, data } with typed parameters. */
export type BlueprintNodeObject = {
$type: 'AuthzAllowAll';
@@ -2569,6 +2626,9 @@ export type BlueprintNodeObject = {
} | {
$type: 'ProcessChunks';
data: ProcessChunksParams;
+} | {
+ $type: 'ProcessCustom';
+ data: ProcessCustomParams;
} | {
$type: 'ProcessExtraction';
data: ProcessExtractionParams;
diff --git a/packages/node-type-registry/src/codegen/generate-types.ts b/packages/node-type-registry/src/codegen/generate-types.ts
index 48d64c9670..a505626c11 100644
--- a/packages/node-type-registry/src/codegen/generate-types.ts
+++ b/packages/node-type-registry/src/codegen/generate-types.ts
@@ -428,6 +428,67 @@ function findTable(
return tables.find((tbl) => tbl.schemaName === schemaName && tbl.name === tableName);
}
+/**
+ * The processing lanes a file field can state, as the backend lists them: the
+ * option key, and the node types whose parameters the lane's value takes (one
+ * per field type the key applies to). `list` is set when the node has a
+ * parameter of the lane's own name, which a bare list stands for.
+ */
+const FILE_FIELD_LANES: { key: string; nodes: string[]; list?: boolean; doc: string }[] = [
+ {
+ key: 'versions',
+ nodes: ['ProcessImageVersions'],
+ list: true,
+ doc: 'Image fields. Resized versions of the image, written into the image document as `versions`. On by default with the default set of sizes; a list states the versions instead, an object any ProcessImageVersions parameter, false turns it off.'
+ },
+ {
+ key: 'embedding',
+ nodes: ['ProcessImageEmbedding', 'ProcessFileEmbedding'],
+ doc: 'Image and upload fields. A vector embedding of the file. Off by default; true takes the node defaults, an object any ProcessImageEmbedding (image) or ProcessFileEmbedding (upload) parameter. The vector column is `_embedding` unless `field_name` names it.'
+ },
+ {
+ key: 'extraction',
+ nodes: ['ProcessExtraction'],
+ doc: 'Upload fields. Text and metadata extracted from the file. Off by default; true takes the node defaults, an object any ProcessExtraction parameter. The columns are `_text` and `_metadata` unless `text_field` / `metadata_field` name them.'
+ }
+];
+
+function buildBlueprintFieldProcessing(): t.ExportNamedDeclaration {
+ const paramsOf = (node: string) => t.tsTypeReference(t.identifier(`${node}Params`));
+ const withoutField = (node: string) =>
+ t.tsTypeReference(
+ t.identifier('Omit'),
+ t.tsTypeParameterInstantiation([paramsOf(node), strLit('file_field')])
+ );
+ return addJSDoc(
+ exportInterface(
+ 'BlueprintFieldProcessing',
+ FILE_FIELD_LANES.map((lane) =>
+ addJSDoc(
+ optionalProp(
+ lane.key,
+ t.tsUnionType([
+ t.tsBooleanKeyword(),
+ ...(lane.list
+ ? lane.nodes.map((node) =>
+ t.tsTypeReference(
+ t.identifier('NonNullable'),
+ t.tsTypeParameterInstantiation([
+ t.tsIndexedAccessType(paramsOf(node), strLit(lane.key))
+ ])
+ ))
+ : []),
+ ...lane.nodes.map(withoutField)
+ ])
+ ),
+ lane.doc
+ )
+ )
+ ),
+ 'What runs on the files of an upload or image field. Each key is a lane and provisions the same node an entry in nodes[] would, with file_field filled in; naming the field in such a node instead leaves that lane to the node.'
+ );
+}
+
function buildBlueprintField(): t.ExportNamedDeclaration {
// Blueprint field input is not the stored metaschema field row.
return addJSDoc(
@@ -440,7 +501,17 @@ function buildBlueprintField(): t.ExportNamedDeclaration {
optionalProp('max', t.tsNumberKeyword()),
optionalProp('regexp', t.tsStringKeyword()),
optionalProp('index', strUnion(['btree', 'gin', 'gist', 'brin', 'hash'])),
- addJSDoc(optionalProp('description', t.tsStringKeyword()), 'Comment/description for this field.')
+ addJSDoc(optionalProp('description', t.tsStringKeyword()), 'Comment/description for this field.'),
+ addJSDoc(
+ optionalProp(
+ 'processing',
+ t.tsUnionType([
+ t.tsLiteralType(t.booleanLiteral(false)),
+ t.tsTypeReference(t.identifier('BlueprintFieldProcessing'))
+ ])
+ ),
+ 'Upload and image fields only. The processing lanes that run on the field\'s files. Omitted, an image field newly added by the blueprint renders the default versions and nothing else runs; false runs nothing.'
+ )
]),
'A custom field (column) to add to a blueprint table.'
);
@@ -624,7 +695,7 @@ function buildNodeTypes(
addJSDoc(
exportTypeAlias(
'BlueprintNodeShorthand',
- strUnion(dataNodes.map((nt) => nt.name))
+ strUnion(dataNodes.filter((nt) => !needsNodeData(nt)).map((nt) => nt.name))
),
'String shorthand -- just the node type name.'
)
@@ -886,9 +957,21 @@ function buildBlueprintBucketSeed(): t.ExportNamedDeclaration {
optionalProp('description', t.tsStringKeyword()),
'Human-readable description of this bucket.'
),
+ addJSDoc(
+ optionalProp('type', strUnion(['public', 'private', 'temp'])),
+ 'Bucket access type. Defaults to public when is_public is true and private otherwise.'
+ ),
addJSDoc(
optionalProp('is_public', t.tsBooleanKeyword()),
- 'Whether the bucket is publicly readable. Defaults to false.'
+ 'Whether the bucket is publicly readable. Must agree with type when both are supplied.'
+ ),
+ addJSDoc(
+ optionalProp('destination', t.tsStringKeyword()),
+ 'Destination bucket key for a temporary bucket.'
+ ),
+ addJSDoc(
+ optionalProp('staging_ttl', t.tsStringKeyword()),
+ 'Maximum staging time for a temporary bucket as a PostgreSQL interval.'
),
addJSDoc(
optionalProp(
@@ -907,7 +990,7 @@ function buildBlueprintBucketSeed(): t.ExportNamedDeclaration {
t.tsArrayType(t.tsStringKeyword())
),
'CORS allowed origins for this bucket.'
- )
+ ),
]),
'A bucket seed entry for storage.buckets[]. Creates an initial bucket row in the {prefix}_buckets table during entity type provisioning. Only used for app-level storage (not entity-scoped).'
);
@@ -935,10 +1018,6 @@ function buildBlueprintStorageConfig(): t.ExportNamedDeclaration {
optionalProp('key', t.tsStringKeyword()),
'Module key discriminator. Defaults to "default" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case.'
),
- addJSDoc(
- optionalProp('storage_key', t.tsStringKeyword()),
- '@deprecated Use `key` instead. Kept for backward compatibility.'
- ),
addJSDoc(
optionalProp(
'buckets',
@@ -969,7 +1048,7 @@ function buildBlueprintStorageConfig(): t.ExportNamedDeclaration {
),
addJSDoc(
optionalProp('confirm_upload_delay', t.tsStringKeyword()),
- 'Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Defaults to "30 seconds".'
+ 'Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Every files table runs the confirm loop: the AFTER INSERT trigger enqueues a storage:confirm_upload job that verifies the object exists in S3 before moving status from requested to uploaded, and expires a requested row whose bytes never arrived within upload_url_expiry_seconds. Defaults to "30 seconds".'
),
addJSDoc(
optionalProp('staging', t.tsBooleanKeyword()),
@@ -1245,6 +1324,10 @@ function buildBlueprintAgentConfig(): t.ExportNamedDeclaration {
optionalProp('has_agents', t.tsBooleanKeyword()),
'Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false.'
),
+ addJSDoc(
+ optionalProp('has_repository_resources', t.tsBooleanKeyword()),
+ 'Whether to attach resources to the repositories they apply to, through an agent_resource_repository junction (resource_id, repository_id, priority). Requires resources and a repository module at this same scope — with no repository catalog to point at, the junction is not created. Defaults to false.'
+ ),
addJSDoc(
optionalProp('has_runs', t.tsBooleanKeyword()),
"Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false."
@@ -1818,7 +1901,9 @@ function tsTypeSchema(type: t.TSType): Json {
if (t.isTSBooleanKeyword(type)) return { type: 'boolean' };
if (t.isTSUnknownKeyword(type) || t.isTSAnyKeyword(type)) return {};
if (t.isTSNeverKeyword(type)) return { not: {} };
- if (t.isTSLiteralType(type) && t.isStringLiteral(type.literal)) return { const: type.literal.value };
+ if (t.isTSLiteralType(type) && (t.isStringLiteral(type.literal) || t.isBooleanLiteral(type.literal) || t.isNumericLiteral(type.literal))) {
+ return { const: type.literal.value };
+ }
if (t.isTSArrayType(type)) return { type: 'array', items: tsTypeSchema(type.elementType) };
if (t.isTSTypeLiteral(type)) return membersSchema(type.members);
if (t.isTSIntersectionType(type)) return { allOf: type.types.map(tsTypeSchema) };
@@ -1831,13 +1916,38 @@ function tsTypeSchema(type: t.TSType): Json {
}
return { anyOf: type.types.map(tsTypeSchema) };
}
+ if (t.isTSIndexedAccessType(type) && t.isTSLiteralType(type.indexType) && t.isStringLiteral(type.indexType.literal)) {
+ return (nodeParams(type.objectType).properties as Json)[type.indexType.literal.value] as Json;
+ }
if (t.isTSTypeReference(type) && t.isIdentifier(type.typeName)) {
- if (type.typeName.name === 'Record') return { type: 'object', additionalProperties: tsTypeSchema(type.typeParameters.params[1]) };
+ const params = type.typeParameters?.params ?? [];
+ if (type.typeName.name === 'Record') return { type: 'object', additionalProperties: tsTypeSchema(params[1]) };
+ // The parameter schemas allow no null, so NonNullable leaves them as they are.
+ if (type.typeName.name === 'NonNullable') return tsTypeSchema(params[0]);
+ if (type.typeName.name === 'Omit') {
+ const omitted = (tsTypeSchema(params[1]).enum as string[]) ?? [tsTypeSchema(params[1]).const as string];
+ const schema = nodeParams(params[0]);
+ return {
+ ...schema,
+ properties: Object.fromEntries(Object.entries(schema.properties as Json).filter(([key]) => !omitted.includes(key))),
+ ...(schema.required ? { required: (schema.required as string[]).filter((key) => !omitted.includes(key)) } : {})
+ };
+ }
return refTo(type.typeName.name);
}
throw new Error(`blueprint JSON Schema: no rule turns the TS type ${type.type} into JSON Schema; add one to tsTypeSchema.`);
}
+// A node's parameters as a caller writes them, for Omit<...Params> and ...Params['key'] in the structural types.
+function nodeParams(type: t.TSType): Json {
+ const name = t.isTSTypeReference(type) && t.isIdentifier(type.typeName) ? type.typeName.name : undefined;
+ const node = allNodeTypes.find((nt) => `${nt.name}Params` === name);
+ if (!node) {
+ throw new Error(`blueprint JSON Schema: ${name ?? type.type} is not a node's parameters; Omit and indexed access are turned into JSON Schema for node parameters only.`);
+ }
+ return nodeDataSchema(node.parameter_schema, new Map());
+}
+
// The `$type` literal of an object type, which makes a union of them a union keyed by `$type`.
function typeTag(type: t.TSType): string | undefined {
if (!t.isTSTypeLiteral(type)) return undefined;
@@ -1867,17 +1977,31 @@ function byType(base: Json, branches: Array<{ name: string; then: Json }>): Json
...base,
required: [...new Set(['$type', ...((base.required as string[]) ?? [])])],
properties: { ...properties, $type: { enum: branches.map((branch) => branch.name) } },
- allOf: branches.map((branch) => ({ if: { properties: { $type: { const: branch.name } }, required: ['$type'] }, then: branch.then }))
+ allOf: [
+ ...((base.allOf ?? []) as Json[]),
+ ...branches.map((branch) => ({ if: { properties: { $type: { const: branch.name } }, required: ['$type'] }, then: branch.then }))
+ ]
};
}
+function needsNodeData(node: NodeTypeDefinition): boolean {
+ return (node.parameter_schema.required ?? []).some((key) => {
+ const property = node.parameter_schema.properties?.[key];
+ return !property?.readOnly && property?.default === undefined;
+ });
+}
+
+function nodeDataBranches(nodes: NodeTypeDefinition[]): Array<{ name: string; then: Json }> {
+ return nodes.map((nt) => ({
+ name: nt.name,
+ then: { properties: { data: refTo(`${nt.name}Params`) }, ...(needsNodeData(nt) ? { required: ['data'] } : {}) }
+ }));
+}
+
function nodeEntrySchema(dataNodes: NodeTypeDefinition[]): Json {
return byType(
{ type: 'object', properties: { data: { type: 'object' } }, additionalProperties: false },
- dataNodes.map((nt) => ({
- name: nt.name,
- then: { properties: { data: refTo(`${nt.name}Params`) }, ...((nt.parameter_schema.required ?? []).length ? { required: ['data'] } : {}) }
- }))
+ nodeDataBranches(dataNodes)
);
}
@@ -1885,7 +2009,7 @@ function nodeEntrySchema(dataNodes: NodeTypeDefinition[]): Json {
const PRIVILEGE_PATTERN = '^([Ss][Ee][Ll][Ee][Cc][Tt]|[Ii][Nn][Ss][Ee][Rr][Tt]|[Uu][Pp][Dd][Aa][Tt][Ee]|[Dd][Ee][Ll][Ee][Tt][Ee])$';
function policySchemas(authzNodes: NodeTypeDefinition[]): Record {
- const data = authzNodes.map((nt) => ({ name: nt.name, then: { properties: { data: refTo(`${nt.name}Params`) } } }));
+ const data = nodeDataBranches(authzNodes);
return {
BlueprintPolicyWithCheck: byType({ type: 'object', properties: { data: { type: 'object' } }, additionalProperties: false }, data),
BlueprintPolicy: {
@@ -1911,6 +2035,31 @@ function policySchemas(authzNodes: NodeTypeDefinition[]): Record {
};
}
+function namedOrModuleTarget(name: string, schema: string, module: string): Json {
+ return {
+ oneOf: [
+ { required: [name], not: { required: [module] } },
+ { required: [module], not: { anyOf: [{ required: [name] }, { required: [schema] }] } }
+ ]
+ };
+}
+
+function tableTargetSchema(): Json {
+ return {
+ ...namedOrModuleTarget('table_name', 'schema_name', 'module'),
+ if: { required: ['provisions'] },
+ then: {
+ required: ['module'],
+ not: { anyOf: ['policies', 'grants', 'nodes', 'fields'].map((key) => ({ required: [key] })) },
+ properties: {
+ module: { not: { required: ['table'] } },
+ provisions: { minProperties: 1 }
+ }
+ },
+ else: { properties: { module: refTo('BlueprintModuleTableRef') } }
+ };
+}
+
function relationSchema(relationNodes: NodeTypeDefinition[]): Json {
const ends: Json = {
source_table: { type: 'string' },
@@ -1921,15 +2070,27 @@ function relationSchema(relationNodes: NodeTypeDefinition[]): Json {
target_module: refTo('BlueprintModuleTableRef')
};
return byType(
- { type: 'object', description: 'A relation entry in a blueprint definition.', properties: ends },
+ {
+ type: 'object',
+ description: 'A relation entry in a blueprint definition.',
+ properties: ends,
+ allOf: ['source', 'target'].map((end) => namedOrModuleTarget(`${end}_table`, `${end}_schema`, `${end}_module`))
+ },
relationNodes.map((nt) => {
const params = nodeDataSchema(nt.parameter_schema, new Map());
const spatial = nt.name === 'RelationSpatial';
+ const resolved = ['source_table_id', 'target_table_id', 'source_field_id', 'target_field_id'];
+ const required = ((params.required ?? []) as string[]).filter((key) => !resolved.includes(key));
+ if (spatial) required.push('source_field', 'target_field');
return {
name: nt.name,
then: {
- properties: { ...(params.properties as Json), ...(spatial ? { source_field: { type: 'string' }, target_field: { type: 'string' } } : {}) },
- ...(spatial ? { required: ['source_field', 'target_field'] } : {})
+ properties: {
+ ...(params.properties as Json),
+ ...(spatial ? { source_field: { type: 'string' }, target_field: { type: 'string' } } : {}),
+ ...(nt.name === 'RelationManyToMany' ? { policies: { type: 'array', items: refTo('BlueprintPolicy') } } : {})
+ },
+ ...(required.length ? { required } : {})
}
};
})
@@ -1944,7 +2105,14 @@ function buildBlueprintJsonSchema(statements: t.Statement[], nodeTypes: NodeType
for (const statement of statements) {
if (!t.isExportNamedDeclaration(statement)) continue;
const declaration = statement.declaration;
- if (t.isTSInterfaceDeclaration(declaration)) declared.set(declaration.id.name, () => withDoc(membersSchema(declaration.body.body), statement));
+ if (t.isTSInterfaceDeclaration(declaration)) {
+ declared.set(declaration.id.name, () => {
+ const schema = withDoc(membersSchema(declaration.body.body), statement);
+ return declaration.id.name === 'BlueprintTable'
+ ? { ...schema, ...tableTargetSchema() }
+ : schema;
+ });
+ }
if (t.isTSTypeAliasDeclaration(declaration)) declared.set(declaration.id.name, () => withDoc(tsTypeSchema(declaration.typeAnnotation), statement));
}
const dataNodes = nodeTypes.filter((nt) => nt.category !== 'relation' && nt.category !== 'view');
@@ -1964,7 +2132,7 @@ function buildBlueprintJsonSchema(statements: t.Statement[], nodeTypes: NodeType
),
additionalProperties: false
});
- declared.set('BlueprintNodeShorthand', { enum: dataNodes.map((nt) => nt.name), description: 'String shorthand -- just the node type name.' });
+ declared.set('BlueprintNodeShorthand', { enum: dataNodes.filter((nt) => !needsNodeData(nt)).map((nt) => nt.name), description: 'String shorthand -- just the node type name.' });
declared.set('BlueprintNodeObject', { ...nodeEntrySchema(dataNodes), description: 'Object form -- { $type, data } with typed parameters.' });
for (const [name, schema] of Object.entries(policySchemas(policyNodeTypes))) declared.set(name, schema);
declared.set('BlueprintRelation', relationSchema(nodeTypes.filter((nt) => nt.category === 'relation')));
@@ -2073,6 +2241,7 @@ function renderBlueprintSchema(schema: Json): string {
'// Regenerate with:',
'// cd packages/node-type-registry && pnpm generate:types',
'',
+ '/* eslint-disable */',
"import type { JSONSchema } from './types';",
'',
'/** JSON Schema (draft-07) of a blueprint definition: the shapes construct_blueprint() reads, with each node\'s data checked against its parameter_schema in the form a caller writes it. */',
@@ -2141,6 +2310,7 @@ function buildProgram(meta?: MetaTableInfo[]): { types: string; schema: string }
? 'Derived from _meta'
: 'Static fallback (no _meta provided)';
statements.push(sectionComment(`Structural types — ${metaSource}`));
+ statements.push(buildBlueprintFieldProcessing());
statements.push(buildBlueprintField());
statements.push(buildBlueprintPolicyWithCheck(policyNodeTypes));
statements.push(buildBlueprintPolicy(policyNodeTypes, meta));
diff --git a/packages/node-type-registry/src/content-presets/agent.ts b/packages/node-type-registry/src/content-presets/agent.ts
new file mode 100644
index 0000000000..c363c9e203
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/agent.ts
@@ -0,0 +1,47 @@
+import type { TrustLadderPreset } from './types';
+
+/**
+ * How an agent principal earns standing in a scope: by finishing runs there.
+ *
+ * `agent_proven` — three completed runs. Cheap, and deliberately so: it says
+ * the agent has done real work here, nothing more.
+ *
+ * `agent_trusted` — ten completed runs inside a 30-day window, and it lapses
+ * 30 days after it is earned, so an idle agent drifts back to proven rather
+ * than keeping a standing nobody has re-checked. A replayed refresh token or a
+ * refused attempt to widen its own scope demotes it on the spot, and demotion
+ * resets the count: the agent re-earns trust from zero, it does not get it
+ * back on the next run.
+ *
+ * Neither rung unlocks anything by itself. Which permissions wait for which
+ * rung is the scope administrator's vocabulary, not the platform's — a tenant
+ * arms the ladder by adding `unlocks: ['manage_domains', …]` in its own
+ * catalog's names, and an unknown name fails the seed rather than silently
+ * un-gating. Seeding `agent` alone therefore changes no principal's mask.
+ *
+ * Trust is earned per scope: the ladder an entity seeds counts that entity's
+ * runs, and an agent proven in one organization is a stranger in the next.
+ */
+export const agent: TrustLadderPreset = {
+ kind: 'trust_ladder',
+ slug: 'agent',
+ label: 'Agent trust',
+ description:
+ 'Proven after three completed runs, trusted after ten in a 30-day window; a replayed refresh token or a refused widening demotes trusted. Unlocks are the scope administrator\'s to name.',
+ rungs: [
+ {
+ level: 'agent_proven',
+ event: 'agent.run.completed',
+ required_count: 3,
+ period_interval: '30 days',
+ },
+ {
+ level: 'agent_trusted',
+ event: 'agent.run.completed',
+ required_count: 10,
+ period_interval: '30 days',
+ expires_interval: '30 days',
+ revoked_by: ['token.refresh_reused', 'PRINCIPAL_CHILD_WIDENS'],
+ },
+ ],
+};
diff --git a/packages/node-type-registry/src/content-presets/approvals.ts b/packages/node-type-registry/src/content-presets/approvals.ts
new file mode 100644
index 0000000000..0b9d48d541
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/approvals.ts
@@ -0,0 +1,27 @@
+import type { RouteBindingsPreset } from './types';
+
+/**
+ * Approvals: where a parked graph node's notification points.
+ *
+ * Its own slug rather than a widening of `mantra`, because the two answer
+ * different questions and a site should be able to take one without the other:
+ * Mantra is who you are, approvals is what is waiting on you. A tenant serving
+ * its own auth pages still wants this set, and a tenant with no human-in-the-
+ * loop graphs wants neither.
+ *
+ * One binding, not two, because a route path is a *prefix*: `resolve_route`
+ * matches the path exactly or followed by `/`, longest first, so `/approvals`
+ * serves both the queue and `/approvals//`. The
+ * question's reference therefore travels in the path — an address, never a
+ * credential — and the page reads it back. Binding the parameterised form
+ * separately would be a second row saying the same thing, and the two could
+ * disagree.
+ */
+export const approvals: RouteBindingsPreset = {
+ kind: 'route_bindings',
+ slug: 'approvals',
+ label: 'Approvals pages',
+ description:
+ "The human-in-the-loop answer surface served by the approvals function image: /approvals is everything waiting on you, and /approvals// is one question, rendered from its graph node-state row and settled through that scope's own approve_node. Bound as a single path prefix; claims no root or catch-all path, and installs independently of the auth pages.",
+ bindings: [{ path: '/approvals', task_identifier: 'approvals:pages' }],
+};
diff --git a/packages/node-type-registry/src/content-presets/index.ts b/packages/node-type-registry/src/content-presets/index.ts
index 53a2ecbe0a..7c6cf5c93a 100644
--- a/packages/node-type-registry/src/content-presets/index.ts
+++ b/packages/node-type-registry/src/content-presets/index.ts
@@ -1,15 +1,53 @@
export type {
+ BlockPageDocument,
ContentPreset,
ContentPresetKind,
+ FunctionRouteBinding,
LimitBaselinePreset,
+ PageDocument,
+ PagesPreset,
+ PrincipalPreset,
+ PrincipalPresetCredentials,
+ PrincipalPresetDefinition,
+ PrincipalPresetScope,
+ ProsePageDocument,
+ RedirectRouteBinding,
+ RobotsDirective,
+ RobotsPreset,
+ RouteBinding,
+ RouteBindingsPreset,
TrustLadderPreset,
} from './types';
+import { agent } from './agent';
+import { approvals } from './approvals';
import { humanity } from './humanity';
+import { layouts } from './layouts';
+import { legal } from './legal';
+import { mantra } from './mantra';
+import { mantraStandalone } from './mantra-standalone';
import { metered, meteredBaseline } from './metered';
+import { deployBot, readOnlyAnalyst } from './principals';
+import { robotsNoAi, robotsOpen } from './robots';
+import { sso } from './sso';
import type { ContentPreset } from './types';
-export { humanity, metered, meteredBaseline };
+export {
+ agent,
+ approvals,
+ deployBot,
+ humanity,
+ layouts,
+ legal,
+ mantra,
+ mantraStandalone,
+ metered,
+ meteredBaseline,
+ readOnlyAnalyst,
+ robotsNoAi,
+ robotsOpen,
+ sso,
+};
/**
* Every shipped content preset, in catalog order. Consumed by `generate.ts`,
@@ -24,6 +62,21 @@ export const allContentPresets: ContentPreset[] = [
humanity,
metered,
meteredBaseline,
+ mantra,
+ legal,
+ approvals,
+ robotsOpen,
+ robotsNoAi,
+ // Appended, not grouped with `legal`: the catalog's order is the order of the
+ // generated alteration files, so inserting a preset in the middle renumbers
+ // every one after it and rewrites alterations deployed databases have already
+ // applied. A new preset goes last.
+ layouts,
+ readOnlyAnalyst,
+ deployBot,
+ agent,
+ mantraStandalone,
+ sso,
];
/** Look up a shipped content preset by kind and slug. */
diff --git a/packages/node-type-registry/src/content-presets/layouts.ts b/packages/node-type-registry/src/content-presets/layouts.ts
new file mode 100644
index 0000000000..70d0c32d3f
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/layouts.ts
@@ -0,0 +1,91 @@
+import type { PagesPreset } from './types';
+
+/**
+ * The one layout a site is worth being born with: chrome around its pages.
+ *
+ * A layout is a page whose content is a block document with a `Slot` in it,
+ * stored at the reserved `_layout/default` path — reserved because a request path
+ * always begins with `/` and this one does not, so the template is addressable by
+ * the page API and by the renderer and by nothing arriving over HTTP. Pages that
+ * name no layout are served in it; a page naming another one gets that one or a
+ * refusal.
+ *
+ * Deliberately one preset rather than a set. The value of shipping a layout at
+ * all is that a site has something real to author over — a document a tenant can
+ * read, edit and publish through the same page API as its prose, instead of a
+ * template compiled into the image. That argument is satisfied by one; a
+ * `login`/`marketing`/`app` trio would be three guesses at product decisions
+ * nobody has made, each of which a tenant would have to delete.
+ *
+ * What it deliberately does not carry:
+ * - no `meta.robots`: served pages default to `noindex`, and a preset that
+ * flipped a site to indexable as a side effect of installing chrome would
+ * make crawlability an accident;
+ * - no `meta.title`/`description`: those are the page's to state, and a layout
+ * stating them would put the same title on every page that omitted one;
+ * - no class names beyond the semantic ones: there is no stylesheet served with
+ * documents yet, so Tailwind/shadcn classes here would name CSS that never
+ * arrives.
+ *
+ * The masthead reads `{{ site.title }}` rather than a name, which is what makes
+ * one layout serve every tenant: the binding is resolved while rendering,
+ * against the site being served, so the seeded document is identical everywhere
+ * and correct everywhere.
+ */
+export const layouts: PagesPreset = {
+ kind: 'pages',
+ slug: 'layouts',
+ label: 'Default page layout',
+ description:
+ 'The starter template a site serves its pages in: a block document with a content slot, stored at the reserved _layout/default page so it is versioned and published exactly like the pages it wraps. Pages that name no layout are served in it — edit it through the page API to change the chrome of every such page.',
+ pages: [
+ {
+ path: '_layout/default',
+ kind: 'block_document',
+ title: 'Default layout',
+ document: {
+ formatVersion: '1.0',
+ type: 'UISchema',
+ id: 'layout-default',
+ page: {
+ type: 'Page',
+ key: 'shell',
+ props: {},
+ children: [
+ {
+ type: 'Section',
+ key: 'masthead',
+ props: { className: 'masthead' },
+ // The tenant's own name, resolved per render rather than seeded.
+ children: [
+ {
+ type: 'Markdown',
+ key: 'brand',
+ props: {},
+ bindings: { content: '{{ site.title }}' },
+ children: []
+ }
+ ]
+ },
+ // Where the page goes. A slot nothing fills renders its own
+ // children, so the fallback text below is what a layout served with
+ // no page in it says — a visible statement rather than a blank page.
+ {
+ type: 'Slot',
+ key: 'content',
+ props: { name: 'content' },
+ children: [
+ {
+ type: 'Markdown',
+ key: 'content-empty',
+ props: { content: 'This layout is serving no page content.' },
+ children: []
+ }
+ ]
+ }
+ ]
+ }
+ }
+ }
+ ]
+};
diff --git a/packages/node-type-registry/src/content-presets/legal.ts b/packages/node-type-registry/src/content-presets/legal.ts
new file mode 100644
index 0000000000..fd5023232f
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/legal.ts
@@ -0,0 +1,34 @@
+import type { PagesPreset } from './types';
+
+/**
+ * Legal: the two documents every signup flow links to, as starter pages.
+ *
+ * These are page rows, not prose anyone should ship as-is: a tenant installs
+ * them into its site's merkle-backed pages, replaces the placeholder text with
+ * its own counsel's, and publishes. From then on the site's active commit is
+ * the version — the `/terms` and `/privacy` pages serve it, and an acceptance
+ * event records exactly which `commit_id` was on screen. That is the point of
+ * seeding them as pages rather than a JSON blob: a blob has no versions to
+ * cite, so acceptance against it is a checkbox rather than evidence.
+ *
+ * `body` is blank-line-separated prose, rendered escaped — never markup.
+ */
+export const legal: PagesPreset = {
+ kind: 'pages',
+ slug: 'legal',
+ label: 'Legal starter pages',
+ description:
+ 'Placeholder Terms of Service and Privacy Policy pages, installed into a site\u2019s merkle-backed pages so publishing versions them and acceptance events can cite the exact commit that was on screen. Replace the placeholder prose before publishing.',
+ pages: [
+ {
+ path: '/terms',
+ title: 'Terms of Service',
+ body: 'These placeholder terms describe the agreement between this service and the people who use it. Replace this text with your own terms before publishing.\n\nUntil then, this page exists so every signup flow has a URL to link to and a version to record.'
+ },
+ {
+ path: '/privacy',
+ title: 'Privacy Policy',
+ body: 'This placeholder policy describes what data this service collects and why. Replace this text with your own policy before publishing.\n\nUntil then, this page exists so every signup flow has a URL to link to and a version to record.'
+ }
+ ]
+};
diff --git a/packages/node-type-registry/src/content-presets/mantra-standalone.ts b/packages/node-type-registry/src/content-presets/mantra-standalone.ts
new file mode 100644
index 0000000000..fac2830a97
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/mantra-standalone.ts
@@ -0,0 +1,28 @@
+import { mantra } from './mantra';
+import type { RouteBindingsPreset } from './types';
+
+/**
+ * Mantra on a host of its own.
+ *
+ * The `mantra` set deliberately claims no `/`, because it layers onto a site
+ * that has content of its own. A hostname provisioned only to carry the auth
+ * pages (`mantra.`) has no such content: its root is the placeholder
+ * the route guard created targeting the empty site, which answers 404. This
+ * set is the same pages plus that one root, as a redirect onto sign-in — a
+ * redirects-table row, not a Mantra task, so the image still owns exactly the
+ * pages it serves.
+ *
+ * Composed from `mantra` rather than copied, so retuning the page set retunes
+ * both; the redirect is the only thing this preset adds.
+ */
+export const mantraStandalone: RouteBindingsPreset = {
+ kind: 'route_bindings',
+ slug: 'mantra-standalone',
+ label: 'Mantra platform pages, on a dedicated host',
+ description:
+ "The mantra page set for a hostname that serves nothing else: every binding of 'mantra', plus the site root redirecting to sign-in. Install onto a site provisioned only to carry the auth pages; a site with authored content keeps its root by installing 'mantra' instead.",
+ bindings: [
+ ...mantra.bindings,
+ { path: '/', target: 'redirect', to_path: '/login', anonymous: true },
+ ],
+};
diff --git a/packages/node-type-registry/src/content-presets/mantra.ts b/packages/node-type-registry/src/content-presets/mantra.ts
new file mode 100644
index 0000000000..8dc1b307bc
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/mantra.ts
@@ -0,0 +1,72 @@
+import type { RouteBindingsPreset } from './types';
+
+/**
+ * Mantra: the platform's own website, as a table of rows.
+ *
+ * Mantra is ONE function image exposing many named tasks — `mantra:signin`,
+ * `mantra:robots_txt`, and so on. Nothing about serving it is a new routing
+ * mode: each binding below becomes an ordinary route row whose target is a
+ * function, which the routing resolver already answers on the function lane by
+ * emitting the definition's task identifier for the sync gateway.
+ *
+ * So the only real question is *which paths* Mantra owns on a site, and that is
+ * a product decision — which is why it lives here as a preset rather than as a
+ * list inside a PL/pgSQL function. Adding `/reset-password` becomes a row a
+ * reviewer can read, a tenant can ship a different set under its own slug, and
+ * retuning the set is an UPDATE with history rather than a migration.
+ *
+ * Deliberately no `/` and no catch-all: a site's own root route keeps serving
+ * authored content, and Mantra layers onto the hostname that site already
+ * serves. A path here is claimed from the site, so every one of them is a page
+ * we intend to own.
+ *
+ * No SSO legs either: `/auth/start` and `/auth/callback` are the `sso` preset,
+ * installed only by a tenant that signs people in with an identity provider.
+ */
+export const mantra: RouteBindingsPreset = {
+ kind: 'route_bindings',
+ slug: 'mantra',
+ label: 'Mantra platform pages',
+ description:
+ "The platform-owned page set served by the mantra function image: authentication (sign in/up/out, confirming an address, password recovery, 2FA), the legal pages, and the well-known crawler and manifest files. Layers onto a site's existing hostname; claims no root or catch-all path.",
+ bindings: [
+ // Authentication.
+ { path: '/login', task_identifier: 'mantra:signin', anonymous: true },
+ // The phone-number lane under it: one page that signs a registered number
+ // in and provisions an unregistered one, so it nests under /login rather
+ // than sitting beside it as a second sign-up surface.
+ { path: '/login/phone', task_identifier: 'mantra:phone_signin', anonymous: true },
+ { path: '/login/magic', task_identifier: 'mantra:magic_link', anonymous: true },
+ { path: '/logout', task_identifier: 'mantra:signout', anonymous: true },
+ { path: '/signup', task_identifier: 'mantra:signup', anonymous: true },
+ { path: '/forgot-password', task_identifier: 'mantra:forgot', anonymous: true },
+ { path: '/reset-password', task_identifier: 'mantra:reset', anonymous: true },
+ { path: '/2fa', task_identifier: 'mantra:two_factor', anonymous: true },
+ { path: '/device-approval', task_identifier: 'mantra:device_approval', anonymous: true },
+ // Turning a second factor on; /login sends a require_mfa sign-in here.
+ { path: '/setup-2fa', task_identifier: 'mantra:setup_two_factor', anonymous: true },
+ { path: '/auth/magic', task_identifier: 'mantra:magic_landing', anonymous: true },
+ // The confirmation link a sign-up mails: a password sign-up stays pending
+ // until this is followed, so without it a new account cannot sign in.
+ { path: '/verify-email', task_identifier: 'mantra:verify_email', anonymous: true },
+
+ // Legal pages every signup flow links to.
+ { path: '/terms', task_identifier: 'mantra:terms', anonymous: true },
+ { path: '/privacy', task_identifier: 'mantra:privacy', anonymous: true },
+
+ // Well-known files a crawler or an installing browser asks for by name.
+ { path: '/robots.txt', task_identifier: 'mantra:robots_txt', anonymous: true },
+ { path: '/sitemap.xml', task_identifier: 'mantra:sitemap_xml', anonymous: true },
+ { path: '/site.webmanifest', task_identifier: 'mantra:webmanifest', anonymous: true },
+
+ // The browser bundle a page that asked to hydrate loads. A path rather than
+ // a page: it is this image's own asset, served immutable by content hash,
+ // and a site whose documents never ask for it never requests it.
+ { path: '/_mantra/runtime.js', task_identifier: 'mantra:runtime_asset', anonymous: true },
+
+ // What every page this image serves looks like: one stylesheet built into
+ // the image, cached immutably by content hash, and overridden by any sheet a
+ // site loads after it.
+ { path: '/_mantra/styles.css', task_identifier: 'mantra:styles_asset', anonymous: true },
+ ],
+};
diff --git a/packages/node-type-registry/src/content-presets/principals.ts b/packages/node-type-registry/src/content-presets/principals.ts
new file mode 100644
index 0000000000..5bcd9eaffb
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/principals.ts
@@ -0,0 +1,87 @@
+import type { PrincipalPreset } from './types';
+
+/**
+ * Principal presets: blueprints a human instantiates in one call.
+ *
+ * Both rows name capabilities rather than bit positions. A principal's SPRT is
+ * `owner_rows & preset_mask`, and the mask is resolved against the tenant's
+ * own capabilities table when the row is instantiated, so the same catalog row
+ * fits a tenant with 64 bits and a tenant with 256 without granting a bit
+ * either does not know. A name the tenant lacks is an error, never a silently
+ * narrower principal.
+ *
+ * The lifetimes are ceilings the tenant's `auth_settings` may lower but a
+ * preset may never raise; a tenant whose settings are tighter than the row
+ * rejects the instantiation rather than quietly widening.
+ */
+
+/**
+ * Reads everything the owner can read, writes nothing. The mask at each scope
+ * is null — every bit the owner holds, so a capability-gated read the owner
+ * has is one the analyst has — and `is_read_only` is what forbids the writes.
+ * No delegation: an analyst does not mint agents.
+ */
+export const readOnlyAnalyst: PrincipalPreset = {
+ kind: 'principal',
+ slug: 'read-only-analyst',
+ label: 'Read-only analyst',
+ description:
+ 'Sees what its owner sees and changes nothing: read-only at every scope, all of the owner\'s bits, no delegation.',
+ definition: {
+ is_read_only: true,
+ use_admin_owner: false,
+ bypass_step_up: false,
+ scopes: [
+ { membership_type: 'app', allowed_mask_capabilities: null },
+ { membership_type: 'org', allowed_mask_capabilities: null }
+ ],
+ entity_policy: 'inherit_owner',
+ delegation: { allowed: false, max_depth: 0 },
+ credentials: {
+ api_key_ttl: '30 days',
+ access_token_ttl: '15 minutes',
+ refresh_token_ttl: '7 days',
+ max_chain_age: '30 days'
+ }
+ }
+};
+
+/**
+ * Ships code: the organization capabilities that move services, sites, and
+ * domains, and nothing else — no member administration, no secrets, no
+ * exports. `require_list` pins it to the organizations it deploys for, and it
+ * may mint exactly one level of child (a per-job worker) beneath itself.
+ * `bypass_step_up` lets an unattended pipeline past the MFA guards its owner
+ * would otherwise have to satisfy in person — so instantiating this preset is
+ * itself MFA-gated: the principals INSERT guard demands a fresh MFA proof from
+ * the human caller (a password re-entry is not enough) before a
+ * `bypass_step_up` principal may come into existence. Narrowing the preset
+ * with `bypass_step_up: false` lifts that requirement.
+ */
+export const deployBot: PrincipalPreset = {
+ kind: 'principal',
+ slug: 'deploy-bot',
+ label: 'Deploy bot',
+ description:
+ 'Manages services, sites, and domains for the organizations it is scoped to; nothing else. Unattended: bypasses step-up, may delegate one level. Creating one requires a fresh MFA proof.',
+ definition: {
+ is_read_only: false,
+ use_admin_owner: false,
+ bypass_step_up: true,
+ scopes: [
+ { membership_type: 'app', allowed_mask_capabilities: [] },
+ {
+ membership_type: 'org',
+ allowed_mask_capabilities: ['manage_services', 'manage_sites', 'manage_domains']
+ }
+ ],
+ entity_policy: 'require_list',
+ delegation: { allowed: true, max_depth: 1 },
+ credentials: {
+ api_key_ttl: '30 days',
+ access_token_ttl: '15 minutes',
+ refresh_token_ttl: '7 days',
+ max_chain_age: '30 days'
+ }
+ }
+};
diff --git a/packages/node-type-registry/src/content-presets/robots.ts b/packages/node-type-registry/src/content-presets/robots.ts
new file mode 100644
index 0000000000..4c234651df
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/robots.ts
@@ -0,0 +1,72 @@
+import type { RobotsPreset } from './types';
+
+/**
+ * Robots: the directives a site puts in front of crawlers, as starter rows.
+ *
+ * A site's `robots` column is emitted verbatim by `/robots.txt`, so what goes
+ * in it is a product decision — which crawlers a tenant is willing to feed —
+ * and a decision belongs in a catalog row a reviewer can read, not inside an
+ * emitter. The image already disallows its own session and token paths, so a
+ * preset never restates them: it carries only what a tenant chooses.
+ *
+ * Two are shipped because the choice is genuinely binary. `open` is the default
+ * a public marketing site wants; `no-ai` is the same file plus the named
+ * training crawlers, listed by name because `User-agent: *` cannot express
+ * "index me, do not train on me". Neither is privileged — a tenant that wants
+ * a third writes a row of exactly this shape.
+ */
+export const robotsOpen: RobotsPreset = {
+ kind: 'robots',
+ slug: 'open',
+ label: 'Open to crawlers',
+ description:
+ 'Nothing disallowed beyond the session and token paths the page set already excludes \u2014 the file a public site wants, stated rather than assumed.',
+ directives: []
+};
+
+/**
+ * The named training crawlers, each as its own group.
+ *
+ * They are listed rather than pattern-matched because robots.txt has no
+ * wildcard for "an AI crawler": a group applies to the user-agent token it
+ * names, so a list is the only thing a crawler actually obeys. It will go stale
+ * as vendors rename — that is a row to update, which is why it is a row.
+ */
+export const robotsNoAi: RobotsPreset = {
+ kind: 'robots',
+ slug: 'no-ai',
+ label: 'Open to search, closed to AI training',
+ description:
+ 'Indexable by search engines, disallowed for the named model-training crawlers. The list names each user-agent because robots.txt has no wildcard for \u201Can AI crawler\u201D, so it is a row to keep current rather than a pattern.',
+ directives: [
+ 'User-agent: GPTBot',
+ 'Disallow: /',
+ '',
+ 'User-agent: ChatGPT-User',
+ 'Disallow: /',
+ '',
+ 'User-agent: CCBot',
+ 'Disallow: /',
+ '',
+ 'User-agent: ClaudeBot',
+ 'Disallow: /',
+ '',
+ 'User-agent: anthropic-ai',
+ 'Disallow: /',
+ '',
+ 'User-agent: Google-Extended',
+ 'Disallow: /',
+ '',
+ 'User-agent: Applebot-Extended',
+ 'Disallow: /',
+ '',
+ 'User-agent: meta-externalagent',
+ 'Disallow: /',
+ '',
+ 'User-agent: Bytespider',
+ 'Disallow: /',
+ '',
+ 'User-agent: PerplexityBot',
+ 'Disallow: /'
+ ]
+};
diff --git a/packages/node-type-registry/src/content-presets/sso.ts b/packages/node-type-registry/src/content-presets/sso.ts
new file mode 100644
index 0000000000..bf253eed05
--- /dev/null
+++ b/packages/node-type-registry/src/content-presets/sso.ts
@@ -0,0 +1,32 @@
+import type { RouteBindingsPreset } from './types';
+
+/**
+ * SSO: the browser legs of signing in with an external identity provider.
+ *
+ * Its own slug rather than part of `mantra`, because a provider sign-in is
+ * something a tenant turns on, not something every site serves: a tenant with
+ * no identity providers has no callback to answer, and a callback path that
+ * answers anyway is a public endpoint that does nothing but advertise itself.
+ * Absent this preset the paths are simply unrouted, so they 404 — there is no
+ * fallback page behind them.
+ *
+ * The pages are mantra's tasks (the `/login` provider buttons link to
+ * `/auth/start`), so this installs beside `mantra` with the same verb:
+ * `_install_mantra(site_id, entity_id, 'sso')`. The tenant still needs
+ * `auth:sso` (identity providers + connected accounts) for there to be a
+ * provider to start against.
+ */
+export const sso: RouteBindingsPreset = {
+ kind: 'route_bindings',
+ slug: 'sso',
+ label: 'SSO sign-in pages',
+ description:
+ "The OAuth/OIDC browser legs served by the mantra function image: /auth/start sends the browser to the tenant's identity provider and /auth/callback consumes the return, signs the browser in and sets the session cookie, and /auth/error sends a return that failed back to /login naming why. Opt-in: install beside 'mantra' on a site whose tenant has auth:sso; without it these paths 404.",
+ bindings: [
+ { path: '/auth/start', task_identifier: 'mantra:oauth_start', anonymous: true },
+ { path: '/auth/callback', task_identifier: 'mantra:oauth_callback', anonymous: true },
+ // Where a return that failed is sent: the tenant's oauth_error_redirect_path
+ // defaults here, so without it a cancelled sign-in ends on a 404.
+ { path: '/auth/error', task_identifier: 'mantra:oauth_error', anonymous: true },
+ ],
+};
diff --git a/packages/node-type-registry/src/content-presets/types.ts b/packages/node-type-registry/src/content-presets/types.ts
index 39eae6f844..2b83201bd5 100644
--- a/packages/node-type-registry/src/content-presets/types.ts
+++ b/packages/node-type-registry/src/content-presets/types.ts
@@ -15,10 +15,18 @@
* lookup — these are simply the ones we ship.
*/
+import type { UIDocument } from 'blocks-schema';
+
import type { LimitDefault, TrustLadderRung } from '../module-presets/types';
/** The catalog kinds a content preset can be authored for. */
-export type ContentPresetKind = 'trust_ladder' | 'limit_defaults';
+export type ContentPresetKind =
+ | 'trust_ladder'
+ | 'limit_defaults'
+ | 'route_bindings'
+ | 'pages'
+ | 'robots'
+ | 'principal';
/** Fields every content preset carries, whatever its kind. */
type ContentPresetBase = {
@@ -46,11 +54,219 @@ export type LimitBaselinePreset = ContentPresetBase & {
limits: LimitDefault[];
};
-export type ContentPreset = TrustLadderPreset | LimitBaselinePreset;
+/**
+ * One URL path served by one named function task, e.g.
+ * `/login` -> `mantra:signin`. The task identifier is resolved through the
+ * functions catalog at install time, so a binding names a task and never an
+ * image, a scope, or a URL.
+ */
+export type FunctionRouteBinding = {
+ /** Path the route claims on the site's hostname; never `/` or a catch-all. */
+ path: string;
+ /** Published function task that serves it. */
+ task_identifier: string;
+ /**
+ * Whether the installed route answers callers carrying no identity. A page
+ * set whose sign-in surface required a session would be unreachable, so a
+ * binding states its half of the anonymous contract here; the targeted
+ * definition must itself declare `anonymous_callable`.
+ */
+ anonymous?: boolean;
+};
+
+/**
+ * One URL path the edge answers with a redirect onto another path of the same
+ * hostname, e.g. `/` -> `/login` on a host that exists only to serve a page set.
+ * A row in the routing plane's redirects table, not a function: no backend is
+ * involved. The one binding kind allowed to take over an existing route — the
+ * placeholder root the route guard created targeting the site itself.
+ */
+export type RedirectRouteBinding = {
+ /** Path the route claims on the site's hostname. */
+ path: string;
+ target: 'redirect';
+ /** Destination path on the same hostname; must start with `/`. */
+ to_path: string;
+ /** HTTP status the edge answers with; 302 when omitted. */
+ status_code?: 301 | 302 | 307 | 308;
+ /** Whether the installed route answers callers carrying no identity. */
+ anonymous?: boolean;
+};
+
+/** One entry of a route-bindings preset. */
+export type RouteBinding = FunctionRouteBinding | RedirectRouteBinding;
+
+/**
+ * A named set of path -> task bindings installed onto a site as ordinary
+ * function-target routes. Which paths a page set owns is a product decision, so
+ * it is a catalog row rather than a list inside a generator.
+ */
+export type RouteBindingsPreset = ContentPresetBase & {
+ kind: 'route_bindings';
+ bindings: RouteBinding[];
+};
+
+/**
+ * One starter page of prose: a path and the `{title, body}` content a site's
+ * merkle-backed pages store at it. `body` is blank-line-separated prose,
+ * rendered escaped — never markup. It states no `kind` because untagged content
+ * *is* prose to the page handlers, which is what every page written before the
+ * discriminator existed holds.
+ */
+export type ProsePageDocument = {
+ /** Path the page is served at on the site's hostname. */
+ path: string;
+ /** The page's own heading. */
+ title: string;
+ /** Blank-line-separated prose. */
+ body: string;
+};
+
+/**
+ * One starter page whose content is a block `UIDocument` — the blocks spec's
+ * JSON, served by the page handlers' document renderer rather than as prose.
+ *
+ * A layout is exactly this: a document with `Slot` nodes, stored at the reserved
+ * `_layout/` path a request can never ask for, so the template a site
+ * serves its pages in is a page row it owns, versioned by its own publishing.
+ */
+export type BlockPageDocument = {
+ /** Path the page is served at, or `_layout/` for a layout. */
+ path: string;
+ /** What the content holds, read by the page handlers before rendering it. */
+ kind: 'block_document';
+ /** The page's own heading, beside the document rather than in it. */
+ title: string;
+ /** The document itself, as `blocks-schema` accepts it. */
+ document: UIDocument;
+};
+
+/** One starter page, of either content kind the page handlers serve. */
+export type PageDocument = ProsePageDocument | BlockPageDocument;
+
+/**
+ * A named set of starter pages a site seeds into its merkle-backed pages and
+ * then authors over. Installed as page rows — versioned by the site's own
+ * publishing — never as a configuration blob.
+ */
+export type PagesPreset = ContentPresetBase & {
+ kind: 'pages';
+ pages: PageDocument[];
+};
+
+/**
+ * One line of a `robots.txt`, in file order — a `User-agent:` group header, a
+ * `Disallow:`, or an empty string separating groups. Lines rather than a parsed
+ * shape because robots.txt is a line-oriented file whose grouping *is* its
+ * order: a site's `robots` column is emitted verbatim, so what is authored here
+ * is exactly what a crawler reads.
+ */
+export type RobotsDirective = string;
+
+/**
+ * A named starter `robots.txt` body a site adopts into its `robots` column.
+ * Which crawlers a tenant feeds is a product decision, so it is a catalog row
+ * rather than a list inside the emitter.
+ */
+export type RobotsPreset = ContentPresetBase & {
+ kind: 'robots';
+ directives: RobotsDirective[];
+};
+
+/**
+ * The capability posture a principal preset grants at one membership scope.
+ * Capabilities are named, never bit positions: the generated
+ * `create_principal_from_preset` resolves each name against the tenant's own
+ * capabilities table at instantiation, so one catalog row fits every tenant
+ * whatever its bit width, and a name the tenant does not know fails loudly
+ * instead of silently narrowing.
+ */
+export type PrincipalPresetScope = {
+ /** Membership scope the mask applies at: `app` or `org`. */
+ membership_type: 'app' | 'org';
+ /**
+ * Capability names the principal keeps at this scope. The owner's own
+ * capabilities are AND-ed with this set, so it can only narrow — an empty
+ * list keeps membership (reads) and drops every capability bit. `null` is
+ * no mask at all: the principal keeps every bit the owner holds there.
+ */
+ allowed_mask_capabilities: string[] | null;
+};
+
+/**
+ * Credential lifetimes a preset asks for. Each is an interval literal and may
+ * only cap the tenant's `auth_settings` defaults, never exceed them.
+ */
+export type PrincipalPresetCredentials = {
+ api_key_ttl: string;
+ access_token_ttl: string;
+ refresh_token_ttl: string;
+ max_chain_age: string;
+};
+
+/**
+ * The shape `create_principal_from_preset` instantiates. `permissions` in the
+ * planning text is `scopes[].allowed_mask_capabilities` plus `is_read_only`;
+ * `session_settings` is `credentials`. There is no `invocable_by`: only the
+ * owning human may instantiate a principal, and organization reach is fenced
+ * by the owner's own membership.
+ */
+export type PrincipalPresetDefinition = {
+ is_read_only: boolean;
+ use_admin_owner: boolean;
+ bypass_step_up: boolean;
+ scopes: PrincipalPresetScope[];
+ /** `require_list`: the caller must scope the principal to named entities; `inherit_owner`: optional, defaults to the owner's reach. */
+ entity_policy: 'require_list' | 'inherit_owner';
+ delegation: {
+ allowed: boolean;
+ max_depth: number;
+ };
+ credentials: PrincipalPresetCredentials;
+};
+
+/**
+ * A named blueprint for a principal — read-only analyst, deploy bot — that a
+ * human instantiates in one call instead of composing create_principal +
+ * set_principal_scope + set_principal_entities by hand. Catalog data, not
+ * code: the row names capabilities and lifetimes, and the generated function
+ * resolves them against the tenant it runs in.
+ */
+export type PrincipalPreset = ContentPresetBase & {
+ kind: 'principal';
+ definition: PrincipalPresetDefinition;
+};
+
+export type ContentPreset =
+ | TrustLadderPreset
+ | LimitBaselinePreset
+ | RouteBindingsPreset
+ | PagesPreset
+ | RobotsPreset
+ | PrincipalPreset;
-/** The document provisioning installs for a preset: an array of rows. */
+/** The document provisioning installs for a preset: an array of rows, or one object for a principal. */
export function contentPresetDefinition(
preset: ContentPreset
-): TrustLadderRung[] | LimitDefault[] {
- return preset.kind === 'trust_ladder' ? preset.rungs : preset.limits;
+):
+ | TrustLadderRung[]
+ | LimitDefault[]
+ | RouteBinding[]
+ | PageDocument[]
+ | RobotsDirective[]
+ | PrincipalPresetDefinition {
+ switch (preset.kind) {
+ case 'principal':
+ return preset.definition;
+ case 'trust_ladder':
+ return preset.rungs;
+ case 'limit_defaults':
+ return preset.limits;
+ case 'route_bindings':
+ return preset.bindings;
+ case 'pages':
+ return preset.pages;
+ case 'robots':
+ return preset.directives;
+ }
}
diff --git a/packages/node-type-registry/src/data/check-owned-relation.ts b/packages/node-type-registry/src/data/check-owned-relation.ts
index 673c6b2b5d..920c8e1003 100644
--- a/packages/node-type-registry/src/data/check-owned-relation.ts
+++ b/packages/node-type-registry/src/data/check-owned-relation.ts
@@ -49,6 +49,11 @@ export const CheckOwnedRelation: NodeTypeDefinition = {
type: 'boolean',
description: "Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database",
default: false
+ },
+ allow_frame_chain: {
+ type: 'boolean',
+ description: "Admit rows owned by any frame on the referencing row's own scope-frame chain (its own scopes, then the platform database's chain) for this column, for pointers naming a definition published UP the hierarchy — the shared platform function image a tenant route targets. Ancestry only: a peer or another keyed owner is on no chain. Requires owner_key_field_name",
+ default: false
}
},
required: ['field_name', 'link_table_name']
diff --git a/packages/node-type-registry/src/data/data-capabilities.ts b/packages/node-type-registry/src/data/data-capabilities.ts
index 4c872bb66e..acced3620e 100644
--- a/packages/node-type-registry/src/data/data-capabilities.ts
+++ b/packages/node-type-registry/src/data/data-capabilities.ts
@@ -16,8 +16,19 @@ export const DataCapabilities: NodeTypeDefinition = {
default: 'required_capabilities'
},
capabilities: {
- type: 'string',
- description: 'Selects the capabilities module whose bit numbering the mask is measured in, by scope (e.g. "app", "org") or by table prefix. Required only when the database has more than one; several with no selector raises naming the candidates.'
+ type: 'object',
+ description: 'Selector for the capabilities module whose bit numbering the mask is measured in, e.g. {"scope": "org"}. Every key given must match exactly one module; none or several raises naming the candidates. Required only when the database has more than one.',
+ properties: {
+ scope: {
+ type: 'string',
+ description: 'Scope the module is installed at ("app", "org", or an entity type prefix).'
+ },
+ prefix: {
+ type: 'string',
+ description: 'Table prefix of the module instance; rarely needed since prefix follows scope.'
+ }
+ },
+ additionalProperties: false
},
default: {
type: 'array',
diff --git a/packages/node-type-registry/src/data/data-inherit-from-parent.ts b/packages/node-type-registry/src/data/data-inherit-from-parent.ts
index ccb7f1b900..8c9b408b24 100644
--- a/packages/node-type-registry/src/data/data-inherit-from-parent.ts
+++ b/packages/node-type-registry/src/data/data-inherit-from-parent.ts
@@ -5,7 +5,7 @@ export const DataInheritFromParent: NodeTypeDefinition = {
slug: 'data_inherit_from_parent',
category: 'data',
display_name: 'Inherit From Parent',
- description: 'BEFORE INSERT trigger that copies specified fields from a parent table via a foreign key. The parent row is looked up through RLS (SECURITY INVOKER), so the insert fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files.',
+ description: 'BEFORE INSERT OR UPDATE trigger that copies specified fields from a parent table via a foreign key; on UPDATE the fields are re-copied only when the parent FK changes. The parent row is looked up through RLS (SECURITY INVOKER), so the insert or update fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files.',
parameter_schema: {
type: 'object',
properties: {
diff --git a/packages/node-type-registry/src/job/trigger.ts b/packages/node-type-registry/src/job/trigger.ts
index aa9dbe866d..b827f698c0 100644
--- a/packages/node-type-registry/src/job/trigger.ts
+++ b/packages/node-type-registry/src/job/trigger.ts
@@ -106,6 +106,11 @@ export const JobTrigger: NodeTypeDefinition = {
type: 'string',
description: 'Job queue name for routing to specific workers'
},
+ queue_key_field: {
+ type: 'string',
+ format: 'column-ref',
+ description: 'Column whose value keys the job queue, so the queue name becomes ":". A named queue is held for the whole job, so a shared literal queue serializes every job that uses it; keying on the work\'s subject keeps same-subject jobs ordered while unrelated subjects run in parallel.'
+ },
priority: {
type: 'integer',
description: 'Job priority (lower = higher priority)',
diff --git a/packages/node-type-registry/src/limit/enforce-feature.ts b/packages/node-type-registry/src/limit/enforce-feature.ts
index 5a4b5fa5dd..f540c9e16a 100644
--- a/packages/node-type-registry/src/limit/enforce-feature.ts
+++ b/packages/node-type-registry/src/limit/enforce-feature.ts
@@ -1,3 +1,4 @@
+import { conditionDefs, conditionProperties } from '../conditions';
import type { NodeTypeDefinition } from '../types';
export const LimitEnforceFeature: NodeTypeDefinition = {
@@ -6,9 +7,10 @@ export const LimitEnforceFeature: NodeTypeDefinition = {
category: 'limit_enforce',
display_name: 'Enforce Feature Flag',
description:
- 'Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE INSERT trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0).',
+ 'Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). Gate INSERT and UPDATE when a row can reach the gated state after creation, and narrow the gate with conditions when only some of the table\'s rows are the gated feature.',
parameter_schema: {
type: 'object',
+ $defs: conditionDefs,
properties: {
feature_name: {
type: 'string',
@@ -51,6 +53,21 @@ export const LimitEnforceFeature: NodeTypeDefinition = {
},
required: ['obj_table', 'obj_field'],
},
+ events: {
+ type: 'array',
+ items: {
+ type: 'string',
+ enum: ['INSERT', 'UPDATE'],
+ },
+ description:
+ 'Which DML events the cap gates. UPDATE is required when a row can reach the gated state after creation (e.g. a discriminator flipped from an ungated value to a gated one). DELETE is not supported: a cap answers whether a row may exist.',
+ default: ['INSERT'],
+ },
+ conditions: {
+ ...conditionProperties.conditions,
+ description:
+ 'Compound conditions for the trigger WHEN clause, so the cap gates a subset of rows rather than the whole table (e.g. only the rows a customer authors on a table the platform also writes). Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema.',
+ },
},
required: ['feature_name'],
},
diff --git a/packages/node-type-registry/src/limit/track-usage.ts b/packages/node-type-registry/src/limit/track-usage.ts
index 4ceb3e71c5..de1648b105 100644
--- a/packages/node-type-registry/src/limit/track-usage.ts
+++ b/packages/node-type-registry/src/limit/track-usage.ts
@@ -59,6 +59,12 @@ export const LimitTrackUsage: NodeTypeDefinition = {
description: 'Which DML events to attach triggers for',
default: ['INSERT', 'DELETE'],
},
+ enforce: {
+ type: 'boolean',
+ description:
+ 'With INSERT tracked, also attach a BEFORE INSERT gate on check_billing_quota that refuses a row past the allowance (BILLING_QUOTA_EXCEEDED), like the invocation quota gate. Off (default), rows past the allowance are inserted and their charge is refused. A slug with no meter row is never refused.',
+ default: false,
+ },
},
required: ['meter_slug'],
},
diff --git a/packages/node-type-registry/src/module-presets/auth-byo.ts b/packages/node-type-registry/src/module-presets/auth-byo.ts
new file mode 100644
index 0000000000..8c7fa24527
--- /dev/null
+++ b/packages/node-type-registry/src/module-presets/auth-byo.ts
@@ -0,0 +1,53 @@
+import type { ModulePreset } from './types';
+
+/**
+ * `auth:byo` — Constructive's users, organizations, memberships,
+ * capabilities, limits, profiles and hierarchy, with no authentication
+ * surface. Authentication and the API layer belong to the adopter.
+ *
+ * Identity arrives on the transaction as the claims contract
+ * (`docs/architecture/claims-contract.md`): a role (`authenticated` /
+ * `anonymous`) and `jwt.claims.user_id`. Every Authz* policy the membership
+ * planes compile reads `jwt_public.current_user_id()`, so nothing here needs
+ * a session, a credential, or a sign-in procedure.
+ *
+ * Invites and events are opt-in: add `invites_module` (needs `emails_module`)
+ * or `events_module` per scope when the app wants them.
+ */
+export const PresetAuthByo: ModulePreset = {
+ name: 'auth:byo',
+ display_name: 'Bring Your Own Auth',
+ summary: 'Users + orgs + memberships + capabilities + RLS. Authentication and API layer are yours.',
+ description:
+ 'Constructive as the multi-tenant authorization layer underneath your own authentication. ' +
+ 'You get users, organizations (org memberships, hierarchy, profiles), app and org ' +
+ 'capabilities and limits, and every Authz* policy type — but no sessions, credentials, ' +
+ 'emails, or sign_up/sign_in procedures. Your API layer verifies its own tokens and sets the ' +
+ 'role plus `jwt.claims.user_id` (and ideally `jwt.claims.database_id`) on each transaction; ' +
+ 'the provider subject is a UUID used directly as `users.id`, and your service role inserts ' +
+ 'the user row the first time it sees one. Add `invites_module` or `events_module` when you ' +
+ 'need them.',
+ good_for: [
+ 'Apps that keep an existing IdP (Auth0, Clerk, Supabase Auth, Cognito, in-house)',
+ 'Teams that run their own API layer and want Constructive orgs, memberships and RLS',
+ 'B2B apps whose sign-in must stay outside the database',
+ ],
+ not_for: [
+ 'Apps that want Constructive to own sign-up and sign-in — use `auth:hardened` or `b2b:storage`',
+ 'Single-tenant apps with no organizations — use `minimal`',
+ 'Providers whose subject is not a UUID, until a mapping table exists — keep your own map to `users.id`',
+ ],
+ modules: [
+ 'users_module',
+ 'membership_types_module',
+ ['capabilities_module', { scope: 'app' }],
+ ['capabilities_module', { scope: 'org' }],
+ ['limits_module', { scope: 'app' }],
+ ['limits_module', { scope: 'org' }],
+ ['memberships_module', { scope: 'app' }],
+ ['memberships_module', { scope: 'org' }],
+ ['profiles_module', { scope: 'app' }],
+ ['profiles_module', { scope: 'org' }],
+ ['hierarchy_module', { scope: 'org' }],
+ ],
+};
diff --git a/packages/node-type-registry/src/module-presets/b2b-saas.ts b/packages/node-type-registry/src/module-presets/b2b-saas.ts
new file mode 100644
index 0000000000..84b4771b52
--- /dev/null
+++ b/packages/node-type-registry/src/module-presets/b2b-saas.ts
@@ -0,0 +1,63 @@
+import { PresetB2bStorage } from './b2b-storage';
+import type { ModulePreset } from './types';
+
+/**
+ * `b2b:saas` — `b2b:storage` plus `billing_provider_module`, the Stripe
+ * provider bridge. The hosted-tenant shape for a B2B SaaS that bills its own
+ * end customers.
+ *
+ * `b2b:storage` already carries the local billing catalog (`plans_module`,
+ * `billing_module`, `rate_limit_meters_module`); this preset adds the provider
+ * tables (customers, products, prices, subscriptions, operations ledger) and
+ * the row-driven `billing:sync_*` triggers that mirror the catalog to Stripe.
+ *
+ * Deliberately no `function_module` / `webhook_module` / `route_module` /
+ * `namespace_module`: a hosted tenant is served by the platform's shared
+ * `functions/billing` and `functions/checkout` images, which resolve the
+ * tenant from the invocation and read that tenant's Stripe key via
+ * `ctx.secrets` per call. Its webhook signing secrets live in the infra lane
+ * of the tenant's hook namespace, where the webhook gateway verifies
+ * deliveries. The sync jobs the triggers enqueue are stamped `scope = 'app'`.
+ * Every execution for the tenant reads the key and the billing config from the
+ * nearest store along the frame walk: the tenant's own app-scope stores, which
+ * `b2b:storage` installs, ahead of the platform's database-scope plane.
+ *
+ * Provisioning does not activate billing. The owner sets it up from the
+ * dashboard's Monetization wizard: routes, key, hook namespace, webhook
+ * endpoints, `billing:connect` (the half that needs the key), a catalog, and a
+ * green `billing:doctor` verdict before `enable_billing` turns on.
+ */
+export const PresetB2bSaas: ModulePreset = {
+ name: 'b2b:saas',
+ display_name: 'B2B SaaS + Billing',
+ summary:
+ 'b2b:storage plus the Stripe provider bridge (customers, products, prices, subscriptions, operations ledger).',
+ description:
+ 'Everything in `b2b:storage`, plus `billing_provider_module`: the Stripe-side mirror of the ' +
+ 'local billing catalog (customers, products, prices, subscriptions, operations ledger) and ' +
+ 'the row-driven sync triggers on `plans`, `plan_pricing` and `plan_subscriptions` that ' +
+ 'enqueue `billing:sync_plan` / `billing:sync_price` / `billing:sync_subscription` at the ' +
+ '`app` scope. The tenant bills its OWN end customers through its OWN Stripe account: the ' +
+ "platform's shared `functions/billing` and `functions/checkout` images serve every tenant " +
+ 'and read `STRIPE_SECRET_KEY` via `ctx.secrets` per invocation (webhook signing secrets ' +
+ "live in the infra lane of the tenant's hook namespace, where the webhook gateway verifies " +
+ 'deliveries), so the preset installs no function, webhook, route, or namespace module. ' +
+ "Provisioning alone does not activate billing — the owner sets it up from the dashboard's " +
+ 'Monetization wizard: the billing and checkout routes on the tenant host, the Stripe key, ' +
+ 'a hook namespace with its webhook definitions and endpoints, `billing:connect` (the half ' +
+ 'that needs the key), a catalog, and a green `billing:doctor` verdict, which ' +
+ '`database_settings.enable_billing = true` is gated on. Choose this when your B2B app ' +
+ 'sells plans to its customers and needs the Stripe bridge from day one.',
+ good_for: [
+ 'B2B SaaS that bills its own end customers through its own Stripe account',
+ 'Apps that sell plans, prices and subscriptions from the local billing catalog',
+ 'Hosted tenants served by the shared `functions/billing` / `functions/checkout` images'
+ ],
+ not_for: [
+ 'Apps without customer billing — use `b2b:storage`, which already carries plans, billing and meters',
+ 'The kitchen-sink / dev shape — use `full`, which adds `function_module` and `namespace_module`',
+ 'Turnkey billing — activation still needs Stripe secrets, webhook rows, `checkout:session` route rows and `enable_billing`'
+ ],
+ modules: [...PresetB2bStorage.modules, 'billing_provider_module'],
+ extends: ['b2b:storage']
+};
diff --git a/packages/node-type-registry/src/module-presets/b2b-storage.ts b/packages/node-type-registry/src/module-presets/b2b-storage.ts
index 509f343849..5e2815fd7d 100644
--- a/packages/node-type-registry/src/module-presets/b2b-storage.ts
+++ b/packages/node-type-registry/src/module-presets/b2b-storage.ts
@@ -21,7 +21,9 @@ export const PresetB2bStorage: ModulePreset = {
'Everything in `auth:hardened`, plus orgs, invites, capabilities, profiles and hierarchy at ' +
'both app and org membership scopes, an `events_module` at both scopes carrying the ' +
'`humanity` trust ladder (so a member can earn `level.reachable` and a policy can gate on ' +
- 'it), and `storage_module` for file uploads, exposed on the `storage` API. The storage ' +
+ 'it), `plans_module` + `billing_module` + `rate_limit_meters_module` (the chain the sync ' +
+ 'invocation verb requires to rate-limit calls), and `storage_module` for file uploads, ' +
+ 'exposed on the `storage` API. The storage ' +
'module creates `app_buckets` and `app_files` tables with full RLS: AuthzPublishable for public reads, ' +
'AuthzAppMembership for member access, AuthzDirectOwner for uploader-only modify/delete. ' +
'Entity-type provisioning with a non-empty `storage` array adds per-scope storage tables ' +
@@ -74,6 +76,13 @@ export const PresetB2bStorage: ModulePreset = {
['profiles_module', { scope: 'app' }],
['profiles_module', { scope: 'org' }],
['hierarchy_module', { scope: 'org' }],
+ // Billing & plans: invocation_sync_verb fails closed without a provisioned
+ // rate_limit_meters_module whose check function is non-empty, and that
+ // function only exists once billing_module (which needs plans_module) is
+ // installed — so a B2B tenant could not generate a sync verb at all.
+ 'plans_module',
+ 'billing_module',
+ 'rate_limit_meters_module',
['invites_module', { scope: 'app' }],
['invites_module', { scope: 'org' }],
// Binds the database to the typed catalog plane. Buckets are routable
diff --git a/packages/node-type-registry/src/module-presets/dependencies.ts b/packages/node-type-registry/src/module-presets/dependencies.ts
new file mode 100644
index 0000000000..d9846cb4f3
--- /dev/null
+++ b/packages/node-type-registry/src/module-presets/dependencies.ts
@@ -0,0 +1,524 @@
+/**
+ * What a module reads from its siblings, and how to hand `provision_database_modules`
+ * a module list that already contains them.
+ *
+ * Every relationship here mirrors a check in the backend: the module trigger or
+ * generator saying, at the point it fails, which sibling plane it was reading and
+ * at which scope. The backend's tests re-derive this table from those checks and
+ * fail when the two disagree, so the backend stays the source of truth and this
+ * file cannot drift into being its own invention.
+ *
+ * The scope is part of the dependency, not decoration: `user_auth_module` reads
+ * the *app* memberships plane wherever it is installed, while `invites_module`
+ * reads the memberships plane *in its own scope* — an org-scoped invites module
+ * with only an app-scoped memberships plane installed is missing a dependency
+ * even though `memberships_module` appears in the list.
+ */
+
+import type { BaseModuleOptions, ModuleEntry } from './types';
+
+/**
+ * Where a dependency has to be installed, relative to the module that reads it.
+ *
+ * - `same` — the dependent's own scope (`scope => NEW.scope` in SQL). The only
+ * direction that is ever legal implicitly: a plane is read in the scope that
+ * owns it, never borrowed from another one.
+ * - `app` / `org` / `platform` — a fixed scope named by the reader itself.
+ * - `unscoped` — the lookup filters on `database_id` alone, so any installed
+ * plane of that kind satisfies it.
+ * - `runtime` — the scope is computed at write time from data (a policy's
+ * `membership_type`, for instance), so it cannot be closed over statically.
+ * Recorded for documentation and excluded from the closure.
+ */
+export type DependencyScope =
+ | 'same'
+ | 'app'
+ | 'org'
+ | 'platform'
+ | 'unscoped'
+ | 'runtime';
+
+/**
+ * When a dependency applies at all. A trigger that reads a sibling plane only
+ * under a condition does not make that plane a dependency of every install.
+ *
+ * - `entity_scope` — only when the dependent is installed at a scope that names
+ * an entity (an org's own plane, a user's own plane). Decided from the entity
+ * side: `entityScopes` below lists the scopes that name an entity, rather than
+ * mirroring the generators' internal non-entity union, which is documented as
+ * a provision-time implementation detail that must not become a TS constant.
+ * - `group_scope` — only when the dependent is a group plane nested under an org,
+ * which is decided from membership-type data at provision time and cannot be
+ * read off a module list. Recorded, never closed over.
+ * - `{ option }` — only when that option is truthy on the dependent's entry.
+ */
+export type DependencyCondition =
+ | 'entity_scope'
+ | 'group_scope'
+ | { option: string };
+
+/** Scopes that name an entity, and so carry an owner a membership plane keys on. */
+export const entityScopes = ['org', 'user'] as const;
+
+/** One module reading one sibling plane. */
+export interface ModuleDependency {
+ /** Module that must be installed. */
+ module: string;
+ /** Where it must be installed, relative to the reader. */
+ scope: DependencyScope;
+ /** What the reader wants from it, in the reader's own words. */
+ reason: string;
+ /** Options the auto-added entry carries, beyond `scope`. */
+ options?: BaseModuleOptions & Record;
+ /** When the dependency applies; omitted → always. */
+ when?: DependencyCondition;
+}
+
+/**
+ * Module → the planes its triggers and generators read.
+ *
+ * Keyed by module name. A generator that is not itself a module (the group
+ * triggers `memberships_module` installs, the RLS parser) records its
+ * dependency under the module that owns it, because that is the entry a caller
+ * can act on.
+ */
+export const moduleDependencies: Record = {
+ billing_provider_module: [
+ {
+ module: 'memberships_module',
+ scope: 'app',
+ reason: 'the app manage_billing check its provider key reader runs',
+ },
+ {
+ module: 'internal_secrets_module',
+ scope: 'runtime',
+ reason: 'the store its provider key reader reads (database scope, else app)',
+ },
+ ],
+ capabilities_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the actor column its grants carry' },
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ reason: 'the membership plane its permission bits are packed for',
+ },
+ ],
+ connected_accounts_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the account owner' },
+ ],
+ crypto_addresses_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the address owner' },
+ ],
+ crypto_auth_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the signer it authenticates' },
+ { module: 'user_state_module', scope: 'unscoped', reason: 'the state it flips on sign-in' },
+ { module: 'sessions_module', scope: 'unscoped', reason: 'the session it mints' },
+ {
+ module: 'crypto_addresses_module',
+ scope: 'unscoped',
+ reason: 'the addresses a signature is checked against',
+ },
+ ],
+ devices_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the device owner' }],
+ email_sender_module: [
+ {
+ module: 'internal_secrets_module',
+ scope: 'runtime',
+ reason: 'the database-scope credential store read when a platform email module supplies shared transport',
+ },
+ ],
+ emails_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the address owner' }],
+ events_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the event actor' }],
+ hierarchy_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the actor a hierarchy edge is written by' },
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ reason: 'the membership plane a hierarchy climb resolves against',
+ },
+ ],
+ identity_providers_module: [
+ { module: 'sessions_module', scope: 'unscoped', reason: 'the session a federated sign-in mints' },
+ {
+ module: 'internal_secrets_module',
+ scope: 'same',
+ reason: 'where a provider client secret is stored',
+ },
+ ],
+ infra_config_module: [
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ when: 'entity_scope',
+ reason: 'the membership plane its config policies read',
+ },
+ { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' },
+ ],
+ infra_secrets_module: [
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ when: 'entity_scope',
+ reason: 'the membership plane its secret policies read',
+ },
+ { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' },
+ ],
+ internal_config_module: [
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ when: 'entity_scope',
+ reason: 'the membership plane its config policies read',
+ },
+ ],
+ internal_secrets_module: [
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ when: 'entity_scope',
+ reason: 'the membership plane its secret policies read',
+ },
+ ],
+ invites_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the inviting actor' },
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ reason: 'the membership plane an accepted invite writes into',
+ },
+ { module: 'emails_module', scope: 'unscoped', reason: 'the address an invite is sent to' },
+ ],
+ limits_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the actor a limit is spent by' }],
+ memberships_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the member' },
+ {
+ module: 'membership_types_module',
+ scope: 'unscoped',
+ reason: 'the type a membership row carries',
+ },
+ {
+ module: 'capabilities_module',
+ scope: 'same',
+ reason: 'the permission bits its grants and defaults are packed from',
+ },
+ {
+ module: 'memberships_module',
+ scope: 'org',
+ when: 'group_scope',
+ reason: 'the org plane a group\u2019s ancestor chain terminates at',
+ },
+ ],
+ notifications_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the notification recipient' },
+ {
+ module: 'user_settings_module',
+ scope: 'unscoped',
+ when: { option: 'has_settings_extension' },
+ reason: 'the settings table its settings extension reads',
+ },
+ {
+ module: 'internal_secrets_module',
+ scope: 'app',
+ reason: 'where its delivery credentials are stored',
+ },
+ ],
+ oauth_requests_module: [
+ {
+ module: 'user_auth_module',
+ scope: 'unscoped',
+ reason: 'the auth surface link_identity is emitted into and the sessions its step-up reads',
+ },
+ {
+ module: 'connected_accounts_module',
+ scope: 'unscoped',
+ reason: 'where a redeemed link ticket binds the identity',
+ },
+ ],
+ phone_numbers_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the number owner' }],
+ // principals_module is not listed: the insert trigger provisions it.
+ principal_auth_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the human behind a principal' },
+ { module: 'sessions_module', scope: 'unscoped', reason: 'the session a principal mints' },
+ { module: 'user_auth_module', scope: 'unscoped', reason: 'the auth surface it extends' },
+ ],
+ principals_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the human behind a principal' },
+ { module: 'capabilities_module', scope: 'unscoped', reason: 'the bitlen its permission masks use' },
+ {
+ module: 'memberships_module',
+ scope: 'unscoped',
+ reason: 'an sprt table to resolve a principal\u2019s bits at runtime',
+ },
+ ],
+ profiles_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the profile subject' },
+ {
+ module: 'membership_types_module',
+ scope: 'unscoped',
+ reason: 'the type a profile is scoped by',
+ },
+ {
+ module: 'memberships_module',
+ scope: 'same',
+ reason: 'the membership plane its visibility policies read',
+ },
+ ],
+ resource_module: [
+ { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' },
+ ],
+ function_deployment_module: [
+ { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' },
+ ],
+ graph_module: [
+ {
+ module: 'merkle_store_module',
+ scope: 'same',
+ reason: 'the store its graph revisions commit into',
+ options: {
+ prefix: 'function_graph',
+ public_schema_name: 'compute_public',
+ private_schema_name: 'compute_private',
+ api_name: 'compute',
+ capability_key: 'manage_graphs',
+ },
+ },
+ ],
+ rls_module: [
+ { module: 'sessions_module', scope: 'unscoped', reason: 'the session its claims are read from' },
+ {
+ module: 'memberships_module',
+ scope: 'runtime',
+ reason: 'the sprt table a policy\u2019s membership_type resolves to',
+ },
+ {
+ module: 'hierarchy_module',
+ scope: 'runtime',
+ reason: 'the hierarchy sprt table an org-hierarchy policy reads',
+ },
+ ],
+ session_secrets_module: [
+ { module: 'sessions_module', scope: 'unscoped', reason: 'the sessions it signs' },
+ ],
+ sessions_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the session subject' }],
+ user_auth_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the account it authenticates' },
+ {
+ module: 'memberships_module',
+ scope: 'app',
+ reason: 'the app membership a new account is granted',
+ },
+ { module: 'emails_module', scope: 'unscoped', reason: 'the address sign-up verifies' },
+ { module: 'user_state_module', scope: 'unscoped', reason: 'the state sign-in flips' },
+ {
+ module: 'user_credentials_module',
+ scope: 'unscoped',
+ reason: 'where a password hash is stored',
+ },
+ { module: 'sessions_module', scope: 'unscoped', reason: 'the session sign-in mints' },
+ ],
+ user_settings_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the settings owner' },
+ ],
+ user_settings_security_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the settings owner' },
+ ],
+ webauthn_auth_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the account it authenticates' },
+ {
+ module: 'webauthn_credentials_module',
+ scope: 'unscoped',
+ reason: 'the credentials an assertion is checked against',
+ },
+ { module: 'sessions_module', scope: 'unscoped', reason: 'the session an assertion mints' },
+ { module: 'session_secrets_module', scope: 'unscoped', reason: 'the challenge signing key' },
+ {
+ module: 'memberships_module',
+ scope: 'app',
+ reason: 'the app membership whose disabled/banned standing a passkey sign-in checks',
+ },
+ { module: 'user_auth_module', scope: 'unscoped', reason: 'the auth surface it extends' },
+ ],
+ webauthn_credentials_module: [
+ { module: 'users_module', scope: 'unscoped', reason: 'the credential owner' },
+ ],
+};
+
+/** Options of a module entry, or `{}` for a bare name. */
+function entryOptions(entry: ModuleEntry): BaseModuleOptions & Record {
+ return typeof entry === 'string' ? {} : ((entry[1] ?? {}) as BaseModuleOptions & Record);
+}
+
+/** Name of a module entry. */
+export function moduleEntryName(entry: ModuleEntry): string {
+ return typeof entry === 'string' ? entry : entry[0];
+}
+
+/**
+ * Does this dependency apply to this entry? An unmet condition is not a missing
+ * dependency — the reader never looks the plane up.
+ */
+function applies(dependency: ModuleDependency, entry: ModuleEntry): boolean {
+ const condition = dependency.when;
+ if (condition === undefined) return true;
+ if (condition === 'group_scope') return false;
+ if (condition === 'entity_scope') {
+ const scope = entryOptions(entry).scope as string | undefined;
+ return scope !== undefined && (entityScopes as readonly string[]).includes(scope);
+ }
+ return Boolean(entryOptions(entry)[condition.option]);
+}
+
+/**
+ * The scope a dependency has to be satisfied at, or `null` when it cannot be
+ * closed over statically (`runtime`) — that dependency is a caller decision
+ * driven by data, and the database raises a named error if the plane is absent.
+ */
+function requiredScope(
+ dependency: ModuleDependency,
+ dependentScope: string | undefined,
+): string | undefined | null {
+ switch (dependency.scope) {
+ case 'runtime':
+ return null;
+ case 'unscoped':
+ return undefined;
+ case 'same':
+ return dependentScope;
+ default:
+ return dependency.scope;
+ }
+}
+
+/** Does `entries` already carry this module at this scope? */
+function isSatisfied(
+ entries: ModuleEntry[],
+ module: string,
+ scope: string | undefined,
+): boolean {
+ return entries.some((entry) => {
+ if (moduleEntryName(entry) !== module) return false;
+ // An unscoped dependency reads whichever plane exists, so any entry answers it.
+ if (scope === undefined) return true;
+ return entryOptions(entry).scope === scope;
+ });
+}
+
+/** A dependency of a specific entry that the module list does not contain. */
+export interface MissingModuleDependency {
+ /** Module whose trigger or generator reads the missing plane. */
+ dependent: string;
+ /** Scope the dependent is installed at, when it is a scoped module. */
+ dependent_scope?: string;
+ /** Module that has to be installed. */
+ required_module: string;
+ /** Scope it has to be installed at, when the dependency is scoped. */
+ required_scope?: string;
+ /** What the dependent reads from it. */
+ reason: string;
+ /** The module list entry that satisfies it — add this verbatim. */
+ declare: ModuleEntry;
+}
+
+function declarationFor(
+ dependency: ModuleDependency,
+ scope: string | undefined,
+): ModuleEntry {
+ const options = { ...(dependency.options ?? {}), ...(scope ? { scope } : {}) };
+ if (Object.keys(options).length === 0) return dependency.module;
+ return [dependency.module, options] as ModuleEntry;
+}
+
+/**
+ * Every dependency of `modules` that `modules` does not satisfy, transitively:
+ * an added plane is itself a module with dependencies, so the walk runs to a
+ * fixpoint over the list as it grows.
+ *
+ * Nothing here crosses a database — a module list provisions one database, so
+ * every dependency is resolved inside it — and nothing crosses a scope except
+ * where the reader itself names the other scope (`user_auth_module` reading the
+ * app membership plane, a group trigger reading the org one). A `same`-scope
+ * dependency is only ever satisfied by a plane in the dependent's own scope,
+ * never by one that happens to exist elsewhere.
+ */
+export function findMissingModuleDependencies(
+ modules: ModuleEntry[],
+): MissingModuleDependency[] {
+ const missing: MissingModuleDependency[] = [];
+ // Entries the closure has decided on so far: the caller's list plus what has
+ // already been reported missing, so a plane is reported once, not once per reader.
+ const known: ModuleEntry[] = [...modules];
+ const pending: ModuleEntry[] = [...modules];
+
+ while (pending.length > 0) {
+ const entry = pending.shift() as ModuleEntry;
+ const name = moduleEntryName(entry);
+ const scope = entryOptions(entry).scope as string | undefined;
+
+ for (const dependency of moduleDependencies[name] ?? []) {
+ if (!applies(dependency, entry)) continue;
+ const required = requiredScope(dependency, scope);
+ if (required === null) continue;
+ if (dependency.module === name && required === scope) continue;
+ if (isSatisfied(known, dependency.module, required)) continue;
+
+ const declare = declarationFor(dependency, required);
+ missing.push({
+ dependent: name,
+ ...(scope ? { dependent_scope: scope } : {}),
+ required_module: dependency.module,
+ ...(required ? { required_scope: required } : {}),
+ reason: dependency.reason,
+ declare,
+ });
+ known.push(declare);
+ pending.push(declare);
+ }
+ }
+
+ return missing;
+}
+
+/** The same sentence the database raises, for a list that has not been provisioned yet. */
+export function describeMissingModuleDependency(
+ missing: MissingModuleDependency,
+): string {
+ const at = missing.required_scope ? ` at scope '${missing.required_scope}'` : '';
+ const from = missing.dependent_scope
+ ? `${missing.dependent} (scope '${missing.dependent_scope}')`
+ : missing.dependent;
+ return (
+ `${from} reads ${missing.required_module}${at} (${missing.reason}), ` +
+ `which this module list does not install — add ${JSON.stringify(missing.declare)}`
+ );
+}
+
+/**
+ * `modules` plus the dependency closure it is missing.
+ *
+ * Caller entries are returned untouched and win every conflict: a plane the
+ * caller already declared keeps its prefix, storage key, schema names and
+ * feature flags, and only genuinely absent planes are appended. Appending
+ * rather than inserting is safe because `provision_database_modules` orders the
+ * install itself by module group, not by list position.
+ */
+export function withRequiredModules(modules: ModuleEntry[]): ModuleEntry[] {
+ return [
+ ...modules,
+ ...findMissingModuleDependencies(modules).map((missing) => missing.declare),
+ ];
+}
+
+/**
+ * Throws unless `modules` is dependency-complete, naming every missing plane and
+ * the entry that satisfies it. For callers that want the list they wrote to be
+ * the list that installs — a preset under test, a fixture — rather than one
+ * silently grown by `withRequiredModules`.
+ */
+export function assertModuleDependencies(modules: ModuleEntry[]): void {
+ const missing = findMissingModuleDependencies(modules);
+ if (missing.length === 0) return;
+ throw new Error(
+ `module list is missing ${missing.length} dependenc${missing.length === 1 ? 'y' : 'ies'}:\n` +
+ missing.map((m) => ` - ${describeMissingModuleDependency(m)}`).join('\n'),
+ );
+}
diff --git a/packages/node-type-registry/src/module-presets/index.ts b/packages/node-type-registry/src/module-presets/index.ts
index 9841bd5e45..8c4b095ba0 100644
--- a/packages/node-type-registry/src/module-presets/index.ts
+++ b/packages/node-type-registry/src/module-presets/index.ts
@@ -1,3 +1,18 @@
+export type {
+ DependencyCondition,
+ DependencyScope,
+ MissingModuleDependency,
+ ModuleDependency,
+} from './dependencies';
+export {
+ assertModuleDependencies,
+ describeMissingModuleDependency,
+ entityScopes,
+ findMissingModuleDependencies,
+ moduleDependencies,
+ moduleEntryName,
+ withRequiredModules,
+} from './dependencies';
export type {
AgentModuleOptions,
BaseModuleOptions,
@@ -15,23 +30,36 @@ export type {
} from './types';
import { getModuleType } from '../module-types';
+import { PresetAuthByo } from './auth-byo';
import { PresetAuthHardened } from './auth-hardened';
+import { PresetB2bSaas } from './b2b-saas';
import { PresetB2bStorage } from './b2b-storage';
+import { withRequiredModules } from './dependencies';
import { PresetFull } from './full';
import { PresetMinimal } from './minimal';
import type { ModulePreset } from './types';
-export { PresetAuthHardened, PresetB2bStorage, PresetFull, PresetMinimal };
+export {
+ PresetAuthByo,
+ PresetAuthHardened,
+ PresetB2bSaas,
+ PresetB2bStorage,
+ PresetFull,
+ PresetMinimal,
+};
/**
- * Ordered list of all shipped module presets, from smallest to largest
- * module footprint. Stable ordering — CLIs / UIs can present this directly.
+ * Ordered list of all shipped module presets. Registration order: new presets
+ * are appended, never inserted, because the backend seeds the presets in this
+ * order, and an insert in the middle would rewrite presets already applied.
*/
export const allModulePresets: ModulePreset[] = [
PresetMinimal,
PresetAuthHardened,
PresetB2bStorage,
PresetFull,
+ PresetB2bSaas,
+ PresetAuthByo,
];
/** Look up a preset by name. Returns undefined if the name isn't known. */
@@ -43,12 +71,24 @@ function moduleName(entry: ModulePreset['modules'][number]): string {
return typeof entry === 'string' ? entry : entry[0];
}
+/**
+ * The modules a preset installs.
+ *
+ * `includeDependencies` appends the planes the listed modules read but the
+ * preset does not name — the same closure a provisioner would otherwise fail
+ * on, in the scope each dependent asked for. It is opt-in because the shipped
+ * presets are already dependency-complete (a test asserts that), so the closure
+ * only matters for a caller-assembled list.
+ */
export function resolvePresetModules(
preset: ModulePreset,
- options: { includeInternal?: boolean } = {},
+ options: { includeInternal?: boolean; includeDependencies?: boolean } = {},
): ModulePreset['modules'] {
- if (options.includeInternal) return preset.modules;
- return preset.modules.filter(
+ const modules = options.includeDependencies
+ ? withRequiredModules(preset.modules)
+ : preset.modules;
+ if (options.includeInternal) return modules;
+ return modules.filter(
(entry) => !getModuleType(moduleName(entry))?.internal,
);
}
diff --git a/packages/node-type-registry/src/module-presets/types.ts b/packages/node-type-registry/src/module-presets/types.ts
index e7a902d7f5..954a101053 100644
--- a/packages/node-type-registry/src/module-presets/types.ts
+++ b/packages/node-type-registry/src/module-presets/types.ts
@@ -35,6 +35,14 @@ export type BaseModuleOptions = {
private_schema_name?: string;
/** RLS policy overrides for the module's tables. */
policies?: unknown[];
+ /**
+ * Which of the scope's storage planes this module binds to, for the modules
+ * that carry a typed bucket reference (site_surface, route, function). A scope
+ * has exactly one plane of every other kind, but may carry several storage
+ * planes, each with its own semantic `key` — so the binding is named rather
+ * than guessed. Defaults to 'default'.
+ */
+ storage_key?: string;
};
/**
@@ -77,12 +85,19 @@ export type AgentModuleOptions = BaseModuleOptions & {
has_plans?: boolean;
has_resources?: boolean;
has_agents?: boolean;
+ has_repository_resources?: boolean;
has_runs?: boolean;
resources?: unknown[];
};
/** Storage module feature flags. */
export type StorageModuleOptions = BaseModuleOptions & {
+ /**
+ * Semantic identity of this plane within its scope, and what a consuming
+ * module names in `storage_key`. Unique per (database, scope); `prefix` only
+ * names the generated tables. Defaults to 'default'.
+ */
+ key?: string;
has_versioning?: boolean;
has_content_hash?: boolean;
has_custom_keys?: boolean;
@@ -113,6 +128,17 @@ export type TrustLadderRung = {
limit?: string;
/** Credits deposited into `limit`; defaults to 0. */
limit_amount?: number;
+ /** Counting window of `event`, an interval literal ('30 days'); omitted counts for life. */
+ period_interval?: string;
+ /** How long a grant of `level` lasts before it lapses; omitted never lapses. */
+ expires_interval?: string;
+ /** Event names whose recording for an actor revokes `level` and resets their progress toward it. */
+ revoked_by?: string[];
+ /**
+ * Permission names (this scope's own catalog) withheld from principals until
+ * they hold `level`. An unknown name fails the seed rather than un-gating.
+ */
+ unlocks?: string[];
};
/** One baseline limit: a row in the tenant's default-limits table. */
@@ -141,11 +167,12 @@ export type LimitsModuleOptions = BaseModuleOptions & {
* the content catalog — `'humanity'` for evidence that an account belongs to
* someone (one reachable channel plus onboarding), `'metered'` where capacity
* is rationed (reachable → accountable → established → trusted → vouched) —
- * and an array is the caller's own ladder inline. App scope only — an entity ladder belongs to an
- * organization that does not exist at provision time.
+ * and an array of rungs is the caller's own ladder inline. An array of slugs
+ * seeds several presets into one ladder (`['humanity', 'agent']`). At entity
+ * scope the same content is seeded per entity, on the entity's own insert.
*/
export type EventsModuleOptions = BaseModuleOptions & {
- trust_ladder?: string | TrustLadderRung[];
+ trust_ladder?: string | string[] | TrustLadderRung[];
};
/** Catalog module options (table-name overrides). */
diff --git a/packages/node-type-registry/src/module-types/index.ts b/packages/node-type-registry/src/module-types/index.ts
index 2d970d1d0d..5b7d5d4cfb 100644
--- a/packages/node-type-registry/src/module-types/index.ts
+++ b/packages/node-type-registry/src/module-types/index.ts
@@ -81,6 +81,12 @@ export const allModuleTypes: ModuleTypeDefinition[] = [
display_name: 'Database Usage',
description: 'Provisions database usage logging.'
},
+ {
+ name: 'refusal_log_module',
+ display_name: 'Refusal Log',
+ description: 'Provisions the platform-only admission-control refusal ledger and its daily rollup.',
+ internal: true
+ },
{
name: 'devices_module',
display_name: 'Devices',
@@ -266,7 +272,12 @@ export const allModuleTypes: ModuleTypeDefinition[] = [
{
name: 'principal_auth_module',
display_name: 'Principal Auth',
- description: 'Provisions principal authentication state.'
+ description: 'Provisions credentials for principals: API keys, child sessions and token exchange.'
+ },
+ {
+ name: 'principals_module',
+ display_name: 'Principals',
+ description: 'Provisions principals as authorization data: scoped sub-identities, their capability masks and entity scope.'
},
{
name: 'profiles_module',
diff --git a/packages/node-type-registry/src/process/chunks.ts b/packages/node-type-registry/src/process/chunks.ts
index 12bd270a1a..e465edcb14 100644
--- a/packages/node-type-registry/src/process/chunks.ts
+++ b/packages/node-type-registry/src/process/chunks.ts
@@ -38,6 +38,15 @@ export const ProcessChunks: NodeTypeDefinition = {
description: 'Name of the text content column in the chunks table',
default: 'content'
},
+ source_fields: {
+ type: 'array',
+ items: { type: 'string', format: 'column-ref' },
+ description:
+ 'Parent columns the chunks are cut from. When set, the enqueue ' +
+ 'triggers fire only once one of them is populated (INSERT) or ' +
+ 'changed (UPDATE), and the worker chunks exactly those columns. ' +
+ 'Omit to chunk every readable content column on every write.'
+ },
// ── Chunking strategy ──────────────────────────────────────────
chunk_size: {
diff --git a/packages/node-type-registry/src/process/custom.ts b/packages/node-type-registry/src/process/custom.ts
new file mode 100644
index 0000000000..63fff8080c
--- /dev/null
+++ b/packages/node-type-registry/src/process/custom.ts
@@ -0,0 +1,105 @@
+import { conditionDefs, triggerConditionsProperty } from '../conditions';
+import type { NodeTypeDefinition } from '../types';
+
+/**
+ * Tenant-defined file processing node.
+ *
+ * The built-in Process* nodes are wired to platform tasks and platform
+ * writers. ProcessCustom wires a storage module's files table to a task the
+ * tenant registered itself (`register_function --scope database`): when a file
+ * reaches status = 'uploaded' the job is enqueued through the quota-gated
+ * function_invocations ledger, and the generated SECURITY DEFINER writer
+ * `_write_(file_id, result)` is the one way the tenant's
+ * function, over the pg-wire function lane, lands its result and moves the
+ * row uploaded → processed. The node provisions nothing else: the generator
+ * refuses when the task is not registered, when the table is not a storage
+ * files table, or when the module has no confirm-upload loop.
+ */
+export const ProcessCustom: NodeTypeDefinition = {
+ name: 'ProcessCustom',
+ slug: 'process_custom',
+ category: 'process',
+ display_name: 'Custom File Processing',
+ description:
+ 'Enqueues a tenant-registered task when a file on a storage files table reaches ' +
+ 'status = \'uploaded\' and generates the result writer ' +
+ 'the task calls back over the function lane. The task must already be registered ' +
+ 'for the database (register_function with scope database); the node is refused otherwise.',
+ parameter_schema: {
+ type: 'object',
+ $defs: conditionDefs,
+ required: ['task_identifier'],
+ properties: {
+
+ // ── Job routing ───────────────────────────────────────────────
+ task_identifier: {
+ type: 'string',
+ format: 'function-ref',
+ description:
+ 'Task identifier of the tenant-registered function (namespace:name). ' +
+ 'Must resolve through the function registry for this database at provisioning time.'
+ },
+
+ // ── Output field ──────────────────────────────────────────────
+ result_field: {
+ type: 'string',
+ format: 'column-ref',
+ description:
+ 'Optional jsonb field on the files table that receives the result the task ' +
+ 'hands to the generated writer. When omitted the writer only records the ' +
+ 'uploaded → processed transition.'
+ },
+
+ // ── MIME scoping ──────────────────────────────────────────────
+ mime_patterns: {
+ type: 'array',
+ items: { type: 'string' },
+ description:
+ 'Optional MIME type LIKE patterns to match. Multiple patterns are OR\'d together. ' +
+ 'When omitted every uploaded file is processed.'
+ },
+ trigger_conditions: triggerConditionsProperty,
+
+ // ── Entity billing scope ──────────────────────────────────────
+ entity_field: {
+ type: 'string',
+ format: 'column-ref',
+ description: 'Column on the files table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger.'
+ },
+ entity_lookup: {
+ type: 'object',
+ description: 'FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger.',
+ properties: {
+ obj_table: { type: 'string', description: 'Name of the related table to look up entity_id from' },
+ obj_schema: { type: 'string', description: 'Schema of the related table (user-facing name, optional)' },
+ obj_field: { type: 'string', format: 'column-ref', description: 'Column on the related table that holds the entity_id' }
+ },
+ required: ['obj_table', 'obj_field']
+ },
+
+ // ── Job options ───────────────────────────────────────────────
+ queue_name: {
+ type: 'string',
+ description: 'Job queue name for the task',
+ default: 'process_custom'
+ },
+ max_attempts: {
+ type: 'integer',
+ description: 'Maximum number of retry attempts',
+ default: 5
+ },
+ priority: {
+ type: 'integer',
+ description: 'Job priority (lower = higher priority)',
+ default: 0
+ }
+ }
+ },
+ tags: [
+ 'custom',
+ 'files',
+ 'processing',
+ 'jobs',
+ 'functions'
+ ]
+};
diff --git a/packages/node-type-registry/src/process/extraction.ts b/packages/node-type-registry/src/process/extraction.ts
index a8b1da54ef..9c9b73e679 100644
--- a/packages/node-type-registry/src/process/extraction.ts
+++ b/packages/node-type-registry/src/process/extraction.ts
@@ -4,10 +4,12 @@ import type { NodeTypeDefinition } from '../types';
/**
* File extraction processing node.
*
- * Composes a JobTrigger that fires when a file transitions to status = 'uploaded'.
- * The trigger enqueues a
- * text-extraction job that converts the file contents (PDF, DOCX, HTML, etc.)
- * into plain text or markdown, storing the result in configurable output fields.
+ * Composes a JobTrigger that enqueues a text-extraction job converting the file
+ * contents (PDF, DOCX, HTML, etc.) into plain text or markdown, storing the
+ * result in configurable output fields. On a storage module's files table the
+ * trigger fires when the file transitions to status = 'uploaded'; on a business
+ * table with an upload/image column it fires on the configured events (INSERT
+ * by default, plus an UPDATE that changes the file when no events are given).
*
* The extraction worker is external (Knative function) — this node only creates
* the trigger infrastructure and output fields. The worker calls back into the
@@ -20,7 +22,8 @@ export const ProcessExtraction: NodeTypeDefinition = {
display_name: 'File Extraction',
description:
'Creates extraction output fields and a job trigger for file text extraction. ' +
- 'Fires when a file is uploaded (status = \'uploaded\') or on INSERT. ' +
+ 'On a storage files table it fires when the file reaches status = \'uploaded\'; ' +
+ 'on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. ' +
'The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) ' +
'and writes the result back to the configured output fields. ' +
'Typically used upstream of ProcessFileEmbedding or ProcessChunks.',
@@ -68,6 +71,38 @@ export const ProcessExtraction: NodeTypeDefinition = {
default: ['application/pdf', 'text/%']
},
+ routes: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ mime_patterns: {
+ type: 'array',
+ items: { type: 'string' },
+ minItems: 1,
+ description: 'MIME type LIKE patterns this route takes, e.g. [\'application/vnd.openxmlformats-officedocument.%\'].'
+ },
+ task_identifier: {
+ type: 'string',
+ format: 'function-ref',
+ description: 'Job task identifier of the function that extracts these MIME types'
+ },
+ extraction_model: { type: 'string', description: 'Extraction model for this route; the node\'s when omitted' },
+ extraction_provider: { type: 'string', description: 'Extraction provider for this route; the node\'s when omitted' },
+ queue_name: { type: 'string', description: 'Job queue name for this route; the node\'s when omitted' },
+ max_attempts: { type: 'integer', description: 'Maximum retry attempts for this route; the node\'s when omitted' },
+ priority: { type: 'integer', description: 'Job priority for this route; the node\'s when omitted' }
+ },
+ required: ['mime_patterns', 'task_identifier']
+ },
+ description:
+ 'MIME types sent to another extraction function. A file runs the first route whose mime_patterns match it; ' +
+ 'the node\'s own mime_patterns and task_identifier take only the files no route matched, so one file never runs two functions. ' +
+ 'Every route writes the node\'s text_field and metadata_field, and shares its file_field, events, trigger_conditions and billing scope. ' +
+ 'A task is named once across the node and its routes (PROCESS_EXTRACTION_DUPLICATE_ROUTE_TASK). ' +
+ 'Example: [{"mime_patterns": ["application/vnd.openxmlformats-officedocument.%"], "task_identifier": "office:extract_text"}].'
+ },
+
// ── Job routing ───────────────────────────────────────────────
task_identifier: {
type: 'string',
@@ -78,7 +113,10 @@ export const ProcessExtraction: NodeTypeDefinition = {
events: {
type: 'array',
items: { type: 'string', enum: ['INSERT', 'UPDATE'] },
- description: 'Trigger events that fire the job',
+ description:
+ 'Trigger events that fire the job on a business table. Ignored on a storage ' +
+ 'files table, where the trigger is always the status transition to uploaded ' +
+ '(INSERT is rejected there: the row is still requested).',
default: ['INSERT']
},
file_field: {
@@ -89,7 +127,8 @@ export const ProcessExtraction: NodeTypeDefinition = {
'When set, the trigger reads the object key, MIME type and bucket id ' +
'out of that document (NEW. ->> \'key\', ...) instead of ' +
'requiring key/mime_type/bucket_id columns beside it, and the MIME ' +
- 'patterns match against ->> \'mime\'.'
+ 'patterns match against ->> \'mime\'. ' +
+ 'The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and text_field (created as jsonb) and metadata_field hold one entry per element, as jsonb objects keyed by the element\'s object key.'
},
payload_custom: {
type: 'object',
diff --git a/packages/node-type-registry/src/process/file-embedding.ts b/packages/node-type-registry/src/process/file-embedding.ts
index d68386bae3..49b13466d7 100644
--- a/packages/node-type-registry/src/process/file-embedding.ts
+++ b/packages/node-type-registry/src/process/file-embedding.ts
@@ -10,7 +10,10 @@ export const ProcessFileEmbedding: NodeTypeDefinition = {
'Generic, MIME-scoped embedding node for file tables. Supports two modes: ' +
'direct (whole-file to single vector, e.g. CLIP for images) when extraction ' +
'is omitted, or extract (file to text to chunks to per-chunk vectors) when ' +
- 'extraction config is provided. Composes SearchVector + JobTrigger + ' +
+ 'extraction config is provided; extract mode composes ProcessExtraction for the text ' +
+ '(its task, MIME rule, queue and, on a storage files table, its result writer). On a storage files table it fires when the file reaches status = \'uploaded\'; ' +
+ 'on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. ' +
+ 'Composes SearchVector + JobTrigger + ' +
'ProcessChunks (enabled by default in extract mode) internally. Multiple ' +
'instances can coexist on the same table with different MIME scopes, field ' +
'names, and embedding strategies.',
@@ -70,8 +73,9 @@ export const ProcessFileEmbedding: NodeTypeDefinition = {
items: { type: 'string' },
description:
'MIME type LIKE patterns to match. Multiple patterns are OR\'d together. ' +
- 'Examples: [\'image/%\'], [\'application/pdf\', \'text/%\'], [\'audio/%\'].',
- default: ['image/%']
+ 'Examples: [\'image/%\'], [\'application/pdf\', \'text/%\'], [\'audio/%\']. ' +
+ 'Defaults to [\'image/%\'] in direct mode and to [\'application/pdf\', \'text/%\'] ' +
+ 'in extract mode.'
},
// ── Job routing ────────────────────────────────────────────────
@@ -80,13 +84,16 @@ export const ProcessFileEmbedding: NodeTypeDefinition = {
format: 'function-ref',
description:
'Job task identifier for the worker. In direct mode this is the ' +
- 'embedding worker; in extract mode this is the extraction worker.',
- default: 'embedding:process_file_embedding'
+ 'embedding worker (default embedding:process_file_embedding); in extract mode ' +
+ 'this is the extraction worker (default document:extract_file_text).'
},
events: {
type: 'array',
items: { type: 'string', enum: ['INSERT', 'UPDATE'] },
- description: 'Trigger events that fire the job',
+ description:
+ 'Trigger events that fire the job on a business table. Ignored on a storage ' +
+ 'files table, where the trigger is always the status transition to uploaded ' +
+ '(INSERT is rejected there: the row is still requested).',
default: ['INSERT']
},
file_field: {
@@ -97,7 +104,8 @@ export const ProcessFileEmbedding: NodeTypeDefinition = {
'When set, the trigger reads the object key, MIME type and bucket id ' +
'out of that document (NEW. ->> \'key\', ...) instead of ' +
'requiring key/mime_type/bucket_id columns beside it, and the MIME ' +
- 'patterns match against ->> \'mime\'.'
+ 'patterns match against ->> \'mime\'. ' +
+ 'An array column (image[]/upload[]) is refused (PROCESS_FILE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element.'
},
payload_custom: {
type: 'object',
@@ -175,10 +183,11 @@ export const ProcessFileEmbedding: NodeTypeDefinition = {
extraction: {
type: 'object',
description:
- 'Text extraction configuration. When present, the generator creates ' +
- 'extraction output fields on the table and configures SearchVector with ' +
- 'source_fields + stale tracking. When absent, the node operates in direct ' +
- 'mode (single vector per file, no text extraction).',
+ 'Text extraction configuration. When present, the node composes ProcessExtraction ' +
+ '(output fields, MIME-conditional trigger on queue extraction with 5 attempts, and ' +
+ 'on a storage files table the _write_extraction writer) and configures ' +
+ 'SearchVector with the text field as source_fields + stale tracking. When absent, ' +
+ 'the node operates in direct mode (single vector per file, no text extraction).',
properties: {
text_field: {
type: 'string',
@@ -191,6 +200,20 @@ export const ProcessFileEmbedding: NodeTypeDefinition = {
format: 'column-ref',
description: 'JSONB field for extraction metadata (page count, language, etc.)',
default: 'extracted_metadata'
+ },
+ routes: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ mime_patterns: { type: 'array', items: { type: 'string' }, minItems: 1 },
+ task_identifier: { type: 'string', format: 'function-ref' }
+ },
+ required: ['mime_patterns', 'task_identifier']
+ },
+ description:
+ 'MIME types sent to another extraction function, as ProcessExtraction.routes: ' +
+ 'the first matching route takes a file, and the node\'s own mime_patterns and task take the rest.'
}
}
},
diff --git a/packages/node-type-registry/src/process/image-embedding.ts b/packages/node-type-registry/src/process/image-embedding.ts
index 1456037f86..efed6fadc0 100644
--- a/packages/node-type-registry/src/process/image-embedding.ts
+++ b/packages/node-type-registry/src/process/image-embedding.ts
@@ -6,9 +6,13 @@ import type { NodeTypeDefinition } from '../types';
*
* At the SQL layer, data_image_embedding delegates entirely to
* data_file_embedding, merging image-specific defaults before forwarding.
- * The parameter schema here is intentionally identical to ProcessFileEmbedding;
- * only the defaults differ (dimensions: 512, task: embedding:process_image_embedding,
- * mime_patterns: ['image/%']).
+ * The parameter schema is ProcessFileEmbedding's minus extraction/chunks — it
+ * is direct mode only until an OCR worker exists — and the defaults differ
+ * (dimensions: 512, mime_patterns: ['image/%']). The
+ * task is the same file-shaped record worker, embedding:process_file_embedding:
+ * the trigger payload is the file row's columns (file_id, key, mime_type,
+ * bucket_id), which embedding:process_image_embedding — the flow function that
+ * embeds an {image_url, alt_text} it is handed — does not accept.
*
* Kept as a separate node type for backward compatibility — existing
* blueprints that reference ProcessImageEmbedding continue to work unchanged.
@@ -21,8 +25,8 @@ export const ProcessImageEmbedding: NodeTypeDefinition = {
description:
'Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding ' +
'with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=[\'image/%\'], ' +
- 'task_identifier=\'embedding:process_image_embedding\', direct mode (no extraction). ' +
- 'Accepts all ProcessFileEmbedding parameters — any overrides are forwarded through.',
+ 'task_identifier=\'embedding:process_file_embedding\', direct mode only: there is no ' +
+ 'image extraction (OCR) worker, so extraction is refused. Every other parameter is forwarded through.',
parameter_schema: {
type: 'object',
$defs: conditionDefs,
@@ -86,8 +90,12 @@ export const ProcessImageEmbedding: NodeTypeDefinition = {
task_identifier: {
type: 'string',
format: 'function-ref',
- description: 'Job task identifier for the image embedding worker',
- default: 'embedding:process_image_embedding'
+ description:
+ 'Job task identifier for the image embedding worker. The payload is the file ' +
+ 'row (file_id, key, mime_type, bucket_id), so the task must be a record worker ' +
+ 'that reads the object itself — not embedding:process_image_embedding, which ' +
+ 'embeds an image_url it is handed.',
+ default: 'embedding:process_file_embedding'
},
events: {
type: 'array',
@@ -103,7 +111,8 @@ export const ProcessImageEmbedding: NodeTypeDefinition = {
'When set, the trigger reads the object key, MIME type and bucket id ' +
'out of that document (NEW. ->> \'key\', ...) instead of ' +
'requiring key/mime_type/bucket_id columns beside it, and the MIME ' +
- 'patterns match against ->> \'mime\'.'
+ 'patterns match against ->> \'mime\'. ' +
+ 'An array column (image[]/upload[]) is refused (PROCESS_IMAGE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element.'
},
payload_custom: {
type: 'object',
@@ -143,53 +152,6 @@ export const ProcessImageEmbedding: NodeTypeDefinition = {
obj_field: { type: 'string', format: 'column-ref', description: 'Column on the related table that holds the entity_id' }
},
required: ['obj_table', 'obj_field']
- },
-
- // ── Extraction config (optional — enables extract mode) ────────
- extraction: {
- type: 'object',
- description:
- 'Text extraction configuration. Forwarded to ProcessFileEmbedding. ' +
- 'When present, enables extract mode (e.g., OCR for images).',
- properties: {
- text_field: {
- type: 'string',
- format: 'column-ref',
- description: 'Field to store extracted text',
- default: 'extracted_text'
- },
- metadata_field: {
- type: 'string',
- format: 'column-ref',
- description: 'JSONB field for extraction metadata',
- default: 'extracted_metadata'
- }
- }
- },
-
- // ── Chunking config (optional — forwarded to ProcessFileEmbedding) ─
- chunks: {
- type: 'object',
- description:
- 'Chunking configuration. Forwarded to ProcessFileEmbedding. ' +
- 'Only meaningful when extraction is also provided.',
- properties: {
- content_field_name: {
- type: 'string',
- format: 'column-ref',
- default: 'content'
- },
- chunk_size: { type: 'integer', default: 1000 },
- chunk_overlap: { type: 'integer', default: 200 },
- chunk_strategy: {
- type: 'string',
- enum: ['fixed', 'sentence', 'paragraph', 'semantic'],
- default: 'paragraph'
- },
- metadata_fields: { type: 'object' },
- enqueue_chunking_job: { type: 'boolean', default: true },
- chunking_task_name: { type: 'string', format: 'function-ref', default: 'embedding:chunk_record' }
- }
}
}
},
diff --git a/packages/node-type-registry/src/process/image-versions.ts b/packages/node-type-registry/src/process/image-versions.ts
index a8707b0635..a77abbed94 100644
--- a/packages/node-type-registry/src/process/image-versions.ts
+++ b/packages/node-type-registry/src/process/image-versions.ts
@@ -4,15 +4,28 @@ import type { NodeTypeDefinition } from '../types';
/**
* Image version processing node.
*
- * Composes a JobTrigger that fires when an image file transitions to
- * status = 'uploaded'.
- * The trigger enqueues an image-processing job that generates resized,
- * cropped, or reformatted variants of the source image.
+ * Composes a JobTrigger for image variant generation. On a storage module's
+ * files table it also creates the jsonb column the variants manifest is
+ * written back to (`versions_field`, default `image_versions`); on a business
+ * table with an upload/image column the manifest is written inside that
+ * column's own document, as its `versions` member. On a storage module's files table the trigger fires when
+ * the file transitions to status = 'uploaded'; on a business table with an
+ * upload/image column it fires on the configured events (INSERT by default,
+ * plus an UPDATE that changes the file when no events are given).
*
- * The image processing worker is external (Knative function) — this node
- * only creates the trigger infrastructure. The worker generates the variants
- * and writes them back to the storage system as new file records linked to
- * the source file.
+ * The trigger enqueues `image:process_image_versions`, which `functions/image`
+ * answers: it reads the source object from the row's own bucket, renders each
+ * version, writes the variants beside the source
+ * (`.versions/-.`) and lands the manifest — an
+ * array, narrowest first, of each variant's name, object key, format,
+ * dimensions and size — on the row. `versions` is optional: without it the
+ * worker resolves the ladder when the job runs (the `IMAGE_VERSIONS` config
+ * value, else thumbnail 160x160 cover and 320 / 640 / 1280 / 1920 wide, WebP),
+ * so nothing is stamped into the trigger. A version wider or taller than the
+ * source is skipped, never upscaled. SVG sources are left alone unless
+ * `mime_patterns` is given. On a storage module's files table the generator also emits
+ * `_write_image_versions`, the SECURITY DEFINER writer that lands the
+ * manifest and moves the file `uploaded → processed`.
*/
export const ProcessImageVersions: NodeTypeDefinition = {
name: 'ProcessImageVersions',
@@ -21,14 +34,18 @@ export const ProcessImageVersions: NodeTypeDefinition = {
display_name: 'Image Versions',
description:
'Creates a job trigger for image variant generation. ' +
- 'Fires when an image file is uploaded (status = \'uploaded\') or on INSERT. ' +
- 'The external worker generates resized, cropped, or reformatted versions ' +
- '(thumbnails, previews, WebP conversions, etc.) and stores them as new ' +
- 'file records linked to the source image.',
+ 'On a storage files table it fires when the file reaches status = \'uploaded\'; ' +
+ 'on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. ' +
+ 'The image worker generates resized, cropped, or reformatted versions ' +
+ '(thumbnails, previews, WebP conversions, etc.), stores them beside the source object ' +
+ 'in the file\'s own bucket, and records each variant\'s name, key, format, dimensions and size: ' +
+ 'inside the file column\'s own document (its versions member) on a business table, ' +
+ 'in the manifest column on a storage files table. ' +
+ 'With no versions given the worker uses the default ladder (thumbnail, small, medium, large, xlarge), ' +
+ 'resolved when the job runs, and skips any version larger than the source.',
parameter_schema: {
type: 'object',
$defs: conditionDefs,
- required: ['versions'],
properties: {
// ── Version definitions ───────────────────────────────────────
@@ -72,15 +89,28 @@ export const ProcessImageVersions: NodeTypeDefinition = {
description:
'Array of version definitions. Each version specifies dimensions, ' +
'format, and quality for a generated image variant. ' +
- 'Required — the blueprint must explicitly define what variants to generate.',
+ 'Optional: when omitted the worker resolves the default ladder at job time ' +
+ '(thumbnail 160x160 cover, then small 320, medium 640, large 1280 and xlarge 1920 wide, WebP quality 80), ' +
+ 'so a later change to the default reaches tables already provisioned. ' +
+ 'A version larger than the source is skipped rather than upscaled.',
minItems: 1
},
+ // ── Output field ──────────────────────────────────────────────
+ versions_field: {
+ type: 'string',
+ format: 'column-ref',
+ description:
+ 'Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; ' +
+ 'forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document.',
+ default: 'image_versions'
+ },
+
// ── MIME scoping ──────────────────────────────────────────────
mime_patterns: {
type: 'array',
items: { type: 'string' },
- description: 'MIME type LIKE patterns to match. Defaults to all image types.',
+ description: 'MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it.',
default: ['image/%']
},
@@ -94,7 +124,10 @@ export const ProcessImageVersions: NodeTypeDefinition = {
events: {
type: 'array',
items: { type: 'string', enum: ['INSERT', 'UPDATE'] },
- description: 'Trigger events that fire the job',
+ description:
+ 'Trigger events that fire the job on a business table. Ignored on a storage ' +
+ 'files table, where the trigger is always the status transition to uploaded ' +
+ '(INSERT is rejected there: the row is still requested).',
default: ['INSERT']
},
file_field: {
@@ -105,7 +138,8 @@ export const ProcessImageVersions: NodeTypeDefinition = {
'When set, the trigger reads the object key, MIME type and bucket id ' +
'out of that document (NEW. ->> \'key\', ...) instead of ' +
'requiring key/mime_type/bucket_id columns beside it, and the MIME ' +
- 'patterns match against ->> \'mime\'.'
+ 'patterns match against ->> \'mime\'. ' +
+ 'The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and each element carries its own manifest in its versions member.'
},
payload_custom: {
type: 'object',
diff --git a/packages/node-type-registry/src/process/index.ts b/packages/node-type-registry/src/process/index.ts
index 62205f71f9..581f59a9d8 100644
--- a/packages/node-type-registry/src/process/index.ts
+++ b/packages/node-type-registry/src/process/index.ts
@@ -1,4 +1,5 @@
export { ProcessChunks } from './chunks';
+export { ProcessCustom } from './custom';
export { ProcessExtraction } from './extraction';
export { ProcessFileEmbedding } from './file-embedding';
export { ProcessImageEmbedding } from './image-embedding';
diff --git a/packages/node-type-registry/src/relation/relation-belongs-to.ts b/packages/node-type-registry/src/relation/relation-belongs-to.ts
index 5da29adaf2..ea201943f6 100644
--- a/packages/node-type-registry/src/relation/relation-belongs-to.ts
+++ b/packages/node-type-registry/src/relation/relation-belongs-to.ts
@@ -39,6 +39,14 @@ export const RelationBelongsTo: NodeTypeDefinition = {
type: 'boolean',
description: 'Whether the FK field is NOT NULL',
default: true
+ },
+ scope_fields: {
+ type: 'array',
+ items: {
+ type: 'string',
+ format: 'column-ref'
+ },
+ description: 'Columns both tables carry that the referenced row must share with the referencing row (e.g. ["entity_id"], or ["project_id"] for a stage of the same project). Adds a hidden composite FK (field_name, ...scope_fields) -> target (id, ...scope_fields) plus the target unique key it needs, so a row cannot point at another scope\'s row even when it knows the id.'
}
},
required: [
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ca606f3e9a..7b521e3a44 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2844,6 +2844,10 @@ importers:
publishDirectory: dist
packages/node-type-registry:
+ dependencies:
+ blocks-schema:
+ specifier: ^0.5.4
+ version: 0.5.5
devDependencies:
'@babel/generator':
specifier: ^7.29.0
@@ -7280,6 +7284,10 @@ packages:
bl@4.1.0:
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
+ blocks-schema@0.5.5:
+ resolution: {integrity: sha512-dvnFlKk4/ELpNgtmyh6C4XkkqaGbGHjZNo3HjzyPqXBiokikKO0zBQtBZiPsM1lqqfJ4sWE2VKMquImICbUdFg==}
+ engines: {node: '>=24.0.0'}
+
body-parser@2.2.1:
resolution: {integrity: sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==}
engines: {node: '>=18'}
@@ -9083,6 +9091,10 @@ packages:
resolution: {integrity: sha512-fi0NG4bPjCHunUJffmLd0gxssIgkNmArMvis4iNah6Owg1MCJjWhEcDLmsK6iGkJq3tHwbDkTlce70/tmXN4cQ==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ json-renderer@0.4.4:
+ resolution: {integrity: sha512-gk43N1+J0w95wERIQbkI9EE3tfRWEa4305xQYXD5AIAWTTuHc/JszSldnUJf1W9R0+Z75iweP/QcGpcjpDsSHA==}
+ engines: {node: '>=24.0.0'}
+
json-schema-to-ts@3.1.1:
resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==}
engines: {node: '>=16'}
@@ -15095,6 +15107,11 @@ snapshots:
inherits: 2.0.4
readable-stream: 3.6.2
+ blocks-schema@0.5.5:
+ dependencies:
+ json-renderer: 0.4.4
+ zod: 4.4.3
+
body-parser@2.2.1:
dependencies:
bytes: 3.1.2
@@ -17371,6 +17388,10 @@ snapshots:
json-parse-even-better-errors@3.0.2: {}
+ json-renderer@0.4.4:
+ dependencies:
+ zod: 4.4.3
+
json-schema-to-ts@3.1.1:
dependencies:
'@babel/runtime': 7.28.4
From 527c4889ca0d05048ccd77592877259907b72bc2 Mon Sep 17 00:00:00 2001
From: yyyyaaa
Date: Sat, 28 Nov 2026 20:03:15 +0700
Subject: [PATCH 02/10] fix(db-tools): check a rule's keys without asking for
the data it leaves out
The registry's BlueprintPolicy now requires data for a policy type with
required parameters. ruleShapeProblems checks the rule without its data, so
it no longer reports that data as missing: checkRule reports the missing
parameters. Two test blueprints now give the delete_action the backend
requires.
---
agentic/db-tools/__tests__/schema-checks.test.ts | 4 ++--
agentic/db-tools/src/blueprint/blueprint-schema.ts | 5 ++++-
2 files changed, 6 insertions(+), 3 deletions(-)
diff --git a/agentic/db-tools/__tests__/schema-checks.test.ts b/agentic/db-tools/__tests__/schema-checks.test.ts
index a83e82ffee..821c427d21 100644
--- a/agentic/db-tools/__tests__/schema-checks.test.ts
+++ b/agentic/db-tools/__tests__/schema-checks.test.ts
@@ -186,7 +186,7 @@ describe('no plan for a change that cannot work', () => {
it('does not resolve a schema-qualified relation endpoint to an existing table in a different schema', async () => {
const input = { name: 'todo', description: 'Todo', definition: {
tables: [{ table_name: 'notes', policies: [{ $type: 'AuthzAllowAll' }] }],
- relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'users', target_schema: 'app_private', field_name: 'parent_id' }],
+ relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'users', target_schema: 'app_private', field_name: 'parent_id', delete_action: 'c' }],
} };
await backend.close();
backend = await startFakeBackend((request) => /schemas/.test(request.query)
@@ -222,7 +222,7 @@ describe('no plan for a change that cannot work', () => {
description: 'Notes',
definition: {
tables: [{ table_name: 'notes', policies: [{ $type: 'AuthzAppMembership' }] }],
- relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'no_such_table', field_name: 'thing_id' }],
+ relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'no_such_table', field_name: 'thing_id', delete_action: 'c' }],
},
},
'not-found',
diff --git a/agentic/db-tools/src/blueprint/blueprint-schema.ts b/agentic/db-tools/src/blueprint/blueprint-schema.ts
index 9cf0ad9691..fc12fb961d 100644
--- a/agentic/db-tools/src/blueprint/blueprint-schema.ts
+++ b/agentic/db-tools/src/blueprint/blueprint-schema.ts
@@ -60,8 +60,11 @@ export function ruleShapeProblems(rule: unknown, { withCheck = false }: { withCh
if (envelope.privileges === undefined) problems.push({ path: 'privileges', code: 'privileges', message: '"privileges" is missing: give the privileges the rule covers, from select, insert, update and delete.' });
if (!withCheck && envelope.with_check !== undefined) problems.push({ path: 'with_check', code: 'not-supported', message: `"with_check" ${RULE_KEY_HINTS.with_check}` });
const validate = blueprintValidator('BlueprintPolicy');
+ // The rule's own data is left out here, and checkRule reports what it lacks.
+ const dataLeftOut = (error: { instancePath: string; keyword: string; params: Record }) =>
+ error.instancePath === '' && error.keyword === 'required' && error.params.missingProperty === 'data';
if (!validate(jsonCopy(withCheck ? envelope : unchecked))) {
- for (const error of validate.errors.filter(reported)) {
+ for (const error of validate.errors.filter((error) => reported(error) && !dataLeftOut(error))) {
const path = error.instancePath.split('/').slice(1).join('.');
if (error.keyword === 'additionalProperties') {
const key = String(error.params.additionalProperty);
From fc29870040c7f79fce02a116cf1da617889e8762 Mon Sep 17 00:00:00 2001
From: yyyyaaa
Date: Sat, 28 Nov 2026 21:09:34 +0700
Subject: [PATCH 03/10] feat(node-type-registry): a blueprint node reference
page, and --check for the pages
generate-reference now writes into the skills folder of the skills repository:
the Authz node reference, and a blueprint node reference with every other
node, where a blueprint names it, whether a table can name it as a string,
and its parameters. It reads the placement and the required keys from the
blueprint JSON Schema, so the page says what the tools check. --check lists
each page that is missing or stale and exits 1.
---
packages/node-type-registry/README.md | 2 +-
.../__tests__/reference-pages.test.ts | 69 +++++-
.../src/codegen/generate-reference.ts | 205 ++++++++++++++++--
3 files changed, 259 insertions(+), 17 deletions(-)
diff --git a/packages/node-type-registry/README.md b/packages/node-type-registry/README.md
index b4b47ab12c..3cd9cadbf7 100644
--- a/packages/node-type-registry/README.md
+++ b/packages/node-type-registry/README.md
@@ -88,7 +88,7 @@ Every `Authz*` node carries plain words, so a person or an agent can tell who a
Each Authz node's `parameter_schema` is closed (`additionalProperties: false`), so a key the backend would store and ignore is refused instead of making a policy wider than meant. Keys the backend writes when it stores a policy (the member list it resolves, a capability mask, a compiled condition) are listed with `readOnly: true`: a stored policy may hold them, and a rule a caller writes leaves them out. A value that holds an Authz expression (`AuthzComposite`'s data, its `AND`/`OR`/`NOT` parts, `AuthzColumnSecurity.authz`) is marked `format: 'authz-expression'`: one key, which is `AND` or `OR` with a list, `NOT` with one expression, or the name of an Authz node with that node's data. A raw expression cannot be written.
-`pnpm generate:reference --outdir ` writes the nodes as a Markdown reference page, `authz-node-reference.md`, with no date or version in it, so a copy that differs from a fresh render is stale. The page is made at dev time and is not part of the runtime exports.
+`pnpm generate:reference --outdir ` writes two Markdown reference pages into the skills folder of the skills repository: the Authz nodes (`constructive-security/references/authz-node-reference.md`), and every other node with where a blueprint names it (`constructive-blueprints/references/node-reference.md`). They have no date or version in them, so a copy that differs from a fresh render is stale, and `--check` lists the stale pages and exits 1. The pages are made at dev time and are not part of the runtime exports.
## Blueprint JSON Schema
diff --git a/packages/node-type-registry/__tests__/reference-pages.test.ts b/packages/node-type-registry/__tests__/reference-pages.test.ts
index 3216ee4b1e..25c521d89d 100644
--- a/packages/node-type-registry/__tests__/reference-pages.test.ts
+++ b/packages/node-type-registry/__tests__/reference-pages.test.ts
@@ -1,5 +1,10 @@
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+
import * as authz from '../src/authz';
-import { renderAuthzReferencePage } from '../src/codegen/generate-reference';
+import { referencePages, renderAuthzReferencePage, renderBlueprintNodeReferencePage, stalePages } from '../src/codegen/generate-reference';
+import { allNodeTypes, blueprintDefinitionJsonSchema } from '../src/index';
import type { NodeTypeDefinition } from '../src/types';
const authzNodes: NodeTypeDefinition[] = Object.values(authz);
@@ -51,3 +56,65 @@ describe('reference pages', () => {
expect(renderAuthzReferencePage([node])).toContain('a \\| b');
});
});
+
+describe('the blueprint node reference', () => {
+ const page = renderBlueprintNodeReferencePage();
+ const section = (name: string) => page.slice(page.indexOf(`### ${name}\n`)).split('\n### ')[0].split('\n## ')[0];
+
+ test('has every node but the Authz nodes, with its words and the parameters a blueprint gives', () => {
+ for (const node of allNodeTypes) {
+ if (node.category === 'authz') {
+ expect(page).not.toContain(`### ${node.name}\n`);
+ continue;
+ }
+ expect(section(node.name)).toContain(node.description);
+ }
+ expect(section('DataDirectOwner')).toContain('| `owner_field_name` |');
+ });
+
+ test('says where a blueprint names each node, and whether a table can name it as a string', () => {
+ expect(section('DataId')).toContain('**In a blueprint:** in `tables[].nodes[]`, as `"DataId"` or as `{ "$type": "DataId", "data": { … } }`.');
+ expect(section('JobTrigger')).toContain('**In a blueprint:** in `tables[].nodes[]`, as `{ "$type": "JobTrigger", "data": { … } }`. `data` is required.');
+ expect(section('ViewAggregated')).toContain('**In a blueprint:** no key of a blueprint takes it.');
+ });
+
+ test('places every node a blueprint can name, wherever the blueprint schema takes it', () => {
+ const named = JSON.stringify(blueprintDefinitionJsonSchema);
+ for (const node of allNodeTypes) {
+ if (node.category === 'authz' || !named.includes(`"${node.name}"`)) continue;
+ expect(section(node.name)).not.toContain('no key of a blueprint takes it');
+ }
+ expect(section('CheckOneOf')).toContain('- in `tables[].check_constraints[]`, as `{ "$type": "CheckOneOf", … }`. Required: `name` and `data`.');
+ expect(section('CheckOneOf')).toContain('in `check_constraints[]`');
+ });
+
+ test('gives a relation the keys its blueprint entry needs, and leaves out the ids the backend sets', () => {
+ const belongsTo = section('RelationBelongsTo');
+ expect(belongsTo).toContain('Required: `delete_action`.');
+ expect(belongsTo).toContain('The backend sets `source_table_id` and `target_table_id` from the two ends.');
+ expect(belongsTo).toContain('Give exactly one of `source_table`, or `source_module`.');
+ expect(belongsTo).not.toContain('| `source_table_id` |');
+ expect(section('RelationSpatial')).toContain('Required: `name`, `operator`, `source_field` and `target_field`.');
+ });
+
+ test('is the same every time, in name order whatever order the nodes come in', () => {
+ expect(renderBlueprintNodeReferencePage([...allNodeTypes].reverse())).toBe(page);
+ expect(page.split('\n')[2]).toBe('> Generated from `node-type-registry`. Do not edit this file by hand; regenerate it from the registry.');
+ });
+});
+
+describe('stalePages', () => {
+ test('lists each page that is missing or differs from a fresh render, and nothing once they match', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'reference-pages-'));
+ expect(stalePages(dir)).toEqual(referencePages().map(({ path }) => path));
+ for (const { path, text } of referencePages()) {
+ mkdirSync(dirname(join(dir, path)), { recursive: true });
+ writeFileSync(join(dir, path), text);
+ }
+ expect(stalePages(dir)).toEqual([]);
+ const [first] = referencePages();
+ writeFileSync(join(dir, first.path), readFileSync(join(dir, first.path), 'utf8').replace('Authz', 'Auth'));
+ expect(stalePages(dir)).toEqual([first.path]);
+ });
+});
+
diff --git a/packages/node-type-registry/src/codegen/generate-reference.ts b/packages/node-type-registry/src/codegen/generate-reference.ts
index 3fcb6a4c5f..a1cdb83233 100644
--- a/packages/node-type-registry/src/codegen/generate-reference.ts
+++ b/packages/node-type-registry/src/codegen/generate-reference.ts
@@ -1,14 +1,18 @@
/**
- * Write the generated Authz node reference page as Markdown, for the constructive-security skill. A copy that differs
- * from this output is stale. Dev-time only: the page is not part of the runtime exports.
+ * Write the registry's reference pages as Markdown into the skills folder of a constructive-skills checkout: the Authz
+ * node reference for the constructive-security skill, and the blueprint node reference for the constructive-blueprints
+ * skill. A copy that differs from this output is stale; --check lists the stale pages and exits 1. Dev-time only: the
+ * pages are not part of the runtime exports.
*
* Usage:
- * ts-node src/codegen/generate-reference.ts --outdir /.agents/skills/constructive-security/references
+ * ts-node src/codegen/generate-reference.ts [--check] --outdir /.agents/skills
*/
-import { mkdirSync, writeFileSync } from 'fs';
-import { join } from 'path';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
+import { dirname, join } from 'path';
import * as authz from '../authz';
+import { blueprintDefinitionJsonSchema } from '../blueprint-schema.generated';
+import { allNodeTypes } from '../index';
import type { JSONSchema, NodeTypeDefinition } from '../types';
const GENERATED = '> Generated from `node-type-registry`. Do not edit this file by hand; regenerate it from the registry.';
@@ -27,10 +31,9 @@ function typeOf(schema: JSONSchema): string {
return schema.format === 'column-ref' ? `${named} (a column${schema['x-column-scope'] === 'foreign' ? ' of the other table' : ''})` : named;
}
-function parameters(node: NodeTypeDefinition): string[] {
- const properties = Object.entries(node.parameter_schema.properties ?? {}).filter(([, schema]) => !schema.readOnly);
+function parameters(node: NodeTypeDefinition, omit: ReadonlySet = new Set(), required: ReadonlySet = new Set(node.parameter_schema.required ?? [])): string[] {
+ const properties = Object.entries(node.parameter_schema.properties ?? {}).filter(([name, schema]) => !schema.readOnly && !omit.has(name));
if (properties.length === 0) return ['No parameters.'];
- const required = new Set(node.parameter_schema.required ?? []);
return [
'| Parameter | Type | Default | Required | What it does |',
'|---|---|---|---|---|',
@@ -43,6 +46,7 @@ function parameters(node: NodeTypeDefinition): string[] {
}
const keys = (names: string[]): string => names.map(code).join(' and ');
+const listed = (names: string[]): string => (names.length < 2 ? names.map(code).join('') : `${names.slice(0, -1).map(code).join(', ')} and ${code(names[names.length - 1])}`);
// The cross-key rules of a schema that name groups of keys: exactly one of them (oneOf), or at least one (anyOf).
function keyRules(schema: JSONSchema): string[] {
@@ -98,20 +102,191 @@ export function renderAuthzReferencePage(nodes: NodeTypeDefinition[] = Object.va
]);
}
+type Json = Record;
+
+const DEFS = (blueprintDefinitionJsonSchema as Json).$defs as Record;
+
+const refName = (schema: Json | undefined): string | undefined => (typeof schema?.$ref === 'string' ? schema.$ref.split('/').pop() : undefined);
+const resolved = (schema: Json | undefined): Json | undefined => (refName(schema) ? DEFS[refName(schema) as string] : schema);
+
+/** The part of a `$type`-keyed blueprint schema for one node: what an entry of that type must give, if the schema takes it. */
+const branchOf = (schema: Json, name: string): Json | undefined =>
+ (schema.allOf as Json[] | undefined)?.find((part) => (part.then?.properties?.$type?.const ?? part.if?.properties?.$type?.const) === name)?.then;
+
+/** Each key of a blueprint, or of a table in it, that takes a list of entries, and the `$defs` entry its items follow. */
+const ENTRY_KEYS: ReadonlyArray<{ key: string; def: string }> = (
+ [['', 'BlueprintDefinition'], ['tables[].', 'BlueprintTable']] as const
+).flatMap(([prefix, def]) =>
+ Object.entries((DEFS[def].properties ?? {}) as Record).flatMap(([key, property]) => {
+ const items = refName(property?.items);
+ return items ? [{ key: `${prefix}${key}[]`, def: items }] : [];
+ })
+);
+
+/** The `$type` names an entry takes: of the entry itself and of its branches, through `$ref`, never of what it nests. */
+function entryTypes(schema: Json | undefined, seen: Set = new Set()): string[] {
+ const ref = refName(schema);
+ if (ref) return seen.has(ref) ? [] : (seen.add(ref), entryTypes(DEFS[ref], seen));
+ if (!schema) return [];
+ const own = schema.properties?.$type;
+ const parts = [...(schema.allOf ?? []), ...(schema.anyOf ?? []), ...(schema.oneOf ?? [])] as Json[];
+ return [
+ ...(own?.enum ?? []),
+ ...(own?.const !== undefined ? [own.const] : []),
+ ...parts.flatMap((part) => [...entryTypes(part, seen), ...entryTypes(part.then, seen)]),
+ ];
+}
+
+/** The keys an entry of `name` must give, beside `$type`: those of its branch, and those its schema requires of every entry. */
+function entryRequired(schema: Json | undefined, name: string, seen: Set = new Set()): string[] {
+ const ref = refName(schema);
+ if (ref) return seen.has(ref) ? [] : (seen.add(ref), entryRequired(DEFS[ref], name, seen));
+ if (!schema) return [];
+ const plain = ((schema.allOf ?? []) as Json[]).filter((part) => !part.if && !part.then);
+ const keys = [...(schema.required ?? []), ...(branchOf(schema, name)?.required ?? []), ...plain.flatMap((part) => entryRequired(part, name, seen))];
+ return [...new Set(keys as string[])].filter((key) => key !== '$type');
+}
+
+// The families in the order a person builds a table, then the entries beside tables. A new family comes last.
+const FAMILIES = ['data', 'check', 'search', 'process', 'job', 'event', 'guard', 'limit', 'relation', 'view'];
+const familyOf = (node: NodeTypeDefinition): string => node.category.split('_')[0];
+const familyRank = (family: string): number => (FAMILIES.includes(family) ? FAMILIES.indexOf(family) : FAMILIES.length);
+
+interface Placement {
+ where: string;
+ string: string;
+ lines: string[];
+ omit: Set;
+ required?: Set;
+ rules: string[];
+}
+
+// Where a blueprint names a node and what its entry must give, read from the blueprint JSON Schema, which the tools
+// check blueprints with: every key whose entries take the node's `$type`.
+function placementOf(node: NodeTypeDefinition): Placement {
+ // A table's own keys first, then the blueprint's.
+ const keys = ENTRY_KEYS.filter((entry) => entryTypes(DEFS[entry.def]).includes(node.name)).sort((a, b) => Number(!a.key.startsWith('tables[].')) - Number(!b.key.startsWith('tables[].')));
+ if (!keys.length) return { where: 'none', string: '', lines: ['**In a blueprint:** no key of a blueprint takes it.'], omit: new Set(), rules: [] };
+ const shorthand = (DEFS.BlueprintNodeShorthand.enum as string[]).includes(node.name);
+ const placement: Placement = { where: keys.map(({ key }) => code(key)).join(', '), string: '', lines: [], omit: new Set(), rules: [] };
+ for (const { key, def } of keys) {
+ const relation = def === 'BlueprintRelation' ? branchOf(DEFS.BlueprintRelation, node.name) : undefined;
+ if (def === 'BlueprintNode') {
+ const object = `\`{ "$type": "${node.name}", "data": { … } }\``;
+ placement.string = shorthand ? 'yes' : 'no';
+ placement.lines.push(`in ${code(key)}, as ${shorthand ? `\`"${node.name}"\` or as ${object}.` : `${object}. \`data\` is required.`}`);
+ } else if (relation) {
+ const required: string[] = relation.required ?? [];
+ const set = (node.parameter_schema.required ?? []).filter((name) => !required.includes(name));
+ const ends = (DEFS.BlueprintRelation.allOf as Json[]).filter((part) => !part.if);
+ placement.lines.push(
+ `in ${code(key)}, as \`{ "$type": "${node.name}", … }\` with the parameters at the top level. ` +
+ `${required.length ? `Required: ${listed(required)}.` : 'Nothing is required beyond the two ends.'}` +
+ `${set.length ? ` The backend sets ${listed(set)} from the two ends.` : ''}`
+ );
+ set.forEach((name) => placement.omit.add(name));
+ placement.required = new Set(required);
+ placement.rules.push(...keyRules({ allOf: ends }));
+ } else {
+ const required = entryRequired(resolved({ $ref: `#/$defs/${def}` }), node.name);
+ placement.lines.push(`in ${code(key)}, as \`{ "$type": "${node.name}", … }\`.${required.length ? ` Required: ${listed(required)}.` : ''}`);
+ }
+ }
+ const [only, ...more] = placement.lines;
+ placement.lines = more.length ? ['**In a blueprint:**', '', ...placement.lines.map((line) => `- ${line}`)] : [`**In a blueprint:** ${only}`];
+ return placement;
+}
+
+function blueprintNodeSection(node: NodeTypeDefinition): string[] {
+ const placement = placementOf(node);
+ return [
+ `### ${node.name}`,
+ '',
+ node.description,
+ '',
+ ...placement.lines,
+ '',
+ '**Parameters**',
+ '',
+ ...parameters(node, placement.omit, placement.required),
+ '',
+ ...list('Rules', [...placement.rules, ...keyRules(node.parameter_schema)])
+ ];
+}
+
+/**
+ * Every node that is not an Authz node as a Markdown reference page, by family and in name order: where a blueprint
+ * names it, whether a table can name it as a string, and its parameters. Pure: the same nodes give the same page.
+ */
+export function renderBlueprintNodeReferencePage(nodes: NodeTypeDefinition[] = allNodeTypes): string {
+ const sorted = nodes
+ .filter((node) => node.category !== 'authz')
+ .sort((a, b) => familyRank(familyOf(a)) - familyRank(familyOf(b)) || familyOf(a).localeCompare(familyOf(b)) || a.name.localeCompare(b.name));
+ const families = [...new Set(sorted.map(familyOf))];
+ const heading = (family: string) => `${family[0].toUpperCase()}${family.slice(1)} nodes`;
+ return page([
+ '# Blueprint node reference',
+ '',
+ GENERATED,
+ '',
+ 'Every node of the registry except the Authz nodes, by family and in name order: where a blueprint names it, and its ' +
+ 'parameters. A table names a node in `nodes` as a string only when the node needs no data; otherwise it gives the ' +
+ 'object with `data`. The Authz nodes are in the Authz node reference of the constructive-security skill.',
+ '',
+ '| Node | In a blueprint | As a string |',
+ '|---|---|---|',
+ ...sorted.map((node) => {
+ const placement = placementOf(node);
+ return `| [${code(node.name)}](#${anchor(node.name)}) | ${placement.where} | ${placement.string} |`;
+ }),
+ '',
+ ...families.flatMap((family) => [`## ${heading(family)}`, '', ...sorted.filter((node) => familyOf(node) === family).flatMap(blueprintNodeSection)])
+ ]);
+}
+
+/** Each reference page this package renders, under its path in the skills folder of constructive-skills. */
+export function referencePages(): Array<{ path: string; text: string }> {
+ return [
+ { path: 'constructive-security/references/authz-node-reference.md', text: renderAuthzReferencePage() },
+ { path: 'constructive-blueprints/references/node-reference.md', text: renderBlueprintNodeReferencePage() }
+ ];
+}
+
+/** The pages under `skillsDir` that are missing or differ from a fresh render. */
+export function stalePages(skillsDir: string): string[] {
+ return referencePages()
+ .filter(({ path, text }) => !existsSync(join(skillsDir, path)) || readFileSync(join(skillsDir, path), 'utf8') !== text)
+ .map(({ path }) => path);
+}
+
function main(): void {
const argv = process.argv.slice(2);
const i = argv.indexOf('--outdir');
if (i === -1 || !argv[i + 1]) {
throw new Error(
- 'generate-reference: no output folder was given. Pass --outdir , for example the references folder of the constructive-security skill.'
+ 'generate-reference: no output folder was given. Pass --outdir : the .agents/skills folder of a constructive-skills checkout.'
);
}
- const outdir = argv[i + 1];
- mkdirSync(outdir, { recursive: true });
- const file = join(outdir, 'authz-node-reference.md');
- writeFileSync(file, renderAuthzReferencePage());
- // eslint-disable-next-line no-console
- console.log(`[node-type-registry] wrote ${file}`);
+ const skillsDir = argv[i + 1];
+ if (argv.includes('--check')) {
+ const stale = stalePages(skillsDir);
+ // eslint-disable-next-line no-console
+ for (const path of stale) console.log(`stale ${path}`);
+ if (stale.length) {
+ // eslint-disable-next-line no-console
+ console.error(`\n${stale.length} reference page(s) differ from the registry. Run this again without --check, and commit the pages.`);
+ process.exit(1);
+ }
+ // eslint-disable-next-line no-console
+ console.log('[node-type-registry] the reference pages match the registry.');
+ return;
+ }
+ for (const { path, text } of referencePages()) {
+ mkdirSync(dirname(join(skillsDir, path)), { recursive: true });
+ writeFileSync(join(skillsDir, path), text);
+ // eslint-disable-next-line no-console
+ console.log(`[node-type-registry] wrote ${join(skillsDir, path)}`);
+ }
}
if (require.main === module) main();
From 21f2f57bf7cac609fe74bcf4d878500b065c9ed2 Mon Sep 17 00:00:00 2001
From: yyyyaaa
Date: Thu, 26 Nov 2026 21:14:15 +0700
Subject: [PATCH 04/10] feat(agentic)!: the agent kit: the shared session, the
MCP server and the typed command layer
@agentic-kit/session and the agent CLI:
@agentic-kit/session is a new package with the sign-in that every
Constructive binary shares:
- Backend contexts with all five planes (api, auth, modules, agent and
compute), from the endpoints or from the CONSTRUCTIVE_* overrides. Only
the endpoint check makes a backend: https, or plain http on this machine
only, with no user name or password. A stored context is checked when it
is read, so one with a bad endpoint is invalid-backend and nothing is
sent to it. A request that carries a password or a key never follows a
redirect.
- resolveSession answers who talks to which backend in one of eight
states, and pairs a credential only with the backend it was issued for.
- Every operation that changes the backend and the store runs as steps
with one commit point: a failure before it undoes the steps done so far,
last first, and nothing after it can fail the operation.
- signIn and signOut with email and password. A sign-in checks the store
before it sends anything, mints a 30-day API key and stores the session
with the backend it was issued for, or changes nothing; it revokes the
key of the session it replaces only after that. signOut clears the
session, then revokes its key. signInTarget is where a sign-in goes, the
same for every binary. verifySession asks the backend whether it still
accepts the credential, and keyEndsSoon says when to sign in again.
- Agents: createAgent, listAgents, renewAgentKey and removeAgent manage a
principal of the person with its own key, whose lifetime is capped on
the principal at 30 days. The package uses the key only to mint short
access tokens, which it caches in a 0600 file and reuses until they
end. The backend also accepts the key itself, so whoever holds it can
act as the agent until it ends, is renewed or the agent is removed; it
stays in a 0600 file. An agent cannot change the schema unless it is
allowed to (grantSchemaChanges, revokeSchemaChanges); a change whose
record cannot be stored is set back on the backend. A context with
agents keeps its endpoints. The token cache only saves a mint: a token
is used only for the key that minted it, so the cache never fails an
operation.
- sessionToolsHost, the db-tools host on top of the resolved session.
- The store lives under ~/.constructive/, and CONSTRUCTIVE_STASH_DIR
replaces ~. Context and agent names are checked; an active context name
another tool stored reads as no backend chosen.
The agent CLI (@agentic-kit/cli) signs in and out through it and loses
its own account, backend, API key and credential code. agent login picks
its backend with signInTarget, so it signs in to the backend the
CONSTRUCTIVE_* variables name, with all of its planes. whoami also asks
the backend whether it accepts the credential. The README names the
access tools it registers.
CI runs the session tests in the agentic batch.
@agentic-kit/mcp:
@agentic-kit/mcp is a new package. serveStdio and createMcpServerFactory
serve HarnessTools on @modelcontextprotocol/server 2.x. A tool's name,
title, description, parameters, effect, failures and follow-up calls come
from the tool object; the plan and the gate's decision come from the
harness.
- readOnly: true serves the tools whose effect is read; readOnly: false
adds the tools whose effect is write. A destructive tool is not served
in either mode.
- A write tool is annotated readOnlyHint: false, destructiveHint: true and
idempotentHint: false, with _meta "anthropic/requiresUserInteraction":
true, so a host that honors it asks the person before each call.
- A write call gets its plan from the gate. When the gate blocks it, the
failure comes back and nothing changes. When it runs, the result carries
the plan. A client with form elicitation is shown the plan once as an
optional preview: the host's prompt is the approval, so the "Apply this
change" box starts ticked and accepting the form applies the change. A
decline, a closed question or an unticked box changes nothing.
- structuredContent is an envelope: { ok: true, data, plan?, calls? }, or
{ ok: false, error, data?, plan?, calls? } with isError.
- A tool that throws returns a fixed sentence that names the tool, with
the logged error's id when there is one, and never the error's text.
- The server sends instructions on connect: the read tools to call first,
the tools that change things, and that the host asks before each of
them. The host's own instructions follow.
CI runs the MCP tests in the agentic batch.
@agentic-kit/command:
@agentic-kit/command is a new package: the command layer of the
Constructive CLI, and the binding of a HarnessTool to a command.
- A command's input is a zod object. The layer parses it once; help,
--schema, --llms and --llms --json print JSON Schema made from
it. Each property is a flag; values are coerced by their JSON Schema
type; --input takes the whole input as JSON, @path or stdin. One null
rule: null for an optional key that does not take null reads as not
given.
- Five kinds of command: a read, a change ({ plan, apply }), a change
that runs at once (a write marked immediate), a server, and a
passthrough. A change is planned, and the layer itself decides its
approval: --dry-run returns the plan, --yes approves, a terminal asks,
and any other run exits 3. createCli refuses a change that defines run
without immediate, so no change skips its approval. A plan can name
the flags its apply needs without a terminal (Planned.needs, such as
--password-stdin), and the --yes step after --dry-run or exit 3 carries
them when the run has no terminal.
- One output contract: text with a Next: block on a terminal, otherwise
one JSON envelope. Exit codes: 0 done, 1 failed, 2 usage, 3 approval
required, 4 sign in first, 130 interrupted.
- Help topics are data: createCli takes topics, a built-in help command
prints the CLI's help, a command's or group's help, or a topic, and a
word it does not know is a usage error that names the nearest one.
The --llms index and manifest carry the topics, and renderReference
turns the manifest into one Markdown reference (the source of the
CLI's man page).
- toolCommand and toCliCommands bind tools: the tool's params are the
input, its effect is the command's effect, a change plans through the
gate policy (callChange), a tool failure becomes a CliError with the same
code, and the tool's suggested calls become the first next steps.
toolCallStep writes a call the same way for another host.
inquirerer stays the prompt library and parseArgv.
CI runs the command tests in the agentic batch.
BREAKING CHANGE: agent login stores a 30-day API key, in place of a
5-year key that the CLI renewed by itself; when it ends, run agent login
again. A session stored by an earlier version records no backend, so it
is not used; run agent login again. Plain http to an endpoint on another
machine is refused; use its https URL. CONSTRUCTIVE_STASH_DIR replaces
AGENT_HOME. @agentic-kit/cli no longer exports HOST_ENV_VARS.
---
.github/workflows/run-tests.yaml | 2 +-
agentic/cli/README.md | 21 +-
agentic/cli/__tests__/api-key.test.ts | 135 --
agentic/cli/__tests__/auth.test.ts | 227 ---
agentic/cli/__tests__/commands.test.ts | 187 +-
agentic/cli/__tests__/db-tools.test.ts | 176 +-
agentic/cli/__tests__/stores.test.ts | 125 --
agentic/cli/jest.config.js | 1 +
agentic/cli/jest.setup.js | 11 +
agentic/cli/package.json | 3 +-
agentic/cli/src/account-store.ts | 70 -
agentic/cli/src/api-key.ts | 133 --
agentic/cli/src/auth-error.ts | 107 --
agentic/cli/src/auth.ts | 178 --
agentic/cli/src/backend-store.ts | 78 -
agentic/cli/src/commands.ts | 113 +-
agentic/cli/src/config.ts | 16 +-
agentic/cli/src/credentials.ts | 58 -
agentic/cli/src/db-tools.ts | 34 +-
agentic/cli/src/index.ts | 27 +-
agentic/command/README.md | 69 +
agentic/command/__tests__/approval.test.ts | 21 +
.../command/__tests__/command-process.test.ts | 144 ++
agentic/command/__tests__/command.test.ts | 1625 +++++++++++++++++
.../command/__tests__/tool-command.test.ts | 522 ++++++
agentic/command/jest.config.js | 21 +
agentic/command/package.json | 42 +
agentic/command/src/approval.ts | 65 +
agentic/command/src/cli.ts | 785 ++++++++
agentic/command/src/help.ts | 334 ++++
agentic/command/src/index.ts | 47 +
agentic/command/src/input.ts | 1106 +++++++++++
agentic/command/src/tool-command.ts | 322 ++++
agentic/command/src/types.ts | 337 ++++
agentic/command/test-utils/command-fixture.ts | 73 +
agentic/command/tsconfig.esm.json | 8 +
agentic/command/tsconfig.json | 8 +
agentic/mcp/README.md | 63 +
.../mcp/__tests__/fixtures/stdio-server.ts | 33 +
agentic/mcp/__tests__/server.test.ts | 390 ++++
agentic/mcp/__tests__/stdio.test.ts | 62 +
agentic/mcp/jest.config.js | 21 +
agentic/mcp/package.json | 44 +
agentic/mcp/src/index.ts | 1 +
agentic/mcp/src/server.ts | 297 +++
agentic/mcp/tsconfig.esm.json | 8 +
agentic/mcp/tsconfig.json | 8 +
agentic/session/README.md | 131 ++
agentic/session/__tests__/agent-child.ts | 12 +
agentic/session/__tests__/agent.test.ts | 774 ++++++++
agentic/session/__tests__/api-key.test.ts | 45 +
agentic/session/__tests__/auth.test.ts | 454 +++++
agentic/session/__tests__/fake-principals.ts | 252 +++
agentic/session/__tests__/session.test.ts | 532 ++++++
agentic/session/__tests__/stores.test.ts | 212 +++
agentic/session/jest.config.js | 22 +
agentic/session/jest.setup.js | 11 +
agentic/session/package.json | 43 +
agentic/session/src/account-store.ts | 177 ++
agentic/session/src/agent-store.ts | 239 +++
agentic/session/src/agent.ts | 627 +++++++
agentic/session/src/api-key.ts | 87 +
agentic/session/src/auth-error.ts | 173 ++
agentic/session/src/auth.ts | 391 ++++
agentic/session/src/backend-store.ts | 304 +++
agentic/session/src/env.ts | 13 +
agentic/session/src/index.ts | 66 +
agentic/session/src/operation.ts | 112 ++
agentic/session/src/session.ts | 403 ++++
agentic/session/src/tools-host.ts | 69 +
agentic/session/tsconfig.esm.json | 8 +
agentic/session/tsconfig.json | 8 +
pnpm-lock.yaml | 109 +-
73 files changed, 12049 insertions(+), 1383 deletions(-)
delete mode 100644 agentic/cli/__tests__/api-key.test.ts
delete mode 100644 agentic/cli/__tests__/auth.test.ts
delete mode 100644 agentic/cli/__tests__/stores.test.ts
create mode 100644 agentic/cli/jest.setup.js
delete mode 100644 agentic/cli/src/account-store.ts
delete mode 100644 agentic/cli/src/api-key.ts
delete mode 100644 agentic/cli/src/auth-error.ts
delete mode 100644 agentic/cli/src/auth.ts
delete mode 100644 agentic/cli/src/backend-store.ts
delete mode 100644 agentic/cli/src/credentials.ts
create mode 100644 agentic/command/README.md
create mode 100644 agentic/command/__tests__/approval.test.ts
create mode 100644 agentic/command/__tests__/command-process.test.ts
create mode 100644 agentic/command/__tests__/command.test.ts
create mode 100644 agentic/command/__tests__/tool-command.test.ts
create mode 100644 agentic/command/jest.config.js
create mode 100644 agentic/command/package.json
create mode 100644 agentic/command/src/approval.ts
create mode 100644 agentic/command/src/cli.ts
create mode 100644 agentic/command/src/help.ts
create mode 100644 agentic/command/src/index.ts
create mode 100644 agentic/command/src/input.ts
create mode 100644 agentic/command/src/tool-command.ts
create mode 100644 agentic/command/src/types.ts
create mode 100644 agentic/command/test-utils/command-fixture.ts
create mode 100644 agentic/command/tsconfig.esm.json
create mode 100644 agentic/command/tsconfig.json
create mode 100644 agentic/mcp/README.md
create mode 100644 agentic/mcp/__tests__/fixtures/stdio-server.ts
create mode 100644 agentic/mcp/__tests__/server.test.ts
create mode 100644 agentic/mcp/__tests__/stdio.test.ts
create mode 100644 agentic/mcp/jest.config.js
create mode 100644 agentic/mcp/package.json
create mode 100644 agentic/mcp/src/index.ts
create mode 100644 agentic/mcp/src/server.ts
create mode 100644 agentic/mcp/tsconfig.esm.json
create mode 100644 agentic/mcp/tsconfig.json
create mode 100644 agentic/session/README.md
create mode 100644 agentic/session/__tests__/agent-child.ts
create mode 100644 agentic/session/__tests__/agent.test.ts
create mode 100644 agentic/session/__tests__/api-key.test.ts
create mode 100644 agentic/session/__tests__/auth.test.ts
create mode 100644 agentic/session/__tests__/fake-principals.ts
create mode 100644 agentic/session/__tests__/session.test.ts
create mode 100644 agentic/session/__tests__/stores.test.ts
create mode 100644 agentic/session/jest.config.js
create mode 100644 agentic/session/jest.setup.js
create mode 100644 agentic/session/package.json
create mode 100644 agentic/session/src/account-store.ts
create mode 100644 agentic/session/src/agent-store.ts
create mode 100644 agentic/session/src/agent.ts
create mode 100644 agentic/session/src/api-key.ts
create mode 100644 agentic/session/src/auth-error.ts
create mode 100644 agentic/session/src/auth.ts
create mode 100644 agentic/session/src/backend-store.ts
create mode 100644 agentic/session/src/env.ts
create mode 100644 agentic/session/src/index.ts
create mode 100644 agentic/session/src/operation.ts
create mode 100644 agentic/session/src/session.ts
create mode 100644 agentic/session/src/tools-host.ts
create mode 100644 agentic/session/tsconfig.esm.json
create mode 100644 agentic/session/tsconfig.json
diff --git a/.github/workflows/run-tests.yaml b/.github/workflows/run-tests.yaml
index 28d3601676..121c46f1fc 100644
--- a/.github/workflows/run-tests.yaml
+++ b/.github/workflows/run-tests.yaml
@@ -118,7 +118,7 @@ jobs:
- batch: graphile-unit
packages: 'graphile/graphile-plugin-utils graphile/graphile-realtime-subscriptions graphile/graphile-sql-expression-validator graphile/graphile-storage-registry'
- batch: agentic
- packages: 'agentic/protocol agentic/agentic-kit agentic/agent agentic/harness agentic/permissions agentic/chat agentic/cli agentic/db-tools agentic/pi agentic/dsh agentic/react agentic/agentic-server agentic/anthropic agentic/openai agentic/ollama agentic/run-log agentic/metering agentic/agent-conversation agentic/pi-host agentic/run-log-client agentic/run-log-gate agentic/machine-protocol agentic/machine-runner agentic/agent-cli'
+ packages: 'agentic/protocol agentic/agentic-kit agentic/agent agentic/harness agentic/permissions agentic/chat agentic/cli agentic/db-tools agentic/pi agentic/dsh agentic/react agentic/agentic-server agentic/anthropic agentic/openai agentic/ollama agentic/run-log agentic/metering agentic/agent-conversation agentic/pi-host agentic/run-log-client agentic/run-log-gate agentic/machine-protocol agentic/machine-runner agentic/agent-cli agentic/command agentic/mcp agentic/session'
- batch: pgpm-unit
packages: 'pgpm/types pgpm/naming-spec pgpm/diff pgpm/import pgpm/slice pgpm/transform'
- batch: pglite
diff --git a/agentic/cli/README.md b/agentic/cli/README.md
index f55376e50e..25babb53cc 100644
--- a/agentic/cli/README.md
+++ b/agentic/cli/README.md
@@ -26,7 +26,7 @@ On startup, `agent` assembles the harness skill tree and drops you into an inter
1. **Base layer** — [`constructive-io/constructive-skills`](https://github.com/constructive-io/constructive-skills), fetched as a git tag/branch/SHA tarball into `~/.constructive/data/skills//` (default ref: `main`; offline fallback: newest cached release).
2. **Local overlay** — `~/.constructive/config/skills-overlay//SKILL.md` (agentskills.io layout), highest precedence: a same-name skill replaces the base skill wholesale.
-3. **Typed db tools** — the [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) extension (including `provision_database`, `provision_blueprint`, `describe_schema`, and `run_codegen`) is materialized into the agent dir and loaded by pi automatically. The CLI does not register `add_records`, `update_records`, `delete_records` or `create_api_key`; it has no tenant sign-in or secret-delivery integration for those tools.
+3. **Typed db tools** — the [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) extension (including `provision_database`, `provision_blueprint`, `describe_schema`, `run_codegen`, and the access tools `describe_policy_type`, `explain_access` and `set_access`) is materialized into the agent dir and loaded by pi automatically. The CLI does not register `add_records`, `update_records`, `delete_records` or `create_api_key`; it has no tenant sign-in or secret-delivery integration for those tools.
The merged tree is materialized into the appstash-owned agent dir, so the session picks the skills up natively. All harness state lives in the [appstash](https://github.com/constructive-io/appstash) `~/.constructive/` layout; project directories are untouched.
@@ -35,16 +35,16 @@ The merged tree is materialized into the appstash-owned agent dir, so the sessio
| Command | Description |
|---------|-------------|
| `agent [options...]` | Start an interactive session with the harness skills |
-| `agent -p "prompt"` | One-shot print mode; gated tools are refused |
+| `agent -p "prompt"` | One-shot print mode; every database tool that changes something is refused, and pi's own tools still run |
| `agent init` | Configure the skills source (repo + pin) interactively |
| `agent login` | Sign in to the Constructive platform (interactive) |
-| `agent logout` | Revoke the API key and clear the stored session |
-| `agent whoami` | Show the signed-in account, backend, and masked API key |
+| `agent logout` | Revoke the API key at the backend that issued it and clear the stored session; a session from the environment is not stored, so there is nothing to remove |
+| `agent whoami` | Show the signed-in account, backend, and masked API key, and ask the backend whether it still accepts the credential |
| `agent skills list` | Resolve and list the effective skill set per layer |
| `agent skills update` | Re-fetch the base release and re-materialize |
| `agent help` | Usage |
-Print mode has no confirmation UI, so it refuses gated database changes and `run_codegen`. Setting a credential does not bypass confirmation. Use the interactive TUI or `agent --mode rpc` with a client that handles pi's approval requests for gated operations. Ungated tools, such as `describe_schema`, can still run in print mode.
+Print mode has no confirmation UI, so it refuses every database tool whose effect is a write or a destructive change, `run_codegen` included. Setting a credential does not bypass confirmation. Use the interactive TUI or `agent --mode rpc` with a client that handles pi's approval requests for gated operations. Database tools that only read, such as `describe_schema`, still run in print mode, and so do pi's own tools (`bash`, `edit`, `write`): the gate covers the database tools only.
## Configuration
@@ -63,22 +63,21 @@ Print mode has no confirmation UI, so it refuses gated database changes and `run
}
```
-Env overrides: `AGENT_SKILLS_REPO`, `AGENT_SKILLS_PIN`, `AGENT_HOME` (appstash base dir), `GITHUB_TOKEN` (private skills repos).
+Env overrides: `AGENT_SKILLS_REPO`, `AGENT_SKILLS_PIN`, `CONSTRUCTIVE_STASH_DIR` (base directory that replaces `~` for `~/.constructive/`, shared with the session store and Constructive Desktop), `GITHUB_TOKEN` (private skills repos).
## Authentication
-`agent login` signs in to the Constructive platform with email and password. The CLI ships no backend URLs: the flow asks for the backend's API GraphQL endpoint (e.g. `https://api.example.com/graphql`, defaulting to the last one used or `CONSTRUCTIVE_API_ENDPOINT`) and derives the auth, modules, agent and compute endpoints from its host. With no backend chosen the db tools fail and say so; they never fall back to a default host. After sign-in, the CLI mints a 5-year API key for the db tools and checks it on each startup. `agent logout` revokes the key and deletes the session.
+`agent login` signs in to the Constructive platform with email and password, through [`@agentic-kit/session`](https://www.npmjs.com/package/@agentic-kit/session), the sign-in every Constructive binary shares. The CLI ships no backend URLs: the flow asks for the backend's API GraphQL endpoint (e.g. `https://api.example.com/graphql`), defaulting to the backend the session resolves to: the one `CONSTRUCTIVE_*` names, else the current context. Given that backend's own api endpoint, it signs in with all of that backend's planes, as `constructive login` does; any other endpoint is a new backend whose auth, modules, agent and compute endpoints are derived from its host. With no backend chosen the db tools fail and say so; they never fall back to a default host. After sign-in, the CLI asks for a 30-day API key for the db tools, then ends the password sign-in on the backend, so the key is the only credential it keeps. If no key can be made, the sign-in fails and nothing is stored; at the account's key limit, run `agent logout` first, which revokes this computer's key, or revoke a key in the app. When the key is within 7 days of its end, each startup asks you to run `agent login` again, which signs you in and mints a new key; nothing renews it on its own. `agent logout` deletes the session and revokes its key, and says so when the revoke fails.
-Shared appstash files:
+Shared appstash files (with `CONSTRUCTIVE_STASH_DIR` set, each `~/.constructive/` below is `$CONSTRUCTIVE_STASH_DIR/.constructive/`):
-- `~/.constructive/config/credentials.json` — the signed-in session (user, access token, API key; mode `0600`, plaintext)
+- `~/.constructive/config/credentials.json` — the signed-in session (user and API key; mode `0600`, plaintext)
- `~/.constructive/config/contexts/.json` — endpoints for each backend context
- `~/.constructive/config/settings.json` — shared settings, including the active context
The db tools read these files on each tool call, so a login mid-session is picked up without a restart. The CLI does not export stored credentials to child processes.
-Env overrides for CI and headless use (these win over the stored session; read per tool call):
-`CONSTRUCTIVE_USER_ID`, `CONSTRUCTIVE_ACCESS_TOKEN`, `CONSTRUCTIVE_API_KEY` (optional), `CONSTRUCTIVE_API_ENDPOINT` (picks the backend; the other planes derive from it), and `CONSTRUCTIVE_MODULES_ENDPOINT`, `CONSTRUCTIVE_AGENT_ENDPOINT`, `CONSTRUCTIVE_COMPUTE_ENDPOINT` to override one plane (only together with `CONSTRUCTIVE_API_ENDPOINT`).
+Env overrides for CI and headless use (read per tool call): `CONSTRUCTIVE_USER_ID`, `CONSTRUCTIVE_ACCESS_TOKEN` and `CONSTRUCTIVE_API_KEY` (optional) give the credential, and need `CONSTRUCTIVE_API_ENDPOINT` to name its backend. `CONSTRUCTIVE_API_ENDPOINT` alone picks a backend; the stored session is used with it only when it names the backend of the active context. `CONSTRUCTIVE_AUTH_ENDPOINT`, `CONSTRUCTIVE_MODULES_ENDPOINT`, `CONSTRUCTIVE_AGENT_ENDPOINT` and `CONSTRUCTIVE_COMPUTE_ENDPOINT` give one plane each (only together with `CONSTRUCTIVE_API_ENDPOINT`); the planes are derived only from an api host that starts with `api.`. An incomplete or wrong set is reported at startup, and every db tool call fails with that cause (for example `no-backend` naming `CONSTRUCTIVE_API_ENDPOINT`) in place of a sign-in prompt. See [`@agentic-kit/session`](https://www.npmjs.com/package/@agentic-kit/session) for the rules.
## Roadmap
diff --git a/agentic/cli/__tests__/api-key.test.ts b/agentic/cli/__tests__/api-key.test.ts
deleted file mode 100644
index 5176387b9f..0000000000
--- a/agentic/cli/__tests__/api-key.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import {
- API_KEY_NAME,
- buildCreateApiKeyInput,
- classifyApiKeyError,
- MintedApiKey,
- needsRemint,
- parseMintedKey,
- REMINT_THRESHOLD_MS,
- remintApiKey
-} from '../src/api-key';
-
-describe('buildCreateApiKeyInput', () => {
- it('names the key agentic-cli with full access and no MFA', () => {
- expect(buildCreateApiKeyInput({ years: 5 })).toEqual({
- keyName: API_KEY_NAME,
- accessLevel: 'full_access',
- mfaLevel: 'none',
- expiresIn: { years: 5 }
- });
- expect(API_KEY_NAME).toBe('agentic-cli');
- });
-});
-
-describe('parseMintedKey', () => {
- it('returns the minted key and maps expiresAt', () => {
- expect(parseMintedKey({ apiKey: 'k', keyId: 'id', expiresAt: '2031-01-01' })).toEqual({
- apiKey: 'k',
- keyId: 'id',
- apiKeyExpiresAt: '2031-01-01'
- });
- expect(parseMintedKey({ apiKey: 'k', keyId: 'id' })).toEqual({ apiKey: 'k', keyId: 'id' });
- });
-
- it('throws when the backend returns no secret', () => {
- expect(() => parseMintedKey(undefined)).toThrow('createApiKey returned no API key.');
- expect(() => parseMintedKey({ keyId: 'id' })).toThrow('createApiKey returned no API key.');
- });
-});
-
-describe('classifyApiKeyError', () => {
- it('maps extension codes', () => {
- const err = { errors: [{ extensions: { code: 'STEP_UP_REQUIRED' } }] };
- expect(classifyApiKeyError(err)).toBe('step-up-required');
- });
-
- it('falls back to message text and then unknown', () => {
- expect(classifyApiKeyError(new Error('boom: API_KEY_LIMIT_REACHED'))).toBe('limit-reached');
- expect(classifyApiKeyError(new Error('NOT_AUTHENTICATED'))).toBe('not-authenticated');
- expect(classifyApiKeyError(new Error('nope'))).toBe('unknown');
- expect(classifyApiKeyError(undefined)).toBe('unknown');
- });
-});
-
-describe('needsRemint', () => {
- const now = Date.parse('2026-08-03T00:00:00Z');
-
- it('is false without an expiry or with an unparsable one', () => {
- expect(needsRemint({ apiKeyExpiresAt: undefined, now })).toBe(false);
- expect(needsRemint({ apiKeyExpiresAt: 'garbage', now })).toBe(false);
- });
-
- it('is true at or inside the 7-day threshold, false outside', () => {
- const at = (deltaMs: number) => new Date(now + deltaMs).toISOString();
- expect(needsRemint({ apiKeyExpiresAt: at(REMINT_THRESHOLD_MS), now })).toBe(true);
- expect(needsRemint({ apiKeyExpiresAt: at(REMINT_THRESHOLD_MS + 1000), now })).toBe(false);
- expect(needsRemint({ apiKeyExpiresAt: at(-1000), now })).toBe(true);
- });
-});
-
-describe('remintApiKey', () => {
- const minted: MintedApiKey = { apiKey: 'new', keyId: 'new-id' };
-
- it('mints first, then revokes the old key', async () => {
- const calls: string[] = [];
- const result = await remintApiKey({
- currentKeyId: 'old-id',
- revoke: async keyId => {
- calls.push(`revoke:${keyId}`);
- },
- mint: async () => {
- calls.push('mint');
- return minted;
- }
- });
- expect(result).toEqual(minted);
- expect(calls).toEqual(['mint', 'revoke:old-id']);
- });
-
- it('on limit-reached, revokes first and retries the mint once', async () => {
- const calls: string[] = [];
- let attempts = 0;
- const result = await remintApiKey({
- currentKeyId: 'old-id',
- revoke: async keyId => {
- calls.push(`revoke:${keyId}`);
- },
- mint: async () => {
- calls.push('mint');
- attempts += 1;
- if (attempts === 1) throw { errors: [{ extensions: { code: 'API_KEY_LIMIT_REACHED' } }] };
- return minted;
- }
- });
- expect(result).toEqual(minted);
- expect(calls).toEqual(['mint', 'revoke:old-id', 'mint']);
- });
-
- it('rethrows non-limit errors without revoking', async () => {
- const revoke = jest.fn();
- await expect(
- remintApiKey({
- currentKeyId: 'old-id',
- revoke,
- mint: async () => {
- throw { errors: [{ extensions: { code: 'STEP_UP_REQUIRED' } }] };
- }
- })
- ).rejects.toBeDefined();
- expect(revoke).not.toHaveBeenCalled();
- });
-
- it('tolerates a failing revoke', async () => {
- const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
- const result = await remintApiKey({
- currentKeyId: 'old-id',
- revoke: async () => {
- throw new Error('offline');
- },
- mint: async () => minted
- });
- expect(result).toEqual(minted);
- expect(warn).toHaveBeenCalled();
- warn.mockRestore();
- });
-});
diff --git a/agentic/cli/__tests__/auth.test.ts b/agentic/cli/__tests__/auth.test.ts
deleted file mode 100644
index 6cd2a7cd9c..0000000000
--- a/agentic/cli/__tests__/auth.test.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-import { ConfigStore } from 'appstash';
-import * as fs from 'fs';
-import * as os from 'os';
-import * as path from 'path';
-
-const createClient = jest.fn();
-
-jest.mock('@constructive-io/sdk', () => ({
- auth: { createClient: (...args: any[]) => createClient(...args) }
-}));
-
-import { loadSession, saveSession } from '../src/account-store';
-import { refreshApiKeyIfNeeded, signIn, signOut } from '../src/auth';
-import { backendFromApiEndpoint, saveBackendConfig } from '../src/backend-store';
-import { loadConfig } from '../src/config';
-
-const AUTH_ENDPOINT = 'http://auth.localhost:3000/graphql';
-
-const unwrappable = (value: unknown) => ({ unwrap: () => Promise.resolve(value) });
-const failing = (err: unknown) => ({ unwrap: () => Promise.reject(err) });
-
-let home: string;
-let store: ConfigStore;
-
-beforeEach(() => {
- home = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-cli-auth-'));
- store = loadConfig(home).store;
- saveBackendConfig(store, backendFromApiEndpoint('http://api.localhost:3000/graphql'));
- createClient.mockReset();
-});
-
-afterEach(() => {
- fs.rmSync(home, { recursive: true, force: true });
-});
-
-function mockClient(mutation: Record) {
- createClient.mockImplementation(() => ({ mutation }));
- return mutation;
-}
-
-const signInResult = {
- signIn: {
- result: {
- userId: 'user-1',
- accessToken: 'access-token',
- accessTokenExpiresAt: '2026-08-04T00:00:00Z'
- }
- }
-};
-
-const mintedResult = {
- createApiKey: {
- result: { apiKey: 'cnc_live_sk_new', keyId: 'key-new', expiresAt: '2031-08-03T00:00:00Z' }
- }
-};
-
-describe('signIn', () => {
- it('persists the session and mints an API key in the step-up window', async () => {
- const mutation = mockClient({
- signIn: jest.fn(() => unwrappable(signInResult)),
- createApiKey: jest.fn(() => unwrappable(mintedResult)),
- revokeApiKey: jest.fn()
- });
-
- const session = await signIn({
- store,
- authEndpoint: AUTH_ENDPOINT,
- email: ' dev@example.com ',
- password: 'pw'
- });
-
- expect(mutation.signIn).toHaveBeenCalledWith(
- { input: { email: 'dev@example.com', password: 'pw' } },
- expect.anything()
- );
- expect(session.userId).toBe('user-1');
- expect(session.apiKey).toBe('cnc_live_sk_new');
- expect(session.keyId).toBe('key-new');
- expect(loadSession(store)).toEqual(session);
- expect(createClient).toHaveBeenCalledWith({ endpoint: AUTH_ENDPOINT });
- expect(createClient).toHaveBeenCalledWith({
- endpoint: AUTH_ENDPOINT,
- headers: { Authorization: 'Bearer access-token' }
- });
- });
-
- it('keeps the session when the mint fails', async () => {
- const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
- mockClient({
- signIn: jest.fn(() => unwrappable(signInResult)),
- createApiKey: jest.fn(() => failing(new Error('API_KEYS_DISABLED'))),
- revokeApiKey: jest.fn()
- });
-
- const session = await signIn({ store, authEndpoint: AUTH_ENDPOINT, email: 'dev@example.com', password: 'pw' });
- expect(session.apiKey).toBeUndefined();
- expect(loadSession(store)?.accessToken).toBe('access-token');
- warn.mockRestore();
- });
-
- it('rejects when no access token comes back (MFA)', async () => {
- mockClient({ signIn: jest.fn(() => unwrappable({ signIn: { result: {} } })) });
- await expect(
- signIn({ store, authEndpoint: AUTH_ENDPOINT, email: 'dev@example.com', password: 'pw' })
- ).rejects.toThrow('Authentication returned no access token (MFA may be required).');
- expect(loadSession(store)).toBeNull();
- });
-
- it('rejects empty credentials without a network call', async () => {
- await expect(
- signIn({ store, authEndpoint: AUTH_ENDPOINT, email: ' ', password: 'pw' })
- ).rejects.toThrow('Email and password are required.');
- expect(createClient).not.toHaveBeenCalled();
- });
-
- it('maps sign-in errors through describeAuthError', async () => {
- const gqlError = Object.assign(new Error('request failed'), {
- errors: [{ message: 'GraphQL Error: Invalid credentials' }]
- });
- mockClient({ signIn: jest.fn(() => failing(gqlError)) });
- await expect(
- signIn({ store, authEndpoint: AUTH_ENDPOINT, email: 'dev@example.com', password: 'nope' })
- ).rejects.toThrow('Invalid credentials');
- });
-});
-
-describe('refreshApiKeyIfNeeded', () => {
- const baseSession = {
- userId: 'user-1',
- email: 'dev@example.com',
- accessToken: 'access-token',
- signedInAt: 1754000000000
- };
-
- it('returns signed-out without a session', async () => {
- await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('signed-out');
- });
-
- it('returns ok for a fresh key without a network call', async () => {
- saveSession(store, {
- ...baseSession,
- apiKey: 'k',
- keyId: 'id',
- apiKeyExpiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365).toISOString()
- });
- await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('ok');
- expect(createClient).not.toHaveBeenCalled();
- });
-
- it('re-mints an expiring key and persists it', async () => {
- saveSession(store, {
- ...baseSession,
- apiKey: 'old',
- keyId: 'old-id',
- apiKeyExpiresAt: new Date(Date.now() + 1000).toISOString()
- });
- const mutation = mockClient({
- createApiKey: jest.fn(() => unwrappable(mintedResult)),
- revokeApiKey: jest.fn(() => unwrappable({ revokeApiKey: { result: true } }))
- });
-
- await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('reminted');
- expect(mutation.revokeApiKey).toHaveBeenCalledWith({ input: { keyId: 'old-id' } }, expect.anything());
- expect(loadSession(store)?.apiKey).toBe('cnc_live_sk_new');
- });
-
- it('returns reauth-required on a step-up error', async () => {
- saveSession(store, baseSession);
- mockClient({
- createApiKey: jest.fn(() => failing({ errors: [{ extensions: { code: 'STEP_UP_REQUIRED' } }] })),
- revokeApiKey: jest.fn()
- });
- await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('reauth-required');
- });
-
- it('returns unavailable on other errors', async () => {
- const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
- saveSession(store, baseSession);
- mockClient({
- createApiKey: jest.fn(() => failing(new Error('boom'))),
- revokeApiKey: jest.fn()
- });
- await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('unavailable');
- warn.mockRestore();
- });
-});
-
-describe('signOut', () => {
- it('revokes the key and clears the session', async () => {
- saveSession(store, {
- userId: 'user-1',
- email: 'dev@example.com',
- accessToken: 'access-token',
- apiKey: 'k',
- keyId: 'key-1',
- signedInAt: 1754000000000
- });
- const mutation = mockClient({
- revokeApiKey: jest.fn(() => unwrappable({ revokeApiKey: { result: true } }))
- });
-
- await expect(signOut({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe(true);
- expect(mutation.revokeApiKey).toHaveBeenCalledWith({ input: { keyId: 'key-1' } }, expect.anything());
- expect(loadSession(store)).toBeNull();
- });
-
- it('clears the session even when the revoke fails', async () => {
- const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
- saveSession(store, {
- userId: 'user-1',
- email: 'dev@example.com',
- accessToken: 'access-token',
- keyId: 'key-1',
- signedInAt: 1754000000000
- });
- mockClient({ revokeApiKey: jest.fn(() => failing(new Error('offline'))) });
-
- await expect(signOut({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe(true);
- expect(loadSession(store)).toBeNull();
- warn.mockRestore();
- });
-
- it('is a no-op when signed out', async () => {
- await expect(signOut({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe(false);
- expect(createClient).not.toHaveBeenCalled();
- });
-});
diff --git a/agentic/cli/__tests__/commands.test.ts b/agentic/cli/__tests__/commands.test.ts
index 45a5781c4c..6a81da717f 100644
--- a/agentic/cli/__tests__/commands.test.ts
+++ b/agentic/cli/__tests__/commands.test.ts
@@ -2,23 +2,35 @@ import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
-jest.mock('../src/auth', () => ({
+jest.mock('@agentic-kit/session', () => ({
+ ...jest.requireActual('@agentic-kit/session'),
signIn: jest.fn(),
signOut: jest.fn(),
- refreshApiKeyIfNeeded: jest.fn()
+ verifySession: jest.fn()
}));
-import { AccountSession, saveSession } from '../src/account-store';
-import { signIn, signOut } from '../src/auth';
-import { backendFromApiEndpoint, loadBackendConfig, saveBackendConfig } from '../src/backend-store';
+import {
+ AccountSession,
+ addBackend,
+ backendFromEndpoints,
+ saveSession,
+ selectBackend,
+ signIn,
+ signOut,
+ verifySession
+} from '@agentic-kit/session';
+
import { login, logout, whoami } from '../src/commands';
import { AgentCliConfig, loadConfig } from '../src/config';
-const LOCAL = backendFromApiEndpoint('http://api.localhost:3000/graphql');
-const REMOTE = backendFromApiEndpoint('https://api.example.com/graphql');
+const LOCAL = backendFromEndpoints({ api: 'http://api.localhost:3000/graphql' });
+const REMOTE = backendFromEndpoints({ api: 'https://api.example.com/graphql' });
+
+const useBackend = (config: AgentCliConfig) => selectBackend(config.store, addBackend(config.store, LOCAL).name);
const signInMock = signIn as jest.Mock;
const signOutMock = signOut as jest.Mock;
+const verifyMock = verifySession as jest.Mock;
let home: string;
let config: AgentCliConfig;
@@ -44,6 +56,8 @@ beforeEach(() => {
});
signInMock.mockReset();
signOutMock.mockReset();
+ verifyMock.mockReset();
+ verifyMock.mockResolvedValue({ kind: 'accepted' });
process.exitCode = undefined;
});
@@ -56,47 +70,59 @@ afterEach(() => {
const output = () => logs.join('\n');
describe('login', () => {
- it('signs in against the named API endpoint and persists all five planes', async () => {
- signInMock.mockResolvedValue(session);
+ it('signs in against the backend derived from the named API endpoint', async () => {
+ signInMock.mockResolvedValue({ session, context: 'example.com', previousKey: { kind: 'absent' } });
- await login(config, { apiUrl: LOCAL.apiEndpoint, email: 'dev@example.com', password: 'pw' });
+ await login(config, { apiUrl: REMOTE.apiEndpoint, email: 'dev@example.com', password: 'pw' });
expect(signInMock).toHaveBeenCalledWith({
store: config.store,
- context: 'localhost-3000',
- authEndpoint: LOCAL.authEndpoint,
+ backend: REMOTE,
email: 'dev@example.com',
password: 'pw'
});
- expect(loadBackendConfig(config.store)).toEqual(LOCAL);
expect(output()).toContain('signed in as dev@example.com');
expect(output()).toContain('cnc_li...abcd');
+ expect(output()).toContain('session stored in context example.com');
});
- it('derives auth and modules endpoints from a custom API URL', async () => {
- signInMock.mockResolvedValue(session);
-
- await login(config, {
- apiUrl: 'https://api.example.com/graphql',
- email: 'dev@example.com',
- password: 'pw'
+ it("signs in with every stored plane of the current context when the API endpoint is that context's", async () => {
+ const custom = backendFromEndpoints({
+ api: 'https://graphql.example.com/graphql',
+ auth: 'https://identity.example.net/graphql',
+ modules: 'https://modules.example.net/graphql',
+ agent: 'https://agent.example.net/graphql',
+ compute: 'https://compute.example.net/graphql'
});
+ selectBackend(config.store, addBackend(config.store, custom, 'custom').name);
+ signInMock.mockResolvedValue({ session, context: 'custom', previousKey: { kind: 'absent' } });
- expect(signInMock).toHaveBeenCalledWith(
- expect.objectContaining({ authEndpoint: 'https://auth.example.com/graphql' })
- );
- expect(loadBackendConfig(config.store)).toEqual({
- apiEndpoint: 'https://api.example.com/graphql',
- authEndpoint: 'https://auth.example.com/graphql',
- modulesEndpoint: 'https://modules.example.com/graphql',
- agentEndpoint: 'https://agent.example.com/graphql',
- computeEndpoint: 'https://compute.example.com/graphql'
- });
+ await login(config, { apiUrl: custom.apiEndpoint, email: 'dev@example.com', password: 'pw' });
+
+ expect(signInMock).toHaveBeenCalledWith(expect.objectContaining({ backend: custom, context: 'custom' }));
+ });
+
+ it('signs in with the planes CONSTRUCTIVE_* names when the API endpoint is the one CONSTRUCTIVE_API_ENDPOINT names', async () => {
+ const saved = { api: process.env.CONSTRUCTIVE_API_ENDPOINT, auth: process.env.CONSTRUCTIVE_AUTH_ENDPOINT };
+ process.env.CONSTRUCTIVE_API_ENDPOINT = REMOTE.apiEndpoint;
+ process.env.CONSTRUCTIVE_AUTH_ENDPOINT = 'https://identity.example.net/graphql';
+ try {
+ signInMock.mockResolvedValue({ session, context: 'example.com', previousKey: { kind: 'absent' } });
+ await login(config, { apiUrl: REMOTE.apiEndpoint, email: 'dev@example.com', password: 'pw' });
+ expect(signInMock).toHaveBeenCalledWith(
+ expect.objectContaining({ backend: expect.objectContaining({ apiEndpoint: REMOTE.apiEndpoint, authEndpoint: 'https://identity.example.net/graphql' }) })
+ );
+ } finally {
+ for (const [name, value] of [['CONSTRUCTIVE_API_ENDPOINT', saved.api], ['CONSTRUCTIVE_AUTH_ENDPOINT', saved.auth]] as const) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+ }
+ }
});
it('ships no backend: with no API endpoint named it refuses before any network call', async () => {
await expect(login(config, { email: 'dev@example.com', password: 'pw' })).rejects.toThrow(
- 'Invalid API endpoint URL: (empty)'
+ 'is not an absolute URL'
);
expect(signInMock).not.toHaveBeenCalled();
});
@@ -104,62 +130,61 @@ describe('login', () => {
it('rejects an invalid custom URL before any network call', async () => {
await expect(
login(config, { apiUrl: 'not a url', email: 'dev@example.com', password: 'pw' })
- ).rejects.toThrow('Invalid API endpoint URL');
+ ).rejects.toThrow('is not an absolute URL');
expect(signInMock).not.toHaveBeenCalled();
});
- it('warns when the session lacks an API key after sign-in', async () => {
- signInMock.mockResolvedValue({ ...session, apiKey: undefined, keyId: undefined });
+ it('warns when the replaced key could not be revoked', async () => {
+ signInMock.mockResolvedValue({ session, context: 'localhost-3000', previousKey: { kind: 'failed', keyId: 'key-0', reason: 'offline' } });
await login(config, { apiUrl: LOCAL.apiEndpoint, email: 'dev@example.com', password: 'pw' });
- expect(output()).toContain('API key mint failed');
- });
-
- it('does not persist the backend config when sign-in fails', async () => {
- signInMock.mockRejectedValue(new Error('Invalid credentials'));
-
- await expect(
- login(config, { apiUrl: REMOTE.apiEndpoint, email: 'dev@example.com', password: 'bad' })
- ).rejects.toThrow('Invalid credentials');
- expect(loadBackendConfig(config.store)).toBeNull();
+ expect(output()).toContain('key-0 of the replaced session could not be revoked (offline)');
});
});
describe('logout', () => {
- it('signs out against the stored backend', async () => {
- saveBackendConfig(config.store, REMOTE);
- signOutMock.mockResolvedValue(true);
+ it('signs out of the active backend', async () => {
+ signOutMock.mockResolvedValue({ kind: 'cleared', context: 'localhost-3000', key: { kind: 'revoked', keyId: 'key-1' } });
await logout(config);
- expect(signOutMock).toHaveBeenCalledWith({
- store: config.store,
- authEndpoint: REMOTE.authEndpoint
- });
+ expect(signOutMock).toHaveBeenCalledWith({ store: config.store, session: expect.objectContaining({ kind: 'no-backend' }) });
expect(output()).toContain('signed out');
});
+ it('signs out of the session the environment gives, and says nothing stored was removed', async () => {
+ const saved = { ...process.env };
+ Object.assign(process.env, { CONSTRUCTIVE_USER_ID: 'env-user', CONSTRUCTIVE_ACCESS_TOKEN: 'env-token', CONSTRUCTIVE_API_ENDPOINT: REMOTE.apiEndpoint });
+ try {
+ signOutMock.mockResolvedValue({ kind: 'from-environment' });
+ await logout(config);
+ expect(signOutMock).toHaveBeenCalledWith({ store: config.store, session: expect.objectContaining({ kind: 'signed-in', source: 'env' }) });
+ expect(output()).toContain('the session comes from the environment');
+ } finally {
+ process.env = saved;
+ }
+ });
+
it('reports when there is no session', async () => {
- saveBackendConfig(config.store, LOCAL);
- signOutMock.mockResolvedValue(false);
+ signOutMock.mockResolvedValue({ kind: 'not-signed-in', context: null });
await logout(config);
expect(output()).toContain('not signed in');
});
- it('never signs out against a guessed backend when none was chosen', async () => {
+ it('says the session was cleared but the key stays valid when the revoke failed', async () => {
+ signOutMock.mockResolvedValue({ kind: 'cleared', context: 'localhost-3000', key: { kind: 'failed', keyId: 'key-1', reason: 'offline' } });
await logout(config);
- expect(signOutMock).not.toHaveBeenCalled();
- expect(output()).toContain('not signed in');
+ expect(output()).toContain('session cleared, but the API key key-1 could not be revoked (offline)');
});
});
describe('whoami', () => {
- it('prints the session details with a masked API key', () => {
- saveBackendConfig(config.store, LOCAL);
- saveSession(config.store, session);
+ it('prints the session details with a masked API key', async () => {
+ useBackend(config);
+ saveSession(config.store, { ...session, issuedFor: LOCAL });
- whoami(config);
+ await whoami(config);
expect(process.exitCode).toBeUndefined();
expect(output()).toContain('signed in as dev@example.com');
@@ -170,8 +195,46 @@ describe('whoami', () => {
expect(output()).not.toContain('access-token');
});
- it('exits 1 with a sign-in hint when signed out', () => {
- whoami(config);
+ it('says the backend rejected the credential, and exits 1', async () => {
+ useBackend(config);
+ saveSession(config.store, { ...session, issuedFor: LOCAL });
+ verifyMock.mockResolvedValue({ kind: 'rejected', reason: 'The server rejected the credential (UNAUTHENTICATED).', code: 'UNAUTHENTICATED' });
+
+ await whoami(config);
+
+ expect(process.exitCode).toBe(1);
+ expect(output()).toContain('credential: rejected');
+ expect(output()).toContain('Run `agent login` to sign in again');
+ });
+
+ it('names a stored session that another backend issued, and does not use it', async () => {
+ useBackend(config);
+ saveSession(config.store, { ...session, issuedFor: { ...LOCAL, authEndpoint: 'http://auth.elsewhere.localhost/graphql' } });
+
+ await whoami(config);
+
+ expect(process.exitCode).toBe(1);
+ expect(output()).toContain('but the session was issued for http://auth.elsewhere.localhost/graphql');
+ expect(verifyMock).not.toHaveBeenCalled();
+ });
+
+ it('names the missing plane of a context another app wrote instead of reporting a backend', async () => {
+ const four = LOCAL;
+ config.store.createContext('localnet', {
+ endpoint: four.apiEndpoint,
+ targets: { api: { endpoint: four.apiEndpoint }, auth: { endpoint: four.authEndpoint }, modules: { endpoint: four.modulesEndpoint }, agent: { endpoint: four.agentEndpoint } }
+ });
+ config.store.setCurrentContext('localnet');
+ saveSession(config.store, session);
+
+ await whoami(config);
+
+ expect(process.exitCode).toBe(1);
+ expect(output()).toContain('"localnet" lacks the compute endpoint');
+ });
+
+ it('exits 1 with a sign-in hint when signed out', async () => {
+ await whoami(config);
expect(process.exitCode).toBe(1);
expect(output()).toContain('run `agent login`');
});
diff --git a/agentic/cli/__tests__/db-tools.test.ts b/agentic/cli/__tests__/db-tools.test.ts
index fdba1f86f0..004570ea6d 100644
--- a/agentic/cli/__tests__/db-tools.test.ts
+++ b/agentic/cli/__tests__/db-tools.test.ts
@@ -1,26 +1,18 @@
import { constructiveDbTools } from '@agentic-kit/pi';
+import {
+ addBackend,
+ backendFromEndpoints,
+ OVERRIDE_ENV_VARS,
+ saveSession,
+ selectBackend
+} from '@agentic-kit/session';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
-import { saveSession } from '../src/account-store';
-import { backendFromApiEndpoint, saveBackendConfig } from '../src/backend-store';
import { loadConfig } from '../src/config';
import { materializeDbTools } from '../src/db-tools';
-const LOCAL = backendFromApiEndpoint('http://api.localhost:3000/graphql');
-const REMOTE = backendFromApiEndpoint('https://api.example.com/graphql');
-
-const CONSTRUCTIVE_VARS = [
- 'CONSTRUCTIVE_USER_ID',
- 'CONSTRUCTIVE_ACCESS_TOKEN',
- 'CONSTRUCTIVE_API_KEY',
- 'CONSTRUCTIVE_API_ENDPOINT',
- 'CONSTRUCTIVE_MODULES_ENDPOINT',
- 'CONSTRUCTIVE_AGENT_ENDPOINT',
- 'CONSTRUCTIVE_COMPUTE_ENDPOINT'
-];
-
describe('materializeDbTools', () => {
let home: string;
let prevEnv: NodeJS.ProcessEnv;
@@ -28,8 +20,8 @@ describe('materializeDbTools', () => {
beforeEach(() => {
home = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-cli-dbtools-'));
prevEnv = { ...process.env };
- process.env.AGENT_HOME = home;
- for (const name of CONSTRUCTIVE_VARS) delete process.env[name];
+ process.env.CONSTRUCTIVE_STASH_DIR = home;
+ for (const name of OVERRIDE_ENV_VARS) delete process.env[name];
});
afterEach(() => {
@@ -37,7 +29,7 @@ describe('materializeDbTools', () => {
fs.rmSync(home, { recursive: true, force: true });
});
- it('writes a loadable extension entry into /extensions', () => {
+ function registeredTools(): string[] {
const config = loadConfig(home);
const file = materializeDbTools(config, () => {});
expect(file).toBe(path.join(config.agentDir, 'extensions', 'constructive-db-tools.js'));
@@ -54,14 +46,12 @@ describe('materializeDbTools', () => {
registerTool: (tool: { name: string }) => registered.push(tool.name),
on: () => {}
});
- expect(registered).toContain('provision_database');
- expect(registered).not.toContain('add_records');
- expect(registered).not.toContain('update_records');
- expect(registered).not.toContain('delete_records');
- expect(registered).not.toContain('create_api_key');
- const excluded = ['add_records', 'update_records', 'delete_records', 'create_api_key'];
- const expected = constructiveDbTools.map((tool) => tool.name).filter((name) => !excluded.includes(name));
- expect(registered.sort()).toEqual(expected.sort());
+ return registered;
+ }
+
+ it('registers every db tool except add_records, update_records and delete_records (row data needs a tenant sign-in the CLI lacks) and create_api_key (a minted key needs secret delivery the CLI lacks)', () => {
+ const expected = constructiveDbTools.map((tool) => tool.name).filter((name) => !['add_records', 'update_records', 'delete_records', 'create_api_key'].includes(name));
+ expect(registeredTools().sort()).toEqual(expected.sort());
});
function loadHost() {
@@ -71,82 +61,23 @@ describe('materializeDbTools', () => {
require(file!);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { getHost } = require('@agentic-kit/pi');
- return { config, host: getHost() };
+ return getHost();
}
- it('signals a signed-out host until env vars or a stored session exist', () => {
- const { host } = loadHost();
+ it('reads the session stored under CONSTRUCTIVE_STASH_DIR per call', () => {
+ const host = loadHost();
expect(host.account()).toBeNull();
- expect(host.backendConfig()).toBeUndefined();
-
- process.env.CONSTRUCTIVE_USER_ID = 'u1';
- process.env.CONSTRUCTIVE_ACCESS_TOKEN = 't1';
- process.env.CONSTRUCTIVE_API_ENDPOINT = 'http://api.localhost:3000/graphql';
- expect(host.account()).toMatchObject({ userId: 'u1', accessToken: 't1' });
- expect(host.backendConfig()).toEqual({
- apiEndpoint: 'http://api.localhost:3000/graphql',
- modulesEndpoint: 'http://modules.localhost:3000/graphql',
- agentEndpoint: 'http://agent.localhost:3000/graphql',
- computeEndpoint: 'http://compute.localhost:3000/graphql'
- });
- process.env.CONSTRUCTIVE_MODULES_ENDPOINT = 'http://modules.other.test/graphql';
- expect(host.backendConfig()).toMatchObject({
- apiEndpoint: 'http://api.localhost:3000/graphql',
- modulesEndpoint: 'http://modules.other.test/graphql'
- });
- });
+ const { store } = loadConfig(home);
+ selectBackend(store, addBackend(store, backendFromEndpoints({ api: 'https://api.example.com/graphql' })).name);
+ saveSession(store, { userId: 'stored-user', email: 'dev@example.com', accessToken: 'stored-token', signedInAt: 1, issuedFor: backendFromEndpoints({ api: 'https://api.example.com/graphql' }) });
- it('rejects a plane override that names no api endpoint instead of completing it with a guess', () => {
- const { host } = loadHost();
- process.env.CONSTRUCTIVE_MODULES_ENDPOINT = 'https://modules.example.com/graphql';
- expect(() => host.backendConfig()).toThrow('CONSTRUCTIVE_API_ENDPOINT is required');
- });
-
- it('reads the stored session and backend per call when env vars are absent', () => {
- const { config, host } = loadHost();
- expect(host.account()).toBeNull();
-
- saveBackendConfig(config.store, REMOTE);
- saveSession(config.store, {
- userId: 'stored-user',
- email: 'dev@example.com',
- accessToken: 'stored-token',
- apiKey: 'stored-key',
- signedInAt: 1
- });
-
- expect(host.account()).toEqual({
- userId: 'stored-user',
- accessToken: 'stored-token',
- apiKey: 'stored-key'
- });
- expect(host.backendConfig()).toEqual({
- apiEndpoint: REMOTE.apiEndpoint,
- modulesEndpoint: REMOTE.modulesEndpoint,
- agentEndpoint: REMOTE.agentEndpoint,
- computeEndpoint: REMOTE.computeEndpoint
- });
- });
-
- it('lets env vars beat the stored session', () => {
- const { config, host } = loadHost();
- saveBackendConfig(config.store, LOCAL);
- saveSession(config.store, {
- userId: 'stored-user',
- email: 'dev@example.com',
- accessToken: 'stored-token',
- signedInAt: 1
- });
-
- process.env.CONSTRUCTIVE_USER_ID = 'env-user';
- process.env.CONSTRUCTIVE_ACCESS_TOKEN = 'env-token';
- expect(host.account()).toMatchObject({ userId: 'env-user', accessToken: 'env-token' });
+ expect(host.account()).toMatchObject({ userId: 'stored-user', accessToken: 'stored-token' });
+ expect(host.backendConfig()).toMatchObject({ apiEndpoint: 'https://api.example.com/graphql' });
});
it('bakes the sign-in hint for pi failure reasons', () => {
- const { host } = loadHost();
- expect(host.signInHint).toBe('Run `agent login` to sign in.');
+ expect(loadHost().signInHint).toBe('Run `agent login` to sign in.');
});
it('surfaces `agent login` in the signed-out pi context reason', async () => {
@@ -156,11 +87,66 @@ describe('materializeDbTools', () => {
const project = path.join(home, 'project');
fs.mkdirSync(project);
- fs.writeFileSync(path.join(project, '.env'), 'DATABASE_ID=00000000-0000-4000-8000-000000000001\n');
+ fs.writeFileSync(path.join(project, '.env'), 'DATABASE_ID=0190f1a0-0000-7000-8000-000000000001\n');
const result = await resolveProjectContext(project);
expect(result.context).toBeNull();
expect(result.code).toBe('missing-credentials');
expect(result.reason).toContain('Run `agent login` to sign in.');
});
+
+ const boundProject = () => {
+ const project = path.join(home, 'project');
+ fs.mkdirSync(project);
+ fs.writeFileSync(path.join(project, '.env'), 'DATABASE_ID=0190f1a0-0000-7000-8000-000000000001\n');
+ return project;
+ };
+
+ it.each([
+ ['a credential without an api endpoint', { CONSTRUCTIVE_USER_ID: 'u1', CONSTRUCTIVE_ACCESS_TOKEN: 'secret-token' }],
+ ['a plane variable alone', { CONSTRUCTIVE_MODULES_ENDPOINT: 'https://modules.example.com/graphql' }]
+ ])('reports no-backend naming CONSTRUCTIVE_API_ENDPOINT for %s, not a missing sign-in', async (_name, env) => {
+ loadHost();
+ Object.assign(process.env, env);
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const { resolveProjectContext } = require('@agentic-kit/pi');
+
+ const result = await resolveProjectContext(boundProject());
+ expect(result.context).toBeNull();
+ expect(result.code).toBe('no-backend');
+ expect(result.reason).toContain('CONSTRUCTIVE_API_ENDPOINT');
+ expect(result.reason).not.toContain('secret-token');
+ });
+
+ it('names the missing plane and `agent login` for a context another app wrote', async () => {
+ loadHost();
+ const { store } = loadConfig(home);
+ const api = 'http://api.localhost/graphql';
+ store.createContext('localnet', {
+ endpoint: api,
+ targets: { api: { endpoint: api }, auth: { endpoint: 'http://auth.localhost/graphql' }, modules: { endpoint: 'http://modules.localhost/graphql' }, agent: { endpoint: 'http://agent.localhost/graphql' } }
+ });
+ store.setCurrentContext('localnet');
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const { resolveProjectContext } = require('@agentic-kit/pi');
+
+ const result = await resolveProjectContext(boundProject());
+ expect(result.code).toBe('no-backend');
+ expect(result.reason).toMatch(/"localnet" lacks the compute endpoint.*`agent login`/);
+ });
+
+ it('says a stored session was issued by another backend instead of only asking to sign in', async () => {
+ loadHost();
+ const { store } = loadConfig(home);
+ selectBackend(store, addBackend(store, backendFromEndpoints({ api: 'https://api.example.com/graphql' })).name);
+ saveSession(store, { userId: 'u', email: 'e', accessToken: 'secret-token', signedInAt: 1, issuedFor: backendFromEndpoints({ api: 'http://api.a.localhost/graphql' }) });
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const { resolveProjectContext } = require('@agentic-kit/pi');
+
+ const result = await resolveProjectContext(boundProject());
+ expect(result.context).toBeNull();
+ expect(result.reason).toContain('was issued for another backend');
+ expect(result.reason).toContain('the session was issued for http://api.a.localhost/graphql');
+ expect(result.reason).not.toContain('secret-token');
+ });
});
diff --git a/agentic/cli/__tests__/stores.test.ts b/agentic/cli/__tests__/stores.test.ts
deleted file mode 100644
index 08002815ec..0000000000
--- a/agentic/cli/__tests__/stores.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { ConfigStore } from 'appstash';
-import * as fs from 'fs';
-import * as os from 'os';
-import * as path from 'path';
-
-import { AccountSession, clearSession, loadSession, saveSession } from '../src/account-store';
-import { backendFromApiEndpoint, loadBackendConfig, saveBackendConfig } from '../src/backend-store';
-import { loadConfig } from '../src/config';
-
-const LOCAL = backendFromApiEndpoint('http://api.localhost:3000/graphql');
-const REMOTE = backendFromApiEndpoint('https://api.example.com/graphql');
-
-let home: string;
-
-beforeEach(() => {
- home = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-cli-store-'));
-});
-
-afterEach(() => {
- fs.rmSync(home, { recursive: true, force: true });
-});
-
-const session: AccountSession = {
- userId: 'user-1',
- email: 'dev@example.com',
- accessToken: 'access-token',
- accessTokenExpiresAt: '2026-08-04T00:00:00Z',
- apiKey: 'cnc_live_sk_abc',
- keyId: 'key-1',
- apiKeyExpiresAt: '2031-08-03T00:00:00Z',
- signedInAt: 1754000000000
-};
-
-const store = (): ConfigStore => {
- const s = loadConfig(home).store;
- if (!s.getCurrentContext()) saveBackendConfig(s, LOCAL);
- return s;
-};
-const bareStore = (): ConfigStore => loadConfig(home).store;
-
-describe('config', () => {
- it('shares the constructive stash rather than an agent-specific directory', () => {
- const config = loadConfig(home);
- saveBackendConfig(config.store, LOCAL);
- expect(fs.existsSync(path.join(config.dirs.stash.config, 'agent', 'account.json'))).toBe(false);
- saveSession(config.store, session);
- // credentials land in the shared stash root, not an agent-only subdirectory
- expect(fs.existsSync(path.join(config.dirs.stash.config, 'credentials.json'))).toBe(true);
- });
-});
-
-describe('account-store', () => {
- it('round-trips a session through the shared store', () => {
- const s = store();
- saveSession(s, session);
- expect(loadSession(s)).toEqual(session);
- });
-
- it('files the session under the active backend context, keeping backends independent', () => {
- const s = store();
- saveBackendConfig(s, REMOTE);
- saveSession(s, session);
- saveBackendConfig(s, LOCAL);
- expect(loadSession(s)).toBeNull();
- saveBackendConfig(s, REMOTE);
- expect(loadSession(s)).toEqual(session);
- });
-
- it('refuses to file a session before a backend is chosen', () => {
- const s = bareStore();
- expect(() => saveSession(s, session)).toThrow('No backend chosen');
- expect(s.getCurrentContext()).toBeNull();
- });
-
- it('writes credentials with mode 0600', () => {
- const s = store();
- saveSession(s, session);
- const file = path.join(loadConfig(home).dirs.stash.config, 'credentials.json');
- expect(fs.statSync(file).mode & 0o777).toBe(0o600);
- });
-
- it('returns null when nothing is stored', () => {
- expect(loadSession(store())).toBeNull();
- });
-
- it('clearSession removes the credentials and tolerates a signed-out store', () => {
- const s = store();
- saveSession(s, session);
- clearSession(s);
- expect(loadSession(s)).toBeNull();
- expect(() => clearSession(s)).not.toThrow();
- });
-});
-
-describe('backend-store', () => {
- it('derives all five planes from the api endpoint the user names', () => {
- expect(REMOTE).toEqual({
- apiEndpoint: 'https://api.example.com/graphql',
- authEndpoint: 'https://auth.example.com/graphql',
- modulesEndpoint: 'https://modules.example.com/graphql',
- agentEndpoint: 'https://agent.example.com/graphql',
- computeEndpoint: 'https://compute.example.com/graphql'
- });
- expect(() => backendFromApiEndpoint('not a url')).toThrow('Invalid API endpoint URL');
- });
-
- it('round-trips all five planes and returns null before one is chosen', () => {
- const s = bareStore();
- expect(loadBackendConfig(s)).toBeNull();
- expect(saveBackendConfig(s, REMOTE)).toBe('example.com');
- expect(loadBackendConfig(s)).toEqual(REMOTE);
- expect(saveBackendConfig(s, LOCAL)).toBe('localhost-3000');
- expect(loadBackendConfig(s)).toEqual(LOCAL);
- });
-
- it('treats a context missing a plane as no backend rather than guessing one', () => {
- const s = store();
- s.createContext('partial', {
- endpoint: REMOTE.apiEndpoint,
- targets: { api: { endpoint: REMOTE.apiEndpoint }, auth: { endpoint: REMOTE.authEndpoint } }
- });
- s.setCurrentContext('partial');
- expect(loadBackendConfig(s)).toBeNull();
- });
-});
diff --git a/agentic/cli/jest.config.js b/agentic/cli/jest.config.js
index 8a26efd6d0..b3b5381fb7 100644
--- a/agentic/cli/jest.config.js
+++ b/agentic/cli/jest.config.js
@@ -2,6 +2,7 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
+ setupFilesAfterEnv: ['/jest.setup.js'],
transform: {
'^.+\\.tsx?$': [
'ts-jest',
diff --git a/agentic/cli/jest.setup.js b/agentic/cli/jest.setup.js
new file mode 100644
index 0000000000..e23b1a597a
--- /dev/null
+++ b/agentic/cli/jest.setup.js
@@ -0,0 +1,11 @@
+// Points appstash's default base at a temporary directory for the whole suite,
+// so no test can resolve the real home directory when a variable is missing.
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+const base = fs.mkdtempSync(path.join(os.tmpdir(), 'jest-stash-base-'));
+process.env.APPSTASH_BASE_DIR = base;
+delete process.env.CONSTRUCTIVE_STASH_DIR;
+
+afterAll(() => fs.rmSync(base, { recursive: true, force: true }));
diff --git a/agentic/cli/package.json b/agentic/cli/package.json
index 8275684318..9c2c3ddfaa 100644
--- a/agentic/cli/package.json
+++ b/agentic/cli/package.json
@@ -34,9 +34,8 @@
"dependencies": {
"@agentic-kit/harness": "workspace:*",
"@agentic-kit/pi": "workspace:*",
- "@constructive-io/sdk": "workspace:^",
+ "@agentic-kit/session": "workspace:^",
"@earendil-works/pi-coding-agent": "1.4.0",
- "appstash": "^0.8.0",
"inquirerer": "^4.9.8"
},
"keywords": [
diff --git a/agentic/cli/src/account-store.ts b/agentic/cli/src/account-store.ts
deleted file mode 100644
index 4364df117c..0000000000
--- a/agentic/cli/src/account-store.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { ConfigStore } from 'appstash';
-
-
-export interface AccountSession {
- userId: string;
- email: string;
- accessToken: string;
- accessTokenExpiresAt?: string;
- apiKey?: string;
- keyId?: string;
- apiKeyExpiresAt?: string;
- signedInAt: number;
-}
-
-/**
- * Sessions live in the shared Constructive stash, as the credentials of the
- * active context (the chosen backend). The store owns the file layout, the
- * atomic 0600 writes and the at-rest encoding; this module only maps between
- * its `ContextCredentials` and the session shape the CLI passes around.
- */
-function currentContextName(store: ConfigStore): string | null {
- return store.getCurrentContext()?.name ?? null;
-}
-
-/** The active context; a session is never filed under a backend nobody chose. */
-function ensureContextName(store: ConfigStore): string {
- const name = currentContextName(store);
- if (!name) throw new Error('No backend chosen — run `agent login` first.');
- return name;
-}
-
-export function loadSession(store: ConfigStore, context?: string): AccountSession | null {
- const contextName = context ?? currentContextName(store);
- if (!contextName) return null;
- const creds = store.getCredentials(contextName);
- if (!creds?.token || !creds.userId) return null;
- return {
- userId: creds.userId,
- email: creds.email ?? '',
- accessToken: creds.token,
- accessTokenExpiresAt: creds.expiresAt,
- apiKey: creds.apiKey,
- keyId: creds.keyId,
- apiKeyExpiresAt: creds.apiKeyExpiresAt,
- signedInAt: creds.signedInAt ?? 0
- };
-}
-
-/**
- * `context` names the backend the session belongs to; it does not have to exist
- * as a context yet, so a sign-in can be filed before the backend is committed
- * and a failed sign-in leaves nothing behind.
- */
-export function saveSession(store: ConfigStore, session: AccountSession, context?: string): void {
- store.setCredentials(context ?? ensureContextName(store), {
- token: session.accessToken,
- expiresAt: session.accessTokenExpiresAt,
- userId: session.userId,
- email: session.email,
- apiKey: session.apiKey,
- keyId: session.keyId,
- apiKeyExpiresAt: session.apiKeyExpiresAt,
- signedInAt: session.signedInAt
- });
-}
-
-export function clearSession(store: ConfigStore, context?: string): void {
- const contextName = context ?? currentContextName(store);
- if (contextName) store.removeCredentials(contextName);
-}
diff --git a/agentic/cli/src/api-key.ts b/agentic/cli/src/api-key.ts
deleted file mode 100644
index 26abab0827..0000000000
--- a/agentic/cli/src/api-key.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-export const API_KEY_NAME = 'agentic-cli';
-export const API_KEY_ACCESS_LEVEL = 'full_access';
-export const API_KEY_MFA_LEVEL = 'none';
-export const API_KEY_YEARS = 5;
-
-/**
- * Re-mint once the key is within a week of expiry. The mint needs a
- * fresh-password step-up window, so in practice the refresh succeeds only right
- * after a sign-in; otherwise it surfaces as a re-auth prompt.
- */
-export const REMINT_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 7;
-
-export interface MintedApiKey {
- apiKey: string;
- keyId: string;
- apiKeyExpiresAt?: string;
-}
-
-export interface CreateApiKeyInputShape {
- keyName: string;
- accessLevel: string;
- mfaLevel: string;
- expiresIn: { years: number };
-}
-
-export function buildCreateApiKeyInput({ years }: { years: number }): CreateApiKeyInputShape {
- return {
- keyName: API_KEY_NAME,
- accessLevel: API_KEY_ACCESS_LEVEL,
- mfaLevel: API_KEY_MFA_LEVEL,
- expiresIn: { years }
- };
-}
-
-interface RawApiKeyRecord {
- apiKey?: string | null;
- keyId?: string | null;
- expiresAt?: string | null;
-}
-
-export function parseMintedKey(record: RawApiKeyRecord | null | undefined): MintedApiKey {
- if (!record?.apiKey || !record.keyId) {
- throw new Error('createApiKey returned no API key.');
- }
- return {
- apiKey: record.apiKey,
- keyId: record.keyId,
- ...(record.expiresAt ? { apiKeyExpiresAt: record.expiresAt } : {})
- };
-}
-
-export type ApiKeyErrorKind =
- | 'step-up-required'
- | 'disabled'
- | 'limit-reached'
- | 'not-authenticated'
- | 'invalid-access-level'
- | 'unknown';
-
-const ERROR_CODE_MAP: Record = {
- STEP_UP_REQUIRED: 'step-up-required',
- API_KEYS_DISABLED: 'disabled',
- API_KEY_LIMIT_REACHED: 'limit-reached',
- NOT_AUTHENTICATED: 'not-authenticated',
- INVALID_ACCESS_LEVEL: 'invalid-access-level'
-};
-
-export function classifyApiKeyError(err: unknown): ApiKeyErrorKind {
- const errors = (err as { errors?: Array<{ message?: string; extensions?: { code?: string } }> })?.errors;
- if (Array.isArray(errors)) {
- for (const e of errors) {
- const code = e.extensions?.code;
- if (code && ERROR_CODE_MAP[code]) return ERROR_CODE_MAP[code];
- }
- }
- const message = err instanceof Error ? err.message : typeof err === 'string' ? err : '';
- for (const code of Object.keys(ERROR_CODE_MAP)) {
- if (message.includes(code)) return ERROR_CODE_MAP[code];
- }
- return 'unknown';
-}
-
-export function needsRemint({
- apiKeyExpiresAt,
- now,
- thresholdMs = REMINT_THRESHOLD_MS
-}: {
- apiKeyExpiresAt: string | undefined;
- now: number;
- thresholdMs?: number;
-}): boolean {
- if (!apiKeyExpiresAt) return false;
- const expires = Date.parse(apiKeyExpiresAt);
- if (Number.isNaN(expires)) return false;
- return expires - now <= thresholdMs;
-}
-
-/**
- * Mint-first, revoke-on-success: revoking before minting would destroy a
- * still-valid key whenever the mint then fails, leaving no credential at all.
- * The one case that needs the old key gone first is the live-key cap
- * (API_KEY_LIMIT_REACHED): there we revoke, then retry the mint once.
- */
-export async function remintApiKey({
- currentKeyId,
- revoke,
- mint
-}: {
- currentKeyId: string | undefined;
- revoke: (keyId: string) => Promise;
- mint: () => Promise;
-}): Promise {
- const revokeOld = async () => {
- if (!currentKeyId) return;
- try {
- await revoke(currentKeyId);
- } catch (err) {
- console.warn(
- `[agent] failed to revoke superseded API key ${currentKeyId}: ${err instanceof Error ? err.message : String(err)}`
- );
- }
- };
-
- try {
- const minted = await mint();
- await revokeOld();
- return minted;
- } catch (err) {
- if (classifyApiKeyError(err) !== 'limit-reached') throw err;
- await revokeOld();
- return mint();
- }
-}
diff --git a/agentic/cli/src/auth-error.ts b/agentic/cli/src/auth-error.ts
deleted file mode 100644
index 7f5114fa2c..0000000000
--- a/agentic/cli/src/auth-error.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-const NETWORK_ERROR_CODES = new Set([
- 'ECONNREFUSED',
- 'ECONNRESET',
- 'ENOTFOUND',
- 'EAI_AGAIN',
- 'EHOSTUNREACH',
- 'ENETUNREACH',
- 'ETIMEDOUT',
- 'UND_ERR_CONNECT_TIMEOUT',
- 'UND_ERR_SOCKET'
-]);
-
-function errorCode(err: unknown): string | undefined {
- if (!err || typeof err !== 'object') return undefined;
- const { code, cause } = err as { code?: unknown; cause?: unknown };
- if (typeof code === 'string') return code;
- if (cause && typeof cause === 'object') {
- const causeCode = (cause as { code?: unknown }).code;
- if (typeof causeCode === 'string') return causeCode;
- }
- return undefined;
-}
-
-export function isNetworkError(err: unknown): boolean {
- const code = errorCode(err);
- if (code !== undefined) return NETWORK_ERROR_CODES.has(code);
- if (err instanceof AggregateError) return true;
- return err instanceof TypeError && /fetch failed/i.test(err.message);
-}
-
-function extractGraphqlMessages(err: unknown): string[] {
- const messages: string[] = [];
- const codes: string[] = [];
- const visited = new Set