---
title: "Coding in Fluent (ServiceNow SDK)"
description: "Guide for coding in Fluent (ServiceNow SDK) with examples for specific metadata types"
arguments:
  - name: metadata_list
    description: 'Comma-separated list of metadata types to include in the guide (e.g., "table,business-rule,script-include")'
    required: false
---

# Coding in ServiceNow Fluent

Guide for coding in ServiceNow Fluent with metadata type examples.

Fluent (ServiceNow SDK) is a TypeScript-based domain-specific language that allows you to create and manage metadata, modules, records, and tests in the ServiceNow platform. It features:

- Strong typing with TypeScript
- Declarative syntax for better readability
- Integration with modern development tools
- Testability and portability

## Key Concepts

- **Metadata Types**: Each ServiceNow object type (tables, business rules, client scripts, etc.) has a corresponding Fluent API
- **Fluent API**: Each metadata record is one constructor call (`Table({...})`, `BusinessRule({...})`) taking a typed configuration object — declarative, not method chaining. `Now` is a global, so `Now.ID[...]`, `Now.ref(...)`, and `Now.include(...)` need no import
- **TypeScript Support**: Full type checking and editor completion
- **SDK Commands**: CLI tools for initializing, building, and deploying ServiceNow applications

## Syntax and Best Practices

1. **Use Fluent Syntax** — a `.now.ts` file is declarative: each record is one top-level constructor call whose properties are values, not logic.
    - The Fluent compiler rejects imperative statements: a `for`/`for…of` loop (TS250) or an `if`/`else` (TS245) fails the build. Never generate records with `.map()` or another callback either — the build "succeeds" but writes `Symbol(Now.UNRESOLVED)` into the record. Write one call per record. (Flow and playbook branching use their own APIs, such as `wfa.flowLogic.if(...)`.)
    - Use template literals for interpolation; `'+'` concatenation in a property value fails to parse (TS303). Incorrect: `{ value: 'x_acme.' + suffix }`; Correct: `` { value: `x_acme.${suffix}` } ``.
    - Reference other records as the `now-ref-guide` lays out: the constructor's return value in the same file (`const role = Role({...})`), an `export`/`import` across files, `Now.ref('<table>', '<sys_id>')` for an existing instance record whose sys_id is known, or `Now.ref('<table>', { <unique field>: '<value>' })` by coalesce keys. Coalesce keys resolve only where the consuming property supports them (a Role's `containsRoles`, an ApplicationMenu `category`, `Record` data); an ACL's `roles`, ATF step inputs and a ScheduledScript's `businessCalendar` write a fresh random sys_id for them instead, and a List `view` fails the build. So give an ACL the role name (`'itil'`) and the others the sys_id form. `get_sys_id(...)` is **not** an SDK API: a real `now-sdk build` fails with `TS2304: Cannot find name 'get_sys_id'`.
    - `Now` (`Now.ID`, `Now.ref`, `Now.include`, `Now.attach`, `Now.del`) and the data helpers (`Duration`, `TemplateValue`, …) are globals — never import them.
    - Import Fluent (ServiceNow SDK) APIs from '@servicenow/sdk/core', except the automation APIs (`Flow`, `Subflow`, `Action`, `PlaybookDefinition`, `wfa`, and friends), which come from '@servicenow/sdk/automation'.
    - Never delete a `Table()`, `BusinessRule()`, `Record()` or other call as a quick way to "remove" something, and never without telling the user first: each `$id` is tracked in `keys.ts`, so deleting the code ships a delete record that removes the record from every instance the app is installed on. Confirm whether the record was ever installed and whether the deletion should propagate, then update `keys.ts` accordingly.
2. **Utilize tools**: Use this server's tools to get the metadata API spec, snippets, and instructions before writing Fluent (ServiceNow SDK) code
   - tools also wrap now-sdk CLI commands to initialize a project, build, deploy, transform, query, and run CI/CD; `explain_fluent_api` looks up any SDK API or guide (`now-sdk explain`)
   - when working with a local Fluent project, pass `workingDirectory` (the absolute path of the project root, the folder holding `now.config.json`) on project tools, or have the server configured with `FLUENT_MCP_WORKING_DIR`
