# Instructions for Fluent Flow API
Always reference the Flow API specification for more details.
1. Import `Flow`, `wfa`, `trigger`, and `action` from `@servicenow/sdk/automation` — NOT from `@servicenow/sdk/core`.
2. Every `$id` value — in the flow config, trigger instance, and every `wfa.action()` / `wfa.flowLogic.*` call — must use `Now.ID['unique_key']` with a descriptive, unique key. Duplicate `$id` values within a flow cause build errors.
3. The flow body callback is the third argument to `Flow()`. All `wfa.action()` and `wfa.flowLogic.*` calls must be placed inside this callback, not outside it.
4. `wfa.trigger()` takes three arguments: the built-in trigger definition (e.g., `trigger.record.created`), a trigger instance config object with `$id`, and the trigger inputs object. The trigger inputs vary by trigger type — always specify at least `table` for record triggers.
5. Use `wfa.dataPill(value, type)` to reference output values from triggers or previous actions. The second argument specifies the data type: `'string'`, `'reference'`, `'integer'`, `'boolean'`, `'array.string'`, etc. Mismatched types cause runtime errors.
6. `wfa.flowLogic.if()`, `elseIf()`, and `else()` form a logical group. `elseIf` and `else` must immediately follow the `if` block without intervening action calls.
7. `wfa.flowLogic.forEach()` iterates over an array data pill. Use `wfa.flowLogic.exitLoop()` or `wfa.flowLogic.skipIteration()` inside the loop body when needed.
8. Earlier MVP limitations (SDK 4.3.0) have been progressively lifted: SubFlow support arrived in SDK v4.5.0, and **try/catch error handling arrived in SDK v4.7.0** (see item 17). Step rewind (Go-Back-To) and native DateTime flow variables remain unsupported — use `StringColumn` as a workaround for DateTime flow variables.
9. Flow variables declared in `flowVariables` within the config object are accessible via `params.flowVariables` in the body, fully typed. Use `wfa.flowLogic.setFlowVariables()` to update them at runtime.
10. `runAs` defaults to `'system'` since SDK v4.5.0 (previously defaulted to `'user'`). With `'system'`, the flow runs under the system context (no user-specific restrictions). Use `runAs: 'user'` when the flow should respect the triggering user's permissions.
11. Service Catalog trigger and catalog actions (`getCatalogVariables`, `createCatalogTask`, `submitCatalogItemRequest`) require SDK 4.4.0 or later.
12. The `protection: 'read'` option makes the flow read-protected (cannot be directly edited on the instance). Omit or use `''` for no protection.
13. **SDK v4.5.0**: Flows and subflows are now auto-published during `install` by default. Use the `--skip-flow-activation` flag on the install command to disable this behavior.
14. **SDK v4.6.0**: Subflow invocation expanded — Subflows can now call other Subflows as steps (subflow-of-subflow). Use `wfa.subflow(<importedSubflow>, { $id }, { …inputs })` from inside a Subflow body just as you would from a Flow.
15. **SDK v4.6.0**: Custom Actions (created via `Action()` in `@servicenow/sdk/automation`) are usable as Flow / Subflow steps via `wfa.action(<importedCustomAction>, { $id }, { …inputs })`. Inputs and outputs are typed from the Action definition.
16. **SDK v4.6.0**: Cross-scope Subflow and Custom Action references are supported — declare the dependency in `now.config.json` under `dependencies.<scope>.{subflows|actions}` and run `now-sdk dependencies` to pull type definitions before referencing them.
17. **SDK v4.7.0** — error handling: `wfa.flowLogic.tryCatch({ $id, annotation? }, { try: () => {...}, catch: () => {...} })`. Both `try` and `catch` must be arrow functions; the `catch` block runs only if the `try` block errors. `tryCatch` blocks can be nested.
18. **SDK v4.7.0** — parallelism: `wfa.flowLogic.doInParallel({ $id, annotation? }, () => {...}, () => {...})` runs blocks concurrently. It cannot be nested inside another `doInParallel`. Blocks may finish in any order — never rely on one branch reading another branch's output mid-run (use flow variables for that). To use a branch's action output AFTER the block, hoist it (item 25) instead of copying it into a flow variable.
19. **SDK v4.7.0** — array variables: `wfa.flowLogic.appendToFlowVariables({ $id }, params.flowVariables, { arrayVar: element })` appends element(s) to an `Array.Object` flow variable declared via `FlowArray({ elementType: FlowObject(...) })`. Accepts a single object, an array of objects, a data pill, or a template string.
20. **SDK v4.7.0** — stage tracking: declare `stages` in the Flow config with `FlowStage({ label, value, duration?, alwaysShow?, states? })` (import `FlowStage` from `@servicenow/sdk/automation`; `value` must equal the property key). Activate a stage in the body with `wfa.stage(params.stages.<key>)`; all subsequent actions belong to that stage until the next `wfa.stage()` call.
21. **SDK v4.11.0** — do-while retry loop: `wfa.flowLogic.doTheFollowing({ $id, label?, annotation? }, () => { ... })` repeats its body until an exit condition is met, with **do-while** semantics — the body always runs at least once and the condition is evaluated only after each run. The names are `doTheFollowing` and `until`; there is **no** function named "doTheFollowingUntil" (that string appears only as a documentation tag keyword), so do not write one.
22. **SDK v4.11.0** — the loop's condition is set by calling `wfa.flowLogic.until('<condition>')` as the body's **last statement**. It must be *called*, not returned: omitting it, or writing `return wfa.flowLogic.until(...)`, fails build-time validation. Because it lives inside the body, it may reference `wfa.dataPill(...)` outputs from actions declared earlier in that same body — which is the whole point of the construct.
23. **SDK v4.11.0** — choose `doTheFollowing` over `forEach` only when the iteration count is unknown at author time: polling a record or external system until its status changes, retrying a flaky action, or accumulating until a threshold. For a known, fixed-size collection, `forEach` remains correct. Guard every loop with a bounded signal (retry counter, timeout field, max-attempts flag) since the condition is checked *after* the body, and add a `waitForADuration` inside the body when polling so you do not spin tightly. `exitLoop` and `skipIteration` work inside its body exactly as in `forEach`; `endFlow` still terminates the whole flow, not just the loop.
24. **SDK v4.11.0** — dependent input checking: `Action()` return values now carry `rawInputs` alongside `rawOutputs`, so `wfa.action(...)` call sites type-check an input against the table chosen by a sibling input (a `sys_user` `updateRecord` rejects an `incident` record pill). `rawInputs` is inference machinery — never write it in an `Action()` config. Note the release note's "`Decimal` inside `FlowObject`/`FlowArray`" item is a build-pipeline fix, not a type change: `FlowTypes.d.ts` and `Decimal.d.ts` are byte-identical to v4.10.1.
25. **SDK v4.13.0 — output hoisting (CHANGED GUIDANCE).** The old rule "datapills inside a tryCatch/doInParallel block are not accessible outside it — use setFlowVariables" is retired. An arm or branch may now return the actions it exposes, and code after the block dot-walks them: `doInParallel` returns `output_0`, `output_1`, … (one per branch, by position), while `tryCatch` returns the merged outputs of both arms directly, and its `catch` arm receives the try arm's outputs as the `tryOutputs` parameter. Hoisting works ONLY out of `doInParallel` branches and `tryCatch` arms — an action nested inside `if`/`forEach`/`doTheFollowing` is never exposed, and only actions declared directly in the arm body can be returned.
26. **Hoisting must use the build-verified form.** (a) Return explicit property assignments — return { lookup: lookup } — never the shorthand "return { lookup }" shown in the SDK doc/JSDoc examples, which the Fluent build rejects (shorthand properties are not allowed in Fluent files). (b) Give every exposed action an explicit string-literal `uuid` in its instance config (a fresh random UUID per action): without it a catch-arm reference through `tryOutputs` fails to build with "Invalid pill reference", and references after the block build but point the pill at the tryCatch/doInParallel container instead of at the action. (c) If a `catch` arm does not use its parameter, omit it or name it "_tryOutputs" — an unused "tryOutputs" parameter fails the build. (d) Inside an arm, reach try-arm actions only through `tryOutputs`, never through the outer constant the `tryCatch` result is assigned to.
27. **`endFlow` placement.** `wfa.flowLogic.endFlow` must sit inside an `if`/`elseIf`/`else`, `forEach`, `doTheFollowing`, `doInParallel` or — SDK v4.13.0+ — `tryCatch` block (either the `try` or the `catch` arm); a top-level `endFlow` in the flow body is a build error. Ending the flow from a `catch` arm is the idiomatic way to stop after an unrecoverable failure.
