# Workflows: API (api-workflows and the app packages) How the workflows API is built: `packages/api-workflows` (the engine), `packages/api-headless-cms-workflows` (Headless CMS entries) and `packages/api-website-builder-workflows` (Website Builder pages). Paths are relative to the package root unless they start with `/packages`. Sections 1 to 10 describe the code as it is after phase 9c; sections 11 to 14 record what phases 8b, 9a, 9b and 9c added. The design is in `/docs/.bruno/specs/2026-10-05-workflows-refactor-design.md`, the reasons in `decisions.md`. Developer guides: `automations.md`, `ai-tools.md`, `notifications.md`. ## 1. Packages, entry points, registration - `api-workflows` exports `WorkflowsFeature` and the type augmentation of `src/types.ts` (`ICmsEntrySystem.workflow?: ReviewSystemWorkflow | null`, `IWorkflowsSecurityPermission`). `package.json` also exports `"./*"`; the app packages deep-import the engine's abstractions, domain types and errors. - `api-headless-cms-workflows` exports `CmsWorkflowsFeature`; `api-website-builder-workflows` exports `WebsiteBuilderWorkflowsFeature`. - `/packages/api-event-handler-core/src/registerApiRequestStack.ts` registers `WebsiteBuilderWorkflowsFeature`, then `WorkflowsFeature`, then `CmsWorkflowsFeature`, each once. The CMS feature no longer registers the engine itself. - Every one of the three returns early unless `FeatureFlags.get().isEnabled("advancedPublishingWorkflow")`, checked at register time, so no per-request licence guard exists. - `WorkflowsFeature` (`src/WorkflowsFeature.ts`) registers, in order: the four private models; notifications (transports, the review notification handlers); step types, automation definitions, the AI tool registry and the built-in AI tools; the workflow use cases; the review lifecycle (`ReviewLifecycleFeature`: `RoutingStepAssignmentResolver`, `ReviewStepReacher`, `ReviewSaver`, `ReviewTargetEditorService`) and the review use cases; routing; the assignment log; settings; the shared configuration use cases behind `editor`; the building blocks for the app wrappers (`WorkflowsPermissions`, `CurrentUserTeams`, `CurrentReviewViewer`, `CandidateReadAccess`); `WorkflowBypassService`; the step run services and task; and `WorkflowsSchemaFactory`. - `CmsWorkflowsFeature` registers its local `Workflows` feature (bindable-model checks on the engine's workflow before-save events), `CmsTargetFeature` (the `cms.*` adapter), `CmsHooksFeature` (CMS event handlers and model-delete decorators), `CmsWrappersFeature`, `CmsWorkflowsSchemaFactory` and a `CmsGraphQLSchemaFactory` instance that adds `CmsEntrySystem.workflow` to the CMS endpoints. - `WebsiteBuilderWorkflowsFeature` registers `WebsiteBuilderPageSchemaFactory` (`WbPageSystem.workflow` on `/graphql`), `WebsiteBuilderWorkflowsSchemaFactory`, `WbTargetFeature` (the `wb.page` adapter), `WbHooksFeature` and `WbWrappersFeature`. - `ai-powerups` registers the `ai` step type, its runner, the "Workflow review" capability and `workflows { listAiModels }` only when both `aiPowerups` and `advancedPublishingWorkflow` are on (`/packages/ai-powerups/src/api/Extension.ts`, `features/WorkflowReview/`). - Layout of `api-workflows/src`: `domain//` (types, errors, CMS model factories, pure functions, repository abstractions) and `features///` (`abstractions.ts`, implementation named after the class, `feature.ts`, `index.ts`). Areas: `workflow`, `review`, `assignment`, `routing`, `settings`, `config`, `identity`, `permissions`, `notifications`, `stepTypes`, `stepRun`, `automation`, `aiTools`, `bypass`. GraphQL is one file, `graphql/WorkflowsSchemaFactory.ts`. ## 2. Domain model and storage All workflow data lives in four private CMS models (`src/constants.ts`), registered as `ModelFactory` implementations so the CMS builds them with the tenant's model list: | Model id | Factory | Holds | |---|---|---| | `wbyWorkflow` | `domain/workflow/workflow.model.ts` | Workflows: `name`, `models[]`, `steps[] { id, title, color, description, type, notifications[{id}], config (json) }` | | `wbyWorkflowReview` | `domain/review/review.model.ts` | Reviews: target reference, `isActive`, `state`, the current-step fields, `targetContext`, a `workflow { name, models }` snapshot, the step snapshot with run data, `requester`, `cancelledBy`, `lastChangedOn` | | `wbyWorkflowAssignment` | `domain/assignment/assignment.model.ts` | The assignment log: one record per outcome or skip (`reviewId`, `workflowId`, `stepId`, `userId`, `assignedOn`, `source`, `ruleId`, `by`, `reason`, `kind`) | | `wbyWorkflowSettings` | `domain/settings/settings.model.ts` | One entry per tenant (id `settings`): `exclusions[] { userId, reason, endsOn }` | - Workflow (`domain/workflow/types.ts`): `WorkflowValues { id, name, models, steps }`; `Workflow` adds `createdOn`, `savedOn`, `createdBy`, `savedBy`. `models` holds namespace ids (`cms.` or `wb.page`), exactly one in v1 (D15). The id is chosen by the caller and stored as revision 1 (`createIdentifier({ id, version: 1 })`). A step is `WorkflowStep { id, title, color, description?, type, notifications, config }`; `config` is validated by the step type (`ReviewStepConfig { teams, assignment { strategy, allowManualPick, rules } }` for `review`). Step type ids: `review`, `automation` (engine), `ai` (ai-powerups), `domain/workflow/stepTypes.ts`. - Review (`domain/review/types.ts`): `ReviewData` with `state: "inProgress" | "approved" | "rejected" | "cancelled"`, steps with `state: "pending" | "awaiting" | "inReview" | "approved" | "rejected" | "failed"`, `owner: Actor | null`, `candidateTeamIds`, `assignment`, `taskId`, `runs`, `issues`. `Actor { type: "user" | "ai" | "automation", id, displayName, identityType? }`; AI and automation actors carry the requester's id (D58). `TargetContext { folder, modelId, title, author }` comes from the target adapter. The requester is stored as `requester` because `createdBy` is a reserved CMS field id; the domain calls it `createdBy`. - The current-step fields (`currentStepId`, `currentStepState`, `currentStepType`, `currentOwnerId`, `currentCandidateTeamIds`) are top-level so lists and the least-loaded strategy can query them (D19). - `system.workflow` on the target revision is `ReviewSystemWorkflow { workflowId, reviewState, stepId, stepName, stepState }`, derived by `Review.getSystemWorkflow()` and written by the app's `ReviewTargetSync` through the CMS `UpdateEntrySystemUseCase`. - Repositories (`domain/*/abstractions/`, implementations in `features/*/shared/`) wrap the CMS entry use cases on the private models: `WorkflowRepository` (get, list, create, update, delete), `ReviewRepository` (get, `getActiveByTarget`, counts and lists by workflow, by owners and by target, the paged list index, `save`, `delete`), `AssignmentRepository` and `WorkflowSettingsRepository`. Lists read the index; reads that decide something confirm rows from primary storage (R18), because an OpenSearch row can be stale. ## 3. Review lifecycle The aggregate is `domain/review/Review.ts`. It holds no identity: every transition takes the acting `Actor` and returns a `Result`; each has a `check*` twin used for the viewer flags. - Request (`RequestReviewUseCase`): finds the workflow bound to the namespace (`ReviewWorkflowNotFoundError` when none), refuses a revision that already has an active review (`ReviewAlreadyActiveError`, one active review per revision, D23), loads the target through the adapter, validates the title and the picks, snapshots the workflow's steps, then reaches step 1. - Reach (`ReviewStepReacher`): a `review` step is routed (section 8). With an owner it goes `pending → inReview`; without one it goes to the pool as `awaiting`. An `automation` or `ai` step is reached with `reachRun`: the engine triggers the step run task as the requester (`StepRunReachService`, `IdentityContext.withIdentity`), the AI or automation actor owns the step at once and its `taskId` is stored. - Start: a member of the step's candidate teams takes an `awaiting` step (`awaiting → inReview`, source `poolStart`). Take over: another candidate takes an `inReview` user-owned step, optionally without telling the previous owner (`notifyPreviousOwner`, D111). Reassign: a user with `reassign` gives an `awaiting` or user-owned `inReview` step to a chosen member. AI and automation steps cannot be taken over or reassigned. The requester can never own a step of their own review. - Approve: the owner approves; the next step is reached in the same save, and the last approval makes the review `approved`. Reject: the owner rejects with a comment of at least 10 characters; the review becomes `rejected` and is final for that revision (D10). - Fail and restart: a run that fails, or a step that `StuckStepService` finds stuck on a single read, is `failed` with a fixed reason; the review stays in progress. Restart moves the failed attempt into `runs` and reaches the step again. - Cancel: allowed while in progress; sets `isActive: false`, `state: "cancelled"` and `cancelledBy`. - Single save path (`ReviewSaver`): prepare the review-level fields, persist, write the assignment records of the recorded facts (a failed write is only logged), sync `system.workflow`, then publish one event per fact. A failed sync keeps the save and the events and returns `ReviewTargetSyncError`; a failed persist aborts the step run tasks the save would have started. - Events (`features/review/events.ts`): `Workflows/Review/{Requested, StepReached, StepStarted, StepTakenOver, StepReassigned, StepApproved, StepRejected, StepFailed, StepRestarted, Approved, Cancelled}`, each with an `*EventHandler` abstraction. Workflow events: `Workflows/Workflow/{Before,After}{Create,Update,Delete}`. The engine's notification handlers subscribe to the review events (`features/notifications/handlers/`); the CMS package subscribes to the workflow before-create and before-update events to refuse models that cannot be bound. - Publishing stays a separate, manual action, gated by the app hooks (section 9). ## 4. Use cases The engine's use cases are internal (D132): they take an explicit actor or viewer and check no permissions. Only the app wrappers, the shared configuration use cases and the AI and automation tasks call them. - Workflows: `StoreWorkflowUseCase` (create or update through one validation path, optimistic `savedOn` check on update), `DeleteWorkflowUseCase` (refused while reviews are in progress), `GetWorkflowUseCase`, `ListWorkflowsUseCase`, `GetBoundWorkflowUseCase` (the workflow of a namespace or `null`), `ReadableBlockingReviewsService`. - Reviews: `RequestReviewUseCase`, `GetReviewUseCase`, `GetTargetReviewUseCase`, `ListReviewsUseCase`, `ListTargetReviewsUseCase`, `StartReviewStepUseCase`, `TakeOverReviewStepUseCase`, `ReassignReviewStepUseCase`, `RestartReviewStepUseCase`, `ApproveReviewStepUseCase`, `RejectReviewStepUseCase`, `CancelReviewUseCase`, `CancelTargetReviewsUseCase` (the cancel-for-delete path), `DeleteTargetReviewsUseCase` (after a permanent delete of the content; also cleans up the kept tasks), `ListReviewCandidateTeamsUseCase`, `ResolveReviewUserNameUseCase`, `ListReviewAssignmentsUseCase`. - Routing: `InspectRoutingUseCase`, `ListStepCandidatesUseCase`, `RoutingEvaluatorService`, `RoutingStrategyService`. - Settings: `GetWorkflowSettingsUseCase`, `SaveWorkflowSettingsUseCase`. - Step runs: `GetReviewStepRunUseCase`, `StepRunReachService`, `StepRunStaleCheckService`, `StuckStepService`, `ReviewTaskAbortService`, `StepRunnerRegistryService`. - Shared configuration (`features/config/`, behind `editor`, called by the `workflows` GraphQL root): `GetWorkflowSettingsForEditorUseCase`, `SaveWorkflowSettingsForEditorUseCase`, `ListWorkflowStepTypesUseCase`, `ListAutomationDefinitionsUseCase`, `ListWorkflowAiToolsUseCase`, `ListWorkflowNotificationTransportsUseCase`, `ListWorkflowUsersUseCase`, `ListWorkflowTeamsUseCase`. - App wrappers (`features/wrappers/` in each app package), one per operation: CMS `CmsEntry...UseCase` (for example `RequestCmsEntryReviewUseCase`, `StoreCmsEntryWorkflowUseCase`, `ListCmsEntryReviewsUseCase`, `ListCmsEntryWorkflowModelsUseCase`, `ListCmsEntryBlockingReviewsUseCase`), WB `WebsiteBuilderPage...UseCase`. They read the identity, build the actor or viewer, check the `workflows` permission and the target access, check that the namespace belongs to their app (another app's workflow or review is not found, R46), then call the engine. `CmsEntryReviewGuardService` and `WbPageReviewGuardService` hold the checks every review action shares (signed in, own namespace, read access to the target). ## 5. Permissions - The stored permission is `{ name: "workflows", editor?: true, reassign?: true }`; full access is `workflows.*`. `WorkflowsPermissions` (`features/permissions/WorkflowsPermissions/`) returns `WorkflowsPermissionSet { fullAccess, editor, reassign }`; full access sets both flags. Details in section 14. - Who may do what (checked in the wrappers and the shared configuration use cases; the domain rules on top are in the aggregate): | Action | Needs | |---|---| | List and get workflows | any signed-in identity (D78) | | Store and delete a workflow, the CMS model list, routing inspection, folder exists, every `workflows` root operation | `editor` | | Get a review, get the target review | read access to the target | | Request a review, list the candidates for a request | write access to the revision (D77) | | Start, take over, approve, reject | read access to the target; candidate team membership and ownership in the engine | | Cancel, restart | read access to the target; the requester or `reassign` | | Reassign, list the candidates for a reassign | read access to the target and `reassign` | | Failed steps list | `reassign` (D112) | | Step run details | read access to the target and `editor` or `reassign` | | Cancel for delete | delete access to the content; no cancel right needed (D134) | - Lists skip rows whose target the viewer cannot read; a row carries the viewer's flags (`WorkflowsViewerFlags`). Skip entries of the assignment log and exclusion reasons are shown only to viewers with `editor` or `reassign` (D89, D97). - No identity is `Workflows/NotAuthenticated`; a refusal is `Workflows/NotAuthorized`, whose message names the action. ## 6. GraphQL All workflows operations are on `/graphql`. Responses are `{ data, error: WorkflowsError }`, lists add `meta: WorkflowsListMeta { cursor, hasMoreItems }`. `WorkflowsError` is `{ code, message, data, stack }`. - Shared types (`api-workflows/src/graphql/WorkflowsSchemaFactory.ts`, `SHARED_TYPE_DEFS`): `WorkflowsWorkflow`, `WorkflowsStep`, `WorkflowsWorkflowInput`, `WorkflowsStepInput`, `WorkflowsReview`, `WorkflowsReviewStep`, `WorkflowsReviewWithFlags`, `WorkflowsViewerFlags`, `WorkflowsActor`, `WorkflowsUser`, `WorkflowsTeam`, `WorkflowsAssignmentEntry`, `WorkflowsStepRun`, `WorkflowsStepRunInfo`, `WorkflowsAiIssue`, `WorkflowsStepCandidate`, `WorkflowsRoutingInspection` (with its trace and skip types), `WorkflowsBlockingReview`, the enums `WorkflowsReviewState`, `WorkflowsStepState`, `WorkflowsReviewListKind` (`assignedToMe`, `pool`, `teamInReview`, `myRequests`, `failedSteps`) and `WorkflowsReviewListSort` (`lastChangedOn_ASC`, `lastChangedOn_DESC`), and the inputs `WorkflowsReviewListWhere`, `WorkflowsReviewPickInput` and `WorkflowsReviewsForDeleteAction` (`trash`, `delete`). `WorkflowsReviewStep.candidateTeams` and `WorkflowsAssignmentEntry.userDisplayName` have resolvers that never fail the read. - `workflows` root (`Query.workflows`, `Mutation.workflows`): `getSettings(includeExpired)`, `listStepTypes`, `listAutomationDefinitions`, `listAiTools`, `listNotificationTransports`, `listUsers(search, ids, limit, teamIds)`, `listTeams(search, ids, limit)`, `updateSettings(data)`; ai-powerups adds `listAiModels`. - CMS (`api-headless-cms-workflows/src/graphql/CmsWorkflowsSchemaFactory.ts`, on `CmsQuery` / `CmsMutation`, which `/graphql` exposes as `cms`): queries `listCmsEntryWorkflows`, `getCmsEntryWorkflow`, `getCmsEntryReview`, `getCmsEntryTargetReview`, `getCmsEntryReviewStepRun`, `listCmsEntryReviews`, `listCmsEntryBlockingReviews`, `listCmsEntryWorkflowModels`, `listCmsEntryStepCandidates`, `listCmsEntryReviewStepCandidates`, `inspectCmsEntryRouting`, `cmsEntryFolderExists`; mutations `storeCmsEntryWorkflow(data, savedOn)`, `deleteCmsEntryWorkflow`, `requestCmsEntryReview(modelId, revisionId, title, picks)`, `startCmsEntryReviewStep`, `takeOverCmsEntryReviewStep(..., notifyPreviousOwner = true)`, `reassignCmsEntryReviewStep`, `restartCmsEntryReviewStep`, `approveCmsEntryReviewStep`, `rejectCmsEntryReviewStep`, `cancelCmsEntryReview`, `cancelCmsEntryReviewsForDelete`. The CMS read endpoints get `CmsEntrySystem.workflow: CmsEntrySystemWorkflow` (`graphql/entrySystemSchema.ts`). - Website Builder (`api-website-builder-workflows/src/graphql/WebsiteBuilderWorkflowsSchemaFactory.ts`, on `WbQuery` / `WbMutation`, the `websiteBuilder` root): the same set named `...WebsiteBuilderPage...` (`listWebsiteBuilderPageWorkflows`, `getWebsiteBuilderPageTargetReview(revisionId)`, `requestWebsiteBuilderPageReview(revisionId, title, picks)`, `cancelWebsiteBuilderPageReviewsForDelete(pageId, revisionId, action)`, `websiteBuilderPageFolderExists(id)` and so on), without the model list and the blocking-reviews query, and with `WbPageReviewListWhere` for list filters. `WbPageSystem.workflow: WbPageSystemWorkflow` comes from `WebsiteBuilderPageSchemaFactory`. - Resolvers call one wrapper or configuration use case each. On a failure whose error carries a storage `source`, the resolver logs that source through `Logger` and returns the error; the client gets only the error's fixed message and code. ## 7. Errors Every error is a `BaseError` with a stable `code` (`domain/*/errors.ts`): - Workflow: `Workflows/Workflow/NotFound`, `Conflict` (the `savedOn` check, names who saved and when), `Validation` (`data { stepId, ruleId, field, workflowId }`, section 12), `Persistence`, `HasActiveReviews` (exact count; the wrapper lists up to 5 readable blocking reviews). - Review: `Workflows/Review/NotFound`, `Persistence`, `Validation`, `InvalidState`, `StepNotCurrent`, `StepRunNotFound`, `ActorNotUser`, `RequesterCannotReview`, `NotCandidate`, `AlreadyOwner`, `NotOwner`, `StepNotTakeable`, `StepNotReassignable`, `ReassignTargetInvalid`, `AlreadyActive`, `WorkflowNotFound`, `TargetNotFound`, `TargetSync`, `TargetLocked` (save block), `PublishBlocked`, `ActiveReviewOnTrash`; `Workflows/ReviewTarget/EditorError` for the AI tools' target editor. - Others: `Workflows/NotAuthenticated`, `Workflows/NotAuthorized`, `Workflows/Assignment/Persistence`, `Workflows/Settings/Validation`, `Workflows/Settings/Persistence`, `Workflows/Routing/Dependency`; in `api-headless-cms-workflows`, `Workflows/Model/BoundToWorkflow` (model delete refused while a workflow binds it). - The persistence errors (`WorkflowPersistenceError`, `ReviewPersistenceError`, `AssignmentPersistenceError`, `WorkflowSettingsPersistenceError`) and `RoutingDependencyError` have one fixed message per class and only the storage error's `code` in `data.cause`. The storage error itself sits on a non-enumerable `source` field (`domain/hasErrorSource.ts`), so it never reaches a client and the resolvers log it. The four configuration list use cases (step types, automation definitions, AI tools, notification transports) report their own failures as `WorkflowPersistenceError`, so a client sees that class's fixed message for them. ## 8. Routing, settings, step types and step runs - Routing (spec 6): `RoutingStepAssignmentResolver` evaluates a review step when it is reached. Rules are ordered, first match wins; conditions are requester user, requester team and folder (with descendants, through the app's `ReviewTargetFolderChain`); a target is a user or a team. Without a matching rule the strategy picks: `none` (pool), `roundRobin` or `leastLoaded` (load counted from in-review reviews per owner). The order is the requester's pick (when the step allows one, `allowManualPick`), the rules, the strategy, then the pool; any failure falls through to the pool. The requester, non-members, excluded users (settings) and users without read access to the target (`CandidateReadAccess`) are skipped with a fixed reason (`domain/routing/reasons.ts`). Each decision and skip is written to the assignment log. `InspectRoutingUseCase` runs the same evaluator in inspector mode (section 13). - Teams: `CurrentUserTeams` reads the current user's teams for the viewer. `ListWorkflowUsersUseCase`, `ListWorkflowTeamsUseCase` and `ReviewStepType` read `TEAMS_FEATURE_FLAG` (`advancedAccessControlLayer.teams`) on each call (D176, section 13). - Settings: the exclusion list, one entry per tenant (section 14). - Step types (`features/stepTypes/`): `StepType` implementations registered in `StepTypeRegistryService`: `ReviewStepType`, `AutomationStepType`, and `AiStepType` from ai-powerups. Each validates its config and reports availability. - Step runs (`features/stepRun/`): one private task, `workflowsStepRun` (`WorkflowStepRunTaskDefinition`), dispatches to the `StepRunner` of the step's type (`AutomationStepRunner` in the engine, the AI runner in ai-powerups). The task is kept after the step ends and cleaned up with the review (D161). `StepRunStaleCheckService` guards against a run whose step moved on; `StuckStepService` fails a step whose task ended without a result, on single reads only. - Bypass: `WorkflowBypassService` is a request-scoped context that `AutomationStepRunner` and the AI tool `updateTargetFields` set, so their own content save passes the save block; no other rule reads it. ## 9. App adapters and hooks - Ports the engine resolves per namespace (`features/review/`): `ReviewTargetLoader`, `ReviewTargetSync`, `ReviewTargetReadAccess`, `ReviewTargetFolderChain`, `ReviewTargetEditor` (AI tools), and `ReviewTargetLink` (notification links). The CMS registers `CmsEntryReviewTarget*` (`features/target/`), WB `WbPageReviewTarget*`. The last registered match wins; none matching means nothing to load, sync or read. - CMS hooks (`api-headless-cms-workflows/src/features/hooks/`): `NullReviewStateOnRevisionCreate` (a new revision starts without `system.workflow`, also for pages), `BlockUpdateWhileInReview` (save block on bound models, also for pages), `RequireApprovedReviewOnPublish` and `RequireApprovedReviewOnRepublish`, `BlockMoveWhileInReview` and `BlockFolderChangeWhileInReview`, `BlockDeleteWhileInReview`, `BlockRevisionDeleteWhileInReview`, `BlockDeleteMultipleWhileInReview`, `DeleteReviewsOnEntryDelete`, `DeleteReviewsOnRevisionDelete`, `DeleteReviewsOnEntriesDeleteMultiple`, and the model delete decorators `DeleteModelBoundToWorkflowDecorator`, `FullyDeleteModelBoundToWorkflowDecorator`, `DeleteModelTaskBoundToWorkflowDecorator`. - WB hooks (`api-website-builder-workflows/src/features/hooks/`): `RequireApprovedReviewOnPagePublish`, `BlockPageMoveWhileInReview`, `BlockPageTrashWhileInReview`, `BlockPageDeleteWhileInReview`, `BlockPageRevisionDeleteWhileInReview`, `DeleteReviewsOnPageDelete`, `DeleteReviewsOnPageRevisionDelete`. - The rules act only on bound models; lookup failures block (fail closed). A revision publishes only with its active review approved. Trash and delete are refused while a review is in progress; the admin confirms through the cancel-for-delete operation and repeats the action. Review cleanup after a permanent delete is logged on failure, never thrown. Details per hook are in `integrations.md`. ## 10. Tests - `api-workflows/__tests__/` has one folder per area (`workflow`, `review`, `routing`, `assignment`, `settings`, `config`, `permissions`, `identity`, `notifications`, `stepRun`, `stepTypes`, `automation`, `aiTools`, `bypass`, `domain`, `graphql`) plus `registration.test.ts` and `types.test.ts`; `__helpers/` holds the fakes (target ports, users, teams, task service, websockets) and `teamsFlag.ts`. - `api-headless-cms-workflows/__tests__/` (`wrappers`, `hooks`, `target`, `graphql`, `workflows`, `utils`) and `api-website-builder-workflows/__tests__/` (`wrappers`, `target`, `graphql`) test the wrappers, hooks and resolvers against the real engine. - `ci.config.json` runs `ddb` and `ddb-os,ddb`. The test handler loads the full test licence, so `advancedPublishingWorkflow` and teams are on by default. ## 11. Phase 8b additions (as built) - **Change message (D160).** `ReviewWebsocketSender` (`src/features/notifications/ReviewWebsocketSender/`) holds the tenant-scoped, batched send loop that `ReviewNotifierService` used to own (current tenant only, ten recipients at a time, never throws); `ReviewNotifierService` and the new `ReviewChangeNotifierService` both send through it. Four handlers (`Review{Requested,StepStarted,StepApproved,StepRestarted}ChangeNotifications`, `src/features/notifications/handlers/`; a failure sends none, its owner is AI or automation and the requester gets the `failed` notification) send the action `workflows.reviewChanged` (`WORKFLOWS_REVIEW_CHANGED_WEBSOCKET_ACTION`, data `WorkflowReviewChangedWebsocketData`, `src/domain/notifications/`). Recipients come from `getReviewChangeRecipients(review, actor)`: the requester and the current user owner, minus the acting user; `stepApproved` sends only while the review is `inProgress`. - **Kept run tasks (D161).** `WorkflowStepRunTaskDefinition` has no `selfCleanup`. `DeleteTargetReviewsUseCase` calls `CleanupTaskSubtreeUseCase` for every `taskId` and `runs[].taskId` of every deleted review after its abort; a failing cleanup is logged ("Could not clean up the background task of a deleted review.") and the delete still succeeds. Cancel only aborts. - **Step run read (D161).** `GetReviewStepRunUseCase` (`src/features/stepRun/GetReviewStepRun/`, internal) returns `ReviewStepRunInfo | null` and fails with `ReviewStepRunNotFoundError` (`Workflows/Review/StepRunNotFound`) for a task that is not the step's current task or one of its `runs`. `canViewStepRunByPermission(viewer)` (`src/domain/review/`) is `editor || reassign`. The type `WorkflowsStepRunInfo` is in `WorkflowsSchemaFactory`; the queries `getCmsEntryReviewStepRun` (`api-headless-cms-workflows`) and `getWebsiteBuilderPageReviewStepRun` (`api-website-builder-workflows`) wrap the engine behind the apps' guards. - **Blocking reviews (D164).** `listCmsEntryBlockingReviews(modelId, entryIds)` (`api-headless-cms-workflows`, `ListCmsEntryBlockingReviewsUseCase`): at most `BLOCKING_REVIEWS_MAX_IDS` (200) ids, batches of `BLOCKING_REVIEWS_CONCURRENCY` (10), only reviews `inProgress` of entries the viewer can read (`CmsEntryAccess.canRead`), the shared type `WorkflowsBlockingReview`. ## 12. Phase 9a additions (as built) - **Validation error data (D165).** `WorkflowValidationError` (`src/domain/workflow/errors.ts`) takes an optional second argument, a partial `WorkflowValidationErrorData { stepId, field, workflowId }` (each `string | null`, default `null`), exposed as `data`. The sites that set it: `WorkflowValidator` (name, models, steps, step id, title), `StoreWorkflowUseCase` (an unknown step type sets `field: "type"`, a user rule target outside the step's teams sets `config.assignment.rules`, the duplicate model sets `field: "models"` and the other workflow's `workflowId`), `ReviewStepType` (`config.teams`, `config.assignment.rules`, the review config zod path), `AutomationStepType` (`config.automationId`, `config.settings`, `config.settings.`), `AiStepType` in `ai-powerups` (`config.instructions`, `config.model`, `config.tools`, the config zod path), and the CMS and WB before-create and before-update handlers and app-mismatch guards (`field: "models"`). The server does not validate the colour or the notification ids, so it never names them. Codes and messages did not change. `parseAutomationSettingsIssue(schema, settings)` (`src/domain/automation/`) returns `Result`; `parseAutomationSettings` and its callers are unchanged. - **`workflows.listTeams` (D166).** `ListWorkflowTeamsUseCase` (`src/features/config/ListWorkflowTeams/`, built like `ListWorkflowUsers`) lists teams with api-core `ListTeamsUseCase` and counts members with one `ListUsersUseCase` call per request, both inside `identityContext.withoutAuthorization`; the `editor` check runs outside it. `search` filters by name in memory, `ids` reports unknown ones in `missingIds` and refuses more than 200 (`Too many team ids.`), `limit` defaults to 50 and is capped at 200; a search is sorted by name and an `ids` request keeps the request order. The GraphQL types are `WorkflowsTeamListResponse`, `WorkflowsTeamListResult { teams, missingIds }` and `WorkflowsTeamSummary { id, name, memberCount }`; `WorkflowsTeam` stays for review steps. - **`changesContent` on AI tools (D167).** `WorkflowAiTool` has an optional `changesContent` (`ReadTargetTool` false, `UpdateTargetFieldsTool` true); `ListWorkflowAiToolsUseCase` returns it as a boolean (absent is false) and `WorkflowsAiTool.changesContent` is `Boolean!`. ## 13. Phase 9b additions (as built) - **`workflows.listUsers` team scope (D170).** `ListWorkflowUsersUseCase` (`src/features/config/ListWorkflowUsers/`) takes `teamIds` and returns `WorkflowListedUser { id, displayName, teamIds }` (GraphQL `WorkflowsListedUser`; `WorkflowsUser` stays for owners and candidates). It lists the users with the api-core admin users use case (the `teams_in` filter) and reads each user's team ids from the listed user; an `ids` lookup ignores `search`, `limit` and `teamIds`. It injects the api-core `FeatureFlags` and reads `TEAMS_FEATURE_FLAG` (`advancedAccessControlLayer.teams`, `src/constants.ts`) on every call: with teams off it queries no teams, returns `[]` as `teamIds` and returns no users for a `teamIds` request. - **Rule error data (D171).** `WorkflowValidationErrorData` gained `ruleId`. The three rule messages are constants in `src/domain/workflow/ruleErrorMessages.ts`, used by `ReviewStepType`, `StoreWorkflowUseCase` and `InspectRoutingUseCase`; rule-level failures set `stepId`, `ruleId` and the field `config.assignment.rules.target`. `ReviewStepType.validate` (which already rejected a team target outside the step's teams on save) now reports it with the rule-neutral message, the field and the `ruleId`, and `InspectRoutingUseCase` runs the same check; `StoreWorkflowUseCase` keeps the user-target membership check. The no-target message names the step on save and has no step title in the inspector. Schema issues keep `config.assignment.rules..`. - **`inspectRouting` (D172).** The trace lists every rule (`WorkflowsRoutingTraceOutcome` gained `notEvaluated`), `WorkflowsRoutingTraceEntry.failedConditions` lists `WorkflowsRoutingCondition` values (`requesterUser`, `requesterTeam`, `folder`), and `WorkflowsRoutingInspection` gained `narrowedTeamId`, `candidateIds` (the first `INSPECTION_CANDIDATE_LIMIT` = 3) and `candidateCount`. `RoutingEvaluateParams.explain` switches the evaluator to inspector mode (every condition of every rule evaluated, the rules after the deciding one walked and marked `notEvaluated`); live assignment does not set it and stays lazy. - **Teams off (D176).** `ReviewStepType` reports `available: false` with `unavailableReason` "Teams are not enabled." when the flag is off; `ListWorkflowTeamsUseCase` returns `{ teams: [], missingIds: [] }` without querying (the `editor` gate and the 200-ids refusal stay). - **Tests.** `__tests__/__helpers/teamsFlag.ts` is a `FeatureFlags` decorator that turns the teams flag on or off for a test; teams are ON by default in API tests (the test handler loads the full test licence and teams are licence-governed), so a teams-off test turns them off explicitly (`teams: false` of the GraphQL test `createApi`, or `setTeamsFlag(container, false)`). ## 14. Phase 9c: settings and permissions (as built) Phase 9c changed no API code (Q65); this section records what the admin settings page and the role form rely on. - **Settings types.** `WorkflowSettings { exclusions: WorkflowExclusion[] }` and `WorkflowExclusion { userId; reason?; endsOn? }` (`src/domain/settings/types.ts`; `endsOn` an ISO datetime in UTC). GraphQL: `WorkflowsSettings { exclusions }`, `WorkflowsExclusion { userId, reason, endsOn: DateTime }`, the input `WorkflowsSettingsInput { exclusions: [WorkflowsExclusionInput!]! }` with `endsOn: String`, and the response `WorkflowsSettingsResponse { data, error }`. - **Operations.** `workflows { getSettings(includeExpired: Boolean) }` returns only the active entries (`endsOn` missing or later than now, `filterActiveExclusions` in `src/domain/settings/`) unless `includeExpired` is true; the admin page always sends `true`, because `workflows { updateSettings(data) }` validates and replaces the whole record and returns it as saved, expired entries included (`SaveWorkflowSettingsUseCase` returns `repository.save(...)`). Both need `editor` (`GetWorkflowSettingsForEditorUseCase`, `SaveWorkflowSettingsForEditorUseCase` in `src/features/config/`): a refusal is `Workflows/NotAuthorized` ("You are not allowed to view the workflow settings." or "You are not allowed to change the workflow settings."), no identity is `Workflows/NotAuthenticated`. Last save wins, no version check (D106). - **Validation** (`WorkflowSettingsValidator`, `src/domain/settings/`; code `Workflows/Settings/Validation`, `data: { userId }`): "Every exclusion needs a user.", "This user is already in the list. Edit it instead." (D105) and `The end date "{endsOn}" is not a valid date.`. It trims `userId` and `reason`, drops an empty reason, normalises `endsOn` with `toISOString()`, accepts a past `endsOn`, has no reason length cap and does not check that the user exists (the admin trims and caps the reason at 500 characters, D180). A storage failure is `Workflows/Settings/Persistence` with a fixed message and only the storage error's code in `data.cause` (section 7). - **Permission shapes and the checker.** The stored `workflows` permission is `{ name: "workflows", editor?: true, reassign?: true }` or full access `{ name: "workflows.*" }`; the 9c role form writes exactly these (D182), and an older role's `{ name: "workflows.*", editor: true }` reads the same. `WorkflowsPermissions` (`src/features/permissions/WorkflowsPermissions/`) treats any entry whose stored name matches `workflows.*` as full access (`IdentityContext.getPermission` matches the stored name as a pattern, so `workflows.*`, `*` and other patterns such as `workflows*` or `*.*` grant it) and otherwise grants `editor` or `reassign` when any `workflows` entry (one per role) has that flag `=== true`; it reads the identity's permissions on every call (`IdentityContext` caches them per identity).