3. **Write server-side logic in TypeScript modules** — TypeScript first; JavaScript is only the fallback.
   - Put server-side logic in TypeScript module files under `src/server/` (the `serverModulesDir` in `now.config.json`), `export` a function, and import it into the `.now.ts` file: `script: validateIncident`. Modules are the SDK's preferred approach for all server-side code (`module-guide`): typed Glide APIs, code reuse, and npm libraries.
   - In a module, import every Glide API you use from `@servicenow/glide` (`import { gs, GlideRecord } from '@servicenow/glide'`) — they are not globals there — and type records as `GlideRecord<'<table>'>`. Call only methods that exist in the `@servicenow/glide` types.
   - APIs whose script fields accept a module function: `BusinessRule`, `ScriptAction`, `UiAction`, `ScheduledScript`, `RestApi` route handlers, and `CatalogItemRecordProducer` (`script`, `postInsertScript`).
   - Fall back to JavaScript only where a function is not accepted. String-only fields (`ScriptInclude`, `ClientScript`, `CatalogClientScript`, `CatalogUiPolicy`, `UiPolicy`, `SPWidget`, `Record` data) take `Now.include('<path relative to the .now.ts file>')` pointing at a `.js` file; passing a function there fails with `TS2322 … is not assignable to type 'string'`. Client-side scripts, CSS, and HTML stored as-is in a record field (a Jelly `UiPage`, a Service Portal template) use `Now.include()`. **The one exception is the HTML entry of a bundled UI Page** — the React page whose `index.html` loads `./main.tsx`: `import page from '../client/index.html'` and pass `html: page`. The build rewrites the script reference to the packaged `/uxasset/externals/<scope>/main.jsdbx` URL only for an imported file; `Now.include()` there builds successfully but ships the unbuilt `src="./main.tsx"`, so the page loads nothing (see `create_custom_ui`). Write a module in JavaScript only when the user asks for it.
   - A Script Include `.js` file uses `Class.create()` with a `type` that matches the class name and the Fluent `name`, and does **not** import Glide APIs (they are auto-available there). To expose module logic through GlideAjax or by Script Include name, write a thin `Class.create()` wrapper that `require()`s the module (`script-include-guide`).
4. **Validate Early**: Run `build_fluent_app` after every change — it reports Fluent compiler diagnostics before anything reaches an instance — then deploy
5. **Use SDK Commands**: Utilize the ServiceNow SDK CLI for efficient workflows
6. **Server-side JavaScript level**: Fluent projects run server scripts in ECMAScript 2021 mode by default (`jsLevel: 'es_latest'` in `now.config.json`), so modern syntax (`const`/`let`, arrow functions, template literals, destructuring, optional chaining) is fine in modules and in `Now.include` files. Avoid what the platform disallows: `async` class methods, async generators / `for await`, `new Function()`, and `WeakRef`. Write ES5 only when the app's `jsLevel` is `helsinki_es5` or `traditional`. In scoped apps use `new GlideDateTime()` rather than `gs.nowDateTime()`. Keep inline `script` strings to one-liners; anything longer belongs in a module or a `Now.include()` file
7. **SDK v4.6.0 capabilities** — when generating code, take advantage of these additions where applicable:
    - **Declarative Form API** publicly exported from `@servicenow/sdk/core` — prefer `Form({ table, view, sections })` over hand-written `Record()` chains for `sys_ui_section` / `sys_ui_element`.
    - **Subflow-of-subflow** — Subflows can call other Subflows via `wfa.subflow(<importedSubflow>, …)`.
    - **Custom Actions in flows** — define reusable actions with `Action()` from `@servicenow/sdk/automation` (the body is sequential action steps only — no flow logic, no nested custom actions), invoke from flows and subflows via `wfa.action(<importedAction>, …)`. For an action owned by another application, either add it as a `now.config.json` dependency (alias `automation.actions`) for typed definitions, or pass its sys_id string to `wfa.action()` — outputs then become untyped.
    - **AIAF auto-ACL** — `AiAgent` / `AiAgenticWorkflow` build automatically generates `sys_security_acl` and `sys_security_acl_role` records from the mandatory `securityAcl` property. Do not author a separate `Acl()` for the agent's execution ACL; table ACLs for the tables an agent's CRUD tools touch are still separate `Acl()` records.
    - **NASK** — when `outputs` is omitted, the SDK auto-generates `response`, `provider`, `errorcode`, `status`, `error`. New `dataType` values: `glide_record` (requires `tableName`), `simple_array`, `json_object`, `json_array`.
    - **Table dictionary overrides** — in a child table (`extends` set), key an `OverrideColumn({ … })` by the inherited field name inside `schema` instead of authoring `sys_dictionary_override` records by hand; `baseTable` is optional — add it only when the field is defined further up the chain than the `extends` table. Overrides express unconditional behaviour only; conditional rules belong in Data/UI Policies or Business Rules.
    - **InboundEmailAction**, **SPHeaderFooter**, **SPPageRouteMap** — new dedicated APIs for these metadata types (see their per-type specs).
8. **SDK v4.7.0 capabilities** — when generating code, take advantage of these additions where applicable:
    - **DataPolicy** — new API from `@servicenow/sdk/core` for `sys_data_policy2`. Enforces mandatory / read-only field rules **server-side** (cannot be bypassed via API, import, or web service). Prefer it over UI Policy for security/data-integrity rules. See the `data-policy` spec.
    - **Flow error handling & parallelism** — `wfa.flowLogic.tryCatch({ $id }, { try, catch })`, `wfa.flowLogic.doInParallel({ $id }, ...blocks)`, and `wfa.flowLogic.appendToFlowVariables({ $id }, params.flowVariables, { arrayVar: … })` (it targets only `FlowArray({ elementType: FlowObject(…) })` variables, and `doInParallel` cannot nest). As of SDK v4.13.0 an arm or branch can `return { name: action }` to expose action outputs after the block (see item 13 and the `flow` spec); flow variables are only needed to share data between parallel branches mid-run.
    - **Flow stages** — declare `stages` in the `Flow` config with `FlowStage({ label, value, … })` and activate them in the body with `wfa.stage(params.stages.<key>)` for progress tracking.
    - **Table augments** — add columns to an existing platform/cross-scope table with `export const <table> = Table({ augments: '<table>', schema })` (the export name must equal the table name); only `augments`, `schema` and (SDK v4.13.0+) `index` are allowed. Added column names must use the current app's ownership prefix: `<scope>_` in an `x_` scope (e.g. `x_acme_`) or `u_` in global — the build rejects anything else, so a Store app (always an `x_` scope) uses its scope prefix, never `u_`.
    - **AI Agent** — new optional `agentDescriptor` (`'require_caller_id'` | `'created_by_ai_agent_advisor'` | `'created_by_build_agent'`); `dataAccess` now takes `roleMap` (role names, preferred) or `roleList` (role sys_ids).
    - **NASK** — `securityControls` now takes `roleMap` (role names, preferred) in addition to `roleRestrictions` (role sys_ids); supply at least one.
    - **`$override` (universal field override)** — escape hatch on Fluent constructors to set columns the typed API does not model: `$override: { db_column_name: value }` where values are `string | boolean | number` and keys are **database column names** (snake_case). No type-checking; prefer the typed property whenever the field is modeled. Use for customer-added `x_`/`u_` columns or fields owned by another app.
    - **`protectionPolicy`** — post-install edit/view protection on `sys_policy`-backed APIs, with two value sets. `Action`/`Subflow` take `'read' | ''` (default `''`; `'read'` read-protects the body). Business-logic APIs (`BusinessRule`, `ScriptInclude`, `AiAgent`, …) take `'read'` (others can view but not change) or `'protected'` (others cannot change); omit it to allow customization.
9. **SDK v4.8.0 capabilities** — when generating code, take advantage of these additions where applicable:
    - **PlaybookDefinition** — new API from `@servicenow/sdk/automation` for guided, record-driven processes (`sys_pd_process_definition`). Uses a 3-argument DSL `PlaybookDefinition(config, dependentConfig, body)` — `dependentConfig` carries `triggers` plus optional `permissions` (SDK v4.11.0+) and `variants` (SDK v4.13.0+) — with lanes, activities, inputs/outputs, and inline `startRule` ordering. See the `playbook` spec.
    - **RestMessage** — new API from `@servicenow/sdk/core` for outbound HTTP integrations (`sys_rest_message`): base URL, shared auth (`basic`/`oauth2` via auth profiles), shared/per-function headers, and callable `functions` with `${var}` substitution. See the `rest-message` spec.
    - **Alias / AliasTemplate** — new APIs from `@servicenow/sdk/core` for Connection & Credential aliases (`sys_alias`) and reusable connection-setup templates (`sys_alias_templates`). An `Alias` can compose a `RetryPolicy`, an `AliasTemplate`, and a parent alias inline. See the `alias` and `alias-template` specs.
    - **RetryPolicy** — new API from `@servicenow/sdk/core` (`sys_retry_policy`) controlling transient-failure handling for connections. Discriminated union over `retryStrategy`: `'fixed_time_interval'` / `'exponential_backoff'` (use `count` + `interval`) and `'retry_after'` (use `maxElapsedTime`, HTTP only). See the `retry-policy` spec.
    - **DataLookup** — new API from `@servicenow/sdk/core` (`dl_definition`) that auto-copies field values from a matcher table to a source record via `matchRules`/`setRules`. The matcher table must extend `dl_matcher`; in an `x_` scope **both** `sourceTable` and `matcherTable` must be in the app's scope (to target `incident` and the like, use a global app or a scoped table that extends it). Seed matcher rows with `Record()` and always set `active: true` — `Record()` does not apply dictionary defaults. Note `runOnUpdate` defaults to `false`. See the `data-lookup` spec.
    - **`Now.del()`** — declarative record deletion (cross-cutting, top-level statement only). `Now.del(table, { coalesceKey: value })` or `Now.del(table, '<sys_id>')`. Use it to remove OOB records you don't own; for records authored in Fluent, prefer deleting the code (deletes are tracked automatically).
    - **`$meta.installMethod`** — `Record`, `Acl`, `Alias`, and `UserPreference` accept `$meta: { installMethod: 'first install' | 'demo' | 'once' }` to map a record to an output folder that loads only in specific circumstances; most other constructors accept it too (check the type's spec). Use `'demo'` on `Record()` for sample data.
    - **`$override` on more APIs** — `DataPolicy` and `UserPreference` now support `$override` for setting unmodeled columns (same flat `{ db_column: value }` escape-hatch shape as other constructors).
    - **ACL `field`** — typed `keyof FullSchema<T> | SystemColumns | '*' | (string & {})`: schema fields, system columns, and the wildcard `'*'` autocomplete, and any other column name also compiles — so the type does not catch a typo.
    - **Table `accessibleFrom`** — defaults to `'public'`; set `'package_private'` only to restrict cross-scope read access (note that doing so removes the table from some platform features such as Business Rules).
    - **CLI `now-sdk query`** — new read-only Table REST query command (surfaced as the `query_fluent_records` MCP tool) for inspecting instance data without leaving the terminal.
10. **SDK v4.9.0 capabilities** — when generating code, take advantage of these additions where applicable:
    - **UI Test Script (TestingLibrary) ATF step** — `atf.uiTestScript.runTest({ $id, script })` runs a TestingLibrary test body in the client test runner to test custom UI components (Angular/React widgets, embedded SPAs, custom workspaces, `now-*` web components) that the standard `atf.form.*` / `atf.catalog.*` steps cannot reach. Prefer `script: Now.include('./file.script.js')`; inside the body `screen`/`user`/`sn_atf`/`expect`/`waitFor`/`within`/`steps`/`params` are injected (no imports). See the `atf-ui-test-script` spec.
    - **Multi-language choice labels** — a choice field's `choices` value may be an **array of `ChoiceConfig`** objects, each with a `language` (BCP 47) key, producing one translated `sys_choice` record per language: `choices: { 1: [{ label: 'Critical', language: 'en' }, { label: 'Critique', language: 'fr' }] }`. See the `column` spec.
    - **`protectionPolicy` on AI Agent & AI Agentic Workflow** — `AiAgent` and `AiAgenticWorkflow` accept `protectionPolicy: 'read' | 'protected'` to control post-install edit/view access for other developers: `'read'` lets others see but not change the record, `'protected'` prevents changes; omit it to allow customization. (`Action`/`Subflow` take `'read' | ''` instead.)
    - **`Role.federatedId`** — the `Role` API accepts an optional `federatedId` string used to match a role to an externally federated role during identity federation.
    - **Table index platform columns** — a table `index` entry's `element` may reference platform default columns (e.g. `'sys_created_on'`) in addition to custom columns.
    - **Now Assist Skill Kit providers** — never hard-code or pre-select a provider: query the instance's approved providers and models first, present them, and let the user choose (`nowassist-skills-guide`). `provider` is the `sys_gen_ai_provider.gen_ai_provider` name and `model` the `sys_generative_ai_model_config.model` value; both are free strings. The type also autocompletes `'Now LLM LTS Generic'` and the aliases `'Google Cloud Vertex AI'` (= Google Gemini) and `'Amazon Bedrock'` (= AWS Claude).
11. **SDK v4.10.1 capabilities** (shipped across 4.10.0–4.10.1) — when generating code, take advantage of these additions where applicable:
    - **StateModel** — new API from `@servicenow/sdk/core` defining a table's **state machine** in one call: states, transitions, and the conditions that gate them (`sttrm_model`, or `chg_model`/`prb_model`/`prb_task_model` auto-selected from `table`). **Put gate logic in a transition `condition`, never in a per-transition Business Rule calling `current.setAbortAction(true)`** — a rule whose core logic is a state-gated abort is a State Model in disguise. Only `change_request`/`problem`/`problem_task` evaluate conditions out of the box; on any other table also add the single generic enforcement rule (calls `STTRMModel.evaluateTransition`, no gate logic of its own) or the model is inert. A `change_request` model with an `Assess`/`Authorize` state also needs a companion approval `Flow` whose trigger is scoped to that `chg_model`. `$id` is the sole identity mechanism at every level (no coalesce fallback), and every declared row is fully re-written, so restate OOB values you want to keep. See the `state-model` spec.
    - **ATF list steps** — new `atf.list.*` namespace with six steps: `relatedListVisibility`, `applyFilterToList` (returns `{ first_record }`), `recordPresentInList`, `openRecordInList`, `listUIActionVisibility`, and `clickListUIAction` (which really executes the action). `relatedList` values are platform-generated and **not guessable** — format `<child_table>.<field>` (e.g. `task.parent`), or `REL:<sys_id>`. Only author these when a client script, UI policy, or app-defined relationship actually drives the list's behavior. See the `atf-list` spec.
    - **`$meta.useEsLatest`** — new cross-cutting flag on the APIs whose type carries `$meta` (`BusinessRule`, `Acl`, `ScriptInclude`, `ScriptAction`, `ScheduledScript`, `UiPage`, `RestApi`, `SPWidget`, `SPMenu`, and others): `$meta: { useEsLatest: true }` runs that record's script field(s) at the latest ECMAScript version the platform supports instead of the app's `sys_app`/`now.config` default. It applies to **all** script fields on the entity (on `RestApi`, set it on the API — routes carry no `$meta`). It is **not** on every API with a server script, whatever `fluent-overview` says: `StateModel`, `AliasTemplate`, `InboundEmailAction`, and `CatalogItem` reject `$meta`. Omit it to keep the app-level default — most records don't need it.
    - **Table `actions` object form** — `actions` now accepts the exported `TableActionAccess` shape `{ read?, update?, delete?, create? }`, where each action is three-state: `true` and `false` are both written, and an omitted action is not written at all. **The array form is deprecated** because it is a complete enumeration — `actions: ['read']` also writes `update_access=false`, `delete_access=false`, and `create_access=false`. The SDK also no longer derives defaults for `actions`, `allowClientScripts`, `allowConfiguration` (SDK v4.13.3+), `allowNewFields`, `allowUiActions`, or `allowWebServiceAccess`; each is written only when you set it.
    - **Reference column `mtom`** — `ReferenceColumn` gained `mtom: '<relationship label>'` to create a many-to-many relationship (surfaced as a related list on the referenced table; ServiceNow-scoped apps only — other scoped apps use the `sys_m2m` table). **Note the semantic split:** `referenceKey` no longer means m2m — it now specifies a field on the referenced table to store instead of `sys_id` (that field must be unique and mandatory there).
    - **UI Action icons** — `UiAction`'s `form` and `list` objects both accept `iconName` (see `/styles/retina_icons/retina_icons.html` on the instance) and `showIconOnly`. When using `showIconOnly`, add a tooltip on the UI Action so the button stays identifiable.
    - **`Form` `$meta`** — `Form` now accepts `$meta.installMethod` to route its output folder; the property previously had no effect.
    - **Playbook `timerSchedule`** — `startWithDelay` accepts an optional `timerSchedule` (`string | Record<'cmn_schedule'>`) on all three variants (`explicit`, `relative`, `percentage`), evaluating the delay against a schedule (business hours/calendar) instead of elapsed clock time.
    - **Catalog dynamic default values** — a variable's `dependentQuestion` widened to `string | ReturnType<typeof ReferenceVariable> | ReturnType<typeof RequestedForVariable>`. This is a **dynamic default value** (auto-populating by dot-walking from another variable's referenced record via `dotWalkPath`, with `useDynamicDefault: true`), **not** visibility or option filtering — those remain `CatalogUiPolicy` and reference qualifiers. Prefer the source variable's name as a string. Also: `CatalogUiPolicy` actions accept `variable`, and `CatalogClientScript` accepts `order`.
    - **`$override` on `sys_*` fields** — `$override` can set `sys_domain` and most other `sys_*` columns on **any** table, not just specific APIs. Four are always framework-managed and error if overridden: `sys_id`, `sys_scope`, `sys_update_name`, `sys_domainpath`. On transform, a non-`global` `sys_domain` is captured into `$override` automatically — but only when the call has no `$override` block yet.
    - **Service Portal** — widget, page, and instance CSS fields accept **SCSS or CSS**; `widgetParameters` now correctly serializes a plain object (`{ param1: 'value1' }`, previously string-only); `SPInstance`'s `preservePlaceholderSize`/`placeholderDimensions`/`placeholderConfigurationScript`/`placeholderTemplate` are now functional rather than ignored; and `urlSuffix` accepts hyphens.
    - **CLI `now-sdk cicd`** — new CI/CD command surfaced as two MCP tools: `cicd_fluent_app` (install/publish/rollback an app — changes instance state) and `cicd_fluent_test` (run/watch/fetch results for ATF suites and tests, plus `logs` for a single test result, SDK v4.12.0+). **CLI `now-sdk query --select`** adds a dot/bracket path extractor, surfaced as the `select` argument on `query_fluent_records`.
12. **SDK v4.11.2 capabilities** (shipped across 4.11.0–4.11.2) — when generating code, take advantage of these additions where applicable:
    - **TestSuite** — new API from `@servicenow/sdk/core` grouping existing ATF `Test()` records into a named, orderable, optionally nested suite (`sys_atf_test_suite` + `sys_atf_test_suite_test`). Run order comes from **array position** in `tests`, not an authored field; use the object form only for `abortOnFailure` or to pin an existing `order`. **Authoring only** — it never runs anything; trigger suites via ATF's UI/scheduler or `cicd_fluent_test`. Do not combine `testFilter` with an explicit `tests` list: ATF re-syncs membership from the filter on every instance save and can silently drop listed tests. See the `test-suite` spec.
    - **GraphQLApi** — new API from `@servicenow/sdk/core` defining a scripted GraphQL API (`sys_graphql_schema`) with its resolvers, type resolvers, and two-tier security. A resolver's `script` accepts an **imported named server-module function**, an inline string, or `Now.include(...)` — writing the function **inline** type-checks but is a build error. Keep the two path formats straight: resolver `paths` are `Type:field`, field-level ACL names are slash-delimited runtime paths (`/xSncMyApp/myApi/items/cost`). Note `enforceAcl` is an ACL **array defaulting to empty**, not a secure-by-default boolean; `contextualAclMaxDepth` counts the two envelope segments, so depth 4 is the default reach. See the `graphql-api` spec.
    - **Field Styles** — `sys_ui_style` is now a supported `Record()` table, so conditional list/form field styling is authorable in Fluent (there is no `FieldStyle()` constructor). `style` is **not** limited to `background-color` — any CSS property works, which makes this the mechanism for list column `width` and `text-align`. **An empty `value` does not mean "always"**: it applies unconditionally on the *form* but only to blank cells in a *list*; use `value: 'javascript:1==1;'` for an unconditional list style. See the `field-style` spec.
    - **Flow do-while loop** — `wfa.flowLogic.doTheFollowing({ $id, label?, annotation? }, () => { ... })` repeats a body until `wfa.flowLogic.until('<condition>')` — called as the body's **last statement**, not returned — is satisfied. Do-while semantics: the body always runs once and the condition can reference outputs from actions inside the same body. There is **no** `doTheFollowingUntil` function. Use it for polling and retries; `forEach` still owns fixed-size collections.
    - **Playbook `executionType: 'on_demand'`** — standalone playbooks started explicitly rather than by a trigger. These restrictions apply together: omit `triggers` entirely, no `parentTable`, no `params.parentRecord`, no launcher record-form fields, no `publicAccess` (typed `never`, SDK v4.13.0+), and **at least one permission set must grant `launch: true`** (this fails the build even with `permissions` omitted). In exchange, `allowAsNested` may be `true` (record-driven playbooks allow only `false`).
    - **Playbook permissions** — playbook-level `permissions` is a **callback** on argument 2 (so pills can reach `params.parentRecord`); lane-level `permissions` is a **plain object** on `LaneConfig`. On a playbook set, `view` is required and **gates every other flag**; on a lane set all four flags are independent. Use `wfa.playbook.activityRef(Now.ID['x'])` inside `dataPill()` to reach an activity's outputs from a permissions block.
    - **Playbook optional activities** — `startRule: wfa.playbook.run.Manually()` for an activity a user starts by hand. Omit `order`/`conditionToRun`/`startWithDelay`/`variant`/`variantOverrides` and pin `restartRule: 'RUN_ONLY_ONCE'`. It returns a `ManualActivityReference` with **no outputs and no `run.After()` eligibility** — it may never run, so never build a dependency chain through one, and never target it with `GoBack` or `evaluateVariantChildrenAfter`.
    - **Playbook launcher + `SetPlaybookOutputs`** — `launcherTitle`/`launcherDescription`/`launcherInputs` configure the on-demand launcher (pass **strings** for boolean/integer inputs). The record-form fields (`launcherShowRecordForm`, `launcherRecordFormView`, `launcherTemplateFields`) are for **record-driven** playbooks and are forbidden on `'on_demand'`. New OOB activity `ActivityDefinitions.Core.SetPlaybookOutputs` writes the playbook's declared `outputs` via a `playbook_outputs` `TemplateValue`.
    - **Playbook AI-agent activities** — AI-agent config fields are exposed only on definitions declaring `enableAiAgent: 'on'`: `RecordForm`, `AutocompletingRecordForm`, `NewRecordForm`, `EmailForm`. Once `enableAiAgent` is true, `aiAgentObjective` must resolve — omitting it inherits the definition's default where one exists (e.g. `RecordForm`), and an explicit `''` fails the build. AI-agent activities are forbidden in `publicAccess` playbooks. Requires the `sn_genai_platform` store app and `sn_pa_designer.enable_agentic_playbooks`, neither of which the SDK validates.
    - **Dependent record inputs** — `UpdateRecord`/`CreateNewRecord` (playbook and flow) now type-check a `record` pill against the sibling `table_name`, and `Action()` carries `rawInputs` for the same purpose. A wrong-table pill is a compile error rather than a runtime surprise.
    - **`Table.sizeClass` and `List.domain`** — `Table` accepts `sizeClass?: number` (size classification); `List` accepts `domain?: string` (the `sys_domain` applied to the list, defaulting to `'global'`).
13. **SDK v4.13.6 capabilities** (shipped across 4.12.0–4.13.6) — when generating code, take advantage of these additions where applicable:
    - **Assessment** / **RiskAssessment** (SDK v4.12.0+) — new APIs from `@servicenow/sdk/core`. `Assessment()` defines an assessment or survey (`asmt_metric_type` → categories → metrics → metric definitions); `evaluationMethod` is only `'assessment'` or `'survey'`, `scaleFactor` (an integer) is required by the build unless `evaluationMethod: 'survey'`, and Yes/No answers are `'1'`/`'0'`. `RiskAssessment()` defines a change risk assessment (`change_risk_asmt` + thresholds) and has **no** `table` or `evaluationMethod`; confirm the `com.snc.change_management.risk_assessment` plugin is active (query `sys_plugins`) before authoring one. Always use the **array** form of `displayedWhen` / `displayedWhenTemplate` / `correctAnswerChoice` / `correctAnswerTemplate` — the string form is silently written empty. Reference another metric with `Now.ref('asmt_metric', '<key>')`, not `Now.ID`. See the `assessment` and `risk-assessment` specs.
    - **DatabaseView** (SDK v4.13.0+) — new API from `@servicenow/sdk/core` joining existing tables into a read-only reportable view (`sys_db_view`). `name` is the identity — no top-level `$id` — and must start with `u_` (global) or `<scope>_` (`x_` scope). Each joined table needs `$id`, `table` and a `variablePrefix` (no underscore); its `fields` are nested under it, and `whereClause` is a raw `<prefix>_<field>` predicate, not an encoded query. See the `database-view` spec.
    - **Interceptor** (SDK v4.13.0+) — new API from `@servicenow/sdk/core` for a guided-question wizard (`sys_wizard` + `sys_wizard_answer`) that routes users to the right form or page. `name` is the identity (no top-level `$id`), every answer needs an `$id`, and renaming orphans the old record. Author multiple-choice options with `Record({ table: 'sys_wizard_choice', data: { answer: Now.ref('sys_wizard_answer', '<key>'), … } })`. See the `interceptor` spec.
    - **Playbook variants** (SDK v4.13.0+) — declare `variants: (params) => ({...})` on argument 2 with `wfa.playbook.variant({ $id, label, condition, order, color?, parentVariant? })` and reference them as `params.variants.<name>`. An activity uses **either** `variant` (exists only in that variant) **or** `variantOverrides` (changes only `startRule`/`order` for that variant), never both. `evaluateVariantChildrenAfter` delays variant selection until an activity finishes; variant conditions may read only activities that run **strictly before** it. Declaring any variant requires `parentTable` (a build error otherwise).
    - **Playbook Go Back and `isIdealPath`** — `ActivityDefinitions.Core.GoBack` restarts an earlier activity, stage, or the whole playbook, but only as the **last activity of a `match_first` decision branch**; give the target `restartRule: 'RUN_ALWAYS'` or it is silently skipped. `isIdealPath` marks a decision branch as the golden path.
    - **Playbook `publicAccess`, `actionOverrides`, `automationPlan`** — `publicAccess` lets **unauthenticated users run the playbook from public pages** (it is not a public API; it needs `parentTable`, public-safe definitions only, and no AI-agent activity, and it is not allowed on `'on_demand'`). `actionOverrides` is set **per activity** and **replaces** the card's default buttons. `wfa.playbook.automationPlan(uiId?)` pills are legal **only in experience properties**.
    - **Playbook breaking changes** — `NewRecordForm` now requires `table` (no default, so omitting it fails the build); `ChecklistTask.checklist_items` is mandatory too, but its default fills an omitted value, so only an explicit `''` fails; and `BaseActivityConfig` is now a type, so `interface … extends BaseActivityConfig` fails (TS2312). Never author `preservedAttachment`; transform manages it.
    - **Flow output hoisting** (SDK v4.13.0+) — `doInParallel` branches and `tryCatch` arms can return outputs, and `catch: (tryOutputs) => …` receives the try arm's. Write `return { lookup: lookup }`, never the shorthand `{ lookup }` (a Fluent build error), give each exposed action a literal string `uuid`, and name an unused catch parameter `_tryOutputs`. `endFlow` is allowed inside either `tryCatch` arm.
    - **Table, columns, ACL, UI Action** — `Table` augment mode now accepts `index` (SDK v4.13.0+); non-augment tables gain `allowConfiguration` / `dbObjectId` (SDK v4.13.3+; neither is allowed with `augments`). `UrlColumn` accepts any string including relative URLs (SDK v4.12.0+). ACL types `aiux_page` / `aiux_widget` / `aiux_experience` (SDK v4.12.0+) **require `name`**, and `roles` entries accept `{ role, protectionPolicy }` (SDK v4.13.6+). `UiAction` `form: true` / `list: true` declares a programmatic-only action (UI26), and `style` adds `'primary-ai'` / `'secondary-ai'`.
    - **`$meta` on more APIs** (SDK v4.13.0+) — `EmailNotification`, `UiPolicy`, `ScriptOnlyCheck`, `TableCheck`, `CatalogClientScript`, `CatalogItemRecordProducer` and every catalog variable accept `$meta`. GraphQL resolver entries type-check with `$meta`, but the build ignores it — don't rely on it there.
    - **Dashboard** — the widget grid is **48** columns wide (half = 24), and widgets bind data inline with `dataSources` + `metrics` + `groupBy` (or `trendBy` for time trends) rather than a report sys_id. See the `dashboard` spec for filters and the component names that still need instance verification.
14. **SDK v4.14.0 capabilities** — when generating code, take advantage of these additions where applicable:
    - **UiMacro** (SDK v4.14.0+) — new API from `@servicenow/sdk/core` for a reusable Jelly macro (`sys_ui_macro`); use it instead of `Record({ table: 'sys_ui_macro' })`. `$id` is the identity. Write `name` without the scope prefix and invoke the macro as `<g:x_myapp_<name> />` in a scoped app. Keep the Jelly in its own file with `xml: Now.include('./x.jelly.xml')`; inline in a template literal, every Jelly `${...}` must be escaped as `\${...}`. Never put `&&` or `<` in an inline `<script>` body, not even entity-escaped. Omit `mediaType` (it is not a MIME type). See the `ui-macro` spec.
    - **Reusable ATF tests** (SDK v4.14.0+) — `Test({ ..., isReusable: true, inputs: {...}, outputs: {...} }, (atf, inputs, outputs) => {...})` (all three keys in the **first** argument) writes a `sys_atf_test_callable`. Call it from another test with `atf.executeTest(reusableTest, { $id }, { ...every input })`, whose return value carries the typed outputs. Populate the outputs inside the reusable test with `atf.setReusableTestOutputs(outputs, { $id }, { ... })`. Use `StringColumn` for sys_id outputs that feed later steps. Reusable tests cannot be listed in a `TestSuite`. `atf.server.setOutputVariables` was removed. `Test()` never accepted `$meta`. See the `atf` spec.
    - **Unused locals and parameters fail `now-sdk build`** (TS6133) — the build type-checks `.now.ts` files with `noUnusedLocals` / `noUnusedParameters` (not new, but the 4.14.0 release-note reusable-test example trips it). Never leave an unused `const` (e.g. an unused step result) or parameter; prefix an intentionally unused parameter with `_`.
    - **Columns and tables** (SDK v4.14.0+) — any column accepts `createRoles` / `readRoles` / `writeRoles` / `deleteRoles` (one role per entry); a non-augment `Table` accepts the same four plus `basePolicy: 'public' | 'private'`, the default for access flags you leave unset. `arrayDenormalized: true` keeps a comma-separated copy of an array column on the parent row; always pair it with `array: true`. `ReferenceColumn` / `ListColumn` accept `referenceQualCondition` (camelCase; the snake_case key is silently dropped).
    - **Role / Property `suffix`, Assessment `domain`** (SDK v4.14.0+) — `Role()` and `Property()` accept an explicit `suffix` (default: the name without the scope prefix). `Assessment()` / `RiskAssessment()` accept `domain` + `domainPath`; always set `domainPath` with a non-global `domain`.
    - **Dashboard `componentProps` is written verbatim** (SDK v4.14.0+) — the build no longer merges the SDK's widget defaults; install still fills in the component's remaining defaults, so a partial object is fine. Set `followFilters: true` and `filterConfigurations: '@state.parFilters'` explicitly on every widget that must follow dashboard filters.
    - **`$meta` on `CatalogUiPolicy`** (SDK v4.14.0+), and catalog custom variables / `customCart` accept a `UiMacro` (and `widget` an `SPWidget`) object directly.
    - **`fluent_exec_script`** (SDK v4.14.0+ `now-sdk exec`) — runs a server-side script on the instance with the user's admin permissions. Use it only for one-off operational tasks the user explicitly asks for, never for logic that should ship with the app. Pass the script inline, or as a `.js` `file` inside the Fluent project (show the user the file's content, not just its path). Show the user the full script, scope, and reason, and get approval for every run. Never retry automatically after a timeout, because the script keeps running on the instance.
15. **SDK v4.14.2 capabilities** — when generating code, take advantage of these additions where applicable:
    - **Sample, demo and seed rows** (demo-data-guide, new in SDK v4.14.2) — add each row with `Record()` and `$meta: { installMethod: 'demo' }`, which writes it to the `unload.demo` folder that `now-sdk install` loads by default. A sample row without it installs as application source, and later incremental installs can fail with `Found <file>.xml with invalid scope`. Use it only for rows of tables that do not extend `sys_metadata` (such as the app's own data tables); application metadata (properties, roles, choices and other `sys_metadata` records) is not demo data, so leave `installMethod` unset on it. The build does not check this.
    - **`CatalogUiPolicy` on a record producer** (SDK v4.14.2+) — `catalogItem` accepts a `CatalogItemRecordProducer`, so the policy can reference the producer's own `variables`; keep `appliesTo: 'item'`. `CatalogClientScript` already accepted one.
    - **Ranked documentation search** — when `explain_fluent_api` finds no exact topic, it returns the closest topics ranked by relevance; pass `range` (`"7"` or `"3-7"`) to page through them instead of guessing other topic names.
    - **Slow instance conversion** — `init_fluent_app` accepts `timeoutSeconds` for a conversion from an instance (`from` is a sys_id); raise it for a large application on a slow instance.

## Working with Specific Metadata Types

Fluent provides a strongly-typed API for every supported ServiceNow metadata type — a dedicated constructor for most, and a typed `Record()` table for a few (e.g. `field-style`). This server ships the full specification, authoring instructions, and runnable snippets for each type — fetch them on demand instead of guessing an API shape:

- **API specification** — the `get_fluent_knowledge` tool with `kind: "spec"` (or resource URI `sn-spec://<type>`)
- **Authoring instructions & best practices** — `kind: "instruct"` (or `sn-instruct://<type>`)
- **Runnable code snippet** — `kind: "snippet"`, optionally with a `snippetId` (or `sn-snippet://<type>/<id>`)

Call `get_fluent_knowledge` with only a `kind` at any time to list every metadata type that has one. When this prompt is invoked with a `metadata_list`, per-type guidance and the full type catalog are appended below.
