@gravity-rail/sdk 8.2.0 → 9.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- package/dist/{agent_standing_job-CQqd8LDQ.d.ts → agent_team-C4ZYR_m1.d.ts} +731 -354
- package/dist/{agent_standing_job-DfjwGfg_.d.cts → agent_team-C6FdNgYH.d.cts} +731 -354
- package/dist/{chunk-U2U5X3LY.js → chunk-7LQYEV5Y.js} +245 -226
- package/dist/chunk-7LQYEV5Y.js.map +1 -0
- package/dist/{chunk-IIIRXFKG.js → chunk-MWTQXZGB.js} +1 -1
- package/dist/chunk-MWTQXZGB.js.map +1 -0
- package/dist/{chunk-6KPGCPGW.js → chunk-ZJJDZUAK.js} +40 -1
- package/dist/chunk-ZJJDZUAK.js.map +1 -0
- package/dist/{client-Bd-zXY42.d.ts → client-DVF3qwNq.d.ts} +2380 -1113
- package/dist/{client-BGGgZhKg.d.cts → client-DwslF70Y.d.cts} +2380 -1113
- package/dist/helpers.cjs +41 -0
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +2 -2
- package/dist/helpers.d.ts +2 -2
- package/dist/helpers.js +5 -1
- package/dist/helpers.js.map +1 -1
- package/dist/index.cjs +290 -305
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -23
- package/dist/index.d.ts +7 -23
- package/dist/index.js +14 -84
- package/dist/index.js.map +1 -1
- package/dist/internal.cjs +252 -230
- package/dist/internal.cjs.map +1 -1
- package/dist/internal.d.cts +775 -999
- package/dist/internal.d.ts +775 -999
- package/dist/internal.js +12 -9
- package/dist/internal.js.map +1 -1
- package/dist/member-import-BpcX-swC.d.ts +92 -0
- package/dist/member-import-CA9YWv3Y.d.cts +92 -0
- package/dist/realtime.cjs +109 -54
- package/dist/realtime.cjs.map +1 -1
- package/dist/realtime.d.cts +7 -2
- package/dist/realtime.d.ts +7 -2
- package/dist/realtime.js +109 -54
- package/dist/realtime.js.map +1 -1
- package/dist/schemas.cjs +24 -6
- package/dist/schemas.cjs.map +1 -1
- package/dist/schemas.d.cts +53 -39
- package/dist/schemas.d.ts +53 -39
- package/dist/schemas.js +24 -7
- package/dist/schemas.js.map +1 -1
- package/dist/{tasks-2LhXIwL8.d.ts → tasks-BGLfmf5y.d.ts} +69 -904
- package/dist/{tasks-BTURuIlD.d.cts → tasks-BZb3rt5m.d.cts} +69 -904
- package/package.json +10 -9
- package/dist/chunk-6KPGCPGW.js.map +0 -1
- package/dist/chunk-IIIRXFKG.js.map +0 -1
- package/dist/chunk-U2U5X3LY.js.map +0 -1
- package/dist/member-import-4VSE3yYo.d.cts +0 -46
- package/dist/member-import-BQDFoSyf.d.ts +0 -46
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/generated/organization_webhook.ts","../src/types/generated/workspace_selection.ts","../src/types/generated/bundle_contract.ts","../src/types/generated/bundle_publication.ts","../src/types/generated/installation_contract.ts","../src/workspace-builder/resource.ts","../src/workspace-builder/automation.ts","../src/workspace-builder/forms.ts","../src/workspace-builder/journeys.ts","../src/workspace-builder/workflows.ts","../src/workspace-builder/orchestrator.ts","../src/types/generated/event_type.ts","../src/types/generated/ref.ts"],"sourcesContent":["/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: organization_webhook\n */\n\nimport type { OrgWorkspaceScopeResponse } from './workspace_scope';\nimport type { OrgWorkspaceScopeRequest, WorkspaceScopeMode } from './workspace_selection';\n\n/**\n * Hide history, retaining dedupe keys and failure evidence. In-flight sends finish.\n */\nexport interface ClearOrgWebhookDeliveriesRequest {\n failedOnly?: boolean;\n}\n\n/**\n * Create an organization webhook endpoint.\n */\nexport interface CreateOrgWebhookEndpointRequest {\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n /**\n * @minLength 1\n * @maxLength 2048\n */\n url: string;\n /** @minItems 1 */\n eventTypes: string[];\n workspaceScope: OrgWorkspaceScopeRequest;\n signingSecret?: string | null;\n}\n\n/**\n * Create response: the ONE place the plaintext signing secret appears.\n *\n * Generated server-side when the client omits ``signingSecret``. This\n * response is the only time it is readable; every later read is masked.\n * The configured ``url`` is likewise echoed only here — the configurator\n * typed it moments ago; later reads carry the destination fingerprint.\n */\nexport interface CreatedOrgWebhookEndpointResponse {\n id: number;\n uuid: string;\n name: string;\n destinationHost: string;\n destinationDigest: string;\n status: string;\n eventTypes: string[];\n workspaceScope: OrgWorkspaceScopeResponse;\n includePayload?: boolean;\n signingSecretSet: boolean;\n /** @minLength 1 */\n signingSecret: string;\n statusHistory: OrgWebhookEndpointStatusHistoryEntry[];\n recentFailures?: OrgWebhookRecentFailure[];\n deliveryHealth: OrgWebhookDeliveryHealth;\n createdAt: string;\n updatedAt: string;\n url: string;\n}\n\n/**\n * Deliberately empty — discarding the pending backlog takes no parameters.\n *\n * Same CSRF barrier as ``ReplayOrgWebhookDeliveryRequest``: clients send\n * ``{}``.\n */\nexport interface DiscardPendingOrgWebhookDeliveriesRequest { [key: string]: unknown }\n\nexport interface OrgWebhookAttemptDiagnosticResponse {\n destinationHost?: string | null;\n destinationDigest?: string | null;\n attemptNumber: number;\n requestBody: OrgWebhookAttemptDiagnosticResponseRequestBody;\n responseBody?: string | null;\n responseTruncated?: boolean;\n durationMs: number;\n}\n\nexport type OrgWebhookAttemptDiagnosticResponseRequestBody = { [key: string]: unknown };\n\nexport interface OrgWebhookClearDeliveriesResponse {\n cleared: number;\n}\n\n/**\n * Which covered workspaces will actually emit the subscribed record events.\n */\nexport interface OrgWebhookCoverageResponse {\n recordEventsSubscribed: boolean;\n workspaces: OrgWebhookWorkspaceCoverageResponse[];\n}\n\n/**\n * One try at a delivery, from ``webhook_delivery_attempts`` (activities DB).\n */\nexport interface OrgWebhookDeliveryAttemptResponse {\n attemptNumber: number;\n startedAt: string;\n finishedAt?: string | null;\n outcome?: string | null;\n failureClass?: string | null;\n errorType?: string | null;\n responseStatusCode?: number | null;\n}\n\nexport interface OrgWebhookDeliveryDetailResponse {\n delivery: OrgWebhookDeliveryResponse;\n requestBody: OrgWebhookDeliveryDetailResponseRequestBody;\n diagnostics: OrgWebhookAttemptDiagnosticResponse[];\n}\n\nexport type OrgWebhookDeliveryDetailResponseRequestBody = { [key: string]: unknown };\n\n/**\n * How deliveries to one endpoint are going, from the activities database.\n *\n * ``state`` is ``held`` while the drain holds the endpoint's queue (it sends\n * one probe at ``nextProbeAt``; the first success releases the backlog),\n * ``failing`` while attempts fail but the queue still flows, and\n * ``healthy`` otherwise, including an endpoint with no attempt yet.\n * ``failing`` has no time window, like the drain's own counter: the run ends\n * only at the next success, however long ago its last failure was. Health\n * never changes ``status``: a paused endpoint can be held, and it sends no\n * probe until it is resumed.\n *\n * Closed vocabulary, counts and timestamps only. ``lastFailureClass`` is the\n * drain's ``failure_class`` vocabulary (``network``, ``http_4xx``,\n * ``http_5xx``, ``unsafe_target``, ``missing_secret``, ``retryable``).\n */\nexport interface OrgWebhookDeliveryHealth {\n state: OrgWebhookDeliveryHealthState;\n consecutiveFailures: number;\n failingSince: string | null;\n lastSuccessAt: string | null;\n lastFailureAt: string | null;\n lastFailureClass: string | null;\n nextProbeAt: string | null;\n pendingDeliveries: number;\n}\n\nexport type OrgWebhookDeliveryHealthState = typeof OrgWebhookDeliveryHealthState[keyof typeof OrgWebhookDeliveryHealthState];\n\n\nexport const OrgWebhookDeliveryHealthState = {\n healthy: 'healthy',\n failing: 'failing',\n held: 'held',\n} as const;\n\n/**\n * Bounded page of deliveries for one endpoint.\n */\nexport interface OrgWebhookDeliveryListResponse {\n items: OrgWebhookDeliveryResponse[];\n total: number;\n}\n\n/**\n * A requeued delivery. Identifiers only — the envelope is not echoed.\n *\n * ``dedupeKey`` and ``occurredAt`` are the row's own, unchanged, so a\n * receiver that collapses duplicates sees the same event. ``status`` is\n * ``pending``: the drain signs a fresh timestamp when it sends.\n */\nexport interface OrgWebhookDeliveryReplayResponse {\n id: number;\n status: 'pending';\n dedupeKey: string;\n occurredAt: string;\n}\n\n/**\n * One delivery-queue row (``webhook_deliveries``, activities DB), with\n * its attempts oldest first — the queue state and every try at it.\n */\nexport interface OrgWebhookDeliveryResponse {\n id: number;\n eventType: string;\n occurredAt: string;\n dedupeKey: string;\n workspaceUuid?: string | null;\n status: OrgWebhookDeliveryResponseStatus;\n availableAt: string;\n createdAt: string;\n replayable: boolean;\n attempts: OrgWebhookDeliveryAttemptResponse[];\n}\n\nexport type OrgWebhookDeliveryResponseStatus = typeof OrgWebhookDeliveryResponseStatus[keyof typeof OrgWebhookDeliveryResponseStatus];\n\n\nexport const OrgWebhookDeliveryResponseStatus = {\n pending: 'pending',\n processing: 'processing',\n sent: 'sent',\n dead_letter: 'dead_letter',\n expired: 'expired',\n} as const;\n\n/**\n * How many pending deliveries an operator discard moved to ``expired``.\n */\nexport interface OrgWebhookDiscardPendingResponse {\n discarded: number;\n}\n\n/**\n * One endpoint. ``signingSecret`` is always the masked sentinel.\n *\n * The destination is a FINGERPRINT (``scheme://host`` plus a SHA-256 digest\n * of the full URL), never the raw URL — webhook paths and queries routinely\n * carry per-tenant tokens, and every holder of the read scope would\n * otherwise harvest the credentials another administrator embedded\n * (round-9 finding). The full URL is known to whoever configured it and is\n * returned only in the create response, exactly like the one-time secret.\n */\nexport interface OrgWebhookEndpointResponse {\n id: number;\n uuid: string;\n name: string;\n destinationHost: string;\n destinationDigest: string;\n status: string;\n eventTypes: string[];\n workspaceScope: OrgWorkspaceScopeResponse;\n includePayload?: boolean;\n signingSecretSet: boolean;\n signingSecret?: string;\n statusHistory: OrgWebhookEndpointStatusHistoryEntry[];\n recentFailures?: OrgWebhookRecentFailure[];\n deliveryHealth: OrgWebhookDeliveryHealth;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * One row of ``webhook_endpoint_status_history``.\n */\nexport interface OrgWebhookEndpointStatusHistoryEntry {\n status: string;\n reason: string;\n changedAt: string;\n changedByAccountId?: number | null;\n}\n\n/**\n * The event types an org endpoint may subscribe to.\n *\n * Served from ``workspace_deliverable_event_types`` — the same set the\n * create/update validators accept — so the org UI enumerates exactly the\n * vocabulary the API will store, in the vocabulary's own order.\n */\nexport interface OrgWebhookEventTypesResponse {\n eventTypes: string[];\n}\n\n/**\n * One Form and whether record events are opted in for it.\n *\n * ``name`` is the Form's configured name, not a patient identifier.\n */\nexport interface OrgWebhookFormCoverageResponse {\n id: number;\n uuid: string;\n name: string;\n slug: string;\n webhookEventsEnabled: boolean;\n}\n\n/**\n * How many dead-lettered deliveries of one class finished in the last 24 hours.\n *\n * Only deliveries that dead-lettered after the endpoint last became\n * ``active`` count.\n * ``failureClass`` is the closed vocabulary the drain writes. One delivery\n * counts once, by its newest terminal attempt in that window.\n */\nexport interface OrgWebhookRecentFailure {\n failureClass: string;\n count: number;\n}\n\n/**\n * A representative delivery body for one event type.\n *\n * What the org UI prefills its test-send editor with, and what the public\n * event catalog is generated from — one builder\n * (``lib.activity.samples.sample_event``), so the payload an operator edits\n * and the payload the docs describe cannot diverge.\n *\n * The body is a real, validated envelope wrapped by the same\n * ``build_delivery_payload`` a queued delivery goes through, so it carries\n * the ``endpoint`` block and the endpoint's own ``org_uuid`` exactly as a\n * live delivery would. Every uuid in it is synthetic: the sample names no\n * row in any database.\n */\nexport interface OrgWebhookSamplePayloadResponse {\n eventType: string;\n family: string;\n payload: OrgWebhookSamplePayloadResponsePayload;\n}\n\nexport type OrgWebhookSamplePayloadResponsePayload = { [key: string]: unknown };\n\n/**\n * One workspace the endpoint covers, and its Form opt-in.\n *\n * ``formOptIn`` is ``not_applicable`` when the endpoint does not subscribe\n * to ``data_record.created`` or ``data_record.updated``. It is\n * ``covered_but_opted_out`` when those events are subscribed and no Form\n * has ``webhookEventsEnabled``. ``opted_in`` means at least one Form does.\n */\nexport interface OrgWebhookWorkspaceCoverageResponse {\n workspaceUuid: string;\n workspaceName: string;\n formOptIn: OrgWebhookWorkspaceCoverageResponseFormOptIn;\n forms: OrgWebhookFormCoverageResponse[];\n}\n\nexport type OrgWebhookWorkspaceCoverageResponseFormOptIn = typeof OrgWebhookWorkspaceCoverageResponseFormOptIn[keyof typeof OrgWebhookWorkspaceCoverageResponseFormOptIn];\n\n\nexport const OrgWebhookWorkspaceCoverageResponseFormOptIn = {\n opted_in: 'opted_in',\n covered_but_opted_out: 'covered_but_opted_out',\n not_applicable: 'not_applicable',\n} as const;\n\n/**\n * Deliberately empty — a replay takes no parameters.\n *\n * The body exists as the repo's CSRF barrier for cookie-authenticated POSTs:\n * FastAPI parses a body only for an ``application/json`` content type, which\n * a cross-site HTML form cannot send. Clients send ``{}``.\n */\nexport interface ReplayOrgWebhookDeliveryRequest { [key: string]: unknown }\n\n/**\n * Send one payload to an endpoint, now, outside the delivery queue.\n *\n * ``eventType`` picks which sample the server builds when ``payload`` is\n * omitted, and it stays in the closed subscribable vocabulary for the same\n * reason the subscription list does. It is deliberately NOT required to be\n * one of the endpoint's *subscribed* types: an operator wiring up a new\n * receiver wants to exercise a type before subscribing to it, and a test\n * send writes nothing to the queue that a subscription would govern.\n *\n * ``payload`` is the operator's own edit of that sample — the whole point of\n * the feature is that they can put their own identifiers in it and watch\n * their handler run. It is sent as given (canonicalized and signed like any\n * delivery), not merged into a server-built envelope: a merge would mean an\n * operator could not test what happens when a field is *absent*.\n *\n * **So the two can disagree, and that is allowed.** When ``payload`` is\n * supplied, the body's ``event_type`` is whatever the operator wrote — this\n * request's ``eventType`` no longer describes what the receiver will see.\n * Reconciling them would defeat the feature: \"what does my handler do when\n * the body says one thing and the header another\" is a case worth being able\n * to exercise. ``eventType`` remains the value the audit trail records\n * alongside ``bodySource``, which says whether the body was ours or theirs,\n * so a reader of the audit log is never misled about which one it describes.\n */\nexport interface TestOrgWebhookEndpointRequest {\n eventType: string;\n payload?: TestOrgWebhookEndpointRequestPayload;\n}\n\nexport type TestOrgWebhookEndpointRequestPayload = { [key: string]: unknown } | null;\n\n/**\n * What one test send did.\n *\n * Mirrors the delivery log's vocabulary rather than inventing a second one:\n * ``failureClass`` and ``errorType`` are the same closed values an\n * operator reads on a real delivery attempt (``lib.services.\n * org_webhook_delivery_service``), so \"what happened to my test\" and \"what\n * happened to my deliveries\" are answered in one language.\n *\n * ``responseBody`` is a bounded prefix of the RECEIVER's reply — the\n * operator's own server talking back. It is the reason the button is worth\n * pressing, and it is truncated because an arbitrary third-party body has no\n * size we control.\n */\nexport interface TestOrgWebhookEndpointResponse {\n delivered: boolean;\n statusCode?: number | null;\n failureClass?: string | null;\n errorType?: string | null;\n responseBody?: string | null;\n durationMs: number;\n}\n\n/**\n * Update an organization webhook endpoint. None = leave unchanged.\n */\nexport interface UpdateOrgWebhookEndpointRequest {\n name?: string | null;\n url?: string | null;\n eventTypes?: string[] | null;\n workspaceScope?: OrgWorkspaceScopeRequest | null;\n status?: UpdateOrgWebhookEndpointRequestStatus;\n signingSecret?: string | null;\n}\n\nexport type UpdateOrgWebhookEndpointRequestStatus = typeof UpdateOrgWebhookEndpointRequestStatus[keyof typeof UpdateOrgWebhookEndpointRequestStatus] | null;\n\n\nexport const UpdateOrgWebhookEndpointRequestStatus = {\n active: 'active',\n paused: 'paused',\n} as const;\n\n/**\n * Workspace-side visibility (GRA-8314 §5 (b)'s visibility).\n *\n * What any member holding `webhooks:read` — the workspace's webhook-read\n * scope, which workspace admins hold — sees from THEIR side: that their\n * workspace feeds an org endpoint. IDs and the endpoint's public shape only\n * — never the signing secret, never delivery contents, and never the full\n * URL: the endpoint is ORG configuration authored by an org admin, and a\n * webhook URL's path and query routinely carry per-tenant tokens, so the\n * workspace side gets the same PHI-safe ``destination_fingerprint`` the\n * audit trail records — ``scheme://host`` plus a digest prefix that lets a\n * reader tell two endpoints on one host apart.\n */\nexport interface WorkspaceOrgEndpointResponse {\n /** Endpoint uuid (org-side identifier) */\n uuid: string;\n name: string;\n /** scheme://host[:port] of the endpoint URL — never the path or query */\n destinationHost: string;\n /** First 12 hex characters of SHA-256 over the full URL */\n destinationDigest: string;\n status: string;\n eventTypes: string[];\n workspaceScopeMode: WorkspaceScopeMode;\n organizationId: number;\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: workspace_selection\n */\n\n\n/**\n * Which of the organization's workspaces a source or sink may reach.\n *\n * ``selected`` reaches ``workspaceUuids`` plus every workspace carrying ALL\n * of ``labelSelector`` and needs at least one of the two; ``all`` and\n * ``none`` carry neither list.\n */\nexport interface OrgWorkspaceScopeRequest {\n mode: WorkspaceScopeMode;\n /** @maxItems 100 */\n workspaceUuids?: string[];\n /** @maxItems 10 */\n labelSelector?: string[];\n}\n\n/**\n * The three modes a person picks and reads (ADR-55).\n *\n * Stored as ``all_workspaces`` plus the selection rows, never as a fourth\n * column: ``all`` is the stored bit, ``selected`` is a limited selection with\n * at least one workspace or label, and ``none`` is a limited selection with\n * neither. A limited selection whose last workspace was deleted therefore\n * reads as ``none`` — what it reaches.\n */\nexport type WorkspaceScopeMode = typeof WorkspaceScopeMode[keyof typeof WorkspaceScopeMode];\n\n\nexport const WorkspaceScopeMode = {\n all: 'all',\n selected: 'selected',\n none: 'none',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: bundle_contract\n */\n\nimport type { InboxBundleItem, InboxBundleReference, PhoneNumberBundleItem, PhoneNumberBundleReference } from './channel_bundle';\nimport type { DisclosureMode } from './disclosure_contract';\nimport type { JourneyBundleItem, JourneyRecipeProblem } from './journey_bundle';\nimport type { MemberFilterBundleItem, MemberFilterBundleReference } from './member_filter_bundle';\nimport type { SystemRoleKey } from './member_role';\nimport type { MemberRoleBundleItem, MemberRoleBundleReference } from './member_role_bundle';\nimport type { EnumOption } from './schema_field';\nimport type { DataTypeRequirement, RequirementSchemaField } from './site';\n\n/**\n * A Workspace Field value an installation must enter: a required field of a Workspace Fields Data Type item.\n *\n * Derived from the version's own Data Type items (workspace-scoped and\n * singular), never declared separately. The installed Data Type's schema is\n * what an installation checks (``missingWorkspaceFields`` on its readiness).\n */\nexport interface BundleConfigurationInput {\n itemKey: string;\n fieldSlug: string;\n label: string;\n fieldType: string;\n}\n\nexport interface BundleGrantRequest {\n granteeType: BundleGrantRequestGranteeType;\n granteeUuid?: string | null;\n expiresAt?: string | null;\n disclosureMode?: DisclosureMode;\n}\n\nexport type BundleGrantRequestGranteeType = typeof BundleGrantRequestGranteeType[keyof typeof BundleGrantRequestGranteeType];\n\n\nexport const BundleGrantRequestGranteeType = {\n organization: 'organization',\n global: 'global',\n} as const;\n\nexport interface BundleGrantResponse {\n granteeName?: string | null;\n id: number;\n granteeType: string;\n granteeUuid: string | null;\n effective?: boolean;\n disclosureMode: string;\n expiresAt: string | null;\n revokedAt: string | null;\n revocationMode?: string | null;\n revocationReason?: string | null;\n}\n\nexport interface BundleItemLabel {\n name: string;\n version?: number | null;\n versionName?: string | null;\n}\n\n/**\n * One reason a draft item cannot be published yet.\n *\n * A reader names a Site setting by ``settingLabel``, the theme's label,\n * never by its key. ``ref`` is the item key a reference names.\n */\nexport interface BundleItemProblem {\n code: BundleItemProblemCode;\n settingKey?: string | null;\n settingLabel?: string | null;\n ref?: string | null;\n}\n\nexport type BundleItemProblemCode = typeof BundleItemProblemCode[keyof typeof BundleItemProblemCode];\n\n\nexport const BundleItemProblemCode = {\n site_setting_required: 'site_setting_required',\n site_setting_reference: 'site_setting_reference',\n workflow_not_included: 'workflow_not_included',\n form_not_included: 'form_not_included',\n filter_not_included: 'filter_not_included',\n phone_number_not_included: 'phone_number_not_included',\n release_collision: 'release_collision',\n label_conflict: 'label_conflict',\n slug_collision: 'slug_collision',\n source_not_portable: 'source_not_portable',\n source_deleted: 'source_deleted',\n source_archived: 'source_archived',\n} as const;\n\n/**\n * One local Journey as the Bundle item that adds it.\n *\n * ``item`` is the whole recipe, built by the server from the Journey: its\n * definition, the actions of its steps and the Member labels they name. It is\n * absent when ``problems`` name what the Journey must change first.\n *\n * ``forms`` are the Forms its conditions, its Form updates and its saved\n * filters read, ``filters`` the saved Member filters its conditions use, and\n * ``workflows`` the Workflows its actions start. A draft that holds the\n * Journey must hold each of them.\n *\n * The recipe carries who enters the Journey: its enrollment conditions, or\n * its single saved filter when it has none.\n */\nexport interface BundleJourneyCandidate {\n id: number;\n uuid: string;\n name: string;\n item?: JourneyBundleItem | null;\n problems?: JourneyRecipeProblem[];\n forms?: FormBundleItem[];\n filters?: MemberFilterBundleItem[];\n workflows?: BundleJourneyStartedWorkflow[];\n}\n\n/**\n * This workspace's Journeys for the Bundle picker.\n *\n * ``available`` is the server rollout of Journey items\n * (``JOURNEY_BUNDLE_WRITES_ENABLED``), not authorization. When it is false a\n * draft save refuses a Journey item, and no Journey is listed.\n */\nexport interface BundleJourneyCandidates {\n available: boolean;\n journeys?: BundleJourneyOption[];\n}\n\n/**\n * A local Journey the Bundle picker lists. Nothing is built for the list.\n */\nexport interface BundleJourneyOption {\n id: number;\n uuid: string;\n name: string;\n executionModel: string;\n}\n\n/**\n * A Workflow of this workspace that one Journey step starts.\n *\n * A Workflow that two steps start is listed once for each step.\n */\nexport interface BundleJourneyStartedWorkflow {\n workflowUuid: string;\n workflowName?: string | null;\n stepUuid?: string | null;\n stepName?: string | null;\n}\n\n/**\n * One named link an author publishes with a Bundle version.\n */\nexport interface BundleLink {\n /**\n * @minLength 1\n * @maxLength 80\n */\n label: string;\n /**\n * @minLength 1\n * @maxLength 2048\n */\n url: string;\n kind?: BundleLinkKind;\n}\n\nexport type BundleLinkKind = typeof BundleLinkKind[keyof typeof BundleLinkKind];\n\n\nexport const BundleLinkKind = {\n link: 'link',\n demo: 'demo',\n} as const;\n\nexport interface BundleScenarioPreflightRequest {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n workflowItemKey: string;\n /**\n * @minItems 1\n * @maxItems 100\n */\n selections: ScenarioSelection[];\n}\n\n/**\n * One Site setting or Journey/Workflow channel that can be configured after installation.\n *\n * A Site slot is a reference-typed setting naming a workspace\n * entity rather than another item in the version. A Workflow's default Inbox\n * is a required destination slot when its\n * published dependency manifest requires one. Each per-workspace Ability\n * setting the manifest lists (``installationFields``) is a slot too, keyed\n * ``<ability kind>.<setting>`` and required when the Ability kind requires\n * it. Other Workflow references are\n * not slots — an installed Workflow's Abilities carry ordinary\n * export-shaped configuration the installer relocates by identity, and an\n * unmapped dependency refuses the install rather than becoming an open slot\n * somebody may fill later. This is a response projection: the theme vocabulary\n * stays where it is declared.\n *\n * A shared install field (``lib/models/resources/installation_fields.py``)\n * is one slot keyed by the field, and ``fills`` lists the settings its one\n * value is written to; those settings are not slots of their own.\n */\nexport interface BundleSlot {\n key: string;\n kind: string;\n required: boolean;\n label: string;\n description?: string | null;\n defaultValue?: string | number | boolean | null;\n options?: EnumOption[] | null;\n requirement?: DataTypeRequirement | null;\n fills?: BundleSlot[] | null;\n}\n\nexport interface BundleSummary {\n uuid: string;\n name: string;\n description: string | null;\n publishedVersion: number | null;\n publishedAt: string | null;\n draftGeneration: number;\n owned: boolean;\n}\n\nexport interface BundleVersionResponse {\n bundleUuid: string;\n version: number | null;\n publishedAt: string | null;\n releaseNotes?: string | null;\n items: (WorkflowBundleItem | FormBundleItem | SiteBundleItem | JourneyBundleItem | MemberFilterBundleItem | PhoneNumberBundleItem | InboxBundleItem | MemberRoleBundleItem)[];\n links?: BundleLink[];\n itemLabels?: BundleVersionResponseItemLabels;\n itemProblems?: BundleVersionResponseItemProblems;\n sourceIds?: BundleVersionResponseSourceIds;\n slots?: BundleSlot[];\n requiresDefaultPhoneNumber?: boolean;\n draftGeneration: number;\n /** The required workspace values an installation enters: each required field of the version's Workspace Fields Data Type items. */\n configurationInputs?: BundleConfigurationInput[];\n}\n\nexport type BundleVersionResponseItemLabels = {[key: string]: BundleItemLabel};\n\nexport type BundleVersionResponseItemProblems = {[key: string]: BundleItemProblem[]};\n\nexport type BundleVersionResponseSourceIds = {[key: string]: number};\n\nexport interface BundleVersionSummary {\n version: number | null;\n publishedAt: string | null;\n releaseNotes?: string | null;\n subscriberCount?: number | null;\n}\n\n/**\n * A local Workflow the Bundle picker lists, and whether it can be added.\n *\n * ``revisionUuid`` is the newest published revision, the one publishing the\n * Bundle carries. ``dependenciesChecked`` is true when dependency\n * validation finds no issues for the acting Member. Listing does not store\n * a manifest; adding the Workflow captures its release.\n */\nexport interface BundleWorkflowCandidate {\n id: number;\n uuid: string;\n name: string;\n status: BundleWorkflowCandidateStatus;\n revisionUuid?: string | null;\n revisionNumber?: number | null;\n revisionName?: string | null;\n dependenciesChecked?: boolean;\n issues?: BundleWorkflowCandidateIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n forms?: FormBundleItem[];\n}\n\nexport type BundleWorkflowCandidateIssuesItem = typeof BundleWorkflowCandidateIssuesItem[keyof typeof BundleWorkflowCandidateIssuesItem];\n\n\nexport const BundleWorkflowCandidateIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\nexport type BundleWorkflowCandidateStatus = typeof BundleWorkflowCandidateStatus[keyof typeof BundleWorkflowCandidateStatus];\n\n\nexport const BundleWorkflowCandidateStatus = {\n eligible: 'eligible',\n unpublished: 'unpublished',\n} as const;\n\nexport interface CreateBundleRequest {\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n description?: string | null;\n}\n\n/**\n * A whole Form definition, created in the installing workspace.\n *\n * ``dataTypeUuid`` is the **source** workspace's DataType identity: the uuid a\n * published Workflow ability names in its ``data_access`` configuration. It is\n * the relocation key — installation maps it to the local DataType it creates\n * — and a new draft must carry it (:class:`ReplaceBundleDraftRequest`).\n *\n * Stored items published before this identity existed omit the key. Reading\n * them back leaves it unset so the version stays readable; installation\n * refuses that item instead of answering 500 or inventing an identity.\n *\n * No connector ownership travels here: a source Form's binding to its local\n * AppConnection is workspace wiring, and ``extra=\"forbid\"`` refuses one.\n */\nexport interface FormBundleItem {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind: 'form';\n dataTypeUuid?: string | null;\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n /**\n * @minLength 1\n * @maxLength 255\n */\n slug: string;\n description?: string | null;\n prompt?: string | null;\n isCollection?: boolean;\n recordScope?: FormBundleItemRecordScope;\n webhookEventsEnabled?: boolean;\n /**\n * @minItems 1\n * @maxItems 100\n */\n fields: RequirementSchemaField[];\n}\n\nexport type FormBundleItemRecordScope = typeof FormBundleItemRecordScope[keyof typeof FormBundleItemRecordScope];\n\n\nexport const FormBundleItemRecordScope = {\n member: 'member',\n workspace: 'workspace',\n anonymous: 'anonymous',\n} as const;\n\n/**\n * Select a Journey from the publishing workspace; the server captures it.\n */\nexport interface JourneyBundleReference {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind: 'journey';\n journeyUuid: string;\n /** `managed`: each installation keeps one Journey and updates it in place (ADR-62). Absent: each release installs an editable copy. */\n updateMode?: 'managed' | null;\n}\n\n/**\n * 409 body when a Journey action starts a Workflow the draft does not hold.\n */\nexport interface JourneyWorkflowNotIncludedResponse {\n detail: string;\n code: 'journey_workflow_not_included';\n journeyKey: string;\n journeyName: string;\n stepName?: string | null;\n workflowKey?: string | null;\n workflowUuid?: string | null;\n workflowName?: string | null;\n}\n\n/**\n * Read-only org Library row: identity, latest contents, version history.\n */\nexport interface OrgBundleCatalogItem {\n uuid: string;\n name: string;\n description: string | null;\n workspaceUuid: string;\n workspaceName: string;\n publishedVersion: number | null;\n publishedAt: string | null;\n subscriberCount?: number;\n orgShared?: boolean;\n items?: (WorkflowBundleItem | FormBundleItem | SiteBundleItem | JourneyBundleItem | MemberFilterBundleItem | PhoneNumberBundleItem | InboxBundleItem | MemberRoleBundleItem)[];\n versions?: BundleVersionSummary[];\n}\n\nexport interface PublishBundleRequest {\n /** @minimum 0 */\n expectedGeneration: number;\n releaseNotes?: string | null;\n /** @maxItems 100 */\n scenarioSelections?: BundleScenarioPreflightRequest[];\n expectedPlan?: string | null;\n}\n\nexport interface ReplaceBundleDraftRequest {\n /** @minimum 0 */\n expectedGeneration: number;\n /**\n * @minItems 1\n * @maxItems 100\n */\n items: (WorkflowBundleItem | FormBundleItem | SiteBundleItem | JourneyBundleReference | MemberFilterBundleReference | PhoneNumberBundleReference | InboxBundleReference | MemberRoleBundleReference)[];\n links?: BundleLink[] | null;\n}\n\n/**\n * One publisher-selected example and its distribution decisions.\n */\nexport interface ScenarioSelection {\n scenarioUuid: string;\n driver: ScenarioSelectionDriver;\n persona: ScenarioSelectionPersona;\n fixtures: ScenarioSelectionFixtures;\n includeCriteria: boolean;\n contentReviewedForDistribution?: boolean;\n syntheticContentAttested?: boolean;\n}\n\nexport type ScenarioSelectionDriver = typeof ScenarioSelectionDriver[keyof typeof ScenarioSelectionDriver];\n\n\nexport const ScenarioSelectionDriver = {\n human: 'human',\n automated: 'automated',\n} as const;\n\nexport type ScenarioSelectionFixtures = typeof ScenarioSelectionFixtures[keyof typeof ScenarioSelectionFixtures];\n\n\nexport const ScenarioSelectionFixtures = {\n none: 'none',\n include_synthetic: 'include_synthetic',\n recipient_binding: 'recipient_binding',\n} as const;\n\nexport type ScenarioSelectionPersona = typeof ScenarioSelectionPersona[keyof typeof ScenarioSelectionPersona];\n\n\nexport const ScenarioSelectionPersona = {\n none: 'none',\n include_synthetic: 'include_synthetic',\n recipient_binding: 'recipient_binding',\n} as const;\n\n/**\n * A Site, with the theme settings an installation must resolve.\n */\nexport interface SiteBundleItem {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind: 'site';\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n slug?: string | null;\n siteUuid?: string | null;\n /** @minLength 1 */\n theme: string;\n isPublic?: boolean;\n allowSignup?: boolean;\n authenticationMethods?: 'name_dob'[];\n memberRoleSystemKeys?: SystemRoleKey[];\n signupMemberRoleSystemKey?: SystemRoleKey | null;\n settings?: SiteBundleItemSettings;\n}\n\nexport type SiteBundleItemSettings = { [key: string]: unknown };\n\n/**\n * A setting whose value is another item in this Bundle version.\n */\nexport interface SlotRef {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n slot: string;\n}\n\nexport interface UpdateBundleRequest {\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n description?: string | null;\n}\n\n/**\n * A pin to an existing published Workflow revision.\n */\nexport interface WorkflowBundleItem {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind?: 'workflow';\n workflowUuid: string;\n revisionUuid: string;\n}\n\n/**\n * 409 body when a draft save adds a Workflow whose dependencies refuse it.\n */\nexport interface WorkflowNotShareableResponse {\n detail: string;\n code: 'workflow_not_shareable';\n workflowUuid: string;\n issues: WorkflowNotShareableResponseIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n workflows?: WorkflowReleaseRefusal[];\n}\n\nexport type WorkflowNotShareableResponseIssuesItem = typeof WorkflowNotShareableResponseIssuesItem[keyof typeof WorkflowNotShareableResponseIssuesItem];\n\n\nexport const WorkflowNotShareableResponseIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\n/**\n * An offending definition, without its configuration or runtime data.\n */\nexport interface WorkflowReleaseProblem {\n code: WorkflowReleaseProblemCode;\n abilityUuid?: string | null;\n abilityType?: string | null;\n abilityTitle?: string | null;\n ruleUuid?: string | null;\n actionType?: string | null;\n taskUuid?: string | null;\n taskId?: number | null;\n taskName?: string | null;\n dependencyKind?: WorkflowReleaseProblemDependencyKind;\n dependencyRef?: string | null;\n dependencyName?: string | null;\n reason?: WorkflowReleaseProblemReason;\n correction?: WorkflowReleaseProblemCorrection;\n resourceId?: number | null;\n}\n\nexport type WorkflowReleaseProblemCode = typeof WorkflowReleaseProblemCode[keyof typeof WorkflowReleaseProblemCode];\n\n\nexport const WorkflowReleaseProblemCode = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\nexport type WorkflowReleaseProblemCorrection = typeof WorkflowReleaseProblemCorrection[keyof typeof WorkflowReleaseProblemCorrection] | null;\n\n\nexport const WorkflowReleaseProblemCorrection = {\n edit_workflow: 'edit_workflow',\n open_resource: 'open_resource',\n review_sharing: 'review_sharing',\n upload_file: 'upload_file',\n republish_workflow: 'republish_workflow',\n retry_capture: 'retry_capture',\n} as const;\n\nexport type WorkflowReleaseProblemDependencyKind = typeof WorkflowReleaseProblemDependencyKind[keyof typeof WorkflowReleaseProblemDependencyKind] | null;\n\n\nexport const WorkflowReleaseProblemDependencyKind = {\n form: 'form',\n file: 'file',\n folder: 'folder',\n member_label: 'member_label',\n} as const;\n\nexport type WorkflowReleaseProblemReason = typeof WorkflowReleaseProblemReason[keyof typeof WorkflowReleaseProblemReason] | null;\n\n\nexport const WorkflowReleaseProblemReason = {\n missing_resource: 'missing_resource',\n read_access_required: 'read_access_required',\n share_access_required: 'share_access_required',\n unsupported_file_source: 'unsupported_file_source',\n missing_file_content: 'missing_file_content',\n invalid_configuration: 'invalid_configuration',\n resource_limit: 'resource_limit',\n unsupported_role: 'unsupported_role',\n legacy_label_configuration: 'legacy_label_configuration',\n fixed_member_target: 'fixed_member_target',\n missing_label: 'missing_label',\n republish_required: 'republish_required',\n storage_unavailable: 'storage_unavailable',\n} as const;\n\nexport interface WorkflowReleaseRefusal {\n workflowUuid: string;\n issues: WorkflowReleaseRefusalIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n}\n\nexport type WorkflowReleaseRefusalIssuesItem = typeof WorkflowReleaseRefusalIssuesItem[keyof typeof WorkflowReleaseRefusalIssuesItem];\n\n\nexport const WorkflowReleaseRefusalIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: bundle_publication\n */\n\nimport type { BundleItemLabel, WorkflowReleaseProblem } from './bundle_contract';\nimport type { JourneyRecipeProblem } from './journey_bundle';\n\n/**\n * One item of the draft, or of the last published version, at publish.\n */\nexport interface BundlePublishItem {\n key: string;\n kind: string;\n name: string;\n status: BundlePublishItemStatus;\n change?: BundlePublishItemChange;\n revisionBefore?: BundleItemLabel | null;\n revisionAfter?: BundleItemLabel | null;\n newestRevision?: BundleItemLabel | null;\n reason?: BundlePublishItemReason;\n detail?: string | null;\n issues?: BundlePublishItemIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n journeyProblems?: JourneyRecipeProblem[];\n}\n\nexport type BundlePublishItemChange = typeof BundlePublishItemChange[keyof typeof BundlePublishItemChange] | null;\n\n\nexport const BundlePublishItemChange = {\n added: 'added',\n removed: 'removed',\n revisionChanged: 'revisionChanged',\n definitionChanged: 'definitionChanged',\n unchanged: 'unchanged',\n} as const;\n\nexport type BundlePublishItemIssuesItem = typeof BundlePublishItemIssuesItem[keyof typeof BundlePublishItemIssuesItem];\n\n\nexport const BundlePublishItemIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\nexport type BundlePublishItemReason = typeof BundlePublishItemReason[keyof typeof BundlePublishItemReason] | null;\n\n\nexport const BundlePublishItemReason = {\n workflow_not_shareable: 'workflow_not_shareable',\n not_portable: 'not_portable',\n needed_by_another_item: 'needed_by_another_item',\n} as const;\n\nexport type BundlePublishItemStatus = typeof BundlePublishItemStatus[keyof typeof BundlePublishItemStatus];\n\n\nexport const BundlePublishItemStatus = {\n ready: 'ready',\n held: 'held',\n left_out: 'left_out',\n blocked: 'blocked',\n} as const;\n\n/**\n * What publishing the saved draft now would put in the next version.\n *\n * Publishing computes the same answer again. ``planToken`` names it: pass\n * it as ``expectedPlan`` and publication refuses with 409\n * ``bundle_publish_plan_changed``, writing nothing, if what would go out\n * has changed since.\n */\nexport interface BundlePublishPreview {\n bundleUuid: string;\n fromVersion: number | null;\n draftGeneration: number;\n items: BundlePublishItem[];\n planToken: string;\n unchanged: boolean;\n publishable: boolean;\n}\n\n/**\n * The Bundles a Workflow is in, and what of its draft cannot go into one.\n *\n * ``issues`` and ``problems`` are the same check a Bundle runs when it adds\n * or publishes the Workflow, run on the Workflow's draft for the acting\n * Member. Both are empty when the Workflow is in no Bundle.\n */\nexport interface WorkflowBundleMembership {\n bundles?: WorkflowBundleMembershipEntry[];\n issues?: WorkflowBundleMembershipIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n}\n\n/**\n * One Bundle of this workspace that holds the Workflow.\n */\nexport interface WorkflowBundleMembershipEntry {\n bundleUuid: string;\n name: string;\n publishedVersion?: number | null;\n publishedRevision?: BundleItemLabel | null;\n inDraft?: boolean | null;\n}\n\nexport type WorkflowBundleMembershipIssuesItem = typeof WorkflowBundleMembershipIssuesItem[keyof typeof WorkflowBundleMembershipIssuesItem];\n\n\nexport const WorkflowBundleMembershipIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: installation_contract\n */\n\nimport type { BundleSlot } from './bundle_contract';\nimport type { WidgetSlug } from './workspace_widget_domain';\n\n/**\n * One access effect a request would apply, exactly as it would apply it (ADR-63).\n *\n * Sent back when a request applies an effect it does not approve. Approving\n * means sending the request again with ``{effect, itemKey, fingerprint}`` in\n * ``approvals``. An approval of no effect the request applies changes\n * nothing, so a retry of a request that already applied it succeeds.\n * ``member_role`` creates the role, or changes it to a new release's name\n * and scopes; ``role_assignment`` gives the role to the operators an\n * operator group slot names (existing Members by id, new ones by their\n * request identity), replacing the role each of those existing Members\n * holds now (``replacedRoles``, by name); ``widget_enablement`` enables\n * ``widget`` on a verified\n * domain with the origin settings listed. Ids, names the publisher or the\n * installer gave, scopes and domain settings only.\n */\nexport interface AccessEffect {\n effect: AccessEffectEffect;\n itemKey: string;\n fingerprint: string;\n roleName?: string | null;\n grantedScopes?: string[];\n previousScopes?: string[] | null;\n slotKey?: string | null;\n memberIds?: number[];\n replacedRoles?: string[];\n newMemberRequestUuids?: string[];\n widget?: WidgetSlug | null;\n orgDomainUuid?: string | null;\n domain?: string | null;\n allowSubdomains?: boolean | null;\n port?: number | null;\n widgets?: string[];\n}\n\n/**\n * The installer's approval of one access effect, for this request only (ADR-63).\n *\n * ``fingerprint`` is the one the server showed for the effect: the\n * installation, the release's definition of ``itemKey`` and the concrete\n * local targets. The server recomputes it under the operation fence and\n * current authority; a stale or different effect is refused. Nothing stores\n * the approval.\n */\nexport interface AccessEffectApproval {\n effect: AccessEffectApprovalEffect;\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n itemKey: string;\n /** @pattern ^[0-9a-f]{64}$ */\n fingerprint: string;\n}\n\nexport type AccessEffectApprovalEffect = typeof AccessEffectApprovalEffect[keyof typeof AccessEffectApprovalEffect];\n\n\nexport const AccessEffectApprovalEffect = {\n member_role: 'member_role',\n role_assignment: 'role_assignment',\n widget_enablement: 'widget_enablement',\n} as const;\n\nexport type AccessEffectEffect = typeof AccessEffectEffect[keyof typeof AccessEffectEffect];\n\n\nexport const AccessEffectEffect = {\n member_role: 'member_role',\n role_assignment: 'role_assignment',\n widget_enablement: 'widget_enablement',\n} as const;\n\n/**\n * ``POST /installations/{uuid}/bindings``.\n *\n * Fills unconfigured slots and repairs missing or archived targets. A key\n * with a live target is refused; local working choices remain unchanged.\n *\n * ``replace`` changes a filled slot that is a local setting of the\n * installation, while the Bundle stays attached: a per-workspace Ability\n * setting (``lib/abilities/installation_contract.py``), whose new value\n * replaces the held one on every installed Ability of its kind; an installed\n * Workflow's default Inbox or outbound Phone Number (ADR-52); a recording;\n * and a shared install field, whose value replaces every setting it fills\n * (ADR-56). Any other filled slot is still refused.\n *\n * ``approvals`` approve the access effects this request applies (ADR-63),\n * ``widgets`` choose the verified domain each required widget is enabled on,\n * and ``roleNames`` give a declared role a local name where its own is taken.\n * Each is refused while the Bundle launch writers are off.\n */\nexport interface BindInstallationSlotsRequest {\n bindings?: BindInstallationSlotsRequestBindings;\n replace?: boolean;\n /** @maxItems 100 */\n approvals?: AccessEffectApproval[];\n /** @maxItems 10 */\n widgets?: WidgetEnablementInput[];\n roleNames?: BindInstallationSlotsRequestRoleNames;\n}\n\nexport type BindInstallationSlotsRequestBindings = {[key: string]: FormTargetInput | InboxTargetInput | NewInboxTargetInput | NewInboxWithoutAddressTargetInput | NewPhoneNumberTargetInput | ProviderPhoneNumberTargetInput | NewOperatorGroupTargetInput | ReferenceTargetInput | ScalarTargetInput};\n\nexport type BindInstallationSlotsRequestRoleNames = { [key: string]: unknown };\n\n/**\n * One binding whose target no longer satisfies what the item needs.\n */\nexport interface BrokenBinding {\n key: string;\n /** Stable reason code, rather than a workspace row name or free-form message. Accepted codes: abilities_not_materialised, channel_unrouted, filter_invalid, form_requirement, inbox_not_provisioned, operator_group_empty, phone_not_assigned, phone_not_provisioned, phone_sms_disabled, phone_voice_disabled, revision_unavailable, target_unauthorized, target_unavailable, unbound_binding, unreadable_binding, webhooks_not_configured, webhooks_unverified. */\n code: string;\n /** For phone_not_assigned and the webhook codes, the Phone Number the binding names: its settings are where its number is linked again. */\n phoneNumberId?: number | null;\n}\n\n/**\n * A Form in the installing workspace, by uuid.\n */\nexport interface FormTargetInput {\n kind: 'data_type';\n /**\n * @minLength 1\n * @maxLength 36\n */\n uuid: string;\n}\n\nexport interface InboxTargetInput {\n kind: 'inbox';\n /**\n * @minLength 1\n * @maxLength 36\n */\n uuid: string;\n}\n\n/**\n * ``POST /bundles/{uuid}/installations``.\n *\n * ``siteBindings`` carries one target per open **Site** theme-setting slot.\n * It may omit a required one: installing with an unfilled required slot\n * succeeds and ``readiness()`` reports it, because the alternative is an\n * install dialog that refuses before the workspace has anything to point at.\n * An **unknown** key is refused, because it means the caller and the version\n * disagree about what this Bundle is.\n *\n * Workflow content references relocate from the Bundle. A required Inbox\n * slot needs a destination before install: an authorized existing Inbox\n * (``inbox``, with or without an address), ``new_inbox`` to have the install\n * create one with an address on the platform domain, or\n * ``new_inbox_without_address`` to have it create one with no address yet,\n * which readiness reports as waiting for an address (ADR-52).\n *\n * A phone slot takes an existing Phone Number (``phone_number``), with or\n * without a provider number, ``new_phone_number``, or one of the\n * organization's provider numbers (``provider_phone_number``), which the\n * install links to a Phone Number it creates. One left out stays open\n * and readiness reports it: the workspace default Phone Number is only the\n * answer a client pre-selects, never one the install picks (ADR-52).\n */\nexport interface InstallBundleRequest {\n /** @minimum 1 */\n version: number;\n siteBindings?: InstallBundleRequestSiteBindings;\n}\n\nexport type InstallBundleRequestSiteBindings = {[key: string]: FormTargetInput | InboxTargetInput | NewInboxTargetInput | NewInboxWithoutAddressTargetInput | NewPhoneNumberTargetInput | ProviderPhoneNumberTargetInput | NewOperatorGroupTargetInput | ReferenceTargetInput | ScalarTargetInput};\n\n/**\n * One per-workspace Ability setting of an installation, and its current value.\n *\n * ``value`` is the value the installed Abilities hold, or ``None`` when the\n * setting is unfilled, when the installed Abilities disagree, or when the\n * caller cannot read any installed Workflow that carries it: the value is\n * shown only to someone who could already read it on that Workflow's\n * Ability.\n */\nexport interface InstallationAbilitySetting {\n slot: BundleSlot;\n value?: string | number | boolean | null;\n}\n\n/**\n * One item's difference between two versions of the same Bundle.\n */\nexport interface InstallationItemChange {\n key: string;\n kind: string;\n change: InstallationItemChangeChange;\n}\n\nexport type InstallationItemChangeChange = typeof InstallationItemChangeChange[keyof typeof InstallationItemChangeChange];\n\n\nexport const InstallationItemChangeChange = {\n added: 'added',\n removed: 'removed',\n revisionChanged: 'revisionChanged',\n definitionChanged: 'definitionChanged',\n unchanged: 'unchanged',\n} as const;\n\n/**\n * One item of an installation and the workspace row it produced.\n *\n * ``localUuid`` and ``localId`` are the same row addressed two ways: a Form\n * and a Workflow are addressed by uuid in the API, a Site by id in the\n * builder. Both are present for every kind so a caller does not need a\n * per-kind lookup table, and both are ``None`` while the installation is\n * still ``pending``.\n */\nexport interface InstallationItemResponse {\n key: string;\n kind: string;\n localUuid?: string | null;\n localId?: number | null;\n escalationRoutingRequired?: boolean;\n skippedRules?: InstallationSkippedRuleResponse[];\n journeyRollout?: ManagedJourneyRollout | null;\n}\n\n/**\n * An installed item whose name another row of its kind also has.\n *\n * Names are not identities, so installation never adopts or refuses a\n * same-named row: it creates the Bundle's own beside it and reports the\n * pair here. The other row is the workspace's own and is not named.\n */\nexport interface InstallationNameConflict {\n key: string;\n kind: 'member_filter';\n name: string;\n}\n\n/**\n * A Phone Number this operation linked that does not answer yet.\n *\n * Reported once, on the response to the install, upgrade or slot binding\n * that linked it (``provider_phone_number``), and not stored: a later read\n * of the installation, and its readiness, do not show it. ``key`` is the\n * slot the Phone Number fills; the fix is in that Phone Number's settings.\n * Identifiers and a closed code only, never the number.\n */\nexport interface InstallationPhoneNumberNotice {\n key: string;\n phoneNumberId: number;\n code: InstallationPhoneNumberNoticeCode;\n}\n\nexport type InstallationPhoneNumberNoticeCode = typeof InstallationPhoneNumberNoticeCode[keyof typeof InstallationPhoneNumberNoticeCode];\n\n\nexport const InstallationPhoneNumberNoticeCode = {\n webhooks_not_configured: 'webhooks_not_configured',\n webhooks_routed_elsewhere: 'webhooks_routed_elsewhere',\n number_not_assigned: 'number_not_assigned',\n} as const;\n\n/**\n * A bound Phone Number linked to one of the organization's provider numbers.\n */\nexport interface InstallationPhoneNumberState {\n /** The phone slot, or Journey action, that sends from it. */\n key: string;\n phoneNumberId: number;\n providerPhoneUuid: string;\n /** The organization's record of the number names this workspace's Phone Number. */\n assigned: boolean;\n /** The number's recorded A2P activation: not_requested, pending, active, failed or not_required; none for a number with no recorded state. */\n a2pStatus?: string | null;\n /** Only with verifyProvider: whether the number's live callbacks point at this workspace when read. A failed read is unverified, never configured. */\n callbacks?: InstallationPhoneNumberStateCallbacks;\n}\n\n/**\n * Only with verifyProvider: whether the number's live callbacks point at this workspace when read. A failed read is unverified, never configured.\n */\nexport type InstallationPhoneNumberStateCallbacks = typeof InstallationPhoneNumberStateCallbacks[keyof typeof InstallationPhoneNumberStateCallbacks] | null;\n\n\nexport const InstallationPhoneNumberStateCallbacks = {\n configured: 'configured',\n mismatch: 'mismatch',\n unverified: 'unverified',\n} as const;\n\n/**\n * Computed on read, never stored.\n *\n * Storing readiness would mean answering \"is this installation still wired\n * up?\" from a cache of a decision about rows that change underneath it. Every\n * field here is re-derived from the version's slots and the workspace's\n * current rows.\n */\nexport interface InstallationReadiness {\n ready: boolean;\n escalationRoutingRequired?: string[];\n recordEventsWithheld?: string[];\n workflowDependencies?: UnavailableWorkflowDependency[];\n unboundSlots?: BundleSlot[];\n brokenBindings?: BrokenBinding[];\n archivedItems?: string[];\n unavailableItems?: UnavailableInstallationItem[];\n nameConflicts?: InstallationNameConflict[];\n unmetRequirements?: UnmetRequirement[];\n /** Access effects the installer has not approved yet; each makes the installation unready. */\n pendingAccessEffects?: PendingAccessEffect[];\n /** Required Workspace Fields with no value yet; each makes the installation unready. */\n missingWorkspaceFields?: MissingWorkspaceField[];\n /** Each bound Phone Number linked to an organization number: who the organization's record names, its A2P activation and, when verified, its live callbacks. */\n phoneNumbers?: InstallationPhoneNumberState[];\n}\n\nexport interface InstallationResponse {\n workspaceName?: string | null;\n uuid: string;\n workspaceUuid: string;\n bundleUuid: string;\n bundleName: string;\n version: number;\n activeVersion?: number | null;\n status: string;\n subscribed: boolean;\n mode: string;\n upgradePolicy: string;\n items: InstallationItemResponse[];\n boundSlotKeys: string[];\n latestVersion?: number | null;\n updateAvailable?: boolean;\n latestReleaseNotes?: string | null;\n versionsBehind?: number;\n activeAt?: string | null;\n nameConflicts?: InstallationNameConflict[];\n phoneNumberNotices?: InstallationPhoneNumberNotice[];\n}\n\n/**\n * A rule of the pinned revision this workspace does not run, and why.\n *\n * Derived from the pinned snapshot on every read, never stored. Today the\n * only case is a retired action (``reasonCode`` ``retired_action``): the\n * published revision keeps the rule as released, and the workspace gets no\n * stub for it. IDs and fixed text only — no rule name or parameter.\n */\nexport interface InstallationSkippedRuleResponse {\n ruleUuid: string;\n resourceTaskId?: number | null;\n reasonCode: string;\n reason: string;\n}\n\n/**\n * The badge an installed workspace row wears: which Bundle, which version.\n *\n * A Workflow stub knows only its ``installation_uuid``; the Bundle's name and\n * the version it holds live in the resource database. This is the smallest\n * join of the two that lets a list row or a detail page say \"installed from\n * Enrollment v3\" without the reader also fetching the whole installation.\n */\nexport interface InstallationSummaryResponse {\n uuid: string;\n bundleUuid: string;\n bundleName: string;\n version: number;\n}\n\n/**\n * What ``GET /installations/{uuid}/upgrade-preview?to=N`` answers.\n *\n * Every field is derived from the two versions' stored items and the\n * installation's own ``boundSlotKeys`` — nothing here is a prediction about\n * what the upgrade will do to workspace rows.\n *\n * ``newSlots`` is the exact set the dialog must offer pickers for: the target\n * version's slots this installation has **no** binding for. That is wider\n * than \"slots the target version added\" on purpose — a slot left unfilled at\n * install is still unbound when previewed. Required slots must be supplied\n * for the upgrade to succeed; optional slots may remain open.\n */\nexport interface InstallationUpgradePreview {\n from: number;\n to: number;\n scenarioInstallationUnavailable?: boolean;\n items: InstallationItemChange[];\n newSlots?: BundleSlot[];\n releaseNotes?: VersionReleaseNotes[];\n /** The roles this workspace holds that the target version changes; the upgrade needs each approved (ADR-63). */\n accessEffects?: AccessEffect[];\n}\n\n/**\n * Where a managed Journey stands after its definition is installed (ADR-62).\n *\n * The definition is installed when the installation holds its version;\n * enrollments follow eventually. Counts only.\n */\nexport interface ManagedJourneyRollout {\n /** The installed Journey's own status: draft, active or paused. */\n status: string;\n /** The Journey version enrollments move to; none before it first runs. */\n headVersion?: number | null;\n /** Enrollments on an older version that can move now. */\n pending?: number;\n /** Enrollments that move once their in-flight step finishes. */\n deferred?: number;\n /** Enrollments kept on their version: their position has no mapping, their version cannot be read, or an operator rolled them back from the head. */\n held?: number;\n /** Enrollments an Ending finished on an older version. */\n latched?: number;\n /** Only the first enrollments were classified; the rest count as pending. */\n truncated?: boolean;\n}\n\n/**\n * A required field of an installed Workspace Fields Data Type with no value yet.\n *\n * ``unreadable``: the caller cannot read the Data Type's values, so whether\n * it has one is unknown here. Labels and keys only, never a value.\n */\nexport interface MissingWorkspaceField {\n itemKey: string;\n dataTypeUuid: string;\n fieldSlug: string;\n label: string;\n fieldType: string;\n code?: MissingWorkspaceFieldCode;\n}\n\nexport type MissingWorkspaceFieldCode = typeof MissingWorkspaceFieldCode[keyof typeof MissingWorkspaceFieldCode];\n\n\nexport const MissingWorkspaceFieldCode = {\n missing: 'missing',\n unreadable: 'unreadable',\n} as const;\n\n/**\n * Create the Inbox this slot needs instead of naming an existing one.\n *\n * The installer creates one Inbox per installation, with the product's\n * ordinary new-Inbox defaults and the Bundle's name, inside the install. It\n * carries no fields: nothing about the Inbox is caller-supplied. Requires\n * ``inboxes:write``. See ``lib/services/bundle_inbox_creation.py``.\n */\nexport const NewInboxTargetInputValue = {\n kind: 'new_inbox',\n} as const;\nexport type NewInboxTargetInput = typeof NewInboxTargetInputValue;\n\n/**\n * Create the Inbox this slot needs, with no address yet.\n *\n * The second way to create the slot's Inbox, for a practice whose address\n * will be on its organization's domain later (ADR-52). Like ``new_inbox`` it\n * creates one Inbox per installation, named for the Bundle, with the\n * product's new-Inbox defaults, inside the install, and requires\n * ``inboxes:write``. Unlike it, the Inbox gets no address and nothing routes\n * to it: it neither sends nor receives until an address is given to it in its\n * settings, and readiness reports the binding as waiting for an address\n * (``inbox_not_provisioned``). It carries no fields. See\n * ``lib/services/bundle_inbox_creation.py``.\n */\nexport const NewInboxWithoutAddressTargetInputValue = {\n kind: 'new_inbox_without_address',\n} as const;\nexport type NewInboxWithoutAddressTargetInput = typeof NewInboxWithoutAddressTargetInputValue;\n\n/**\n * An operator the installation creates as a Member of this workspace.\n *\n * ``requestUuid`` is the caller's stable identity for this creation: a retry\n * carrying it creates no second Member.\n */\nexport interface NewOperatorGroupMemberInput {\n requestUuid: string;\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n email: string;\n}\n\n/**\n * Create the operator group this slot rings instead of choosing an existing one.\n *\n * The group takes the routing strategy the Bundle declares for it.\n * ``memberIds`` are existing Members and ``newMembers``\n * Members the installation creates; all are added to the group through the\n * ordinary group writer. ``assignRoleKey`` names the Bundle's ``member_role``\n * item those operators are given, which needs the installer's approval in\n * the same request. ``requestUuid`` is the caller's stable identity for this\n * creation, so a retry finds the group it made.\n */\nexport interface NewOperatorGroupTargetInput {\n kind: 'new_operator_group';\n requestUuid: string;\n name?: string | null;\n /**\n * @maxItems 100\n * @items.exclusiveMinimum 0\n */\n memberIds?: number[];\n /** @maxItems 100 */\n newMembers?: NewOperatorGroupMemberInput[];\n assignRoleKey?: string | null;\n}\n\n/**\n * Create the Phone Number this slot needs instead of naming an existing one.\n *\n * The installer creates one Phone Number per installation, named for the\n * Bundle, with no provider number linked (ADR-52). Every slot bound this way\n * points at it, and it starts sending once a provider number is linked to it\n * under Phone Numbers. It never becomes the workspace default. It carries no\n * fields. Requires ``phones:write`` and ``phones:read``. See\n * ``lib/services/bundle_phone_number_creation.py``.\n */\nexport const NewPhoneNumberTargetInputValue = {\n kind: 'new_phone_number',\n} as const;\nexport type NewPhoneNumberTargetInput = typeof NewPhoneNumberTargetInputValue;\n\n/**\n * An access effect the installation still needs, derived from the live rows.\n *\n * ``role_not_created``: the Bundle's role item has no role in this\n * workspace yet; ``fingerprint`` approves creating it under its own name.\n * ``role_name_taken``: as before, but another role holds that name, so the\n * approval needs a local name (``roleNames``) and its fingerprint comes back\n * from that request. ``widget_not_enabled``: no verified domain of the\n * organization serves ``widget`` for this workspace; the request that names\n * a domain gets its fingerprint back.\n */\nexport interface PendingAccessEffect {\n effect: PendingAccessEffectEffect;\n itemKey: string;\n code: PendingAccessEffectCode;\n roleName?: string | null;\n grantedScopes?: string[];\n widget?: WidgetSlug | null;\n fingerprint?: string | null;\n}\n\nexport type PendingAccessEffectCode = typeof PendingAccessEffectCode[keyof typeof PendingAccessEffectCode];\n\n\nexport const PendingAccessEffectCode = {\n role_not_created: 'role_not_created',\n role_name_taken: 'role_name_taken',\n widget_not_enabled: 'widget_not_enabled',\n} as const;\n\nexport type PendingAccessEffectEffect = typeof PendingAccessEffectEffect[keyof typeof PendingAccessEffectEffect];\n\n\nexport const PendingAccessEffectEffect = {\n member_role: 'member_role',\n role_assignment: 'role_assignment',\n widget_enablement: 'widget_enablement',\n} as const;\n\n/**\n * Fill this slot with one of the organization's provider numbers.\n *\n * ``uuid`` names a provider number of the workspace's organization that no\n * other workspace holds: one not assigned to any workspace, or assigned to\n * this one. The installer creates a Phone Number for it, named like the one\n * ``new_phone_number`` creates, and links the provider number to it inside\n * the install, with the checks linking a number makes under Phone Numbers. A\n * Phone Number of this workspace that already holds the number is used\n * instead. A number another workspace took is refused with the code\n * ``provider_phone_number_taken``, and nothing is created. Requires\n * ``phones:write`` and ``phones:read``. See\n * ``lib/services/bundle_provider_phone_numbers.py``.\n */\nexport interface ProviderPhoneNumberTargetInput {\n kind: 'provider_phone_number';\n /**\n * @minLength 1\n * @maxLength 36\n */\n uuid: string;\n}\n\n/**\n * A workspace row addressed by its local serial id.\n */\nexport interface ReferenceTargetInput {\n kind: ReferenceTargetInputKind;\n /** @exclusiveMinimum 0 */\n id: number;\n}\n\nexport type ReferenceTargetInputKind = typeof ReferenceTargetInputKind[keyof typeof ReferenceTargetInputKind];\n\n\nexport const ReferenceTargetInputKind = {\n file: 'file',\n file_folder: 'file_folder',\n image: 'image',\n phone_number: 'phone_number',\n member_role: 'member_role',\n page: 'page',\n operator_group: 'operator_group',\n} as const;\n\n/**\n * Recreate a deleted Form from the installation's held release.\n */\nexport interface RestoreInstallationFormRequest {\n /**\n * @minLength 1\n * @maxLength 100\n */\n itemKey: string;\n}\n\n/**\n * Repair missing dependency resources from the held Workflow release.\n */\nexport interface RestoreInstallationWorkflowResourcesRequest {\n /**\n * @minLength 1\n * @maxLength 100\n */\n itemKey: string;\n}\n\n/**\n * A literal the installing workspace supplies for a scalar theme setting or Ability setting.\n */\nexport interface ScalarTargetInput {\n kind: ScalarTargetInputKind;\n value: string | number | boolean;\n}\n\nexport type ScalarTargetInputKind = typeof ScalarTargetInputKind[keyof typeof ScalarTargetInputKind];\n\n\nexport const ScalarTargetInputKind = {\n text: 'text',\n textarea: 'textarea',\n url: 'url',\n color: 'color',\n number: 'number',\n boolean: 'boolean',\n select: 'select',\n} as const;\n\n/**\n * ``PATCH /installations/{uuid}``.\n *\n * ``pinned`` holds the version the workspace installed until an\n * administrator upgrades it. ``auto`` upgrades on publication of a new\n * version, carrying the bindings the installation already holds.\n */\nexport interface SetInstallationPolicyRequest {\n upgradePolicy: SetInstallationPolicyRequestUpgradePolicy;\n}\n\nexport type SetInstallationPolicyRequestUpgradePolicy = typeof SetInstallationPolicyRequestUpgradePolicy[keyof typeof SetInstallationPolicyRequestUpgradePolicy];\n\n\nexport const SetInstallationPolicyRequestUpgradePolicy = {\n pinned: 'pinned',\n auto: 'auto',\n} as const;\n\n/**\n * A held resource's name, kind and current condition.\n */\nexport interface UnavailableInstallationItem {\n key: string;\n kind: UnavailableInstallationItemKind;\n name: string;\n condition: UnavailableInstallationItemCondition;\n}\n\nexport type UnavailableInstallationItemCondition = typeof UnavailableInstallationItemCondition[keyof typeof UnavailableInstallationItemCondition];\n\n\nexport const UnavailableInstallationItemCondition = {\n missing: 'missing',\n archived: 'archived',\n} as const;\n\nexport type UnavailableInstallationItemKind = typeof UnavailableInstallationItemKind[keyof typeof UnavailableInstallationItemKind];\n\n\nexport const UnavailableInstallationItemKind = {\n form: 'form',\n workflow: 'workflow',\n site: 'site',\n journey: 'journey',\n member_filter: 'member_filter',\n phone_number: 'phone_number',\n inbox: 'inbox',\n member_role: 'member_role',\n} as const;\n\nexport interface UnavailableWorkflowDependency {\n itemKey: string;\n kind: UnavailableWorkflowDependencyKind;\n reference: string;\n name: string;\n condition: UnavailableWorkflowDependencyCondition;\n}\n\nexport type UnavailableWorkflowDependencyCondition = typeof UnavailableWorkflowDependencyCondition[keyof typeof UnavailableWorkflowDependencyCondition];\n\n\nexport const UnavailableWorkflowDependencyCondition = {\n missing: 'missing',\n changed: 'changed',\n moved: 'moved',\n notPackaged: 'notPackaged',\n} as const;\n\nexport type UnavailableWorkflowDependencyKind = typeof UnavailableWorkflowDependencyKind[keyof typeof UnavailableWorkflowDependencyKind];\n\n\nexport const UnavailableWorkflowDependencyKind = {\n file: 'file',\n folder: 'folder',\n member_label: 'member_label',\n} as const;\n\n/**\n * Something the installing workspace must have that it does not.\n *\n * Installing grants nothing, so a requirement an installed resource carries\n * (a feature, an app connection, a phone number) is reported here rather than\n * supplied. ``kind`` and ``slug`` name it in the requirement's own vocabulary\n * (``lib/abilities/requirements.py`` for an Ability's), ``name`` and\n * ``description`` say what it is and how to supply it, and the item fields\n * say what needs it when that is known. ``kind`` is open, so another kind of\n * requirement can be reported without a model change. Registry names and\n * slugs, and an administrator-set connection name for an MCP server — never\n * a configuration value.\n */\nexport interface UnmetRequirement {\n kind: string;\n slug: string;\n name: string;\n description: string;\n itemKey?: string | null;\n abilityType?: string | null;\n abilityTitle?: string | null;\n}\n\n/**\n * ``POST /installations/{uuid}/upgrade``.\n *\n * ``bindings`` supplies targets for slots the **target** version opens and\n * the installation does not already hold. New required Site or Workflow Inbox\n * slots must be supplied before an active release is replaced. Automatic upgrades with\n * unresolved required slots leave the held release in place for repair.\n * ``approvals`` approve the release's changed access effects (ADR-63), and\n * ``roleNames`` give a declared role a local name where its own is taken, as\n * on the bindings request. Both are refused while the Bundle launch writers\n * are off.\n */\nexport interface UpgradeInstallationRequest {\n /** @minimum 1 */\n toVersion: number;\n bindings?: UpgradeInstallationRequestBindings;\n /** @maxItems 100 */\n approvals?: AccessEffectApproval[];\n roleNames?: UpgradeInstallationRequestRoleNames;\n}\n\nexport type UpgradeInstallationRequestBindings = {[key: string]: FormTargetInput | InboxTargetInput | NewInboxTargetInput | NewInboxWithoutAddressTargetInput | NewPhoneNumberTargetInput | ProviderPhoneNumberTargetInput | NewOperatorGroupTargetInput | ReferenceTargetInput | ScalarTargetInput};\n\nexport type UpgradeInstallationRequestRoleNames = { [key: string]: unknown };\n\n/**\n * One published version's release notes, for the upgrade dialog.\n */\nexport interface VersionReleaseNotes {\n version: number;\n releaseNotes?: string | null;\n}\n\n/**\n * The verified organization domain a required widget is enabled on.\n */\nexport interface WidgetEnablementInput {\n widget: WidgetSlug;\n orgDomainUuid: string;\n}\n","import type { GravityRailWorkspaceClient } from '../client/workspace-client';\n\nexport type AnyRecord = Record<string, any>;\nexport type ResourceSummary = Record<string, Array<number | undefined>>;\n\nexport function isRecord(value: unknown): value is AnyRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isPlainRecord(value: unknown): value is AnyRecord {\n if (!isRecord(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function slugify(name: string): string {\n return name.toLowerCase().replaceAll(' ', '_').replaceAll('-', '_');\n}\n\nexport abstract class WorkspaceBuilderResource {\n _id?: number;\n _uuid?: string;\n _created = false;\n _existed = false;\n\n /** Server-assigned numeric id — available after apply() or adopt(). */\n get id(): number {\n if (this._id === undefined) {\n throw new Error(\n `${this.constructor.name} has no id yet — ids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._id;\n }\n\n /** Server-assigned uuid — available after apply() or adopt(). */\n get uuid(): string {\n if (this._uuid === undefined) {\n throw new Error(\n `${this.constructor.name} has no uuid yet — uuids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._uuid;\n }\n\n /**\n * True for resources the server creates on our behalf (currently a\n * journey's `Start` step). They are kept in the resource list so edges can\n * reference them, but they are never created, printed, or counted.\n */\n get isImplicit(): boolean {\n return false;\n }\n\n /**\n * True when `apply()` is safe — and required — to run against a resource\n * that was ADOPTED rather than created.\n *\n * False by default because most builders create only: re-running their\n * `apply()` on an existing resource would make a duplicate. Override it\n * when `apply()` is an idempotent full write keyed on stable identities,\n * which is the only way a re-run can express an EDIT (a removed goal, a\n * reordered timeline) rather than just an addition.\n */\n get appliesWhenExisting(): boolean {\n return false;\n }\n\n abstract planLine(): string;\n abstract apply(client: GravityRailWorkspaceClient): Promise<void>;\n\n matchKey(): string | undefined {\n return undefined;\n }\n\n adopt(existing: AnyRecord): void {\n this._id = existing.id;\n this._uuid = existing.uuid;\n this._existed = true;\n }\n}\n\nexport function resolveRefs(params: AnyRecord): AnyRecord {\n return resolveRefValue(params) as AnyRecord;\n}\n\nfunction resolveRefValue(value: unknown): unknown {\n if (value instanceof WorkspaceBuilderResource) return value._uuid;\n if (Array.isArray(value)) return value.map(resolveRefValue);\n if (!isPlainRecord(value)) return value;\n\n const out: AnyRecord = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n out[key] = resolveRefValue(nestedValue);\n }\n return out;\n}\n\n/**\n * Same substitution as `resolveRefs`, but to numeric ids.\n *\n * A few surfaces key on id rather than uuid — the query-engine IR is the main\n * one (`member.labelId` takes label ids). Without this a script would have to\n * apply once, read the ids back, and apply again just to write one filter.\n *\n * Returns `unknown` deliberately. A builder standing in a `number` slot is not\n * type-compatible with the payload it is going into, so the cast is real; a\n * generic `<T>(value: T): T` would only hide it, and would additionally claim a\n * `number` where an unresolved ref yields `undefined`. Callers cast at the one\n * place it matters, in view of the reader.\n */\nexport function resolveIdRefs(value: unknown): unknown {\n return resolveIdRefValue(value);\n}\n\nfunction resolveIdRefValue(value: unknown): unknown {\n // `.id` throws with a useful message when the ref has no id yet. Failing\n // here beats writing `undefined` into a payload: an id-keyed predicate that\n // silently loses a term matches everyone or no one, and looks fine doing it.\n if (value instanceof WorkspaceBuilderResource) return value.id;\n if (Array.isArray(value)) return value.map(resolveIdRefValue);\n if (!isPlainRecord(value)) return value;\n\n const out: AnyRecord = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n out[key] = resolveIdRefValue(nestedValue);\n }\n return out;\n}\n","import {\n EventRuleEventType,\n EventRuleObjectType,\n type CreateRoutineRequest,\n type EventRuleActionType,\n type MemberFilterFormData,\n type NotificationRuleCreate,\n} from '../types';\nimport type { QueryPredicate } from '../types/query-engine-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { resolveIdRefs, WorkspaceBuilderResource } from './resource';\nimport type { WorkflowBuilder } from './workflows';\n\nexport class MemberFilterBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n /** Query-engine predicate (JSON IR) authored on MemberFilter.query. */\n query: QueryPredicate | null = null;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.query = options.query ?? null;\n }\n\n /**\n * Set the filter's query-engine predicate (JSON IR).\n *\n * Anywhere the IR wants a numeric id you may pass the builder that will own\n * it (e.g. a label in a `member.labelId` value); refs resolve at apply time.\n */\n setQuery(query: QueryPredicate): MemberFilterBuilder {\n this.query = query;\n return this;\n }\n\n planLine(): string {\n return `MemberFilter: ${this.name}${this.query ? ' (query)' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: MemberFilterFormData = {\n name: this.name,\n description: this.description,\n // Builder refs inside the IR become ids here; see resolveIdRefs.\n query: resolveIdRefs(this.query) as QueryPredicate | null,\n };\n const result = await client.createMemberFilter(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\ninterface RoutineRuleDraft {\n actionType: EventRuleActionType | string;\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams: AnyRecord;\n}\n\nexport class RoutineBuilder extends WorkspaceBuilderResource {\n readonly active: boolean;\n readonly description: string;\n readonly rules: RoutineRuleDraft[] = [];\n\n constructor(\n readonly name: string,\n readonly cronSchedule = '',\n options: AnyRecord = {}\n ) {\n super();\n this.active = options.active ?? false;\n this.description = options.description ?? '';\n }\n\n addRule(\n actionType: string,\n options: {\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams?: AnyRecord;\n } = {}\n ): RoutineBuilder {\n this.rules.push({\n actionType,\n workflow: options.workflow,\n memberFilter: options.memberFilter,\n actionParams: options.actionParams ?? {},\n });\n return this;\n }\n\n planLine(): string {\n const parts = [\n ...(this.cronSchedule ? [`cron=${this.cronSchedule}`] : []),\n ...(this.rules.length ? [`${this.rules.length} rules`] : []),\n this.active ? 'active' : 'inactive',\n ];\n return `Routine: ${this.name} (${parts.join(', ')})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const eventRules = this.rules.map((rule) => {\n const actionParams = { ...rule.actionParams };\n if (rule.workflow?._id !== undefined) actionParams.workflowId = rule.workflow._id;\n if (rule.memberFilter?._id !== undefined)\n actionParams.memberFilterId = rule.memberFilter._id;\n return {\n uuid: crypto.randomUUID(),\n objectType: EventRuleObjectType.ROUTINE,\n eventType: EventRuleEventType.ROUTINE_TRIGGERED,\n actionType: rule.actionType as EventRuleActionType,\n actionParams,\n active: true,\n };\n });\n const payload: CreateRoutineRequest = {\n name: this.name,\n cronString: this.cronSchedule,\n scheduleMode: this.cronSchedule ? 'CRON' : undefined,\n scheduleEnabled: this.active,\n ...(this.description ? { description: this.description } : {}),\n ...(eventRules.length ? { eventRules } : {}),\n };\n const result = await client.createRoutine(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class NotificationRuleBuilder extends WorkspaceBuilderResource {\n readonly noticeType: string;\n readonly memberId: number;\n readonly workflow?: WorkflowBuilder;\n readonly prompt?: string;\n readonly notifySms: boolean;\n readonly notifyEmail: boolean;\n readonly notifyVoice: boolean;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.noticeType = options.noticeType ?? options.notice_type ?? name;\n this.memberId = options.memberId ?? options.member_id;\n this.workflow = options.workflow;\n this.prompt = options.prompt ?? options.message;\n this.notifySms = Boolean(options.notifySms ?? options.notify_sms);\n this.notifyEmail = Boolean(options.notifyEmail ?? options.notify_email);\n this.notifyVoice = Boolean(options.notifyVoice ?? options.notify_voice);\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.memberId !== undefined) parts.push(`memberId=${this.memberId}`);\n if (this.workflow) parts.push(`workflow='${this.workflow.name}'`);\n return `NotificationRule: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n if (this.memberId === undefined) {\n throw new Error(`Notification rule '${this.name}' requires memberId`);\n }\n const payload: NotificationRuleCreate = {\n noticeType: this.noticeType,\n memberId: this.memberId,\n workflowId: this.workflow?._id,\n prompt: this.prompt ?? null,\n notifySms: this.notifySms,\n notifyEmail: this.notifyEmail,\n notifyVoice: this.notifyVoice,\n };\n const result = await client.createNotificationRule(payload);\n this._id = result.id;\n this._created = true;\n }\n}\n","import {\n DataFieldType,\n EventRuleEventType,\n type DataTypeFormData,\n type EnumOption,\n type EventRuleActionType,\n type MemberLabelFormData,\n type SchemaField,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport { type AnyRecord, isRecord, slugify, WorkspaceBuilderResource } from './resource';\n\n// The client DataFieldType enum and the generated SchemaField fieldType\n// literal union share the same string values, but TS string enums are\n// nominal — convert once at draft construction.\ntype WorkspaceFieldDraft = SchemaField;\n\nfunction normalizeOptions(options: any[]): EnumOption[] {\n if (options.length === 0) return [];\n const first = options[0];\n if (isRecord(first)) return options as EnumOption[];\n if (Array.isArray(first)) {\n return options.map((entry) => ({ label: String(entry[0]), value: entry[1] }));\n }\n return options.map((option) => ({ label: String(option), value: String(option) }));\n}\n\nfunction createFieldDraft(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: EnumOption[];\n cel?: string;\n } = {}\n): WorkspaceFieldDraft {\n return {\n name,\n slug,\n fieldType: fieldType as SchemaField['fieldType'],\n required: Boolean(options.required),\n order: options.order ?? 0,\n ...(options.description ? { description: options.description } : {}),\n ...(options.choices ? { options: options.choices } : {}),\n ...(options.cel ? { celFunction: options.cel } : {}),\n };\n}\n\nexport class FormBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly prompt: string;\n readonly collection: boolean;\n readonly fields: WorkspaceFieldDraft[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n\n constructor(name: string, slug?: string, options: AnyRecord = {}) {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.description = options.description ?? '';\n this.prompt = options.prompt ?? '';\n this.collection = options.collection ?? false;\n\n for (const field of options.fields ?? []) {\n if (!isRecord(field) || !field.name) continue;\n const choices = field.options ? normalizeOptions(field.options) : undefined;\n this.fields.push(\n createFieldDraft(\n (field.fieldType ?? field.field_type ?? DataFieldType.TEXT) as DataFieldType,\n field.name,\n field.slug ?? slugify(field.name),\n {\n required: Boolean(field.required ?? field.isRequired),\n order: field.order ?? 0,\n description: field.description,\n choices,\n }\n )\n );\n }\n }\n\n field(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: any[];\n cel?: string;\n } = {}\n ): FormBuilder {\n this.fields.push(createFieldDraft(fieldType, name, slug, options));\n return this;\n }\n\n enumField(name: string, slug: string, options: any[], settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ENUM, name, slug, {\n ...settings,\n choices: normalizeOptions(options),\n });\n }\n\n textField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TEXT, name, slug, settings);\n }\n\n numberField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.NUMBER, name, slug, settings);\n }\n\n dateField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATE, name, slug, settings);\n }\n\n booleanField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.BOOLEAN, name, slug, settings);\n }\n\n functionField(name: string, slug: string, cel: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.FUNCTION, name, slug, { ...settings, cel });\n }\n\n emailField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.EMAIL, name, slug, settings);\n }\n\n phoneField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.PHONE, name, slug, settings);\n }\n\n longtextField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.LONGTEXT, name, slug, settings);\n }\n\n integerField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.INTEGER, name, slug, settings);\n }\n\n datetimeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATETIME, name, slug, settings);\n }\n\n timeOfDayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TIME_OF_DAY, name, slug, settings);\n }\n\n usZipCodeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.US_ZIP_CODE, name, slug, settings);\n }\n\n arrayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ARRAY, name, slug, settings);\n }\n\n objectField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.OBJECT, name, slug, settings);\n }\n\n onRecordCreated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_CREATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n onRecordUpdated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_UPDATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n matchKey(): string {\n return this.slug;\n }\n\n planLine(): string {\n return `Form: ${this.name} (slug=${this.slug}, ${this.fields.length} fields)`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: DataTypeFormData = {\n name: this.name,\n slug: this.slug,\n description: this.description,\n prompt: this.prompt,\n isCollection: this.collection,\n fields: this.fields,\n };\n const result = await client.createDataType(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class MemberLabelBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly color: string;\n readonly description: string;\n\n constructor(name: string, slug?: string, color = '8b5cf6', description = '') {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.color = color;\n this.description = description;\n }\n\n matchKey(): string {\n return this.slug;\n }\n\n planLine(): string {\n return `Label: ${this.name} (slug=${this.slug})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: MemberLabelFormData = {\n name: this.name,\n slug: this.slug,\n color: this.color,\n description: this.description,\n };\n const result = await client.createMemberLabel(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n","import {\n EventRuleEventType,\n EventRuleActionType,\n type EventRuleInput,\n type JourneyV2DefinitionFormData,\n type JourneyV2EndingInput,\n type JourneyV2GoalInput,\n type JourneyV2TouchInput,\n type JourneyV2WaitInput,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { type AnyRecord, resolveRefs, WorkspaceBuilderResource } from './resource';\n\n/** Options for a `JOURNEY_STEP_EXECUTE` outreach rule on a step. */\nexport interface StepRuleOptions {\n /** CEL guard — the action is skipped when this is false. */\n when?: string;\n /** Operator-facing rule name, shown in the journey editor. */\n name?: string;\n /** Delay the action this many seconds after the step activates. */\n delaySeconds?: number;\n active?: boolean;\n}\n\nexport interface StepRuleDraft {\n uuid: string;\n actionType: EventRuleActionType;\n actionParams: AnyRecord;\n options: StepRuleOptions;\n /**\n * The uuid the SERVER already stores for this rule, learned during\n * adoption. `uuid` above is minted by the script at authoring time and is\n * therefore different on every run of the same program; sending that as the\n * identity would make every re-run delete the live rule and create a\n * replacement, resetting its delivery bookkeeping. Preferred over `uuid`\n * when present.\n */\n adoptedUuid?: string;\n}\n\n/**\n * A uuid the action needs, either literal or as the builder that will own it.\n * Builders resolve at apply time, so a step can reference a Workflow created in\n * the same script without the author threading ids through by hand.\n */\nexport type UuidRef = string | WorkspaceBuilderResource;\n\n// ===========================================================================\n// Journey builder\n// ===========================================================================\n//\n// A Journey is one ordered timeline written atomically: touches in order, the\n// wait into each, exclusive branches, ordered Endings and goals.\n\n/** The wait on the edge INTO a touch. */\nexport interface WaitOptions {\n /**\n * Whole elapsed days since the previous touch's durable acceptance. The ONE\n * canonical shape the structured control round-trips — the server\n * regenerates the CEL from this number.\n */\n afterDays?: number;\n /**\n * Any other valid CEL, stored byte for byte. `duration(\"4h\")`, member-local\n * schedules, and everything else lives here; the editor evaluates it but\n * declines to reinterpret it. Mutually exclusive with `afterDays`.\n */\n when?: string;\n /** Hold the touch until the member matches this saved MemberFilter. */\n filterId?: number;\n // NOTE: there is no deadline option here. The evaluator implements no\n // deadline semantics, so the server's wait contract rejects the key rather\n // than accepting a setting that would never fire. Model \"stop waiting\" as\n // an Ending instead: it is evaluated on every tick and terminates the\n // enrollment explicitly.\n}\n\nexport interface TouchOptions {\n description?: string;\n wait?: WaitOptions;\n}\n\nexport interface EndingOptions {\n /**\n * The Ending's CEL condition. Optional ONLY when `filterId` is given —\n * an Ending with neither predicate would match every enrollment\n * (rule-filters plan §3.2).\n */\n when?: string;\n /**\n * A saved MemberFilter the member must be in. Given alongside `when` the two\n * are ANDed: the Ending claims a member only when both pass.\n */\n filterId?: number;\n}\n\nexport interface GoalOptions {\n description?: string;\n /** Touch or Ending whose completion satisfies the goal. */\n step?: TouchBuilder | EndingBuilder;\n completionCel?: string;\n value?: number;\n}\n\n/** One arm of an exclusive branch. */\nexport interface RouteOptions {\n /**\n * The route's CEL condition. Omit BOTH this and `filterId` to declare the\n * **Otherwise** route: an OPTIONAL fallback, taken immediately when nothing\n * above matched. At most one route per branch omits both, and it must be\n * declared last, because Otherwise matches immediately and anything after it\n * could never be reached.\n *\n * Declaring no Otherwise at all is the default shape, not an omission: the\n * branch is checked top to bottom on every pass and members WAIT at it until\n * a route matches. So there are two author intents, not one:\n *\n * - **wait for a match** — declare only conditional routes;\n * - **fall back immediately** — add a final route with no `when` and no\n * `filterId`.\n */\n when?: string;\n /**\n * A saved MemberFilter the member must be in (rule-filters plan §3.2).\n *\n * A route carrying only this is CONDITIONAL, not the fallback — that is the\n * whole reason `when` alone can no longer answer \"is this Otherwise?\".\n * Given alongside `when` the two are ANDed.\n */\n filterId?: number;\n /**\n * The touch this arm continues to after its own touches — the per-arm\n * terminus. Omit it and the arm ENDS: the enrollment completes after the\n * arm's last touch, or — for an arm with no touches at all — as soon as the\n * route is taken. An Ending still applies first. Absence is meaningful, so\n * there is no separate \"stop\" option to get out of step with it.\n */\n continueAt?: TouchBuilder;\n}\n\n/**\n * One route of a branch. Declaration order IS precedence — routes are checked\n * top to bottom and the first match wins.\n */\nexport class RouteBuilder {\n readonly touches: TouchBuilder[] = [];\n /**\n * The DECISION RULE uuid. Adopted for the same reason an Ending's is:\n * `MemberJourneyStep.entry_decision_rule_id` points at this row with\n * `ON DELETE SET NULL`, so recreating it on a re-run would erase which arm\n * every already-routed enrollment is on — invisibly, since both rules\n * \"exist\" afterwards.\n */\n _ruleUuid?: string;\n\n constructor(\n readonly name: string,\n readonly options: RouteOptions = {}\n ) {}\n\n /** Append a touch to this arm. Order is call order. */\n touch(name: string, options: TouchOptions = {}): TouchBuilder {\n const touch = new TouchBuilder(name, options);\n this.touches.push(touch);\n return touch;\n }\n}\n\n/**\n * The ordered route set attached to one touch.\n *\n * There is no branch ENTITY on the server and none is created here — a branch\n * is its rules, and its header is derived from the source touch. This class\n * exists only to group the routes with the touch that owns them.\n *\n * A branch needs at least one CONDITIONAL route. It does not need an Otherwise:\n * with none, members wait at the branch source and the routes are re-checked on\n * every pass until one matches. See {@link RouteOptions.when} for the two\n * fallback intents and how each is expressed.\n */\nexport class BranchBuilder {\n readonly routes: RouteBuilder[] = [];\n\n /** Append a route. Declaration order is evaluation order. */\n route(name: string, options: RouteOptions = {}): RouteBuilder {\n const route = new RouteBuilder(name, options);\n this.routes.push(route);\n return route;\n }\n}\n\n/** One ordinary touch in a timeline, plus the wait that leads into it. */\nexport class TouchBuilder {\n readonly rules: StepRuleDraft[] = [];\n /** Filled in from the server's response so a re-run keeps this touch. */\n _uuid?: string;\n\n /**\n * The exclusive branch that follows this touch, when it has one. A touch\n * carrying a branch gets NO ordinary outgoing connection: its routes are\n * the only way out, so touches declared after it are reached only by an arm\n * naming them in `continueAt`.\n */\n _branch?: BranchBuilder;\n\n readonly name: string;\n\n /**\n * The name is CANONICALIZED here, once, and everything downstream reads it:\n * the `key:<name>` address, the payload, adoption's name lookup, and the\n * uniqueness gate. The API trims it before storing\n * (`JourneyV2TouchInput`/`JourneyV2EndingInput` name validators), so a\n * builder holding `\" Welcome \"` would send an address for a name the server\n * does not have, fail to find its own step on the way back, and treat it as\n * new on the next run — archiving the live step and its history. One\n * representation at the boundary is the only way that cannot happen; a\n * second trim anywhere downstream would be a place for the two to drift.\n */\n constructor(\n name: string,\n readonly options: TouchOptions = {}\n ) {\n this.name = name.trim();\n }\n\n /**\n * Attach an exclusive branch after this touch, or return the existing one.\n *\n * Idempotent so a script can add routes in stages without accidentally\n * declaring two branches on one touch — which the server has no shape for,\n * since a touch owns exactly one ordered route set.\n */\n branch(): BranchBuilder {\n this._branch ??= new BranchBuilder();\n return this._branch;\n }\n\n /**\n * The request-local address this step answers to .\n *\n * A saved step is addressed by its uuid; an unsaved one by a `key` derived\n * from its authored name. Deriving from the NAME rather than minting a\n * uuid4 keeps the payload stable across re-runs of the same script — a\n * fresh random key on every run would make the request differ from itself\n * for no reason, and the server's EventRule sync matches on the uuids the\n * payload carries. Names are already asserted unique within a journey,\n * which is what makes a name-derived key unique.\n *\n * {@link EndingBuilder} INHERITS this rather than deriving its own: an\n * Ending's anchor key and a touch's key land in one server-side namespace\n * (`stepKey` is one field), so two derivations that drifted would produce\n * two spellings of the same address and a goal would 404 on the one its\n * step was not sent under.\n *\n * Two steps of one name therefore answer to one address. {@link preflight}\n * is the first enforcement point and refuses it before any write, counting\n * touches and Endings together and comparing names trimmed, as the API\n * stores them. Without that gate the collision surfaces twice and both\n * times too late: the server rejects the definition PUT after `apply()` has\n * created the Journey, and {@link indexStoredByName} rejects the SECOND run\n * of a script whose two stored steps make `adopt()` a coin flip.\n */\n get _address(): string {\n return this._uuid ?? `key:${this.name}`;\n }\n\n /**\n * Re-attach the EventRule uuids the server already stores for this touch.\n *\n * Identity is the operator-set rule NAME. `.sendsSms(...)` does not require\n * one, so an unnamed rule falls back to its actionType — but ONLY when that\n * answer is 1:1: exactly one unnamed draft of that actionType here, and\n * exactly one stored rule of it left unclaimed there. Anything else throws.\n *\n * The ordinal-within-actionType fallback this replaces was not a weaker\n * identity, it was the wrong one. Inserting a new unnamed rule ABOVE an\n * existing same-type rule shifts every position by one, so the new rule\n * adopted the existing rule's uuid — taking over its delivery bookkeeping —\n * and the existing rule was written as brand new and archived. Nothing in\n * the payload showed it: both rules \"exist\" afterwards. When the script\n * cannot say which rule is which, the honest answer is to ask the author to\n * name them, not to guess by position.\n */\n adoptRuleUuids(serverRules: AnyRecord[]): void {\n const namedDrafts = this.rules.filter((draft) => !!draft.options.name);\n const storedByName = indexStoredByName(\n serverRules,\n new Set(namedDrafts.map((draft) => draft.options.name as string)),\n `touch '${this.name}'`,\n 'action'\n );\n\n // A stored rule a named draft claims is out of the unnamed pool: it has\n // an owner, so it cannot also be the answer to an unnamed draft.\n const claimed = new Set<AnyRecord>();\n for (const draft of namedDrafts) {\n const match = storedByName.get(draft.options.name as string);\n // No stored rule of that name is an ordinary NEW rule — it keeps the\n // uuid the script minted and the server creates it. It must NOT fall\n // through to the unnamed path: a freshly named rule would there take\n // an existing rule's identity, and the existing rule would be\n // recreated and archived under it.\n if (!match) continue;\n draft.adoptedUuid = match.uuid as string;\n claimed.add(match);\n }\n\n const unnamedByActionType = new Map<string, StepRuleDraft[]>();\n for (const draft of this.rules) {\n if (draft.options.name) continue;\n const actionType = String(draft.actionType);\n unnamedByActionType.set(actionType, [\n ...(unnamedByActionType.get(actionType) ?? []),\n draft,\n ]);\n }\n for (const [actionType, drafts] of unnamedByActionType) {\n const candidates = serverRules.filter(\n (rule) => String(rule.actionType) === actionType && !claimed.has(rule)\n );\n // Nothing stored of this type: every draft is new, and creating them\n // is not a guess.\n if (!candidates.length) continue;\n if (drafts.length === 1 && candidates.length === 1) {\n drafts[0]!.adoptedUuid = candidates[0]!.uuid as string;\n continue;\n }\n throw new Error(\n `touch '${this.name}' has ${drafts.length} unnamed ${actionType} action(s) ` +\n `and the server has ${candidates.length} — so there is no way to tell ` +\n 'which stored action each one is. Adopting by position swaps their ' +\n 'identities the moment an action is inserted or removed, which moves ' +\n \"one action's delivery history onto another. Give these actions names \" +\n '(`{ name: ... }`) so each one can be matched to the right rule.'\n );\n }\n }\n\n /** Attach a `JOURNEY_STEP_EXECUTE` action. */\n onExecute(\n actionType: EventRuleActionType,\n params: AnyRecord = {},\n options: StepRuleOptions = {}\n ): TouchBuilder {\n this.rules.push({\n uuid: crypto.randomUUID(),\n actionType,\n actionParams: params,\n options,\n });\n return this;\n }\n\n sendsSms(\n params: {\n phoneNumberUUID: UuidRef;\n messageTemplate?: string;\n workflowUUID?: UuidRef;\n initialUserMessage?: string;\n },\n options: StepRuleOptions = {}\n ): TouchBuilder {\n return this.onExecute(EventRuleActionType.SMS_SEND, params, options);\n }\n\n callsMember(\n params: { phoneNumberUUID: UuidRef; workflowUUID: UuidRef },\n options: StepRuleOptions = {}\n ): TouchBuilder {\n return this.onExecute(EventRuleActionType.PHONE_CALL, params, options);\n }\n\n sendsEmail(\n params: {\n inboxUUID: UuidRef;\n subjectTemplate?: string;\n bodyTemplate?: string;\n workflowUUID?: UuidRef;\n },\n options: StepRuleOptions = {}\n ): TouchBuilder {\n return this.onExecute(EventRuleActionType.EMAIL_SEND, params, options);\n }\n\n get hasOutreach(): boolean {\n return this.rules.length > 0;\n }\n\n eventRuleInputs(): EventRuleInput[] {\n return this.rules.map((rule) => ({\n uuid: rule.adoptedUuid ?? rule.uuid,\n eventType: EventRuleEventType.JOURNEY_STEP_EXECUTE,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.options.name ? { name: rule.options.name } : {}),\n ...(rule.options.when ? { conditions: rule.options.when } : {}),\n ...(rule.options.delaySeconds ? { delay: rule.options.delaySeconds } : {}),\n active: rule.options.active ?? true,\n }));\n }\n}\n\n/** One ordered Ending. List position IS precedence — first match wins. */\nexport class EndingBuilder extends TouchBuilder {\n /**\n * The DECISION RULE uuid, distinct from `_uuid` (the anchor step's).\n *\n * An Ending is two rows: a `JourneyDecisionRule` carrying the condition and\n * precedence, and a `JourneyStep` anchor carrying its actions, goals, and\n * status history. Adopting only the anchor left the rule to be recreated on\n * every re-run — and `MemberJourney.latched_ending_rule_id` /\n * `JourneyStatusLog.journey_decision_rule_id` point at the RULE with\n * `ON DELETE SET NULL`, so every completed enrollment silently forgot which\n * Ending it took.\n */\n _ruleUuid?: string;\n\n constructor(\n name: string,\n readonly when: string | undefined,\n readonly filterId: number | undefined\n ) {\n super(name);\n }\n\n /**\n * An Ending cannot carry a branch, and saying so is the whole override.\n *\n * `EndingBuilder extends TouchBuilder` for the identity and addressing\n * an Ending's anchor shares with a touch, which also inherits every touch\n * method — `branch()` among them. Inherited unchanged it would set\n * `_branch` on an object nothing ever reads it from: the Ending serializer\n * writes `{uuid|key, name, celCondition, filterId, eventRules}` and no\n * `branch`, and `allTouches()` walks only the timeline, so the routes are\n * never numbered, validated, adopted or sent. The author gets no error and\n * a definition quietly missing what they asked for.\n *\n * An Ending is terminal by construction — it is the rule that ENDS an\n * enrollment — so there is no shape to serialize even if the payload had a\n * field for it. Refusing at the call is the only point where the author is\n * still holding the mistake.\n *\n * @see foreignAnchorProblem for why this names no Ending.\n */\n override branch(): never {\n throw new Error(\n 'an Ending cannot carry a branch. An Ending terminates an enrollment, ' +\n 'so there is nothing after it to route to, and the atomic definition ' +\n 'has no field to send one under — the routes would be silently ' +\n 'dropped. Put the branch on the touch that leads to this Ending ' +\n 'instead, and give each arm its own Ending.'\n );\n }\n}\n\nexport interface GoalDraft {\n name: string;\n description?: string;\n step?: TouchBuilder | EndingBuilder;\n completionCel?: string;\n value?: number;\n /** Server-assigned goal uuid, learned during adoption. */\n _uuid?: string;\n}\n\n/**\n * Build a Journey definition and write it through the ATOMIC endpoint.\n *\n * One create plus one `PUT /v2-definition`. That is not an optimization: a\n * definition is only valid as a whole, so a partial write would be rejected by\n * the publish validator anyway, and a half-applied timeline is exactly the\n * state the atomic endpoint exists to make impossible.\n */\nexport class JourneyBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly touches: TouchBuilder[] = [];\n readonly endings: EndingBuilder[] = [];\n readonly goals: GoalDraft[] = [];\n /** Activate after the definition is written and validated. */\n readonly activate: boolean;\n /** Optimistic-concurrency token, from create or adoption. */\n private _expectedUpdatedAt?: string;\n /** Server status at adoption — decides whether a re-run must pause first. */\n private _status?: string;\n /**\n * Server execution model at adoption. Only `'v2'` accepts the whole-definition\n * write `apply()` makes; anything else is refused at adoption, and `apply()`\n * re-checks it before its first write.\n */\n private _executionModel?: string;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.activate = options.activate ?? false;\n }\n\n /**\n * A definition write is idempotent, so an ADOPTED journey is written too.\n * That is the whole point of adopting one: the PUT is a full, uuid-keyed\n * replacement, so re-running a script is how an author expresses an edit.\n */\n get appliesWhenExisting(): boolean {\n return true;\n }\n\n /** Append a touch to the timeline. Order is call order. */\n touch(name: string, options: TouchOptions = {}): TouchBuilder {\n const touch = new TouchBuilder(name, options);\n this.touches.push(touch);\n return touch;\n }\n\n /**\n * Every touch in the timeline, arms included, depth first.\n *\n * Identity adoption, name-uniqueness and validation all have to see arm\n * touches — a walk over the top level alone would leave every arm touch\n * recreated on each re-run, silently archiving its member history.\n */\n allTouches(): TouchBuilder[] {\n const out: TouchBuilder[] = [];\n const walk = (touches: TouchBuilder[]): void => {\n for (const touch of touches) {\n out.push(touch);\n for (const route of touch._branch?.routes ?? []) walk(route.touches);\n }\n };\n walk(this.touches);\n return out;\n }\n\n /** Every route in the timeline, at every nesting depth, depth first. */\n allRoutes(): RouteBuilder[] {\n const out: RouteBuilder[] = [];\n for (const touch of this.allTouches()) {\n for (const route of touch._branch?.routes ?? []) out.push(route);\n }\n return out;\n }\n\n /** Append an Ending. Call order is evaluation order. */\n ending(name: string, options: EndingOptions): EndingBuilder {\n const ending = new EndingBuilder(name, options.when, options.filterId);\n this.endings.push(ending);\n return ending;\n }\n\n goal(name: string, options: GoalOptions = {}): JourneyBuilder {\n this.goals.push({\n name,\n description: options.description,\n step: options.step,\n completionCel: options.completionCel,\n value: options.value,\n });\n return this;\n }\n\n /**\n * Authoring problems the server's publish validator would reject.\n *\n * \"No incoming edge\" has no meaning in a timeline — position is the order —\n * so the checks here cover branch shape and Ending conditions. Touches\n * without actions pass through, with or without a wait.\n */\n validate(): string[] {\n const problems: string[] = [];\n if (!this.touches.length) {\n problems.push(\n `journey '${this.name}' has no touches — an empty timeline has nothing to execute.`\n );\n }\n for (const touch of this.allTouches()) {\n const branch = touch._branch;\n if (!branch) continue;\n // Otherwise is the route with NEITHER predicate. A filter-only route\n // is conditional, so counting it as a fallback here would report a\n // perfectly good branch as having two.\n const fallbacks = branch.routes.filter(\n (route) => !route.options.when?.trim() && route.options.filterId === undefined\n );\n // An Otherwise is OPTIONAL — a branch with only conditional routes\n // holds until one matches, and that is the default shape, so flagging\n // it would stop an author shipping the very thing the server prefers.\n // A CONDITIONAL route is still required: with nothing that can fail to\n // match, the first route takes every member and no decision is made.\n if (branch.routes.length - fallbacks.length < 1) {\n problems.push(\n `branch after touch '${touch.name}' needs at least one conditional ` +\n 'route — one declared with a `when`, a `filterId`, or both. ' +\n 'Members wait at the branch until a route matches, so an ' +\n 'Otherwise is optional.'\n );\n }\n if (fallbacks.length > 1) {\n problems.push(\n `branch after touch '${touch.name}' declares ${fallbacks.length} ` +\n 'Otherwise routes; a branch has at most one unconditional fallback.'\n );\n }\n if (fallbacks.length === 1 && branch.routes[branch.routes.length - 1] !== fallbacks[0]) {\n problems.push(\n `the Otherwise route of the branch after touch '${touch.name}' is ` +\n 'not last; it is taken immediately, so any route after it can ' +\n 'never be reached.'\n );\n }\n // A route with no touches and no `continueAt` is valid: nothing\n // follows it, so taking it ends the Journey.\n }\n for (const ending of this.endings) {\n if (!ending.when?.trim() && ending.filterId === undefined) {\n problems.push(\n `ending '${ending.name}' has no condition — an Ending that always ` +\n 'matches terminates every enrolment on evaluation order alone. ' +\n 'Give it a `when` expression, a `filterId`, or both.'\n );\n }\n }\n return problems;\n }\n\n /**\n * Shapes this definition cannot express, found BEFORE anything is written.\n *\n * A different list from {@link validate}, and a different consequence:\n * those are warnings the orchestrator prints and then writes anyway, these\n * are refusals. For each one the payload has no way to say what the script\n * asked for, so serializing past it would write a DIFFERENT program from\n * the one the script wrote, with nothing afterwards to say so.\n *\n * It has to run before the first write rather than during serialization,\n * because {@link apply} creates the Journey — or pauses a live one — before\n * it builds the payload. A refusal raised from `definitionPayload()` has\n * therefore already left an empty journey shell behind, or taken a\n * production program off the air.\n *\n * PURE: reads only what the script declared, never what the server holds,\n * so it is correct at any point — before adoption included — and\n * `WorkspaceBuilder.preflight()` can stay a synchronous, side-effect-free\n * check a caller may run directly. Nothing here needs adoption to have run:\n * an anchor the server has not seen is addressed by its request-local key,\n * so \"has this Ending been saved\" is no longer a question a refusal\n * depends on.\n */\n preflight(): string[] {\n const problems: string[] = [];\n this.allTouches().forEach((touch, index) => {\n const wait = touch.options.wait;\n if (wait?.afterDays !== undefined && wait.when) {\n problems.push(waitExclusivityProblem(index));\n }\n });\n const owned = this.ownedAnchors();\n this.goals.forEach((goal, index) => {\n const step = goal.step;\n if (step && !owned.has(step)) {\n problems.push(foreignAnchorProblem(index, anchorKind(step)));\n }\n });\n\n // Touches and Endings are ONE step-name namespace, and a repeat in it is\n // a defect whatever the save state. Unsaved, both address themselves\n // `key:<name>` and the definition resolves `stepKey` through a single\n // field, so two rows answer to one address — which the server refuses on\n // the definition PUT, i.e. after `apply()` has created the Journey or\n // paused a live one. Saved, they are two stored steps of one name, which\n // is what {@link indexStoredByName} refuses on the NEXT run.\n //\n // Names arrive canonical (`TouchBuilder` trims in its constructor, and\n // `EndingBuilder` inherits it), so `\"Welcome\"` and `\" Welcome \"` are\n // already one name here rather than two this gate would wave through.\n //\n // `assertUnambiguousNames()` checks each kind separately and runs from\n // `adopt()`, which a brand-new Journey never reaches — so it cannot be\n // this gate. It still owns routes and goals, whose namespaces are their\n // own.\n const stepNames = [\n ...this.allTouches().map((touch) => touch.name),\n ...this.endings.map((ending) => ending.name),\n ];\n const claims = new Map<string, number>();\n for (const name of stepNames) claims.set(name, (claims.get(name) ?? 0) + 1);\n const repeated = [...claims.values()].filter((count) => count > 1).length;\n if (repeated) problems.push(sharedStepNameProblem(repeated));\n\n // A name that is only whitespace canonicalizes to nothing, which the API\n // refuses (\"name cannot be empty\") — but on the definition PUT, after\n // `apply()` has created the Journey or paused a live one. It also has no\n // usable address: every empty name would claim `key:`. Refusing it here\n // is the same answer, before the first write.\n const nameless = stepNames.filter((name) => !name).length;\n if (nameless) problems.push(namelessStepProblem(nameless));\n return problems;\n }\n\n /**\n * Every step a goal in THIS journey can anchor to, compared by object\n * identity — touches AND Endings, which is why the element type names both\n * rather than leaning on `EndingBuilder extends TouchBuilder` to smuggle\n * Endings in under a touch-only annotation.\n *\n * A goal anchored to some other journey's builder is not a near miss the\n * server can catch: an unsaved one sends a `stepKey` this definition never\n * declares (a 404 whose cause is invisible), and a SAVED one sends a real\n * `stepUuid` belonging to a live step somewhere else.\n */\n private ownedAnchors(): ReadonlySet<TouchBuilder | EndingBuilder> {\n return new Set<TouchBuilder | EndingBuilder>([...this.allTouches(), ...this.endings]);\n }\n\n planLine(): string {\n const parts: string[] = [];\n const touchCount = this.allTouches().length;\n const routeCount = this.allRoutes().length;\n if (touchCount) parts.push(`${touchCount} touches`);\n if (routeCount) parts.push(`${routeCount} routes`);\n if (this.endings.length) parts.push(`${this.endings.length} endings`);\n if (this.goals.length) parts.push(`${this.goals.length} goals`);\n return `Journey: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n /**\n * Re-attach every stable child identity the server already holds.\n *\n * The atomic endpoint is a FULL REPLACEMENT keyed on uuids: an omitted\n * uuid does not mean \"unchanged\", it means \"create a new one and archive\n * whatever the old one was\". So anything this misses is silently recreated\n * on every re-run of the same script — and a script is normally re-run,\n * because a program is built in stages. Each identity has a different thing\n * hanging off it, and losing it costs something specific:\n *\n * | identity | what re-creating it destroys |\n * |---|---|\n * | touch step uuid | the touch's `MemberJourneyStep` history |\n * | EventRule uuid | that action's delivery bookkeeping |\n * | Ending RULE uuid | which Ending completed enrollments latched |\n * | Ending anchor uuid | the Ending's status history and goal anchor |\n * | goal uuid | every member's satisfaction row for that goal |\n *\n * `existing` is the journey DETAIL or AUTHORING projection. Both carry\n * `steps[].eventRules`, `goals`, and `decisionRules` —\n * the read projection redacts CEL, not identity — so one fetch is enough\n * and no second round trip is needed. (The orchestrator asks for the\n * authoring projection anyway: this builder holds `journeys:write` because\n * it is about to PUT, and the superset costs nothing.)\n *\n * Names are the only key available on a FIRST adoption, and a duplicate\n * name makes adoption a coin flip between two live resources. That throws\n * rather than guessing: silently attaching a touch to the wrong step\n * archives real member history.\n */\n adopt(existing: AnyRecord): void {\n // First, before any builder state changes: the definition write this\n // builder makes is refused for any other execution model, and `apply()`\n // may PAUSE a live Journey before that write. A missing value means\n // legacy (see `Journey.executionModel`), so it is refused too.\n if (existing.executionModel !== 'v2') {\n throw new UnadoptableJourneyError(this.name, existing.id);\n }\n super.adopt(existing);\n this._expectedUpdatedAt = existing.updatedAt as string | undefined;\n this._status = existing.status as string | undefined;\n this._executionModel = existing.executionModel;\n this.assertUnambiguousNames();\n this.adoptChildIdentities(existing);\n }\n\n /** Reject a script whose own names cannot identify a resource. */\n private assertUnambiguousNames(): void {\n assertUniqueNames(\n this.allTouches().map((touch) => touch.name),\n `journey '${this.name}'`,\n 'touch'\n );\n // Route names are the adoption key for a route's DECISION RULE, exactly\n // as an Ending's name is, so they must be unique across the whole\n // journey rather than only within their own branch — two branches each\n // with a route called \"Escalate\" would make adoption a coin flip\n // between two live rules.\n assertUniqueNames(\n this.allRoutes().map((route) => route.name),\n `journey '${this.name}'`,\n 'route'\n );\n assertUniqueNames(\n this.endings.map((ending) => ending.name),\n `journey '${this.name}'`,\n 'ending'\n );\n assertUniqueNames(\n this.goals.map((goal) => goal.name),\n `journey '${this.name}'`,\n 'goal'\n );\n for (const touch of [...this.allTouches(), ...this.endings]) {\n const names = touch.rules.map((rule) => rule.options.name).filter(Boolean) as string[];\n assertUniqueNames(names, `touch '${touch.name}'`, 'action name');\n }\n }\n\n private adoptChildIdentities(payload: AnyRecord): void {\n const steps = (payload.steps ?? []) as AnyRecord[];\n // The step names this script will actually look up. Everything below\n // matches STORED rows by name, and neither the table nor the publish\n // validator makes those names unique — so a plain `new Map(...)` would\n // quietly keep the last row of a duplicated name and adopt an arbitrary\n // one of two live identities, archiving the other's member history on\n // the next save. A duplicate the script never names is nobody's problem\n // and is left alone.\n const referencedStepNames = new Set([\n ...this.allTouches().map((touch) => touch.name),\n ...this.endings.map((ending) => ending.name),\n ]);\n const stepsByName = indexStoredByName(\n steps,\n referencedStepNames,\n `journey '${this.name}'`,\n 'step'\n );\n const stepsById = new Map(steps.map((step) => [step.id as number, step]));\n\n for (const touch of this.allTouches()) {\n const match = stepsByName.get(touch.name);\n if (!match) continue;\n touch._uuid = match.uuid as string;\n touch.adoptRuleUuids((match.eventRules ?? []) as AnyRecord[]);\n }\n\n // Branch ROUTES are the complement of the Ending filter below: same\n // table, same identity argument, different product. Indexed by name for\n // the same reason Endings are — a route's uuid is the only thing that\n // survives a re-run, and nothing else in the payload identifies it.\n const routeRules = ((payload.decisionRules ?? []) as AnyRecord[]).filter(\n (rule) => rule.sourceStepId !== null && rule.sourceStepId !== undefined\n );\n const declaredRoutes = this.allRoutes();\n const routesByName = indexStoredByName(\n routeRules,\n new Set(declaredRoutes.map((route) => route.name)),\n `journey '${this.name}'`,\n 'route'\n );\n for (const route of declaredRoutes) {\n const stored = routesByName.get(route.name);\n if (stored) route._ruleUuid = stored.uuid as string;\n }\n\n // An Ending's identity is its decision RULE; the anchor is reached\n // through the rule's target rather than by name, so an adopted Ending\n // never picks up a touch's step. (An Ending and a touch DECLARED under\n // one name are still two stored steps sharing a name, which the step\n // index above refuses — from the touch's side, where the ambiguity is\n // real.)\n const endingRules = ((payload.decisionRules ?? []) as AnyRecord[]).filter(\n (rule) => rule.sourceStepId === null || rule.sourceStepId === undefined\n );\n const rulesByName = indexStoredByName(\n endingRules,\n new Set(this.endings.map((ending) => ending.name)),\n `journey '${this.name}'`,\n 'ending'\n );\n for (const ending of this.endings) {\n const rule = rulesByName.get(ending.name);\n const anchor = rule\n ? stepsById.get(rule.targetStepId as number)\n : stepsByName.get(ending.name);\n if (rule) ending._ruleUuid = rule.uuid as string;\n if (!anchor) continue;\n ending._uuid = anchor.uuid as string;\n ending.adoptRuleUuids((anchor.eventRules ?? []) as AnyRecord[]);\n }\n\n const goalsByName = indexStoredByName(\n (payload.goals ?? []) as AnyRecord[],\n new Set(this.goals.map((goal) => goal.name)),\n `journey '${this.name}'`,\n 'goal'\n );\n for (const goal of this.goals) {\n const match = goalsByName.get(goal.name);\n if (match) goal._uuid = match.uuid as string;\n }\n }\n\n /** The atomic request body. Exposed so a test can assert it without HTTP. */\n definitionPayload(): JourneyV2DefinitionFormData {\n const owned = this.ownedAnchors();\n // Depth-first position, numbered exactly as `preflight()` numbers it, so\n // a refusal raised down in the serializer names the same touch the\n // pre-write gate would have named.\n const positions: ReadonlyMap<TouchBuilder, number> = new Map(\n this.allTouches().map((touch, index) => [touch, index])\n );\n return {\n expectedUpdatedAt: this._expectedUpdatedAt ?? '',\n touches: this.touches.map((touch) => serializeTouch(touch, positions)),\n endings: this.endings.map((ending): JourneyV2EndingInput => ({\n ...(ending._ruleUuid ? { uuid: ending._ruleUuid } : {}),\n // Anchor address, exactly as `serializeTouch` sends a touch's:\n // the saved anchor's uuid, or the request-local `key` a goal in\n // this same save names it by. Both come from `_address`, so the\n // Ending and the goal cannot be sent under two spellings.\n ...(ending._uuid ? { anchorUuid: ending._uuid } : { key: ending._address }),\n name: ending.name,\n // The two predicates are sent INDEPENDENTLY (rule-filters plan\n // §3.2). A filter-only Ending carries no `celCondition` at all\n // rather than an empty one the server would have to normalize.\n ...(ending.when ? { celCondition: ending.when } : {}),\n ...(ending.filterId !== undefined ? { filterId: ending.filterId } : {}),\n eventRules: ending.eventRuleInputs(),\n })),\n // ALWAYS sent, `[]` included. The field distinguishes omitted (leave\n // goals alone) from empty (delete them), and this builder owns the\n // goal list — so omitting an empty list would make goal REMOVAL the\n // one edit a script cannot express: delete the `.goal(...)` call, re-run,\n // and the goal stays live forever.\n goals: this.goals.map((goal, index): JourneyV2GoalInput => ({\n ...(goal._uuid ? { uuid: goal._uuid } : {}),\n name: goal.name,\n ...(goal.description ? { description: goal.description } : {}),\n ...serializeGoalAnchor(goal.step, index, owned),\n ...(goal.completionCel ? { completionCel: goal.completionCel } : {}),\n ...(goal.value !== undefined ? { value: goal.value } : {}),\n })),\n };\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n // `WorkspaceBuilder.apply()` gates this, but the class is exported and a\n // direct caller gets no gate at all — while the first statements below\n // are writes. Refuse here too, so an invalid plan never leaves an empty\n // shell behind or pauses a production Journey.\n const problems = this.preflight();\n if (problems.length) {\n throw new Error(\n `Journey has ${problems.length} problem(s) and was not applied:\\n` +\n problems.map((problem) => ` - ${problem}`).join('\\n')\n );\n }\n\n // The class is exported and `_existed` is a public field, so a caller can\n // reach here without `adopt()`. An existing Journey whose execution model\n // is not known to accept the definition write is refused before the\n // pause below — pausing and then having the write refused would leave a\n // live program off.\n if (this._existed && this._executionModel !== 'v2') {\n throw new UnadoptableJourneyError(this.name, this._id);\n }\n\n if (!this._existed) {\n const created = await client.createJourney({\n name: this.name,\n description: this.description,\n });\n this._id = created.id;\n this._uuid = created.uuid;\n this._created = true;\n this._expectedUpdatedAt = created.updatedAt;\n } else if (this._status === 'active' && this.activate) {\n // A live Journey's topology is immutable, so a re-run has to pause\n // before it can write, and re-read for a fresh concurrency token.\n //\n // Only when the script ASKED for an active Journey. Pausing one it\n // did not ask to activate would take a production program off the air\n // as a side effect of re-running a script; without `activate` the\n // server's stable `journey_v2_structural_edit_not_allowed` refusal is\n // the right answer, and it tells the operator exactly what to do.\n const paused = await client.updateJourney(this.id, { status: 'paused' });\n this._expectedUpdatedAt = paused.updatedAt;\n }\n\n const saved = await client.putJourneyDefinition(this.id, this.definitionPayload());\n this._expectedUpdatedAt = saved.updatedAt;\n this.adoptWrittenUuids(saved);\n\n if (this.activate) {\n await client.updateJourney(this.id, { status: 'active' });\n }\n }\n\n /**\n * Re-attach the uuids the server assigned, so a follow-up write matches.\n *\n * The PUT returns the AUTHORING projection, which is the same shape\n * `adopt` reads — so this is the same operation against a payload we just\n * caused, and it uses the same code path rather than a second, thinner\n * copy that would drift.\n */\n private adoptWrittenUuids(saved: AnyRecord): void {\n this.adoptChildIdentities(saved);\n }\n}\n\n/**\n * Index STORED rows by name, refusing a name the script matches that more than\n * one stored row answers to.\n *\n * The mirror image of {@link assertUniqueNames}: that one rejects a script\n * whose own names are ambiguous, this one rejects a SERVER state the script's\n * names cannot resolve. Both halves are needed, because nothing makes a\n * journey's step, Ending, goal, or action names unique — not the tables, not\n * the publish validator — so the ambiguity can arrive from the editor long\n * after a clean script was written.\n *\n * `referenced` is the set of names the script will look up. A stored duplicate\n * outside it is harmless: nothing in this script will ever choose between\n * those two rows, and refusing to run because of a resource the script does\n * not touch would be a gate the author cannot act on.\n */\nfunction indexStoredByName(\n rows: AnyRecord[],\n referenced: Set<string>,\n owner: string,\n kind: string\n): Map<string, AnyRecord> {\n const byName = new Map<string, AnyRecord>();\n const counts = new Map<string, number>();\n for (const row of rows) {\n const name = row.name;\n if (typeof name !== 'string' || !name) continue;\n counts.set(name, (counts.get(name) ?? 0) + 1);\n if (!byName.has(name)) byName.set(name, row);\n }\n for (const [name, count] of counts) {\n if (count < 2 || !referenced.has(name)) continue;\n throw new Error(\n `${owner} already has ${count} ${kind}s named '${name}'. This script adopts ` +\n `by name, so it cannot tell which ${kind} it owns — and the one it does ` +\n 'not pick is archived on the next save, taking its history with it. ' +\n `Rename them so each name identifies one ${kind}.`\n );\n }\n return byName;\n}\n\n/**\n * The refusal for an existing Journey the builder cannot write: its definition\n * write is a whole replacement, which only a current Journey accepts. Thrown\n * before any write, so nothing on the server has changed.\n */\nexport class UnadoptableJourneyError extends Error {\n readonly journeyId: unknown;\n readonly journeyName: string;\n\n constructor(name: string, id: unknown) {\n super(\n `Journey ${String(id)} ('${name}') is a Journey the builder cannot adopt: the ` +\n \"script replaces a Journey's whole definition on save, and this Journey was \" +\n 'built with the older Journey editor, which does not accept that write. ' +\n 'Nothing was changed. Rebuild it as a current Journey, or rename the ' +\n 'journey in the script so the builder creates a new one.'\n );\n this.name = 'UnadoptableJourneyError';\n this.journeyId = id;\n this.journeyName = name;\n }\n}\n\n/** Throw when a builder's own names cannot identify a resource. */\nfunction assertUniqueNames(names: string[], owner: string, kind: string): void {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n throw new Error(\n `${owner} has two ${kind}s named '${name}'. The builder adopts an ` +\n 'existing journey by name, so duplicates would attach a builder to ' +\n \"either one at random — archiving the other's history on the next \" +\n 'save. Rename one.'\n );\n }\n seen.add(name);\n }\n}\n\n/** Translate builder wait options into the server's structured wait. */\n/**\n * Serialize one touch and, recursively, the branch it owns.\n *\n * A free function rather than a method so the recursion reads as one shape:\n * touch -> branch -> routes -> arm touches -> … . `key` is sent whenever the\n * touch has no server uuid yet, because an arm can only name an unsaved\n * rejoin target through the request-local address .\n */\nfunction serializeTouch(\n touch: TouchBuilder,\n positions: ReadonlyMap<TouchBuilder, number>\n): JourneyV2TouchInput {\n return {\n ...(touch._uuid ? { uuid: touch._uuid } : { key: touch._address }),\n name: touch.name,\n ...(touch.options.description ? { description: touch.options.description } : {}),\n ...(touch.options.wait ? { wait: buildWait(touch.options.wait, positions.get(touch)) } : {}),\n eventRules: touch.eventRuleInputs(),\n ...(touch._branch\n ? {\n branch: {\n routes: touch._branch.routes.map((route) => ({\n ...(route._ruleUuid ? { uuid: route._ruleUuid } : {}),\n name: route.name,\n // Omitted, not null, and INDEPENDENT of each other: a route\n // with neither predicate IS the Otherwise marker, one with\n // either is conditional, and one with both is ANDed\n // (rule-filters plan §3.2). The server normalizes \"\" to the\n // same thing as omitted.\n ...(route.options.when ? { celCondition: route.options.when } : {}),\n ...(route.options.filterId !== undefined\n ? { filterId: route.options.filterId }\n : {}),\n touches: route.touches.map((armTouch) => serializeTouch(armTouch, positions)),\n ...(route.options.continueAt\n ? { continueAt: route.options.continueAt._address }\n : {}),\n })),\n },\n }\n : {}),\n };\n}\n\n/**\n * How a goal names its anchor step in the atomic payload.\n *\n * A saved anchor is named by `stepUuid`. An unsaved one — a touch or an\n * Ending's anchor alike — is named by `stepKey`, carrying the same\n * request-local address the step itself is sent under, because on the FIRST\n * save of a timeline nothing has a uuid yet and a client cannot mint one.\n * Sending nothing there is not a missing decoration: an anchored goal is\n * satisfied only when its step is reached AND its CEL holds, so the goal that\n * reached the server would be a different rule from the one the script wrote.\n *\n * `owned` is the set of steps this journey declares, compared by object\n * identity: a goal anchored to another builder's step would otherwise send a\n * `stepKey` this definition never declares, or a live `stepUuid` belonging to\n * a step in some other journey. That is the one thing this cannot express, and\n * it THROWS rather than serializing to nothing — dropping an anchor is silent,\n * the payload is valid, the write succeeds, and nothing afterwards says so.\n *\n * The refusal is the LAST line of defence. `WorkspaceBuilder.apply()` gates on\n * {@link JourneyBuilder.preflight} before it writes anything; this fires\n * only for a caller that reached `definitionPayload()` directly, and it raises\n * the identical sentence so the two paths cannot drift.\n */\nfunction serializeGoalAnchor(\n step: TouchBuilder | EndingBuilder | undefined,\n goalIndex: number,\n owned: ReadonlySet<TouchBuilder | EndingBuilder>\n): Pick<JourneyV2GoalInput, 'stepUuid' | 'stepKey'> {\n if (!step) return {};\n if (!owned.has(step)) throw new Error(foreignAnchorProblem(goalIndex, anchorKind(step)));\n if (step._uuid) return { stepUuid: step._uuid };\n return { stepKey: step._address };\n}\n\n/**\n * The two refusals, worded once.\n *\n * Both the pre-write gate and the serializer raise these, so an author who\n * trips the last line of defence reads the sentence the gate would have\n * printed. Each names the offender by POSITION and the anchor by KIND, never\n * by the name the script gave it: these strings reach operator terminals, CI\n * logs and exception trackers, and an authored touch, goal or Ending name is\n * workspace content that has no business in any of them.\n */\nfunction foreignAnchorProblem(goalIndex: number, kind: 'touch' | 'Ending'): string {\n return (\n `goal at index ${goalIndex} is anchored to ${kind === 'Ending' ? 'an' : 'a'} ` +\n `${kind} that belongs to a different journey builder. A goal anchor is ` +\n 'part of the same atomic definition as its step, so it can only name a ' +\n 'touch or Ending this journey declares.'\n );\n}\n\n/**\n * `touchIndex` is the touch's depth-first position, absent only for a direct\n * caller of {@link buildWait} that has no timeline to position it in.\n *\n * @see foreignAnchorProblem for why these carry positions and not names.\n */\nfunction waitExclusivityProblem(touchIndex: number | undefined): string {\n const where = touchIndex === undefined ? 'this touch' : `touch at index ${touchIndex}`;\n return (\n `${where} sets both afterDays and when; fold the day count into \\`when\\`. ` +\n 'A wait is either a whole-day count or Advanced CEL, not both.'\n );\n}\n\n/**\n * Step names claimed more than once, counted across touches AND Endings.\n *\n * @see foreignAnchorProblem for why this counts them and does not name them.\n */\nfunction sharedStepNameProblem(count: number): string {\n return (\n `${count} step name(s) are claimed more than once. Touches and Endings ` +\n 'are one namespace: until a save mints their uuids they address ' +\n 'themselves by name and the definition resolves those keys through one ' +\n 'field, and once saved they are stored steps the next run cannot tell ' +\n 'apart. Names are canonical (trimmed), as the API stores them. Rename one.'\n );\n}\n\n/**\n * Steps whose canonical name is empty.\n *\n * @see foreignAnchorProblem for why this counts them and does not name them.\n */\nfunction namelessStepProblem(count: number): string {\n return (\n `${count} step(s) have an empty name once trimmed. A step's name is its ` +\n 'request-local address until a save mints its uuid, so a nameless one ' +\n 'has nothing to be addressed by, and the API refuses it. Name them.'\n );\n}\n\n/** How a refusal names an anchor: by what it IS, never by what it is called. */\nfunction anchorKind(step: TouchBuilder | EndingBuilder): 'touch' | 'Ending' {\n return step instanceof EndingBuilder ? 'Ending' : 'touch';\n}\n\nexport function buildWait(wait: WaitOptions, touchIndex?: number): JourneyV2WaitInput {\n if (wait.afterDays !== undefined && wait.when) {\n throw new Error(waitExclusivityProblem(touchIndex));\n }\n const extras = {\n ...(wait.filterId !== undefined ? { filterId: wait.filterId } : {}),\n };\n if (wait.afterDays !== undefined) {\n return { kind: 'wholeDays', days: wait.afterDays, ...extras };\n }\n if (wait.when) {\n return { kind: 'advanced', cel: wait.when, ...extras };\n }\n return { kind: 'none', ...extras };\n}\n","import {\n EventRuleEventType,\n type CreateAgentRequest,\n type EventRuleActionType,\n type WorkflowFormData,\n} from '../types';\nimport type { Ability } from '../types/ability-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport type { FormBuilder } from './forms';\nimport { type AnyRecord, WorkspaceBuilderResource } from './resource';\n\nconst PERM_KEYS: Record<string, string> = {\n canRead: 'canRead',\n canCreate: 'canCreate',\n canEdit: 'canEdit',\n can_read: 'canRead',\n can_create: 'canCreate',\n can_edit: 'canEdit',\n};\n\nconst ABILITY_TYPE_MAP: Record<string, string> = {\n data_access: 'integration:data_access',\n file_access: 'integration:file_access',\n escalation: 'oversight:escalation',\n};\n\nclass AbilityDef {\n readonly uuid = crypto.randomUUID();\n readonly config: AnyRecord;\n readonly enabled: boolean;\n readonly celCondition?: string;\n readonly form?: FormBuilder;\n readonly perms: AnyRecord = {};\n\n constructor(\n readonly abilityType: string,\n options: AnyRecord = {}\n ) {\n this.config = options.config ?? {};\n this.enabled = options.enabled ?? true;\n this.celCondition = options.celCondition ?? options.cel_condition;\n this.form = options.form;\n for (const [inputKey, outputKey] of Object.entries(PERM_KEYS)) {\n if (inputKey in options) this.perms[outputKey] = options[inputKey];\n }\n }\n\n toAbility(): Ability {\n const config = { ...this.config };\n if (this.form?._uuid) {\n config.dataTypeUuid = this.form._uuid;\n Object.assign(config, this.perms);\n }\n return {\n uuid: this.uuid,\n abilityType: ABILITY_TYPE_MAP[this.abilityType] ?? this.abilityType,\n config,\n enabled: this.enabled,\n ...(this.celCondition ? { celCondition: this.celCondition } : {}),\n };\n }\n}\n\n/** Compatibility transport for transitionsTo; CEL is Path availability, flags select automatically. */\nexport interface TaskTransition {\n parent: TaskBuilder;\n child: TaskBuilder;\n when: string;\n autoNext: boolean;\n required: boolean;\n celCondition?: string;\n}\n\nexport interface WorkflowBuilderOptions {\n description?: string;\n prompt?: string;\n copyFromAgentId?: number;\n}\n\nexport class TaskBuilder extends WorkspaceBuilderResource {\n readonly transitions: TaskTransition[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n /** Child task ids the server already has, recorded when this task is adopted. */\n readonly existingChildIds = new Set<number>();\n\n /** Record the edges an adopted task already carries, so a re-run adds only what is missing. */\n adopt(existing: AnyRecord): void {\n super.adopt(existing);\n for (const child of (existing.childTasks ?? []) as AnyRecord[]) {\n const id = child.taskId ?? child.id;\n if (typeof id === 'number') this.existingChildIds.add(id);\n }\n }\n\n constructor(\n readonly name: string,\n readonly workflow: WorkflowBuilder,\n readonly prompt = '',\n readonly start = false,\n readonly description = ''\n ) {\n super();\n }\n\n transitionsTo(\n child: TaskBuilder,\n when: string,\n autoNext = false,\n required = false,\n celCondition?: string\n ): TaskBuilder {\n if (child === this) {\n throw new Error(`Task '${this.name}' cannot transition to itself`);\n }\n this.transitions.push({\n parent: this,\n child,\n when,\n autoNext,\n required,\n celCondition,\n });\n return this;\n }\n\n onEnter(action: string, params: AnyRecord = {}, name?: string): TaskBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.TASK_EXECUTE,\n actionType: action as EventRuleActionType,\n actionParams: params,\n name,\n });\n return this;\n }\n\n initialMessage(message: string, suggestions?: string[]): TaskBuilder {\n return this.onEnter('assistant:message', {\n message,\n ...(suggestions ? { suggestions } : {}),\n });\n }\n\n planLine(): string {\n return `Task: ${this.name}${this.start ? ' [start]' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed || this.workflow._id === undefined) return;\n if (this.workflow._draftRevisionId === undefined) {\n // Root id without a draft revision id means the workflow was\n // created/adopted through a path that skipped revision resolution —\n // creating the task would attach it to whatever revision happens to\n // share the number (cross-workflow corruption). Fail loudly.\n throw new Error(\n `Workflow '${this.workflow.name}' has no draft revision id; ` +\n 'cannot create tasks. Tasks attach to a WorkflowRevision, ' +\n 'not the stable workflow root.'\n );\n }\n // Tasks belong to a revision graph — target the DRAFT revision\n // explicitly (edits always land on the draft; publish makes them live).\n const result = await client.createTask({\n workflowRevisionId: this.workflow._draftRevisionId,\n name: this.name,\n prompt: this.prompt,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class WorkflowBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly prompt?: string;\n private copyFromAgentId?: number;\n readonly tasks: TaskBuilder[] = [];\n readonly abilities: AbilityDef[] = [];\n /** The DRAFT revision's id — where tasks and graph edits attach.\n * `_id` is the STABLE workflow root id; the two are different entities\n * and (after any publish) different numbers. */\n _draftRevisionId?: number;\n\n constructor(\n readonly name: string,\n options: WorkflowBuilderOptions = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.prompt = options.prompt;\n this.copyFromAgentId = options.copyFromAgentId;\n }\n\n task(name: string, options: AnyRecord = {}): TaskBuilder {\n const task = new TaskBuilder(\n name,\n this,\n options.prompt ?? '',\n options.start ?? false,\n options.description ?? ''\n );\n this.tasks.push(task);\n return task;\n }\n\n ability(abilityType: string, options: AnyRecord = {}): WorkflowBuilder {\n this.abilities.push(new AbilityDef(abilityType, options));\n return this;\n }\n\n get startTask(): TaskBuilder | undefined {\n return this.tasks.find((task) => task.start) ?? this.tasks[0];\n }\n\n matchKey(): string {\n return this.name;\n }\n\n adopt(existing: AnyRecord): void {\n // Accepts the WorkflowDetail composition ({ workflow, draftRevision,\n // activeRevision }) — the orchestrator fetches it per matched name.\n // Root facts (id/uuid) live on `workflow`; graph facts (startTaskId)\n // live on the draft revision.\n const root = (existing.workflow ?? existing) as AnyRecord;\n super.adopt(root);\n const draft = existing.draftRevision as AnyRecord | undefined;\n this._draftRevisionId = (draft?.id ?? root.draftRevisionId) as number | undefined;\n const start = this.startTask;\n const startTaskId = draft?.startTaskId as number | undefined;\n if (start && startTaskId) {\n start._id = startTaskId;\n start._existed = true;\n }\n }\n\n planLine(): string {\n const details: string[] = [];\n if (this.tasks.length) details.push(`${this.tasks.length} tasks`);\n if (this.abilities.length) details.push(`${this.abilities.length} abilities`);\n return `Workflow: ${this.name}${details.length ? ` (${details.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: WorkflowFormData = {\n name: this.name,\n description: this.description,\n createMode: 'taskless',\n ...(this.prompt ? { prompt: this.prompt } : {}),\n ...(this.copyFromAgentId ? { copyFromAgentId: this.copyFromAgentId } : {}),\n ...(this.abilities.length\n ? { abilities: this.abilities.map((ability) => ability.toAbility()) }\n : {}),\n };\n const result = await client.createWorkflow(payload);\n this._id = result.workflow.id;\n this._uuid = result.workflow.uuid;\n // Tasks attach to the draft revision, never the root — keep its id.\n this._draftRevisionId = result.draftRevision.id;\n this._created = true;\n }\n}\n\nexport class AgentBuilder extends WorkspaceBuilderResource {\n readonly chatModelId: string;\n readonly systemPrompt: string;\n readonly memberRoleId?: number;\n readonly tools: string[];\n readonly codeInterpreterEnabled: boolean;\n readonly webBrowserEnabled: boolean;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.chatModelId = options.chatModelId ?? options.chat_model_id ?? '';\n this.systemPrompt = options.systemPrompt ?? options.system_prompt ?? '';\n this.memberRoleId = options.roleId ?? options.role_id;\n this.tools = options.tools ?? [];\n this.codeInterpreterEnabled =\n options.codeInterpreterEnabled ?? options.code_interpreter_enabled ?? false;\n this.webBrowserEnabled = options.webBrowserEnabled ?? options.web_browser_enabled ?? false;\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.chatModelId) parts.push(`model=${this.chatModelId}`);\n if (this.tools.length) parts.push(`${this.tools.length} tools`);\n return `Agent: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n if (this.memberRoleId === undefined) {\n throw new Error(`Agent '${this.name}' requires memberRoleId`);\n }\n if (!this.chatModelId) {\n throw new Error(`Agent '${this.name}' requires chatModelId`);\n }\n\n const payload: CreateAgentRequest = {\n name: this.name,\n memberRoleId: this.memberRoleId,\n chatModelId: this.chatModelId,\n systemPrompt: this.systemPrompt,\n ...(this.tools.length ? { tools: this.tools } : {}),\n ...(this.codeInterpreterEnabled ? { codeInterpreterEnabled: true } : {}),\n ...(this.webBrowserEnabled ? { webBrowserEnabled: true } : {}),\n };\n const result = await client.createAgent(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n","import {\n EventRuleObjectType,\n type EventRule,\n type EventRuleFormData,\n type UpdateEventRuleFormData,\n} from '../types';\nimport { ApiError } from '../api/base';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { MemberFilterBuilder, NotificationRuleBuilder, RoutineBuilder } from './automation';\nimport { FormBuilder, MemberLabelBuilder } from './forms';\nimport { JourneyBuilder } from './journeys';\nimport {\n type AnyRecord,\n type ResourceSummary,\n resolveRefs,\n WorkspaceBuilderResource,\n} from './resource';\nimport {\n AgentBuilder,\n TaskBuilder,\n type TaskTransition,\n WorkflowBuilder,\n type WorkflowBuilderOptions,\n} from './workflows';\n\nconst PHASES = new Map<Function, number>([\n [FormBuilder, 0],\n [MemberLabelBuilder, 0],\n [AgentBuilder, 1],\n [WorkflowBuilder, 2],\n [TaskBuilder, 3],\n [MemberFilterBuilder, 5],\n [RoutineBuilder, 6],\n [NotificationRuleBuilder, 6],\n // A Journey is written whole by its own apply(), so it has no child\n // resources to sequence after it.\n [JourneyBuilder, 7],\n]);\n\n/**\n * Page size for the adoption sweeps.\n *\n * Adoption has to see every resource of a type, not the first screenful — the\n * list routes default to 10 per page, so a workspace with a dozen routines\n * would leave the eleventh undiscovered and duplicated on every re-run. 100 is\n * the max these routes allow; `collectPages` walks the rest.\n */\nconst LIST_PAGE_SIZE = 100;\n\n/**\n * Read every page of a paginated list endpoint.\n *\n * `totalPages` is trusted for the bound but the walk also stops on an empty\n * page, so a backend that reports the count differently cannot spin here.\n */\nasync function collectPages<T>(\n fetchPage: (page: number) => Promise<{ items: T[]; totalPages?: number }>\n): Promise<T[]> {\n const first = await fetchPage(1);\n const all = [...first.items];\n const totalPages = first.totalPages ?? 1;\n for (let page = 2; page <= totalPages; page++) {\n const next = await fetchPage(page);\n if (!next.items.length) break;\n all.push(...next.items);\n }\n return all;\n}\n\nfunction notificationRuleKey(\n noticeType: string,\n memberId: number,\n workflowId: number | null\n): string {\n return JSON.stringify([noticeType, memberId, workflowId]);\n}\n\n/**\n * Resolve a resource's build phase, walking the prototype chain.\n *\n * Keyed on the exact constructor a subclass (e.g. the journey `Start` step)\n * misses every entry and silently sorts to the end — applying its edges after\n * everything else and hiding ordering bugs behind an accident.\n */\nfunction phaseFor(resource: WorkspaceBuilderResource): number {\n let ctor: Function | null = resource.constructor;\n while (ctor) {\n const phase = PHASES.get(ctor);\n if (phase !== undefined) return phase;\n ctor = Object.getPrototypeOf(ctor) as Function | null;\n }\n return 99;\n}\n\nexport class WorkspaceBuilder {\n readonly resources: WorkspaceBuilderResource[] = [];\n\n constructor(readonly client: GravityRailWorkspaceClient) {}\n\n form(name: string, options: AnyRecord & { slug?: string } = {}): FormBuilder {\n const form = new FormBuilder(name, options.slug, options);\n this.resources.push(form);\n return form;\n }\n\n workflow(name: string, options: WorkflowBuilderOptions = {}): WorkflowBuilder {\n const workflow = new WorkflowBuilder(name, options);\n this.resources.push(workflow);\n return workflow;\n }\n\n label(\n name: string,\n options: { slug?: string; color?: string; description?: string } = {}\n ): MemberLabelBuilder {\n const label = new MemberLabelBuilder(\n name,\n options.slug,\n options.color,\n options.description ?? ''\n );\n this.resources.push(label);\n return label;\n }\n\n /**\n * A Journey timeline: ordered touches, structured waits, exclusive branches\n * and ordered Endings, written through the atomic definition endpoint.\n *\n * The Journey is adopted by exact name when the workspace already holds one;\n * the write then replaces its definition whole.\n */\n journey(name: string, options: AnyRecord = {}): JourneyBuilder {\n const journey = new JourneyBuilder(name, options);\n this.resources.push(journey);\n return journey;\n }\n\n agent(name: string, options: AnyRecord = {}): AgentBuilder {\n const agent = new AgentBuilder(name, options);\n this.resources.push(agent);\n return agent;\n }\n\n routine(name: string, cronSchedule = '', options: AnyRecord = {}): RoutineBuilder {\n const routine = new RoutineBuilder(name, cronSchedule, options);\n this.resources.push(routine);\n return routine;\n }\n\n memberFilter(name: string, options: AnyRecord = {}): MemberFilterBuilder {\n const filter = new MemberFilterBuilder(name, options);\n this.resources.push(filter);\n return filter;\n }\n\n notificationRule(name: string, options: AnyRecord = {}): NotificationRuleBuilder {\n const rule = new NotificationRuleBuilder(name, options);\n this.resources.push(rule);\n return rule;\n }\n\n plan(): void {\n const resources = this.sortedResources();\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Plan');\n writeLine('='.repeat(50));\n const declared = resources.filter((resource) => !resource.isImplicit);\n for (const resource of declared) {\n writeLine(` + ${resource.planLine()}`);\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n this.reportJourneyWarnings();\n writeLine(`\\n Total: ${declared.length} resources, ${wiring.length} connections`);\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n async preview(): Promise<void> {\n const resources = this.sortedResources();\n await this.resolveExisting(resources);\n\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Preview');\n writeLine('='.repeat(50));\n const declared = resources.filter((resource) => !resource.isImplicit);\n for (const resource of declared) {\n if (resource._existed) {\n writeLine(` = ${resource.planLine()} (exists, id=${resource._id})`);\n } else {\n writeLine(` + ${resource.planLine()}`);\n }\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n this.reportJourneyWarnings();\n const toCreate = declared.filter((resource) => !resource._existed);\n const existing = declared.filter((resource) => resource._existed);\n writeLine(\n `\\n Total: ${toCreate.length} to create, ${existing.length} existing, ${wiring.length} connections`\n );\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n /**\n * Print journey authoring problems that only bite at runtime — a touch with\n * no action does nothing at all. It looks fine in the editor, so it is\n * surfaced before the write rather than discovered from a member's phone.\n */\n private reportJourneyWarnings(): void {\n const problems = this.resources\n .filter((resource): resource is JourneyBuilder => resource instanceof JourneyBuilder)\n .flatMap((journey) => journey.validate());\n if (!problems.length) return;\n writeLine('\\n Journey warnings:');\n for (const problem of problems) writeLine(` ! ${problem}`);\n }\n\n /**\n * Problems that make the plan unwritable, found before the first write.\n *\n * The API validates each CEL when you save it, and its diagnosis is right —\n * but it fires per-write, so a plan whose edges reference a non-collection\n * form gets four labels, two forms, a workflow and six tasks created before\n * the seventh call rejects it. The operator is left with a half-built\n * program to hand-repair. Checking here costs nothing and writes nothing.\n *\n * Deliberately narrow: only cross-resource facts the builder can see with\n * certainty. Per-field CEL schema checking stays server-side, where the\n * real validator lives — duplicating it here would drift.\n *\n * Pure: reads only what the plan declares, never what the server holds, so\n * it is correct before adoption and safe for a caller to run directly. It\n * is also the WHOLE gate: every anchor a v2 definition can name has a\n * request-local address whether or not the server has seen it, so no\n * refusal has to wait for adoption to decide it.\n */\n preflight(): string[] {\n const problems: string[] = [];\n const forms = this.resources.filter(\n (resource): resource is FormBuilder => resource instanceof FormBuilder\n );\n const collectionBySlug = new Map(forms.map((form) => [form.slug, form.collection]));\n\n // `assignment.collections.<slug>` requires <slug> to be a COLLECTION\n // form. This is the exact defect that shipped: the edges were right, the\n // form was declared without `collection: true`, and nothing said so\n // until fourteen resources existed.\n const reference = /assignment\\.collections\\.([A-Za-z0-9_]+)/g;\n for (const resource of this.sortedResources()) {\n if (!(resource instanceof TaskBuilder)) continue;\n for (const transition of resource.transitions) {\n const cel = transition.celCondition;\n if (!cel) continue;\n for (const [, slug] of cel.matchAll(reference)) {\n if (!collectionBySlug.has(slug)) continue; // server resolves it\n if (!collectionBySlug.get(slug)) {\n problems.push(\n `task '${transition.parent.name}' → '${transition.child.name}': CEL reads ` +\n `assignment.collections.${slug}, but this plan creates '${slug}' as a ` +\n `non-collection form. Declare it with { collection: true }.`\n );\n }\n }\n }\n }\n\n // A Journey is written as ONE atomic PUT, and `JourneyBuilder.apply()`\n // has to create the Journey — or pause a live one — before it can build\n // that payload. So a definition the builder cannot express has to be\n // refused here or the refusal lands after those writes, leaving an empty\n // journey shell or a production program off the air.\n for (const resource of this.resources) {\n if (resource instanceof JourneyBuilder) problems.push(...resource.preflight());\n }\n return [...new Set(problems)];\n }\n\n /** The plan-rejection shape: every problem printed, nothing written. */\n private rejectIfProblems(problems: string[]): void {\n if (!problems.length) return;\n writeLine('\\nPlan rejected — nothing was created:');\n for (const problem of problems) writeLine(` ! ${problem}`);\n throw new Error(\n `Plan has ${problems.length} problem(s) and was not applied:\\n` +\n problems.map((problem) => ` - ${problem}`).join('\\n')\n );\n }\n\n async apply(): Promise<ResourceSummary> {\n const resources = this.sortedResources();\n\n // Refuse before writing anything, rather than failing part-way through.\n // One gate, and it is pure: nothing it decides depends on which\n // resources the server already holds, so adoption (reads only) can run\n // after it.\n this.rejectIfProblems(this.preflight());\n await this.resolveExisting(resources);\n\n const summary: ResourceSummary = {};\n\n writeLine('Applying...');\n for (const resource of resources) {\n try {\n // The server already made it (a journey's Start step) — it is here\n // only so edges can point at it.\n if (resource.isImplicit) continue;\n // Most builders are create-only: an adopted resource is left\n // exactly as the server has it, because their `apply()` knows only\n // how to CREATE and re-running it would duplicate. A resource that\n // declares `appliesWhenExisting` writes idempotently — its apply()\n // is a full, uuid-keyed replacement that handles the adopted case\n // itself — so skipping it here would make adoption pointless: the\n // second run of a script would read the journey, resolve every\n // identity, and then write nothing.\n if (resource._existed && !resource.appliesWhenExisting) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n writeLine(` Exists ${resource.planLine()} -> id=${resource._id}`);\n continue;\n }\n\n const updating = resource._existed;\n await resource.apply(this.client);\n if (resource._created || resource._id !== undefined) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n const startTag = resource instanceof TaskBuilder && resource.start ? ' [start]' : '';\n const verb = updating ? 'Updated' : 'Created';\n writeLine(` ${verb} ${resource.planLine()}${startTag} -> id=${resource._id}`);\n } else {\n writeLine(` Skipped: ${resource.planLine()}`);\n }\n } catch (err) {\n writeLine(formatApplyFailureLine(resource, err));\n throw new ApplyError(resource, err, summary);\n }\n }\n\n await this.applyTransitions();\n await this.applyEventRules(resources);\n\n const count = Object.values(summary).reduce((total, ids) => total + ids.length, 0);\n writeLine(`\\nDone! Created ${count} resources.`);\n return summary;\n }\n\n private async resolveExisting(resources: WorkspaceBuilderResource[]): Promise<void> {\n // Before the first server call: a journey name is the ONLY key adoption\n // has, and two builders declared under one name collapse into a single\n // entry of the name→builder map below — so one of them is silently never\n // adopted and never applied, while the other inherits whatever the\n // server holds under that name and replaces it whole.\n assertUniqueJourneyNames(\n resources.filter(\n (resource): resource is JourneyBuilder => resource instanceof JourneyBuilder\n )\n );\n\n const formSlugs = new Map(\n resources\n .filter((resource): resource is FormBuilder => resource instanceof FormBuilder)\n .map((resource) => [resource.slug, resource])\n );\n const labelSlugs = new Map(\n resources\n .filter(\n (resource): resource is MemberLabelBuilder => resource instanceof MemberLabelBuilder\n )\n .map((resource) => [resource.slug, resource])\n );\n const workflowNames = new Map(\n resources\n .filter((resource): resource is WorkflowBuilder => resource instanceof WorkflowBuilder)\n .map((resource) => [resource.name, resource])\n );\n\n if (formSlugs.size) {\n for (const existing of await this.client.getDataTypes()) {\n if (existing.slug && formSlugs.has(existing.slug)) {\n formSlugs.get(existing.slug)!.adopt(existing);\n }\n }\n }\n if (labelSlugs.size) {\n for (const existing of await this.client.getMemberLabels()) {\n if (existing.slug && labelSlugs.has(existing.slug)) {\n labelSlugs.get(existing.slug)!.adopt(existing);\n }\n }\n }\n\n const filterNames = new Map(\n resources\n .filter(\n (resource): resource is MemberFilterBuilder =>\n resource instanceof MemberFilterBuilder\n )\n .map((resource) => [resource.name, resource])\n );\n if (filterNames.size) {\n for (const existing of await this.client.getMemberFilters()) {\n if (existing.name && filterNames.has(existing.name)) {\n filterNames.get(existing.name)!.adopt(existing);\n }\n }\n }\n\n // Journeys adopt by name and pull the AUTHORING projection per journey,\n // because a journey's identity for re-run purposes is its touch, rule and\n // goal uuids, and the list rows carry none of them. The write is a full\n // atomic REPLACEMENT, so an absent rule uuid would silently recreate the\n // Ending. The builder already holds `journeys:write`; it is about to PUT.\n const journeyNames = new Map(\n resources\n .filter((resource): resource is JourneyBuilder => resource instanceof JourneyBuilder)\n .map((resource) => [resource.name, resource])\n );\n if (journeyNames.size) {\n // Every page, not just the first: the default page holds 25 rows, so\n // a match on page 2 would be silently duplicated — and worse, two\n // same-name journeys SPLIT across pages would dodge the ambiguity\n // refusal below and adopt the first one destructively. Max page size,\n // walk totalPages (review round 10).\n const pageSize = 500;\n const firstPage = await this.client.getJourneys(false, { page: 1, pageSize });\n const allJourneys = [...firstPage.items];\n for (let page = 2; page <= firstPage.totalPages; page++) {\n const nextPage = await this.client.getJourneys(false, { page, pageSize });\n allJourneys.push(...nextPage.items);\n }\n // Group first, adopt second. Adopting inside the scan would attach the\n // builder to the FIRST stored journey of that name and then attach it\n // again to the second — each adoption a full, destructive replacement\n // of a different live journey. Only an unambiguous 1:1 match is\n // adoptable; zero matches is the ordinary create path.\n const storedByName = new Map<string, (typeof allJourneys)[number][]>();\n for (const existing of allJourneys) {\n if (!existing.name || !journeyNames.has(existing.name)) continue;\n storedByName.set(existing.name, [...(storedByName.get(existing.name) ?? []), existing]);\n }\n for (const [name, matches] of storedByName) {\n if (matches.length > 1) {\n throw new Error(\n `This workspace has ${matches.length} journeys named '${name}', and ` +\n 'the script adopts an existing journey by name — so it cannot tell ' +\n 'which one it owns. Adopting the wrong one replaces that journey ' +\n 'whole on the next save. Rename the others in the app, or rename ' +\n 'the journey in the script.'\n );\n }\n const existing = matches[0]!;\n const builder = journeyNames.get(name)!;\n // `adopt()` refuses a Journey whose execution model does not\n // accept the whole-definition write. It throws here, during these\n // reads, so nothing has been created or paused yet.\n builder.adopt(await this.client.getJourneyAuthoring(existing.id));\n }\n }\n\n const agentNames = new Map(\n resources\n .filter((resource): resource is AgentBuilder => resource instanceof AgentBuilder)\n .map((resource) => [resource.name, resource])\n );\n if (agentNames.size) {\n // Archived agents are deliberately not adopted: the list endpoint\n // excludes them, and re-adopting one would resurrect a resource the\n // workspace retired rather than create the agent the script asked for.\n for (const existing of await collectPages((page) =>\n this.client.getAgents({ page, pageSize: LIST_PAGE_SIZE })\n )) {\n if (existing.name && agentNames.has(existing.name)) {\n agentNames.get(existing.name)!.adopt(existing);\n }\n }\n }\n\n const routineNames = new Map(\n resources\n .filter((resource): resource is RoutineBuilder => resource instanceof RoutineBuilder)\n .map((resource) => [resource.name, resource])\n );\n if (routineNames.size) {\n for (const existing of await collectPages((page) =>\n this.client.getRoutines({ page, pageSize: LIST_PAGE_SIZE })\n )) {\n if (existing.name && routineNames.has(existing.name)) {\n routineNames.get(existing.name)!.adopt(existing);\n }\n }\n }\n\n await this.resolveExistingWorkflows(resources, workflowNames);\n // Last, because a notification rule's identity includes the workflow it\n // notifies about, and that id is only known once workflows are adopted.\n await this.resolveExistingNotificationRules(resources);\n }\n\n /**\n * Adopt notification rules the server already has.\n *\n * There is no name on the server row — `NotificationRule` is keyed by what\n * it does — so identity is the composite the API enforces uniqueness on in\n * practice: notice type, recipient, and subject workflow.\n */\n private async resolveExistingNotificationRules(\n resources: WorkspaceBuilderResource[]\n ): Promise<void> {\n const rules = resources.filter(\n (resource): resource is NotificationRuleBuilder =>\n resource instanceof NotificationRuleBuilder\n );\n if (!rules.length) return;\n\n const identified = rules.flatMap((rule) => {\n // memberId absent: apply() rejects it, so there is nothing to match.\n if (rule.memberId === undefined) return [];\n // A declared workflow with no id yet is a workflow this run will\n // create, so no server rule can be pointing at it. Matching on\n // \"workflow unset\" here would adopt an unrelated global rule.\n if (rule.workflow && rule.workflow._id === undefined) return [];\n return [\n [\n notificationRuleKey(rule.noticeType, rule.memberId, rule.workflow?._id ?? null),\n rule,\n ] as const,\n ];\n });\n if (!identified.length) return;\n\n const byKey = new Map(identified);\n for (const existing of await this.client.getNotificationRules()) {\n // A shared-destination rule names no Member; the builder declares\n // Member rules only, so it never adopts one.\n if (existing.memberId == null) continue;\n const key = notificationRuleKey(\n existing.noticeType,\n existing.memberId,\n existing.workflowId ?? null\n );\n byKey.get(key)?.adopt(existing);\n }\n }\n\n private async resolveExistingWorkflows(\n resources: WorkspaceBuilderResource[],\n workflowNames: Map<string, WorkflowBuilder>\n ): Promise<void> {\n if (!workflowNames.size) return;\n\n const existingWorkflows = await this.client.getWorkflows();\n for (const { workflow: existing } of existingWorkflows.items) {\n if (existing.name && workflowNames.has(existing.name)) {\n // List rows carry only the root + active-revision summary. Tasks\n // and startTaskId live on the DRAFT revision, so fetch the detail\n // composition for adoption (root ids and revision ids are\n // different entities — matching tasks by root id attaches them to\n // the wrong workflow once any workflow has been published).\n const detail = await this.client.getWorkflow(existing.id);\n workflowNames.get(existing.name)!.adopt(detail);\n }\n }\n\n const adoptedWorkflows = resources.filter(\n (resource): resource is WorkflowBuilder =>\n resource instanceof WorkflowBuilder && resource._existed && resource._id !== undefined\n );\n if (!adoptedWorkflows.length) return;\n\n const existingTasks = await this.client.getTasks();\n for (const workflow of adoptedWorkflows) {\n // Tasks belong to a revision graph — match against the adopted\n // workflow's DRAFT revision id (task.workflowRevisionId), falling\n // back to the legacy field for older payloads.\n const workflowTasks = existingTasks.filter(\n (task) =>\n ((task as { workflowRevisionId?: number }).workflowRevisionId ?? task.workflowId) ===\n workflow._draftRevisionId\n );\n const taskByName = new Map(workflowTasks.map((task) => [task.name, task]));\n for (const taskBuilder of workflow.tasks) {\n const match = taskByName.get(taskBuilder.name);\n if (match) taskBuilder.adopt(match);\n }\n\n const ids = new Map<number, TaskBuilder[]>();\n for (const taskBuilder of workflow.tasks) {\n if (taskBuilder._id !== undefined) {\n ids.set(taskBuilder._id, [...(ids.get(taskBuilder._id) ?? []), taskBuilder]);\n }\n }\n for (const builders of ids.values()) {\n if (builders.length <= 1) continue;\n const nameAdopted = builders.filter((task) => taskByName.has(task.name));\n for (const task of builders.filter((builder) => !nameAdopted.includes(builder))) {\n task._id = undefined;\n task._existed = false;\n }\n }\n }\n }\n\n private sortedResources(): WorkspaceBuilderResource[] {\n const all: WorkspaceBuilderResource[] = [];\n for (const resource of this.resources) {\n all.push(resource);\n if (resource instanceof WorkflowBuilder) {\n const start = resource.startTask;\n const tasks =\n start === undefined\n ? resource.tasks\n : [start, ...resource.tasks.filter((task) => task !== start)];\n all.push(...tasks);\n }\n }\n return all.sort((a, b) => phaseFor(a) - phaseFor(b));\n }\n\n private collectWiringSummary(resources: WorkspaceBuilderResource[]): string[] {\n const lines: string[] = [];\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const transition of resource.transitions) {\n lines.push(`${transition.parent.name} -> ${transition.child.name}`);\n }\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on enter '${resource.name}'`);\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on ${rule.eventType} '${resource.name}'`);\n }\n } else if (resource instanceof RoutineBuilder) {\n for (const rule of resource.rules)\n lines.push(`${rule.actionType} rule on '${resource.name}'`);\n } else if (resource instanceof JourneyBuilder) {\n // A timeline has no edges to name — position IS the order — so\n // the preview shows the sequence itself, then the Endings in the\n // precedence they will be evaluated in.\n resource.touches.forEach((touch, index) => {\n lines.push(`${index + 1}. ${touch.name}`);\n });\n for (const ending of resource.endings) lines.push(`Ending: ${ending.name}`);\n for (const goal of resource.goals) lines.push(`Goal: ${goal.name}`);\n }\n }\n return lines;\n }\n\n private async applyTransitions(): Promise<void> {\n const parentChildren = new Map<TaskBuilder, TaskTransition[]>();\n for (const resource of this.sortedResources()) {\n if (!(resource instanceof TaskBuilder)) continue;\n for (const transition of resource.transitions) {\n parentChildren.set(transition.parent, [\n ...(parentChildren.get(transition.parent) ?? []),\n transition,\n ]);\n }\n }\n\n for (const [parent, transitions] of parentChildren) {\n if (parent._id === undefined) continue;\n const childTasks = transitions.flatMap((transition) => {\n const taskId = transition.child._id;\n if (taskId === undefined || taskId === parent._id) return [];\n // Already wired on a previous run — re-sending it makes the API\n // reject the whole update as a conflict, which reads as \"the\n // template half-worked\" and sends the operator hand-repairing.\n if (parent.existingChildIds.has(taskId)) return [];\n return [\n {\n taskId,\n choicePrompt: transition.when,\n celCondition: transition.celCondition ?? null,\n autoNext: transition.autoNext,\n required: transition.required,\n },\n ];\n });\n if (!childTasks.length) continue;\n await this.client.updateTask(parent._id, { childTasks });\n writeLine(\n ` Wired: ${parent.name} -> [${transitions.map((tr) => tr.child.name).join(', ')}]`\n );\n }\n }\n\n private async applyEventRules(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.TASK,\n taskId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on enter '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.DATA_RECORD,\n dataTypeId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.condition ? { conditions: rule.condition } : {}),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on ${rule.eventType} '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n }\n }\n }\n\n private async applyEventRule(payload: EventRuleFormData, label: string): Promise<void> {\n const existing = await this.findMatchingEventRule(payload);\n if (!existing) {\n await this.client.createEventRule(payload);\n writeLine(` Wired: ${label}`);\n return;\n }\n\n const update = eventRuleUpdate(existing, payload);\n if (Object.keys(update).length) {\n await this.client.updateEventRule(existing.id, update);\n writeLine(` Updated: ${label}`);\n } else {\n writeLine(` Exists: ${label}`);\n }\n }\n\n private async findMatchingEventRule(payload: EventRuleFormData): Promise<EventRule | undefined> {\n const sourceFilter = eventRuleSourceFilter(payload);\n const candidates = await this.client.searchEventRules({\n objectType: payload.objectType,\n eventType: payload.eventType,\n actionType: payload.actionType,\n includeDisabled: true,\n ...sourceFilter,\n });\n return candidates.find((candidate) => eventRulesMatch(candidate, payload));\n }\n}\n\nexport class ApplyError extends Error {\n readonly createdSoFar: ResourceSummary;\n readonly #resource: WorkspaceBuilderResource;\n readonly #cause: unknown;\n\n constructor(resource: WorkspaceBuilderResource, cause: unknown, createdSoFar: ResourceSummary) {\n super(formatApplyErrorMessage(resource, cause, createdSoFar));\n this.name = 'ApplyError';\n this.createdSoFar = createdSoFar;\n this.#resource = resource;\n this.#cause = cause;\n }\n\n get resource(): WorkspaceBuilderResource {\n return this.#resource;\n }\n\n get cause(): unknown {\n return this.#cause;\n }\n}\n\n/**\n * Refuse a script that declares two journeys under one name.\n *\n * A journey has no slug and no author-supplied key, so its NAME is the whole\n * of its identity for adoption. Two builders sharing one collapse into a\n * single map entry, which is silent: the plan prints both, one of them is\n * simply never adopted or applied, and the other inherits whatever the server\n * had under that name.\n */\nfunction assertUniqueJourneyNames(journeys: JourneyBuilder[]): void {\n const seen = new Set<string>();\n for (const journey of journeys) {\n if (seen.has(journey.name)) {\n throw new Error(\n `This script declares two journeys named '${journey.name}'. A journey is ` +\n 'adopted and re-applied by name, so only one of them could ever be ' +\n 'written — and an apply replaces the journey it adopted whole. ' +\n 'Rename one.'\n );\n }\n seen.add(journey.name);\n }\n}\n\nfunction resourceKey(resource: WorkspaceBuilderResource): string {\n if (resource instanceof FormBuilder) return 'forms';\n if (resource instanceof MemberLabelBuilder) return 'labels';\n if (resource instanceof WorkflowBuilder) return 'workflows';\n if (resource instanceof TaskBuilder) return 'tasks';\n if (resource instanceof MemberFilterBuilder) return 'memberFilters';\n if (resource instanceof RoutineBuilder) return 'routines';\n if (resource instanceof NotificationRuleBuilder) return 'notificationRules';\n if (resource instanceof JourneyBuilder) return 'journeys';\n if (resource instanceof AgentBuilder) return 'agents';\n return 'resources';\n}\n\nconst SEARCHABLE_EVENT_RULE_SOURCE_FIELDS = [\n 'taskId',\n 'dataTypeId',\n 'routineId',\n 'workflowRevisionId',\n 'journeyStepId',\n] as const;\n\nconst EVENT_RULE_SOURCE_FIELDS = [\n ...SEARCHABLE_EVENT_RULE_SOURCE_FIELDS,\n 'calendarId',\n 'calendarEventTypeId',\n] as const;\n\ntype SearchableEventRuleSourceField = (typeof SEARCHABLE_EVENT_RULE_SOURCE_FIELDS)[number];\n\nfunction eventRuleSourceFilter(\n payload: EventRuleFormData\n): Partial<Record<SearchableEventRuleSourceField, number>> {\n const filter: Partial<Record<SearchableEventRuleSourceField, number>> = {};\n for (const field of SEARCHABLE_EVENT_RULE_SOURCE_FIELDS) {\n const value = payload[field];\n if (value !== undefined && value !== null) {\n filter[field] = value;\n }\n }\n return filter;\n}\n\nfunction eventRulesMatch(existing: EventRule, payload: EventRuleFormData): boolean {\n if (normalizeString(existing.name) !== normalizeString(payload.name)) return false;\n if (existing.objectType !== payload.objectType) return false;\n if (existing.eventType !== payload.eventType) return false;\n if (existing.actionType !== payload.actionType) return false;\n\n for (const field of EVENT_RULE_SOURCE_FIELDS) {\n if ((existing[field] ?? null) !== (payload[field] ?? null)) return false;\n }\n\n if (normalizeString(payload.name)) return true;\n if (normalizeString(existing.conditions) !== normalizeString(payload.conditions)) return false;\n if (!eventRuleValueEqual(existing.actionParams, payload.actionParams ?? null)) return false;\n if (!eventRuleValueEqual(existing.triggerParams, payload.triggerParams ?? null)) return false;\n return true;\n}\n\nfunction eventRuleUpdate(existing: EventRule, payload: EventRuleFormData): UpdateEventRuleFormData {\n const update: UpdateEventRuleFormData = {};\n const conditions = payload.conditions ?? null;\n if (normalizeString(existing.conditions) !== normalizeString(conditions)) {\n update.conditions = conditions;\n }\n const actionParams = payload.actionParams ?? null;\n if (!eventRuleValueEqual(existing.actionParams, actionParams)) {\n update.actionParams = payload.actionParams;\n }\n const triggerParams = payload.triggerParams ?? null;\n if (!eventRuleValueEqual(existing.triggerParams, triggerParams)) {\n update.triggerParams = payload.triggerParams;\n }\n const active = payload.active ?? true;\n if (existing.active !== active) {\n update.active = active;\n }\n const delay = payload.delay ?? 0;\n if (existing.delay !== delay) {\n update.delay = delay;\n }\n const order = payload.order ?? 0;\n if (existing.order !== order) {\n update.order = order;\n }\n return update;\n}\n\nfunction normalizeString(value: string | null | undefined): string {\n return value ?? '';\n}\n\nfunction eventRuleValueEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(stableValue(left)) === JSON.stringify(stableValue(right));\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (!value || typeof value !== 'object') return value;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, nested]) => [key, stableValue(nested)])\n );\n}\n\nfunction writeLine(message = ''): void {\n process.stdout.write(`${message}\\n`);\n}\n\nfunction handleEventRuleApplyFailure(resourceName: string, err: unknown): void {\n if (hasStatus(err, 403)) {\n writeLine(\n ` WARNING: Event rule on '${resourceName}' failed (retry exec() with scopes=['automations:admin'])`\n );\n return;\n }\n const summary = summarizeError(err);\n writeLine(` FAILED: Event rule on '${resourceName}': ${summary}`);\n throw new Error(`Failed wiring event rule on '${resourceName}': ${summary}`);\n}\n\nfunction writeScopeForResource(resource: WorkspaceBuilderResource): string | null {\n if (resource instanceof FormBuilder) return 'datatypes:write';\n if (resource instanceof WorkflowBuilder || resource instanceof TaskBuilder) {\n return 'workflows:write';\n }\n if (resource instanceof AgentBuilder) return 'agents:write';\n if (resource instanceof MemberLabelBuilder || resource instanceof MemberFilterBuilder) {\n return 'members:write';\n }\n if (resource instanceof RoutineBuilder || resource instanceof NotificationRuleBuilder) {\n return 'automations:admin';\n }\n if (resource instanceof JourneyBuilder) return 'journeys:write';\n return null;\n}\n\nfunction scopeRetryHint(resource: WorkspaceBuilderResource): string {\n const scope = writeScopeForResource(resource);\n return scope ? ` (retry exec with scopes=['${scope}'])` : '';\n}\n\nfunction formatApplyFailureLine(resource: WorkspaceBuilderResource, err: unknown): string {\n const line = ` FAILED: ${resource.planLine()}: ${summarizeError(err)}`;\n return hasStatus(err, 403) ? `${line}${scopeRetryHint(resource)}` : line;\n}\n\nfunction formatApplyErrorMessage(\n resource: WorkspaceBuilderResource,\n cause: unknown,\n createdSoFar: ResourceSummary\n): string {\n let message = `Failed creating ${resource.planLine()}: ${summarizeError(cause)}`;\n if (hasStatus(cause, 403)) {\n const scope = writeScopeForResource(resource);\n if (scope) {\n message += `\\nRetry exec with scopes=['${scope}']`;\n }\n }\n const createdKeys = Object.keys(createdSoFar);\n if (createdKeys.length > 0) {\n message += `\\nAlready created: ${JSON.stringify(createdSoFar)}`;\n }\n return message;\n}\n\nfunction summarizeError(err: unknown): string {\n if (hasStatus(err, 403)) {\n return 'Insufficient permissions for this operation';\n }\n if (err instanceof ApiError) {\n const msg = err.message.trim();\n const availableTypesIdx = msg.indexOf('Available types:');\n if (availableTypesIdx !== -1) {\n const head = msg.slice(0, availableTypesIdx).trim().replace(/\\.$/, '');\n return head ? `${head}.` : 'Request failed';\n }\n return msg.length > 240 ? `${msg.slice(0, 237)}...` : msg;\n }\n if (err instanceof Error) {\n // Name only, deliberately. A non-ApiError can still carry a message the\n // backend supplied, and this string is surfaced to the operator — see the\n // \"backend returned sensitive detail\" tests. Do not widen this.\n return err.name || 'Error';\n }\n return typeof err;\n}\n\nfunction hasStatus(err: unknown, status: number): boolean {\n if (typeof err === 'object' && err !== null) {\n const candidate = err as { status?: unknown; statusCode?: unknown };\n if (candidate.status === status || candidate.statusCode === status) return true;\n }\n const message = err instanceof Error ? err.message : typeof err === 'string' ? err : '';\n return message.includes(String(status));\n}\n\nexport async function runWorkspaceScript(\n client: GravityRailWorkspaceClient,\n build: (workspace: WorkspaceBuilder) => void | Promise<void>,\n mode = 'plan'\n): Promise<ResourceSummary | void> {\n const workspace = new WorkspaceBuilder(client);\n await build(workspace);\n if (mode === 'plan') return workspace.plan();\n if (mode === 'preview') return workspace.preview();\n if (mode === 'apply') return workspace.apply();\n throw new Error(`Unknown mode '${mode}'. Use plan, preview, or apply.`);\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: event_type\n */\n\n\n/**\n * Scope-class capabilities that unlock event types in the feed.\n *\n * These are existing platform scope strings. A grant carries scope-class\n * capabilities and nothing finer, and they decide which event rows a viewer\n * may read. The workspace schemas' second tier (per-object authorization:\n * admin-only Forms, folder ACLs, object-level grants) is never copied into the grants\n * projection: it applies live, per object, when a ref is hydrated into a name\n * (:mod:`lib.activity.ref_readers`).\n */\nexport type ActivityCapability = typeof ActivityCapability[keyof typeof ActivityCapability];\n\n\nexport const ActivityCapability = {\n 'apps:read': 'apps:read',\n 'assignments:read': 'assignments:read',\n 'chats:read': 'chats:read',\n 'journeys:read': 'journeys:read',\n 'members:read': 'members:read',\n 'operator:read': 'operator:read',\n 'org:read': 'org:read',\n 'phones:read': 'phones:read',\n 'records:read': 'records:read',\n 'workflows:read': 'workflows:read',\n 'workspace:read': 'workspace:read',\n} as const;\n\n/**\n * Every occurrence kind the spine records. Closed; grows by review.\n */\nexport type ActivityEventType = typeof ActivityEventType[keyof typeof ActivityEventType];\n\n\nexport const ActivityEventType = {\n membercreated: 'member.created',\n memberremoved: 'member.removed',\n memberrole_changed: 'member.role_changed',\n memberlabels_changed: 'member.labels_changed',\n memberattributes_changed: 'member.attributes_changed',\n importstarted: 'import.started',\n importcompleted: 'import.completed',\n assignmentstarted: 'assignment.started',\n assignmentconcluded: 'assignment.concluded',\n assignmenttask_entered: 'assignment.task_entered',\n journeyenrolled: 'journey.enrolled',\n journeyunenrolled: 'journey.unenrolled',\n journeycompleted: 'journey.completed',\n journeystep_transitioned: 'journey.step_transitioned',\n journeyactivated: 'journey.activated',\n chatstarted: 'chat.started',\n chatawaiting_human: 'chat.awaiting_human',\n chathuman_replied: 'chat.human_replied',\n chatcall_ended: 'chat.call_ended',\n chatauto_replied: 'chat.auto_replied',\n chatsummary: 'chat.summary',\n messagesent: 'message.sent',\n messagesend_failed: 'message.send_failed',\n membermessage_received: 'member.message_received',\n escalationopened: 'escalation.opened',\n escalationresolved: 'escalation.resolved',\n callstarted: 'call.started',\n callcompleted: 'call.completed',\n callmissed: 'call.missed',\n callsummary: 'call.summary',\n callqueued: 'call.queued',\n callnot_placed: 'call.not_placed',\n presencewent_online: 'presence.went_online',\n presencewent_offline: 'presence.went_offline',\n operator_groupmember_added: 'operator_group.member_added',\n operator_groupmember_removed: 'operator_group.member_removed',\n operatorinteraction_declined: 'operator.interaction_declined',\n voicemailreceived: 'voicemail.received',\n voicemailtranscribed: 'voicemail.transcribed',\n voicemaillistened: 'voicemail.listened',\n routinestarted: 'routine.started',\n routinecompleted: 'routine.completed',\n routinefailed: 'routine.failed',\n workflowpublished: 'workflow.published',\n subscriptionstarted: 'subscription.started',\n subscriptionupdated: 'subscription.updated',\n subscriptioncanceled: 'subscription.canceled',\n member_subscriptionstarted: 'member_subscription.started',\n member_subscriptioncanceled: 'member_subscription.canceled',\n purchasecompleted: 'purchase.completed',\n phone_numberprovisioned: 'phone_number.provisioned',\n phone_numberarchived: 'phone_number.archived',\n domainlinked: 'domain.linked',\n domainverified: 'domain.verified',\n configupdated: 'config.updated',\n connectionauthorization_lost: 'connection.authorization_lost',\n connectionauthorization_restored: 'connection.authorization_restored',\n data_recordcreated: 'data_record.created',\n data_recordupdated: 'data_record.updated',\n notificationdelivered: 'notification.delivered',\n} as const;\n\n/**\n * The visibility class an event is *born* with.\n *\n * ``ACCOUNT_PRIVATE`` is structural privacy: such an event is only ever\n * visible to the account named in ``account_uuid``, regardless of any scope a\n * viewer holds, and it never enters a workspace or org rollup. This is how\n * manager and agent-job chat privacy survives aggregation.\n */\nexport type ActivityVisibility = typeof ActivityVisibility[keyof typeof ActivityVisibility];\n\n\nexport const ActivityVisibility = {\n workspace: 'workspace',\n org: 'org',\n account_private: 'account_private',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: ref\n */\n\n\n/**\n * Who or what caused an occurrence.\n *\n * ``AGENT`` is an Agent, recorded as itself even when it acts through a\n * member-shaped session; every emitter derives it through\n * :mod:`lib.activity.attribution`, never by building an actor inline.\n *\n * ``SYSTEM`` means no principal was involved — a Temporal schedule, an\n * inbound carrier or Stripe event with no member attribution. It is never a\n * placeholder for \"did not bother to look\".\n *\n * ``UNATTRIBUTED`` means a principal may well have acted but the event does\n * not name which one. The event backfill writes it: it synthesizes rows from\n * canonical tables and, by operator ruling, derives no principal from them,\n * so claiming ``system`` there would assert that nobody acted. Rows\n * written before this kind existed keep the ``system`` they were written\n * with — the log is append-only.\n *\n * Additive by contract: a reader must treat a kind it does not know as\n * unnamed rather than fail (the feed serves it as ``null``).\n */\nexport type ActorKind = typeof ActorKind[keyof typeof ActorKind];\n\n\nexport const ActorKind = {\n account: 'account',\n agent: 'agent',\n connection: 'connection',\n member: 'member',\n org_account: 'org_account',\n system: 'system',\n unattributed: 'unattributed',\n} as const;\n\n/**\n * Closed vocabulary of entity kinds a spine ref may name.\n *\n * Adding a kind is a code change with review — the same gate the event-type\n * vocabulary gets. Kinds name *entities*, never fields or values.\n */\nexport type EntityKind = typeof EntityKind[keyof typeof EntityKind];\n\n\nexport const EntityKind = {\n account: 'account',\n org: 'org',\n org_account: 'org_account',\n workspace: 'workspace',\n agent: 'agent',\n connection: 'connection',\n member: 'member',\n assignment: 'assignment',\n journey: 'journey',\n journey_step: 'journey_step',\n routine: 'routine',\n task: 'task',\n workflow: 'workflow',\n workflow_revision: 'workflow_revision',\n call: 'call',\n chat: 'chat',\n escalation: 'escalation',\n inbox: 'inbox',\n phone_number: 'phone_number',\n recording: 'recording',\n voicemail: 'voicemail',\n domain: 'domain',\n import: 'import',\n invoice: 'invoice',\n member_label: 'member_label',\n member_subscription: 'member_subscription',\n operator_group: 'operator_group',\n purchase: 'purchase',\n subscription: 'subscription',\n data_type: 'data_type',\n workspace_config: 'workspace_config',\n data_record: 'data_record',\n} as const;\n\n/**\n * A typed reference to one entity, with the scope chain it was observed in.\n *\n * Stored in ``activity_events.refs`` (and in ``activity_open_items``'s\n * ``responsible``) as JSON. Never used for a join: the activities database\n * holds no foreign keys, and a ref whose entity was deleted renders as its\n * kind — the same behavior as a ref the viewer may not resolve.\n *\n * **Two names for one field, on purpose.** This class is a *storage* shape —\n * the JSON the recorder writes and the drain reads — and, since the serving\n * API returns typed detail payloads, it is also a *wire* shape. Storage wants\n * the snake_case names already committed to rows; the API contract requires\n * lowerCamelCase keys (root ``CLAUDE.md``). A serialization-only alias gives\n * both without a mapping layer: validation still reads ``workspace_uuid``, so\n * every stored row and every emitter is untouched, while ``by_alias=True`` —\n * which FastAPI uses to serialize a response, and which nothing on the write\n * path passes — emits ``workspaceUuid``.\n * :class:`lib.activity.details.ActivityDetailBase` carries the same config for\n * the same reason.\n */\nexport interface EntityRef {\n kind: EntityKind;\n uuid: string;\n workspaceUuid?: string | null;\n orgUuid?: string | null;\n accountUuid?: string | null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoJO,IAAM,gCAAgC;AAAA,EAC3C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,MAAM;AACR;AA4CO,IAAM,mCAAmC;AAAA,EAC9C,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS;AACX;;;ACxKO,IAAM,qBAAqB;AAAA,EAChC,KAAK;AAAA,EACL,UAAU;AAAA,EACV,MAAM;AACR;;;ACCO,IAAM,gCAAgC;AAAA,EAC3C,cAAc;AAAA,EACd,QAAQ;AACV;AA8U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AAA,EAChC,WAAW;AAAA,EACX,KAAK;AAAA,EACL,iBAAiB;AACnB;;;ACvFO,IAAM,YAAY;AAAA,EACvB,SAAS;AAAA,EACT,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,cAAc;AAChB;AAWO,IAAM,aAAa;AAAA,EACxB,SAAS;AAAA,EACT,KAAK;AAAA,EACL,aAAa;AAAA,EACb,WAAW;AAAA,EACX,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,cAAc;AAAA,EACd,SAAS;AAAA,EACT,MAAM;AAAA,EACN,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,MAAM;AAAA,EACN,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,cAAc;AAAA,EACd,WAAW;AAAA,EACX,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,cAAc;AAAA,EACd,qBAAqB;AAAA,EACrB,gBAAgB;AAAA,EAChB,UAAU;AAAA,EACV,cAAc;AAAA,EACd,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,aAAa;AACf;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/types/generated/organization_webhook.ts","../src/types/generated/workspace_selection.ts","../src/types/generated/bundle_contract.ts","../src/types/generated/bundle_publication.ts","../src/types/generated/installation_contract.ts","../src/workspace-builder/resource.ts","../src/workspace-builder/automation.ts","../src/workspace-builder/forms.ts","../src/workspace-builder/journeys.ts","../src/workspace-builder/workflows.ts","../src/workspace-builder/orchestrator.ts","../src/types/generated/event_type.ts","../src/types/generated/ref.ts"],"sourcesContent":["/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: organization_webhook\n */\n\nimport type { OrgWorkspaceScopeResponse } from './workspace_scope';\nimport type { OrgWorkspaceScopeRequest, WorkspaceScopeMode } from './workspace_selection';\n\n/**\n * Hide history, retaining dedupe keys and failure evidence. In-flight sends finish.\n */\nexport interface ClearOrgWebhookDeliveriesRequest {\n failedOnly?: boolean;\n}\n\n/**\n * Create an organization webhook endpoint.\n */\nexport interface CreateOrgWebhookEndpointRequest {\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n /**\n * @minLength 1\n * @maxLength 2048\n */\n url: string;\n /** @minItems 1 */\n eventTypes: string[];\n workspaceScope: OrgWorkspaceScopeRequest;\n signingSecret?: string | null;\n}\n\n/**\n * Create response: the ONE place the plaintext signing secret appears.\n *\n * Generated server-side when the client omits ``signingSecret``. This\n * response is the only time it is readable; every later read is masked.\n * The configured ``url`` is likewise echoed only here — the configurator\n * typed it moments ago; later reads carry the destination fingerprint.\n */\nexport interface CreatedOrgWebhookEndpointResponse {\n id: number;\n uuid: string;\n name: string;\n destinationHost: string;\n destinationDigest: string;\n status: string;\n eventTypes: string[];\n workspaceScope: OrgWorkspaceScopeResponse;\n includePayload?: boolean;\n signingSecretSet: boolean;\n /** @minLength 1 */\n signingSecret: string;\n statusHistory: OrgWebhookEndpointStatusHistoryEntry[];\n recentFailures?: OrgWebhookRecentFailure[];\n deliveryHealth: OrgWebhookDeliveryHealth;\n createdAt: string;\n updatedAt: string;\n url: string;\n}\n\n/**\n * Deliberately empty — discarding the pending backlog takes no parameters.\n *\n * Same CSRF barrier as ``ReplayOrgWebhookDeliveryRequest``: clients send\n * ``{}``.\n */\nexport interface DiscardPendingOrgWebhookDeliveriesRequest { [key: string]: unknown }\n\nexport interface OrgWebhookAttemptDiagnosticResponse {\n destinationHost?: string | null;\n destinationDigest?: string | null;\n attemptNumber: number;\n requestBody: OrgWebhookAttemptDiagnosticResponseRequestBody;\n responseBody?: string | null;\n responseTruncated?: boolean;\n durationMs: number;\n}\n\nexport type OrgWebhookAttemptDiagnosticResponseRequestBody = { [key: string]: unknown };\n\nexport interface OrgWebhookClearDeliveriesResponse {\n cleared: number;\n}\n\n/**\n * Which covered workspaces will actually emit the subscribed record events.\n */\nexport interface OrgWebhookCoverageResponse {\n recordEventsSubscribed: boolean;\n workspaces: OrgWebhookWorkspaceCoverageResponse[];\n}\n\n/**\n * One try at a delivery, from ``webhook_delivery_attempts`` (activities DB).\n */\nexport interface OrgWebhookDeliveryAttemptResponse {\n attemptNumber: number;\n startedAt: string;\n finishedAt?: string | null;\n outcome?: string | null;\n failureClass?: string | null;\n errorType?: string | null;\n responseStatusCode?: number | null;\n}\n\nexport interface OrgWebhookDeliveryDetailResponse {\n delivery: OrgWebhookDeliveryResponse;\n requestBody: OrgWebhookDeliveryDetailResponseRequestBody;\n diagnostics: OrgWebhookAttemptDiagnosticResponse[];\n}\n\nexport type OrgWebhookDeliveryDetailResponseRequestBody = { [key: string]: unknown };\n\n/**\n * How deliveries to one endpoint are going, from the activities database.\n *\n * ``state`` is ``held`` while the drain holds the endpoint's queue (it sends\n * one probe at ``nextProbeAt``; the first success releases the backlog),\n * ``failing`` while attempts fail but the queue still flows, and\n * ``healthy`` otherwise, including an endpoint with no attempt yet.\n * ``failing`` has no time window, like the drain's own counter: the run ends\n * only at the next success, however long ago its last failure was. Health\n * never changes ``status``: a paused endpoint can be held, and it sends no\n * probe until it is resumed.\n *\n * Closed vocabulary, counts and timestamps only. ``lastFailureClass`` is the\n * drain's ``failure_class`` vocabulary (``network``, ``http_4xx``,\n * ``http_5xx``, ``unsafe_target``, ``missing_secret``, ``retryable``).\n */\nexport interface OrgWebhookDeliveryHealth {\n state: OrgWebhookDeliveryHealthState;\n consecutiveFailures: number;\n failingSince: string | null;\n lastSuccessAt: string | null;\n lastFailureAt: string | null;\n lastFailureClass: string | null;\n nextProbeAt: string | null;\n pendingDeliveries: number;\n}\n\nexport type OrgWebhookDeliveryHealthState = typeof OrgWebhookDeliveryHealthState[keyof typeof OrgWebhookDeliveryHealthState];\n\n\nexport const OrgWebhookDeliveryHealthState = {\n healthy: 'healthy',\n failing: 'failing',\n held: 'held',\n} as const;\n\n/**\n * Bounded page of deliveries for one endpoint.\n */\nexport interface OrgWebhookDeliveryListResponse {\n items: OrgWebhookDeliveryResponse[];\n total: number;\n}\n\n/**\n * A requeued delivery. Identifiers only — the envelope is not echoed.\n *\n * ``dedupeKey`` and ``occurredAt`` are the row's own, unchanged, so a\n * receiver that collapses duplicates sees the same event. ``status`` is\n * ``pending``: the drain signs a fresh timestamp when it sends.\n */\nexport interface OrgWebhookDeliveryReplayResponse {\n id: number;\n status: 'pending';\n dedupeKey: string;\n occurredAt: string;\n}\n\n/**\n * One delivery-queue row (``webhook_deliveries``, activities DB), with\n * its attempts oldest first — the queue state and every try at it.\n */\nexport interface OrgWebhookDeliveryResponse {\n id: number;\n eventType: string;\n occurredAt: string;\n dedupeKey: string;\n workspaceUuid?: string | null;\n status: OrgWebhookDeliveryResponseStatus;\n availableAt: string;\n createdAt: string;\n replayable: boolean;\n attempts: OrgWebhookDeliveryAttemptResponse[];\n}\n\nexport type OrgWebhookDeliveryResponseStatus = typeof OrgWebhookDeliveryResponseStatus[keyof typeof OrgWebhookDeliveryResponseStatus];\n\n\nexport const OrgWebhookDeliveryResponseStatus = {\n pending: 'pending',\n processing: 'processing',\n sent: 'sent',\n dead_letter: 'dead_letter',\n expired: 'expired',\n} as const;\n\n/**\n * How many pending deliveries an operator discard moved to ``expired``.\n */\nexport interface OrgWebhookDiscardPendingResponse {\n discarded: number;\n}\n\n/**\n * One endpoint. ``signingSecret`` is always the masked sentinel.\n *\n * The destination is a FINGERPRINT (``scheme://host`` plus a SHA-256 digest\n * of the full URL), never the raw URL — webhook paths and queries routinely\n * carry per-tenant tokens, and every holder of the read scope would\n * otherwise harvest the credentials another administrator embedded\n * (round-9 finding). The full URL is known to whoever configured it and is\n * returned only in the create response, exactly like the one-time secret.\n */\nexport interface OrgWebhookEndpointResponse {\n id: number;\n uuid: string;\n name: string;\n destinationHost: string;\n destinationDigest: string;\n status: string;\n eventTypes: string[];\n workspaceScope: OrgWorkspaceScopeResponse;\n includePayload?: boolean;\n signingSecretSet: boolean;\n signingSecret?: string;\n statusHistory: OrgWebhookEndpointStatusHistoryEntry[];\n recentFailures?: OrgWebhookRecentFailure[];\n deliveryHealth: OrgWebhookDeliveryHealth;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * One row of ``webhook_endpoint_status_history``.\n */\nexport interface OrgWebhookEndpointStatusHistoryEntry {\n status: string;\n reason: string;\n changedAt: string;\n changedByAccountId?: number | null;\n}\n\n/**\n * The event types an org endpoint may subscribe to.\n *\n * Served from ``workspace_deliverable_event_types`` — the same set the\n * create/update validators accept — so the org UI enumerates exactly the\n * vocabulary the API will store, in the vocabulary's own order.\n */\nexport interface OrgWebhookEventTypesResponse {\n eventTypes: string[];\n}\n\n/**\n * One Form and whether record events are opted in for it.\n *\n * ``name`` is the Form's configured name, not a patient identifier.\n */\nexport interface OrgWebhookFormCoverageResponse {\n id: number;\n uuid: string;\n name: string;\n slug: string;\n webhookEventsEnabled: boolean;\n}\n\n/**\n * How many dead-lettered deliveries of one class finished in the last 24 hours.\n *\n * Only deliveries that dead-lettered after the endpoint last became\n * ``active`` count.\n * ``failureClass`` is the closed vocabulary the drain writes. One delivery\n * counts once, by its newest terminal attempt in that window.\n */\nexport interface OrgWebhookRecentFailure {\n failureClass: string;\n count: number;\n}\n\n/**\n * A representative delivery body for one event type.\n *\n * What the org UI prefills its test-send editor with, and what the public\n * event catalog is generated from — one builder\n * (``lib.activity.samples.sample_event``), so the payload an operator edits\n * and the payload the docs describe cannot diverge.\n *\n * The body is a real, validated envelope wrapped by the same\n * ``build_delivery_payload`` a queued delivery goes through, so it carries\n * the ``endpoint`` block and the endpoint's own ``org_uuid`` exactly as a\n * live delivery would. Every uuid in it is synthetic: the sample names no\n * row in any database.\n */\nexport interface OrgWebhookSamplePayloadResponse {\n eventType: string;\n family: string;\n payload: OrgWebhookSamplePayloadResponsePayload;\n}\n\nexport type OrgWebhookSamplePayloadResponsePayload = { [key: string]: unknown };\n\n/**\n * One workspace the endpoint covers, and its Form opt-in.\n *\n * ``formOptIn`` is ``not_applicable`` when the endpoint does not subscribe\n * to ``data_record.created`` or ``data_record.updated``. It is\n * ``covered_but_opted_out`` when those events are subscribed and no Form\n * has ``webhookEventsEnabled``. ``opted_in`` means at least one Form does.\n */\nexport interface OrgWebhookWorkspaceCoverageResponse {\n workspaceUuid: string;\n workspaceName: string;\n formOptIn: OrgWebhookWorkspaceCoverageResponseFormOptIn;\n forms: OrgWebhookFormCoverageResponse[];\n}\n\nexport type OrgWebhookWorkspaceCoverageResponseFormOptIn = typeof OrgWebhookWorkspaceCoverageResponseFormOptIn[keyof typeof OrgWebhookWorkspaceCoverageResponseFormOptIn];\n\n\nexport const OrgWebhookWorkspaceCoverageResponseFormOptIn = {\n opted_in: 'opted_in',\n covered_but_opted_out: 'covered_but_opted_out',\n not_applicable: 'not_applicable',\n} as const;\n\n/**\n * Deliberately empty — a replay takes no parameters.\n *\n * The body exists as the repo's CSRF barrier for cookie-authenticated POSTs:\n * FastAPI parses a body only for an ``application/json`` content type, which\n * a cross-site HTML form cannot send. Clients send ``{}``.\n */\nexport interface ReplayOrgWebhookDeliveryRequest { [key: string]: unknown }\n\n/**\n * Send one payload to an endpoint, now, outside the delivery queue.\n *\n * ``eventType`` picks which sample the server builds when ``payload`` is\n * omitted, and it stays in the closed subscribable vocabulary for the same\n * reason the subscription list does. It is deliberately NOT required to be\n * one of the endpoint's *subscribed* types: an operator wiring up a new\n * receiver wants to exercise a type before subscribing to it, and a test\n * send writes nothing to the queue that a subscription would govern.\n *\n * ``payload`` is the operator's own edit of that sample — the whole point of\n * the feature is that they can put their own identifiers in it and watch\n * their handler run. It is sent as given (canonicalized and signed like any\n * delivery), not merged into a server-built envelope: a merge would mean an\n * operator could not test what happens when a field is *absent*.\n *\n * **So the two can disagree, and that is allowed.** When ``payload`` is\n * supplied, the body's ``event_type`` is whatever the operator wrote — this\n * request's ``eventType`` no longer describes what the receiver will see.\n * Reconciling them would defeat the feature: \"what does my handler do when\n * the body says one thing and the header another\" is a case worth being able\n * to exercise. ``eventType`` remains the value the audit trail records\n * alongside ``bodySource``, which says whether the body was ours or theirs,\n * so a reader of the audit log is never misled about which one it describes.\n */\nexport interface TestOrgWebhookEndpointRequest {\n eventType: string;\n payload?: TestOrgWebhookEndpointRequestPayload;\n}\n\nexport type TestOrgWebhookEndpointRequestPayload = { [key: string]: unknown } | null;\n\n/**\n * What one test send did.\n *\n * Mirrors the delivery log's vocabulary rather than inventing a second one:\n * ``failureClass`` and ``errorType`` are the same closed values an\n * operator reads on a real delivery attempt (``lib.services.\n * org_webhook_delivery_service``), so \"what happened to my test\" and \"what\n * happened to my deliveries\" are answered in one language.\n *\n * ``responseBody`` is a bounded prefix of the RECEIVER's reply — the\n * operator's own server talking back. It is the reason the button is worth\n * pressing, and it is truncated because an arbitrary third-party body has no\n * size we control.\n */\nexport interface TestOrgWebhookEndpointResponse {\n delivered: boolean;\n statusCode?: number | null;\n failureClass?: string | null;\n errorType?: string | null;\n responseBody?: string | null;\n durationMs: number;\n}\n\n/**\n * Update an organization webhook endpoint. None = leave unchanged.\n */\nexport interface UpdateOrgWebhookEndpointRequest {\n name?: string | null;\n url?: string | null;\n eventTypes?: string[] | null;\n workspaceScope?: OrgWorkspaceScopeRequest | null;\n status?: UpdateOrgWebhookEndpointRequestStatus;\n signingSecret?: string | null;\n}\n\nexport type UpdateOrgWebhookEndpointRequestStatus = typeof UpdateOrgWebhookEndpointRequestStatus[keyof typeof UpdateOrgWebhookEndpointRequestStatus] | null;\n\n\nexport const UpdateOrgWebhookEndpointRequestStatus = {\n active: 'active',\n paused: 'paused',\n} as const;\n\n/**\n * Workspace-side visibility (GRA-8314 §5 (b)'s visibility).\n *\n * What any member holding `webhooks:read` — the workspace's webhook-read\n * scope, which workspace admins hold — sees from THEIR side: that their\n * workspace feeds an org endpoint. IDs and the endpoint's public shape only\n * — never the signing secret, never delivery contents, and never the full\n * URL: the endpoint is ORG configuration authored by an org admin, and a\n * webhook URL's path and query routinely carry per-tenant tokens, so the\n * workspace side gets the same PHI-safe ``destination_fingerprint`` the\n * audit trail records — ``scheme://host`` plus a digest prefix that lets a\n * reader tell two endpoints on one host apart.\n */\nexport interface WorkspaceOrgEndpointResponse {\n /** Endpoint uuid (org-side identifier) */\n uuid: string;\n name: string;\n /** scheme://host[:port] of the endpoint URL — never the path or query */\n destinationHost: string;\n /** First 12 hex characters of SHA-256 over the full URL */\n destinationDigest: string;\n status: string;\n eventTypes: string[];\n workspaceScopeMode: WorkspaceScopeMode;\n organizationId: number;\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: workspace_selection\n */\n\n\n/**\n * Which of the organization's workspaces a source or sink may reach.\n *\n * ``selected`` reaches ``workspaceUuids`` plus every workspace carrying ALL\n * of ``labelSelector`` and needs at least one of the two; ``all`` and\n * ``none`` carry neither list.\n */\nexport interface OrgWorkspaceScopeRequest {\n mode: WorkspaceScopeMode;\n /** @maxItems 100 */\n workspaceUuids?: string[];\n /** @maxItems 10 */\n labelSelector?: string[];\n}\n\n/**\n * The three modes a person picks and reads (ADR-55).\n *\n * Stored as ``all_workspaces`` plus the selection rows, never as a fourth\n * column: ``all`` is the stored bit, ``selected`` is a limited selection with\n * at least one workspace or label, and ``none`` is a limited selection with\n * neither. A limited selection whose last workspace was deleted therefore\n * reads as ``none`` — what it reaches.\n */\nexport type WorkspaceScopeMode = typeof WorkspaceScopeMode[keyof typeof WorkspaceScopeMode];\n\n\nexport const WorkspaceScopeMode = {\n all: 'all',\n selected: 'selected',\n none: 'none',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: bundle_contract\n */\n\nimport type { InboxBundleItem, InboxBundleReference, PhoneNumberBundleItem, PhoneNumberBundleReference } from './channel_bundle';\nimport type { DisclosureMode } from './disclosure_contract';\nimport type { JourneyBundleItem, JourneyRecipeProblem } from './journey_bundle';\nimport type { MemberFilterBundleItem, MemberFilterBundleReference } from './member_filter_bundle';\nimport type { SystemRoleKey } from './member_role';\nimport type { MemberRoleBundleItem, MemberRoleBundleReference } from './member_role_bundle';\nimport type { EnumOption } from './schema_field';\nimport type { DataTypeRequirement, RequirementSchemaField } from './site';\n\n/**\n * A Workspace Field value an installation must enter: a required field of a Workspace Fields Data Type item.\n *\n * Derived from the version's own Data Type items (workspace-scoped and\n * singular), never declared separately. The installed Data Type's schema is\n * what an installation checks (``missingWorkspaceFields`` on its readiness).\n */\nexport interface BundleConfigurationInput {\n itemKey: string;\n fieldSlug: string;\n label: string;\n fieldType: string;\n}\n\nexport interface BundleGrantRequest {\n granteeType: BundleGrantRequestGranteeType;\n granteeUuid?: string | null;\n expiresAt?: string | null;\n disclosureMode?: DisclosureMode;\n}\n\nexport type BundleGrantRequestGranteeType = typeof BundleGrantRequestGranteeType[keyof typeof BundleGrantRequestGranteeType];\n\n\nexport const BundleGrantRequestGranteeType = {\n organization: 'organization',\n global: 'global',\n} as const;\n\nexport interface BundleGrantResponse {\n granteeName?: string | null;\n id: number;\n granteeType: string;\n granteeUuid: string | null;\n effective?: boolean;\n disclosureMode: string;\n expiresAt: string | null;\n revokedAt: string | null;\n revocationMode?: string | null;\n revocationReason?: string | null;\n}\n\nexport interface BundleItemLabel {\n name: string;\n version?: number | null;\n versionName?: string | null;\n}\n\n/**\n * One reason a draft item cannot be published yet.\n *\n * A reader names a Site setting by ``settingLabel``, the theme's label,\n * never by its key. ``ref`` is the item key a reference names.\n */\nexport interface BundleItemProblem {\n code: BundleItemProblemCode;\n settingKey?: string | null;\n settingLabel?: string | null;\n ref?: string | null;\n}\n\nexport type BundleItemProblemCode = typeof BundleItemProblemCode[keyof typeof BundleItemProblemCode];\n\n\nexport const BundleItemProblemCode = {\n site_setting_required: 'site_setting_required',\n site_setting_reference: 'site_setting_reference',\n workflow_not_included: 'workflow_not_included',\n form_not_included: 'form_not_included',\n filter_not_included: 'filter_not_included',\n phone_number_not_included: 'phone_number_not_included',\n release_collision: 'release_collision',\n label_conflict: 'label_conflict',\n slug_collision: 'slug_collision',\n source_not_portable: 'source_not_portable',\n source_deleted: 'source_deleted',\n source_archived: 'source_archived',\n} as const;\n\n/**\n * One local Journey as the Bundle item that adds it.\n *\n * ``item`` is the whole recipe, built by the server from the Journey: its\n * definition, the actions of its steps and the Member labels they name. It is\n * absent when ``problems`` name what the Journey must change first.\n *\n * ``forms`` are the Forms its conditions, its Form updates and its saved\n * filters read, ``filters`` the saved Member filters its conditions use, and\n * ``workflows`` the Workflows its actions start. A draft that holds the\n * Journey must hold each of them.\n *\n * The recipe carries who enters the Journey: its enrollment conditions, or\n * its single saved filter when it has none.\n */\nexport interface BundleJourneyCandidate {\n id: number;\n uuid: string;\n name: string;\n item?: JourneyBundleItem | null;\n problems?: JourneyRecipeProblem[];\n forms?: FormBundleItem[];\n filters?: MemberFilterBundleItem[];\n workflows?: BundleJourneyStartedWorkflow[];\n}\n\n/**\n * This workspace's Journeys for the Bundle picker.\n *\n * ``available`` is the server rollout of Journey items\n * (``JOURNEY_BUNDLE_WRITES_ENABLED``), not authorization. When it is false a\n * draft save refuses a Journey item, and no Journey is listed.\n */\nexport interface BundleJourneyCandidates {\n available: boolean;\n journeys?: BundleJourneyOption[];\n}\n\n/**\n * A local Journey the Bundle picker lists. Nothing is built for the list.\n */\nexport interface BundleJourneyOption {\n id: number;\n uuid: string;\n name: string;\n executionModel: string;\n}\n\n/**\n * A Workflow of this workspace that one Journey step starts.\n *\n * A Workflow that two steps start is listed once for each step.\n */\nexport interface BundleJourneyStartedWorkflow {\n workflowUuid: string;\n workflowName?: string | null;\n stepUuid?: string | null;\n stepName?: string | null;\n}\n\n/**\n * One named link an author publishes with a Bundle version.\n */\nexport interface BundleLink {\n /**\n * @minLength 1\n * @maxLength 80\n */\n label: string;\n /**\n * @minLength 1\n * @maxLength 2048\n */\n url: string;\n kind?: BundleLinkKind;\n}\n\nexport type BundleLinkKind = typeof BundleLinkKind[keyof typeof BundleLinkKind];\n\n\nexport const BundleLinkKind = {\n link: 'link',\n demo: 'demo',\n} as const;\n\nexport interface BundleScenarioPreflightRequest {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n workflowItemKey: string;\n /**\n * @minItems 1\n * @maxItems 100\n */\n selections: ScenarioSelection[];\n}\n\n/**\n * One Site setting or Journey/Workflow channel that can be configured after installation.\n *\n * A Site slot is a reference-typed setting naming a workspace\n * entity rather than another item in the version. A Workflow's default Inbox\n * is a required destination slot when its\n * published dependency manifest requires one. Each per-workspace Ability\n * setting the manifest lists (``installationFields``) is a slot too, keyed\n * ``<ability kind>.<setting>`` and required when the Ability kind requires\n * it. Other Workflow references are\n * not slots — an installed Workflow's Abilities carry ordinary\n * export-shaped configuration the installer relocates by identity, and an\n * unmapped dependency refuses the install rather than becoming an open slot\n * somebody may fill later. This is a response projection: the theme vocabulary\n * stays where it is declared.\n *\n * A shared install field (``lib/models/resources/installation_fields.py``)\n * is one slot keyed by the field, and ``fills`` lists the settings its one\n * value is written to; those settings are not slots of their own.\n */\nexport interface BundleSlot {\n key: string;\n kind: string;\n required: boolean;\n label: string;\n description?: string | null;\n defaultValue?: string | number | boolean | null;\n options?: EnumOption[] | null;\n requirement?: DataTypeRequirement | null;\n fills?: BundleSlot[] | null;\n}\n\nexport interface BundleSummary {\n uuid: string;\n name: string;\n description: string | null;\n publishedVersion: number | null;\n publishedAt: string | null;\n draftGeneration: number;\n owned: boolean;\n}\n\nexport interface BundleVersionResponse {\n bundleUuid: string;\n version: number | null;\n publishedAt: string | null;\n releaseNotes?: string | null;\n items: (WorkflowBundleItem | FormBundleItem | SiteBundleItem | JourneyBundleItem | MemberFilterBundleItem | PhoneNumberBundleItem | InboxBundleItem | MemberRoleBundleItem)[];\n links?: BundleLink[];\n itemLabels?: BundleVersionResponseItemLabels;\n itemProblems?: BundleVersionResponseItemProblems;\n sourceIds?: BundleVersionResponseSourceIds;\n slots?: BundleSlot[];\n requiresDefaultPhoneNumber?: boolean;\n draftGeneration: number;\n /** The required workspace values an installation enters: each required field of the version's Workspace Fields Data Type items. */\n configurationInputs?: BundleConfigurationInput[];\n}\n\nexport type BundleVersionResponseItemLabels = {[key: string]: BundleItemLabel};\n\nexport type BundleVersionResponseItemProblems = {[key: string]: BundleItemProblem[]};\n\nexport type BundleVersionResponseSourceIds = {[key: string]: number};\n\nexport interface BundleVersionSummary {\n version: number | null;\n publishedAt: string | null;\n releaseNotes?: string | null;\n subscriberCount?: number | null;\n}\n\n/**\n * A local Workflow the Bundle picker lists, and whether it can be added.\n *\n * ``revisionUuid`` is the newest published revision, the one publishing the\n * Bundle carries. ``dependenciesChecked`` is true when dependency\n * validation finds no issues for the acting Member. Listing does not store\n * a manifest; adding the Workflow captures its release.\n */\nexport interface BundleWorkflowCandidate {\n id: number;\n uuid: string;\n name: string;\n status: BundleWorkflowCandidateStatus;\n revisionUuid?: string | null;\n revisionNumber?: number | null;\n revisionName?: string | null;\n dependenciesChecked?: boolean;\n issues?: BundleWorkflowCandidateIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n forms?: FormBundleItem[];\n}\n\nexport type BundleWorkflowCandidateIssuesItem = typeof BundleWorkflowCandidateIssuesItem[keyof typeof BundleWorkflowCandidateIssuesItem];\n\n\nexport const BundleWorkflowCandidateIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\nexport type BundleWorkflowCandidateStatus = typeof BundleWorkflowCandidateStatus[keyof typeof BundleWorkflowCandidateStatus];\n\n\nexport const BundleWorkflowCandidateStatus = {\n eligible: 'eligible',\n unpublished: 'unpublished',\n} as const;\n\nexport interface CreateBundleRequest {\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n description?: string | null;\n}\n\n/**\n * A whole Form definition, created in the installing workspace.\n *\n * ``dataTypeUuid`` is the **source** workspace's DataType identity: the uuid a\n * published Workflow ability names in its ``data_access`` configuration. It is\n * the relocation key — installation maps it to the local DataType it creates\n * — and a new draft must carry it (:class:`ReplaceBundleDraftRequest`).\n *\n * Stored items published before this identity existed omit the key. Reading\n * them back leaves it unset so the version stays readable; installation\n * refuses that item instead of answering 500 or inventing an identity.\n *\n * No connector ownership travels here: a source Form's binding to its local\n * AppConnection is workspace wiring, and ``extra=\"forbid\"`` refuses one.\n */\nexport interface FormBundleItem {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind: 'form';\n dataTypeUuid?: string | null;\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n /**\n * @minLength 1\n * @maxLength 255\n */\n slug: string;\n description?: string | null;\n prompt?: string | null;\n isCollection?: boolean;\n recordScope?: FormBundleItemRecordScope;\n webhookEventsEnabled?: boolean;\n /**\n * @minItems 1\n * @maxItems 100\n */\n fields: RequirementSchemaField[];\n}\n\nexport type FormBundleItemRecordScope = typeof FormBundleItemRecordScope[keyof typeof FormBundleItemRecordScope];\n\n\nexport const FormBundleItemRecordScope = {\n member: 'member',\n workspace: 'workspace',\n anonymous: 'anonymous',\n} as const;\n\n/**\n * Select a Journey from the publishing workspace; the server captures it.\n */\nexport interface JourneyBundleReference {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind: 'journey';\n journeyUuid: string;\n /** `managed`: each installation keeps one Journey and updates it in place (ADR-62). Absent: each release installs an editable copy. */\n updateMode?: 'managed' | null;\n}\n\n/**\n * 409 body when a Journey action starts a Workflow the draft does not hold.\n */\nexport interface JourneyWorkflowNotIncludedResponse {\n detail: string;\n code: 'journey_workflow_not_included';\n journeyKey: string;\n journeyName: string;\n stepName?: string | null;\n workflowKey?: string | null;\n workflowUuid?: string | null;\n workflowName?: string | null;\n}\n\n/**\n * Read-only org Library row: identity, latest contents, version history.\n */\nexport interface OrgBundleCatalogItem {\n uuid: string;\n name: string;\n description: string | null;\n workspaceUuid: string;\n workspaceName: string;\n publishedVersion: number | null;\n publishedAt: string | null;\n subscriberCount?: number;\n orgShared?: boolean;\n items?: (WorkflowBundleItem | FormBundleItem | SiteBundleItem | JourneyBundleItem | MemberFilterBundleItem | PhoneNumberBundleItem | InboxBundleItem | MemberRoleBundleItem)[];\n versions?: BundleVersionSummary[];\n}\n\nexport interface PublishBundleRequest {\n /** @minimum 0 */\n expectedGeneration: number;\n releaseNotes?: string | null;\n /** @maxItems 100 */\n scenarioSelections?: BundleScenarioPreflightRequest[];\n expectedPlan?: string | null;\n}\n\nexport interface ReplaceBundleDraftRequest {\n /** @minimum 0 */\n expectedGeneration: number;\n /**\n * @minItems 1\n * @maxItems 100\n */\n items: (WorkflowBundleItem | FormBundleItem | SiteBundleItem | JourneyBundleReference | MemberFilterBundleReference | PhoneNumberBundleReference | InboxBundleReference | MemberRoleBundleReference)[];\n links?: BundleLink[] | null;\n}\n\n/**\n * One publisher-selected example and its distribution decisions.\n */\nexport interface ScenarioSelection {\n scenarioUuid: string;\n driver: ScenarioSelectionDriver;\n persona: ScenarioSelectionPersona;\n fixtures: ScenarioSelectionFixtures;\n includeCriteria: boolean;\n contentReviewedForDistribution?: boolean;\n syntheticContentAttested?: boolean;\n}\n\nexport type ScenarioSelectionDriver = typeof ScenarioSelectionDriver[keyof typeof ScenarioSelectionDriver];\n\n\nexport const ScenarioSelectionDriver = {\n human: 'human',\n automated: 'automated',\n} as const;\n\nexport type ScenarioSelectionFixtures = typeof ScenarioSelectionFixtures[keyof typeof ScenarioSelectionFixtures];\n\n\nexport const ScenarioSelectionFixtures = {\n none: 'none',\n include_synthetic: 'include_synthetic',\n recipient_binding: 'recipient_binding',\n} as const;\n\nexport type ScenarioSelectionPersona = typeof ScenarioSelectionPersona[keyof typeof ScenarioSelectionPersona];\n\n\nexport const ScenarioSelectionPersona = {\n none: 'none',\n include_synthetic: 'include_synthetic',\n recipient_binding: 'recipient_binding',\n} as const;\n\n/**\n * A Site, with the theme settings an installation must resolve.\n */\nexport interface SiteBundleItem {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind: 'site';\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n slug?: string | null;\n siteUuid?: string | null;\n /** @minLength 1 */\n theme: string;\n isPublic?: boolean;\n allowSignup?: boolean;\n authenticationMethods?: 'name_dob'[];\n memberRoleSystemKeys?: SystemRoleKey[];\n signupMemberRoleSystemKey?: SystemRoleKey | null;\n settings?: SiteBundleItemSettings;\n}\n\nexport type SiteBundleItemSettings = { [key: string]: unknown };\n\n/**\n * A setting whose value is another item in this Bundle version.\n */\nexport interface SlotRef {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n slot: string;\n}\n\nexport interface UpdateBundleRequest {\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n description?: string | null;\n}\n\n/**\n * A pin to an existing published Workflow revision.\n */\nexport interface WorkflowBundleItem {\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n key: string;\n kind?: 'workflow';\n workflowUuid: string;\n revisionUuid: string;\n}\n\n/**\n * 409 body when a draft save adds a Workflow whose dependencies refuse it.\n */\nexport interface WorkflowNotShareableResponse {\n detail: string;\n code: 'workflow_not_shareable';\n workflowUuid: string;\n issues: WorkflowNotShareableResponseIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n workflows?: WorkflowReleaseRefusal[];\n}\n\nexport type WorkflowNotShareableResponseIssuesItem = typeof WorkflowNotShareableResponseIssuesItem[keyof typeof WorkflowNotShareableResponseIssuesItem];\n\n\nexport const WorkflowNotShareableResponseIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\n/**\n * An offending definition, without its configuration or runtime data.\n */\nexport interface WorkflowReleaseProblem {\n code: WorkflowReleaseProblemCode;\n abilityUuid?: string | null;\n abilityType?: string | null;\n abilityTitle?: string | null;\n ruleUuid?: string | null;\n actionType?: string | null;\n taskUuid?: string | null;\n taskId?: number | null;\n taskName?: string | null;\n dependencyKind?: WorkflowReleaseProblemDependencyKind;\n dependencyRef?: string | null;\n dependencyName?: string | null;\n reason?: WorkflowReleaseProblemReason;\n correction?: WorkflowReleaseProblemCorrection;\n resourceId?: number | null;\n}\n\nexport type WorkflowReleaseProblemCode = typeof WorkflowReleaseProblemCode[keyof typeof WorkflowReleaseProblemCode];\n\n\nexport const WorkflowReleaseProblemCode = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\nexport type WorkflowReleaseProblemCorrection = typeof WorkflowReleaseProblemCorrection[keyof typeof WorkflowReleaseProblemCorrection] | null;\n\n\nexport const WorkflowReleaseProblemCorrection = {\n edit_workflow: 'edit_workflow',\n open_resource: 'open_resource',\n review_sharing: 'review_sharing',\n upload_file: 'upload_file',\n republish_workflow: 'republish_workflow',\n retry_capture: 'retry_capture',\n} as const;\n\nexport type WorkflowReleaseProblemDependencyKind = typeof WorkflowReleaseProblemDependencyKind[keyof typeof WorkflowReleaseProblemDependencyKind] | null;\n\n\nexport const WorkflowReleaseProblemDependencyKind = {\n form: 'form',\n file: 'file',\n folder: 'folder',\n member_label: 'member_label',\n} as const;\n\nexport type WorkflowReleaseProblemReason = typeof WorkflowReleaseProblemReason[keyof typeof WorkflowReleaseProblemReason] | null;\n\n\nexport const WorkflowReleaseProblemReason = {\n missing_resource: 'missing_resource',\n read_access_required: 'read_access_required',\n share_access_required: 'share_access_required',\n unsupported_file_source: 'unsupported_file_source',\n missing_file_content: 'missing_file_content',\n invalid_configuration: 'invalid_configuration',\n resource_limit: 'resource_limit',\n unsupported_role: 'unsupported_role',\n legacy_label_configuration: 'legacy_label_configuration',\n fixed_member_target: 'fixed_member_target',\n missing_label: 'missing_label',\n republish_required: 'republish_required',\n storage_unavailable: 'storage_unavailable',\n} as const;\n\nexport interface WorkflowReleaseRefusal {\n workflowUuid: string;\n issues: WorkflowReleaseRefusalIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n}\n\nexport type WorkflowReleaseRefusalIssuesItem = typeof WorkflowReleaseRefusalIssuesItem[keyof typeof WorkflowReleaseRefusalIssuesItem];\n\n\nexport const WorkflowReleaseRefusalIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: bundle_publication\n */\n\nimport type { BundleItemLabel, WorkflowReleaseProblem } from './bundle_contract';\nimport type { JourneyRecipeProblem } from './journey_bundle';\n\n/**\n * One item of the draft, or of the last published version, at publish.\n */\nexport interface BundlePublishItem {\n key: string;\n kind: string;\n name: string;\n status: BundlePublishItemStatus;\n change?: BundlePublishItemChange;\n revisionBefore?: BundleItemLabel | null;\n revisionAfter?: BundleItemLabel | null;\n newestRevision?: BundleItemLabel | null;\n reason?: BundlePublishItemReason;\n detail?: string | null;\n issues?: BundlePublishItemIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n journeyProblems?: JourneyRecipeProblem[];\n}\n\nexport type BundlePublishItemChange = typeof BundlePublishItemChange[keyof typeof BundlePublishItemChange] | null;\n\n\nexport const BundlePublishItemChange = {\n added: 'added',\n removed: 'removed',\n revisionChanged: 'revisionChanged',\n definitionChanged: 'definitionChanged',\n unchanged: 'unchanged',\n} as const;\n\nexport type BundlePublishItemIssuesItem = typeof BundlePublishItemIssuesItem[keyof typeof BundlePublishItemIssuesItem];\n\n\nexport const BundlePublishItemIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n\nexport type BundlePublishItemReason = typeof BundlePublishItemReason[keyof typeof BundlePublishItemReason] | null;\n\n\nexport const BundlePublishItemReason = {\n workflow_not_shareable: 'workflow_not_shareable',\n not_portable: 'not_portable',\n needed_by_another_item: 'needed_by_another_item',\n} as const;\n\nexport type BundlePublishItemStatus = typeof BundlePublishItemStatus[keyof typeof BundlePublishItemStatus];\n\n\nexport const BundlePublishItemStatus = {\n ready: 'ready',\n held: 'held',\n left_out: 'left_out',\n blocked: 'blocked',\n} as const;\n\n/**\n * What publishing the saved draft now would put in the next version.\n *\n * Publishing computes the same answer again. ``planToken`` names it: pass\n * it as ``expectedPlan`` and publication refuses with 409\n * ``bundle_publish_plan_changed``, writing nothing, if what would go out\n * has changed since.\n */\nexport interface BundlePublishPreview {\n bundleUuid: string;\n fromVersion: number | null;\n draftGeneration: number;\n items: BundlePublishItem[];\n planToken: string;\n unchanged: boolean;\n publishable: boolean;\n}\n\n/**\n * The Bundles a Workflow is in, and what of its draft cannot go into one.\n *\n * ``issues`` and ``problems`` are the same check a Bundle runs when it adds\n * or publishes the Workflow, run on the Workflow's draft for the acting\n * Member. Both are empty when the Workflow is in no Bundle.\n */\nexport interface WorkflowBundleMembership {\n bundles?: WorkflowBundleMembershipEntry[];\n issues?: WorkflowBundleMembershipIssuesItem[];\n problems?: WorkflowReleaseProblem[];\n}\n\n/**\n * One Bundle of this workspace that holds the Workflow.\n */\nexport interface WorkflowBundleMembershipEntry {\n bundleUuid: string;\n name: string;\n publishedVersion?: number | null;\n publishedRevision?: BundleItemLabel | null;\n inDraft?: boolean | null;\n}\n\nexport type WorkflowBundleMembershipIssuesItem = typeof WorkflowBundleMembershipIssuesItem[keyof typeof WorkflowBundleMembershipIssuesItem];\n\n\nexport const WorkflowBundleMembershipIssuesItem = {\n unsupported_contributor_roles: 'unsupported_contributor_roles',\n unsupported_task_configuration: 'unsupported_task_configuration',\n unsupported_workflow_knowledge: 'unsupported_workflow_knowledge',\n unsupported_ability: 'unsupported_ability',\n invalid_ability_configuration: 'invalid_ability_configuration',\n file_binding_required: 'file_binding_required',\n file_access_denied: 'file_access_denied',\n missing_rule_label: 'missing_rule_label',\n missing_ability_dependency: 'missing_ability_dependency',\n unsupported_member_role: 'unsupported_member_role',\n unsupported_rule_action: 'unsupported_rule_action',\n invalid_rule_parameters: 'invalid_rule_parameters',\n missing_rule_form: 'missing_rule_form',\n missing_form: 'missing_form',\n publication_actor_required: 'publication_actor_required',\n form_access_denied: 'form_access_denied',\n invalid_form_schema: 'invalid_form_schema',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: installation_contract\n */\n\nimport type { BundleSlot } from './bundle_contract';\nimport type { WidgetSlug } from './workspace_widget_domain';\n\n/**\n * One access effect a request would apply, exactly as it would apply it (ADR-63).\n *\n * Sent back when a request applies an effect it does not approve. Approving\n * means sending the request again with ``{effect, itemKey, fingerprint}`` in\n * ``approvals``. An approval of no effect the request applies changes\n * nothing, so a retry of a request that already applied it succeeds.\n * ``member_role`` creates the role, or changes it to a new release's name\n * and scopes; ``role_assignment`` gives the role to the operators an\n * operator group slot names (existing Members by id, new ones by their\n * request identity), replacing the role each of those existing Members\n * holds now (``replacedRoles``, by name); ``widget_enablement`` enables\n * ``widget`` on a verified\n * domain with the origin settings listed. Ids, names the publisher or the\n * installer gave, scopes and domain settings only.\n */\nexport interface AccessEffect {\n effect: AccessEffectEffect;\n itemKey: string;\n fingerprint: string;\n roleName?: string | null;\n grantedScopes?: string[];\n previousScopes?: string[] | null;\n slotKey?: string | null;\n memberIds?: number[];\n replacedRoles?: string[];\n newMemberRequestUuids?: string[];\n widget?: WidgetSlug | null;\n orgDomainUuid?: string | null;\n domain?: string | null;\n allowSubdomains?: boolean | null;\n port?: number | null;\n widgets?: string[];\n}\n\n/**\n * The installer's approval of one access effect, for this request only (ADR-63).\n *\n * ``fingerprint`` is the one the server showed for the effect: the\n * installation, the release's definition of ``itemKey`` and the concrete\n * local targets. The server recomputes it under the operation fence and\n * current authority; a stale or different effect is refused. Nothing stores\n * the approval.\n */\nexport interface AccessEffectApproval {\n effect: AccessEffectApprovalEffect;\n /**\n * @minLength 1\n * @maxLength 100\n * @pattern ^[a-z][a-z0-9_]*$\n */\n itemKey: string;\n /** @pattern ^[0-9a-f]{64}$ */\n fingerprint: string;\n}\n\nexport type AccessEffectApprovalEffect = typeof AccessEffectApprovalEffect[keyof typeof AccessEffectApprovalEffect];\n\n\nexport const AccessEffectApprovalEffect = {\n member_role: 'member_role',\n role_assignment: 'role_assignment',\n widget_enablement: 'widget_enablement',\n} as const;\n\nexport type AccessEffectEffect = typeof AccessEffectEffect[keyof typeof AccessEffectEffect];\n\n\nexport const AccessEffectEffect = {\n member_role: 'member_role',\n role_assignment: 'role_assignment',\n widget_enablement: 'widget_enablement',\n} as const;\n\n/**\n * ``POST /installations/{uuid}/bindings``.\n *\n * Fills unconfigured slots and repairs missing or archived targets. A key\n * with a live target is refused; local working choices remain unchanged.\n *\n * ``replace`` changes a filled slot that is a local setting of the\n * installation, while the Bundle stays attached: a per-workspace Ability\n * setting (``lib/abilities/installation_contract.py``), whose new value\n * replaces the held one on every installed Ability of its kind; an installed\n * Workflow's default Inbox or outbound Phone Number (ADR-52); a recording;\n * and a shared install field, whose value replaces every setting it fills\n * (ADR-56). Any other filled slot is still refused.\n *\n * ``approvals`` approve the access effects this request applies (ADR-63),\n * ``widgets`` choose the verified domain each required widget is enabled on,\n * and ``roleNames`` give a declared role a local name where its own is taken.\n * Each is refused while the Bundle launch writers are off.\n */\nexport interface BindInstallationSlotsRequest {\n bindings?: BindInstallationSlotsRequestBindings;\n replace?: boolean;\n /** @maxItems 100 */\n approvals?: AccessEffectApproval[];\n /** @maxItems 10 */\n widgets?: WidgetEnablementInput[];\n roleNames?: BindInstallationSlotsRequestRoleNames;\n}\n\nexport type BindInstallationSlotsRequestBindings = {[key: string]: FormTargetInput | InboxTargetInput | NewInboxTargetInput | NewInboxWithoutAddressTargetInput | NewPhoneNumberTargetInput | ProviderPhoneNumberTargetInput | NewOperatorGroupTargetInput | ReferenceTargetInput | ScalarTargetInput};\n\nexport type BindInstallationSlotsRequestRoleNames = { [key: string]: unknown };\n\n/**\n * One binding whose target no longer satisfies what the item needs.\n */\nexport interface BrokenBinding {\n key: string;\n /** Stable reason code, rather than a workspace row name or free-form message. Accepted codes: abilities_not_materialised, channel_unrouted, filter_invalid, form_requirement, inbox_not_provisioned, operator_group_empty, phone_not_assigned, phone_not_provisioned, phone_sms_disabled, phone_voice_disabled, revision_unavailable, target_unauthorized, target_unavailable, unbound_binding, unreadable_binding, webhooks_not_configured, webhooks_unverified. */\n code: string;\n /** For phone_not_assigned and the webhook codes, the Phone Number the binding names: its settings are where its number is linked again. */\n phoneNumberId?: number | null;\n}\n\n/**\n * A Form in the installing workspace, by uuid.\n */\nexport interface FormTargetInput {\n kind: 'data_type';\n /**\n * @minLength 1\n * @maxLength 36\n */\n uuid: string;\n}\n\nexport interface InboxTargetInput {\n kind: 'inbox';\n /**\n * @minLength 1\n * @maxLength 36\n */\n uuid: string;\n}\n\n/**\n * ``POST /bundles/{uuid}/installations``.\n *\n * ``siteBindings`` carries one target per open **Site** theme-setting slot.\n * It may omit a required one: installing with an unfilled required slot\n * succeeds and ``readiness()`` reports it, because the alternative is an\n * install dialog that refuses before the workspace has anything to point at.\n * An **unknown** key is refused, because it means the caller and the version\n * disagree about what this Bundle is.\n *\n * Workflow content references relocate from the Bundle. A required Inbox\n * slot needs a destination before install: an authorized existing Inbox\n * (``inbox``, with or without an address), ``new_inbox`` to have the install\n * create one with an address on the platform domain, or\n * ``new_inbox_without_address`` to have it create one with no address yet,\n * which readiness reports as waiting for an address (ADR-52).\n *\n * A phone slot takes an existing Phone Number (``phone_number``), with or\n * without a provider number, ``new_phone_number``, or one of the\n * organization's provider numbers (``provider_phone_number``), which the\n * install links to a Phone Number it creates. One left out stays open\n * and readiness reports it: the workspace default Phone Number is only the\n * answer a client pre-selects, never one the install picks (ADR-52).\n */\nexport interface InstallBundleRequest {\n /** @minimum 1 */\n version: number;\n siteBindings?: InstallBundleRequestSiteBindings;\n}\n\nexport type InstallBundleRequestSiteBindings = {[key: string]: FormTargetInput | InboxTargetInput | NewInboxTargetInput | NewInboxWithoutAddressTargetInput | NewPhoneNumberTargetInput | ProviderPhoneNumberTargetInput | NewOperatorGroupTargetInput | ReferenceTargetInput | ScalarTargetInput};\n\n/**\n * One per-workspace Ability setting of an installation, and its current value.\n *\n * ``value`` is the value the installed Abilities hold, or ``None`` when the\n * setting is unfilled, when the installed Abilities disagree, or when the\n * caller cannot read any installed Workflow that carries it: the value is\n * shown only to someone who could already read it on that Workflow's\n * Ability.\n */\nexport interface InstallationAbilitySetting {\n slot: BundleSlot;\n value?: string | number | boolean | null;\n}\n\n/**\n * One item's difference between two versions of the same Bundle.\n */\nexport interface InstallationItemChange {\n key: string;\n kind: string;\n change: InstallationItemChangeChange;\n}\n\nexport type InstallationItemChangeChange = typeof InstallationItemChangeChange[keyof typeof InstallationItemChangeChange];\n\n\nexport const InstallationItemChangeChange = {\n added: 'added',\n removed: 'removed',\n revisionChanged: 'revisionChanged',\n definitionChanged: 'definitionChanged',\n unchanged: 'unchanged',\n} as const;\n\n/**\n * One item of an installation and the workspace row it produced.\n *\n * ``localUuid`` and ``localId`` are the same row addressed two ways: a Form\n * and a Workflow are addressed by uuid in the API, a Site by id in the\n * builder. Both are present for every kind so a caller does not need a\n * per-kind lookup table, and both are ``None`` while the installation is\n * still ``pending``.\n */\nexport interface InstallationItemResponse {\n key: string;\n kind: string;\n localUuid?: string | null;\n localId?: number | null;\n escalationRoutingRequired?: boolean;\n skippedRules?: InstallationSkippedRuleResponse[];\n journeyRollout?: ManagedJourneyRollout | null;\n}\n\n/**\n * An installed item whose name another row of its kind also has.\n *\n * Names are not identities, so installation never adopts or refuses a\n * same-named row: it creates the Bundle's own beside it and reports the\n * pair here. The other row is the workspace's own and is not named.\n */\nexport interface InstallationNameConflict {\n key: string;\n kind: 'member_filter';\n name: string;\n}\n\n/**\n * A Phone Number this operation linked that does not answer yet.\n *\n * Reported once, on the response to the install, upgrade or slot binding\n * that linked it (``provider_phone_number``), and not stored: a later read\n * of the installation, and its readiness, do not show it. ``key`` is the\n * slot the Phone Number fills; the fix is in that Phone Number's settings.\n * Identifiers and a closed code only, never the number.\n */\nexport interface InstallationPhoneNumberNotice {\n key: string;\n phoneNumberId: number;\n code: InstallationPhoneNumberNoticeCode;\n}\n\nexport type InstallationPhoneNumberNoticeCode = typeof InstallationPhoneNumberNoticeCode[keyof typeof InstallationPhoneNumberNoticeCode];\n\n\nexport const InstallationPhoneNumberNoticeCode = {\n webhooks_not_configured: 'webhooks_not_configured',\n webhooks_routed_elsewhere: 'webhooks_routed_elsewhere',\n number_not_assigned: 'number_not_assigned',\n} as const;\n\n/**\n * A bound Phone Number linked to one of the organization's provider numbers.\n */\nexport interface InstallationPhoneNumberState {\n /** The phone slot, or Journey action, that sends from it. */\n key: string;\n phoneNumberId: number;\n providerPhoneUuid: string;\n /** The organization's record of the number names this workspace's Phone Number. */\n assigned: boolean;\n /** The number's recorded A2P activation: not_requested, pending, active, failed or not_required; none for a number with no recorded state. */\n a2pStatus?: string | null;\n /** Only with verifyProvider: whether the number's live callbacks point at this workspace when read. A failed read is unverified, never configured. */\n callbacks?: InstallationPhoneNumberStateCallbacks;\n}\n\n/**\n * Only with verifyProvider: whether the number's live callbacks point at this workspace when read. A failed read is unverified, never configured.\n */\nexport type InstallationPhoneNumberStateCallbacks = typeof InstallationPhoneNumberStateCallbacks[keyof typeof InstallationPhoneNumberStateCallbacks] | null;\n\n\nexport const InstallationPhoneNumberStateCallbacks = {\n configured: 'configured',\n mismatch: 'mismatch',\n unverified: 'unverified',\n} as const;\n\n/**\n * Computed on read, never stored.\n *\n * Storing readiness would mean answering \"is this installation still wired\n * up?\" from a cache of a decision about rows that change underneath it. Every\n * field here is re-derived from the version's slots and the workspace's\n * current rows.\n */\nexport interface InstallationReadiness {\n ready: boolean;\n escalationRoutingRequired?: string[];\n recordEventsWithheld?: string[];\n workflowDependencies?: UnavailableWorkflowDependency[];\n unboundSlots?: BundleSlot[];\n brokenBindings?: BrokenBinding[];\n archivedItems?: string[];\n unavailableItems?: UnavailableInstallationItem[];\n nameConflicts?: InstallationNameConflict[];\n unmetRequirements?: UnmetRequirement[];\n /** Access effects the installer has not approved yet; each makes the installation unready. */\n pendingAccessEffects?: PendingAccessEffect[];\n /** Required Workspace Fields with no value yet; each makes the installation unready. */\n missingWorkspaceFields?: MissingWorkspaceField[];\n /** Each bound Phone Number linked to an organization number: who the organization's record names, its A2P activation and, when verified, its live callbacks. */\n phoneNumbers?: InstallationPhoneNumberState[];\n}\n\nexport interface InstallationResponse {\n workspaceName?: string | null;\n uuid: string;\n workspaceUuid: string;\n bundleUuid: string;\n bundleName: string;\n version: number;\n activeVersion?: number | null;\n status: string;\n subscribed: boolean;\n mode: string;\n upgradePolicy: string;\n items: InstallationItemResponse[];\n boundSlotKeys: string[];\n latestVersion?: number | null;\n updateAvailable?: boolean;\n latestReleaseNotes?: string | null;\n versionsBehind?: number;\n activeAt?: string | null;\n nameConflicts?: InstallationNameConflict[];\n phoneNumberNotices?: InstallationPhoneNumberNotice[];\n}\n\n/**\n * A rule of the pinned revision this workspace does not run, and why.\n *\n * Derived from the pinned snapshot on every read, never stored. Today the\n * only case is a retired action (``reasonCode`` ``retired_action``): the\n * published revision keeps the rule as released, and the workspace gets no\n * stub for it. IDs and fixed text only — no rule name or parameter.\n */\nexport interface InstallationSkippedRuleResponse {\n ruleUuid: string;\n resourceTaskId?: number | null;\n reasonCode: string;\n reason: string;\n}\n\n/**\n * The badge an installed workspace row wears: which Bundle, which version.\n *\n * A Workflow stub knows only its ``installation_uuid``; the Bundle's name and\n * the version it holds live in the resource database. This is the smallest\n * join of the two that lets a list row or a detail page say \"installed from\n * Enrollment v3\" without the reader also fetching the whole installation.\n */\nexport interface InstallationSummaryResponse {\n uuid: string;\n bundleUuid: string;\n bundleName: string;\n version: number;\n}\n\n/**\n * What ``GET /installations/{uuid}/upgrade-preview?to=N`` answers.\n *\n * Every field is derived from the two versions' stored items and the\n * installation's own ``boundSlotKeys`` — nothing here is a prediction about\n * what the upgrade will do to workspace rows.\n *\n * ``newSlots`` is the exact set the dialog must offer pickers for: the target\n * version's slots this installation has **no** binding for. That is wider\n * than \"slots the target version added\" on purpose — a slot left unfilled at\n * install is still unbound when previewed. Required slots must be supplied\n * for the upgrade to succeed; optional slots may remain open.\n */\nexport interface InstallationUpgradePreview {\n from: number;\n to: number;\n scenarioInstallationUnavailable?: boolean;\n items: InstallationItemChange[];\n newSlots?: BundleSlot[];\n releaseNotes?: VersionReleaseNotes[];\n /** The roles this workspace holds that the target version changes; the upgrade needs each approved (ADR-63). */\n accessEffects?: AccessEffect[];\n}\n\n/**\n * Where a managed Journey stands after its definition is installed (ADR-62).\n *\n * The definition is installed when the installation holds its version;\n * enrollments follow eventually. Counts only.\n */\nexport interface ManagedJourneyRollout {\n /** The installed Journey's own status: draft, active or paused. */\n status: string;\n /** The Journey version enrollments move to; none before it first runs. */\n headVersion?: number | null;\n /** Enrollments on an older version that can move now. */\n pending?: number;\n /** Enrollments that move once their in-flight step finishes. */\n deferred?: number;\n /** Enrollments kept on their version: their position has no mapping, their version cannot be read, or an operator rolled them back from the head. */\n held?: number;\n /** Enrollments an Ending finished on an older version. */\n latched?: number;\n /** Only the first enrollments were classified; the rest count as pending. */\n truncated?: boolean;\n}\n\n/**\n * A required field of an installed Workspace Fields Data Type with no value yet.\n *\n * ``unreadable``: the caller cannot read the Data Type's values, so whether\n * it has one is unknown here. Labels and keys only, never a value.\n */\nexport interface MissingWorkspaceField {\n itemKey: string;\n dataTypeUuid: string;\n fieldSlug: string;\n label: string;\n fieldType: string;\n code?: MissingWorkspaceFieldCode;\n}\n\nexport type MissingWorkspaceFieldCode = typeof MissingWorkspaceFieldCode[keyof typeof MissingWorkspaceFieldCode];\n\n\nexport const MissingWorkspaceFieldCode = {\n missing: 'missing',\n unreadable: 'unreadable',\n} as const;\n\n/**\n * Create the Inbox this slot needs instead of naming an existing one.\n *\n * The installer creates one Inbox per installation, with the product's\n * ordinary new-Inbox defaults and the Bundle's name, inside the install. It\n * carries no fields: nothing about the Inbox is caller-supplied. Requires\n * ``inboxes:write``. See ``lib/services/bundle_inbox_creation.py``.\n */\nexport const NewInboxTargetInputValue = {\n kind: 'new_inbox',\n} as const;\nexport type NewInboxTargetInput = typeof NewInboxTargetInputValue;\n\n/**\n * Create the Inbox this slot needs, with no address yet.\n *\n * The second way to create the slot's Inbox, for a practice whose address\n * will be on its organization's domain later (ADR-52). Like ``new_inbox`` it\n * creates one Inbox per installation, named for the Bundle, with the\n * product's new-Inbox defaults, inside the install, and requires\n * ``inboxes:write``. Unlike it, the Inbox gets no address and nothing routes\n * to it: it neither sends nor receives until an address is given to it in its\n * settings, and readiness reports the binding as waiting for an address\n * (``inbox_not_provisioned``). It carries no fields. See\n * ``lib/services/bundle_inbox_creation.py``.\n */\nexport const NewInboxWithoutAddressTargetInputValue = {\n kind: 'new_inbox_without_address',\n} as const;\nexport type NewInboxWithoutAddressTargetInput = typeof NewInboxWithoutAddressTargetInputValue;\n\n/**\n * An operator the installation creates as a Member of this workspace.\n *\n * ``requestUuid`` is the caller's stable identity for this creation: a retry\n * carrying it creates no second Member.\n */\nexport interface NewOperatorGroupMemberInput {\n requestUuid: string;\n /**\n * @minLength 1\n * @maxLength 255\n */\n name: string;\n email: string;\n}\n\n/**\n * Create the operator group this slot rings instead of choosing an existing one.\n *\n * The group takes the routing strategy the Bundle declares for it.\n * ``memberIds`` are existing Members and ``newMembers``\n * Members the installation creates; all are added to the group through the\n * ordinary group writer. ``assignRoleKey`` names the Bundle's ``member_role``\n * item those operators are given, which needs the installer's approval in\n * the same request. ``requestUuid`` is the caller's stable identity for this\n * creation, so a retry finds the group it made.\n */\nexport interface NewOperatorGroupTargetInput {\n kind: 'new_operator_group';\n requestUuid: string;\n name?: string | null;\n /**\n * @maxItems 100\n * @items.exclusiveMinimum 0\n */\n memberIds?: number[];\n /** @maxItems 100 */\n newMembers?: NewOperatorGroupMemberInput[];\n assignRoleKey?: string | null;\n}\n\n/**\n * Create the Phone Number this slot needs instead of naming an existing one.\n *\n * The installer creates one Phone Number per installation, named for the\n * Bundle, with no provider number linked (ADR-52). Every slot bound this way\n * points at it, and it starts sending once a provider number is linked to it\n * under Phone Numbers. It never becomes the workspace default. It carries no\n * fields. Requires ``phones:write`` and ``phones:read``. See\n * ``lib/services/bundle_phone_number_creation.py``.\n */\nexport const NewPhoneNumberTargetInputValue = {\n kind: 'new_phone_number',\n} as const;\nexport type NewPhoneNumberTargetInput = typeof NewPhoneNumberTargetInputValue;\n\n/**\n * An access effect the installation still needs, derived from the live rows.\n *\n * ``role_not_created``: the Bundle's role item has no role in this\n * workspace yet; ``fingerprint`` approves creating it under its own name.\n * ``role_name_taken``: as before, but another role holds that name, so the\n * approval needs a local name (``roleNames``) and its fingerprint comes back\n * from that request. ``widget_not_enabled``: no verified domain of the\n * organization serves ``widget`` for this workspace; the request that names\n * a domain gets its fingerprint back.\n */\nexport interface PendingAccessEffect {\n effect: PendingAccessEffectEffect;\n itemKey: string;\n code: PendingAccessEffectCode;\n roleName?: string | null;\n grantedScopes?: string[];\n widget?: WidgetSlug | null;\n fingerprint?: string | null;\n}\n\nexport type PendingAccessEffectCode = typeof PendingAccessEffectCode[keyof typeof PendingAccessEffectCode];\n\n\nexport const PendingAccessEffectCode = {\n role_not_created: 'role_not_created',\n role_name_taken: 'role_name_taken',\n widget_not_enabled: 'widget_not_enabled',\n} as const;\n\nexport type PendingAccessEffectEffect = typeof PendingAccessEffectEffect[keyof typeof PendingAccessEffectEffect];\n\n\nexport const PendingAccessEffectEffect = {\n member_role: 'member_role',\n role_assignment: 'role_assignment',\n widget_enablement: 'widget_enablement',\n} as const;\n\n/**\n * Fill this slot with one of the organization's provider numbers.\n *\n * ``uuid`` names a provider number of the workspace's organization that no\n * other workspace holds: one not assigned to any workspace, or assigned to\n * this one. The installer creates a Phone Number for it, named like the one\n * ``new_phone_number`` creates, and links the provider number to it inside\n * the install, with the checks linking a number makes under Phone Numbers. A\n * Phone Number of this workspace that already holds the number is used\n * instead. A number another workspace took is refused with the code\n * ``provider_phone_number_taken``, and nothing is created. Requires\n * ``phones:write`` and ``phones:read``. See\n * ``lib/services/bundle_provider_phone_numbers.py``.\n */\nexport interface ProviderPhoneNumberTargetInput {\n kind: 'provider_phone_number';\n /**\n * @minLength 1\n * @maxLength 36\n */\n uuid: string;\n}\n\n/**\n * A workspace row addressed by its local serial id.\n */\nexport interface ReferenceTargetInput {\n kind: ReferenceTargetInputKind;\n /** @exclusiveMinimum 0 */\n id: number;\n}\n\nexport type ReferenceTargetInputKind = typeof ReferenceTargetInputKind[keyof typeof ReferenceTargetInputKind];\n\n\nexport const ReferenceTargetInputKind = {\n file: 'file',\n file_folder: 'file_folder',\n image: 'image',\n phone_number: 'phone_number',\n member_role: 'member_role',\n page: 'page',\n operator_group: 'operator_group',\n} as const;\n\n/**\n * Recreate a deleted Form from the installation's held release.\n */\nexport interface RestoreInstallationFormRequest {\n /**\n * @minLength 1\n * @maxLength 100\n */\n itemKey: string;\n}\n\n/**\n * Repair missing dependency resources from the held Workflow release.\n */\nexport interface RestoreInstallationWorkflowResourcesRequest {\n /**\n * @minLength 1\n * @maxLength 100\n */\n itemKey: string;\n}\n\n/**\n * A literal the installing workspace supplies for a scalar theme setting or Ability setting.\n */\nexport interface ScalarTargetInput {\n kind: ScalarTargetInputKind;\n value: string | number | boolean;\n}\n\nexport type ScalarTargetInputKind = typeof ScalarTargetInputKind[keyof typeof ScalarTargetInputKind];\n\n\nexport const ScalarTargetInputKind = {\n text: 'text',\n textarea: 'textarea',\n url: 'url',\n color: 'color',\n number: 'number',\n boolean: 'boolean',\n select: 'select',\n} as const;\n\n/**\n * ``PATCH /installations/{uuid}``.\n *\n * ``pinned`` holds the version the workspace installed until an\n * administrator upgrades it. ``auto`` upgrades on publication of a new\n * version, carrying the bindings the installation already holds.\n */\nexport interface SetInstallationPolicyRequest {\n upgradePolicy: SetInstallationPolicyRequestUpgradePolicy;\n}\n\nexport type SetInstallationPolicyRequestUpgradePolicy = typeof SetInstallationPolicyRequestUpgradePolicy[keyof typeof SetInstallationPolicyRequestUpgradePolicy];\n\n\nexport const SetInstallationPolicyRequestUpgradePolicy = {\n pinned: 'pinned',\n auto: 'auto',\n} as const;\n\n/**\n * A held resource's name, kind and current condition.\n */\nexport interface UnavailableInstallationItem {\n key: string;\n kind: UnavailableInstallationItemKind;\n name: string;\n condition: UnavailableInstallationItemCondition;\n}\n\nexport type UnavailableInstallationItemCondition = typeof UnavailableInstallationItemCondition[keyof typeof UnavailableInstallationItemCondition];\n\n\nexport const UnavailableInstallationItemCondition = {\n missing: 'missing',\n archived: 'archived',\n} as const;\n\nexport type UnavailableInstallationItemKind = typeof UnavailableInstallationItemKind[keyof typeof UnavailableInstallationItemKind];\n\n\nexport const UnavailableInstallationItemKind = {\n form: 'form',\n workflow: 'workflow',\n site: 'site',\n journey: 'journey',\n member_filter: 'member_filter',\n phone_number: 'phone_number',\n inbox: 'inbox',\n member_role: 'member_role',\n} as const;\n\nexport interface UnavailableWorkflowDependency {\n itemKey: string;\n kind: UnavailableWorkflowDependencyKind;\n reference: string;\n name: string;\n condition: UnavailableWorkflowDependencyCondition;\n}\n\nexport type UnavailableWorkflowDependencyCondition = typeof UnavailableWorkflowDependencyCondition[keyof typeof UnavailableWorkflowDependencyCondition];\n\n\nexport const UnavailableWorkflowDependencyCondition = {\n missing: 'missing',\n changed: 'changed',\n moved: 'moved',\n notPackaged: 'notPackaged',\n} as const;\n\nexport type UnavailableWorkflowDependencyKind = typeof UnavailableWorkflowDependencyKind[keyof typeof UnavailableWorkflowDependencyKind];\n\n\nexport const UnavailableWorkflowDependencyKind = {\n file: 'file',\n folder: 'folder',\n member_label: 'member_label',\n} as const;\n\n/**\n * Something the installing workspace must have that it does not.\n *\n * Installing grants nothing, so a requirement an installed resource carries\n * (a feature, an app connection, a phone number) is reported here rather than\n * supplied. ``kind`` and ``slug`` name it in the requirement's own vocabulary\n * (``lib/abilities/requirements.py`` for an Ability's), ``name`` and\n * ``description`` say what it is and how to supply it, and the item fields\n * say what needs it when that is known. ``kind`` is open, so another kind of\n * requirement can be reported without a model change. Registry names and\n * slugs, and an administrator-set connection name for an MCP server — never\n * a configuration value.\n */\nexport interface UnmetRequirement {\n kind: string;\n slug: string;\n name: string;\n description: string;\n itemKey?: string | null;\n abilityType?: string | null;\n abilityTitle?: string | null;\n}\n\n/**\n * ``POST /installations/{uuid}/upgrade``.\n *\n * ``bindings`` supplies targets for slots the **target** version opens and\n * the installation does not already hold. New required Site or Workflow Inbox\n * slots must be supplied before an active release is replaced. Automatic upgrades with\n * unresolved required slots leave the held release in place for repair.\n * ``approvals`` approve the release's changed access effects (ADR-63), and\n * ``roleNames`` give a declared role a local name where its own is taken, as\n * on the bindings request. Both are refused while the Bundle launch writers\n * are off.\n */\nexport interface UpgradeInstallationRequest {\n /** @minimum 1 */\n toVersion: number;\n bindings?: UpgradeInstallationRequestBindings;\n /** @maxItems 100 */\n approvals?: AccessEffectApproval[];\n roleNames?: UpgradeInstallationRequestRoleNames;\n}\n\nexport type UpgradeInstallationRequestBindings = {[key: string]: FormTargetInput | InboxTargetInput | NewInboxTargetInput | NewInboxWithoutAddressTargetInput | NewPhoneNumberTargetInput | ProviderPhoneNumberTargetInput | NewOperatorGroupTargetInput | ReferenceTargetInput | ScalarTargetInput};\n\nexport type UpgradeInstallationRequestRoleNames = { [key: string]: unknown };\n\n/**\n * One published version's release notes, for the upgrade dialog.\n */\nexport interface VersionReleaseNotes {\n version: number;\n releaseNotes?: string | null;\n}\n\n/**\n * The verified organization domain a required widget is enabled on.\n */\nexport interface WidgetEnablementInput {\n widget: WidgetSlug;\n orgDomainUuid: string;\n}\n","import type { GravityRailWorkspaceClient } from '../client/workspace-client';\n\nexport type AnyRecord = Record<string, any>;\nexport type ResourceSummary = Record<string, Array<number | undefined>>;\n\nexport function isRecord(value: unknown): value is AnyRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isPlainRecord(value: unknown): value is AnyRecord {\n if (!isRecord(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function slugify(name: string): string {\n return name.toLowerCase().replaceAll(' ', '_').replaceAll('-', '_');\n}\n\nexport abstract class WorkspaceBuilderResource {\n _id?: number;\n _uuid?: string;\n _created = false;\n _existed = false;\n\n /** Server-assigned numeric id — available after apply() or adopt(). */\n get id(): number {\n if (this._id === undefined) {\n throw new Error(\n `${this.constructor.name} has no id yet — ids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._id;\n }\n\n /** Server-assigned uuid — available after apply() or adopt(). */\n get uuid(): string {\n if (this._uuid === undefined) {\n throw new Error(\n `${this.constructor.name} has no uuid yet — uuids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._uuid;\n }\n\n /**\n * True for resources the server creates on our behalf (currently a\n * journey's `Start` step). They are kept in the resource list so edges can\n * reference them, but they are never created, printed, or counted.\n */\n get isImplicit(): boolean {\n return false;\n }\n\n /**\n * True when `apply()` is safe — and required — to run against a resource\n * that was ADOPTED rather than created.\n *\n * False by default because most builders create only: re-running their\n * `apply()` on an existing resource would make a duplicate. Override it\n * when `apply()` is an idempotent full write keyed on stable identities,\n * which is the only way a re-run can express an EDIT (a removed goal, a\n * reordered timeline) rather than just an addition.\n */\n get appliesWhenExisting(): boolean {\n return false;\n }\n\n abstract planLine(): string;\n abstract apply(client: GravityRailWorkspaceClient): Promise<void>;\n\n matchKey(): string | undefined {\n return undefined;\n }\n\n adopt(existing: AnyRecord): void {\n this._id = existing.id;\n this._uuid = existing.uuid;\n this._existed = true;\n }\n}\n\nexport function resolveRefs(params: AnyRecord): AnyRecord {\n return resolveRefValue(params) as AnyRecord;\n}\n\nfunction resolveRefValue(value: unknown): unknown {\n if (value instanceof WorkspaceBuilderResource) return value._uuid;\n if (Array.isArray(value)) return value.map(resolveRefValue);\n if (!isPlainRecord(value)) return value;\n\n const out: AnyRecord = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n out[key] = resolveRefValue(nestedValue);\n }\n return out;\n}\n\n/**\n * Same substitution as `resolveRefs`, but to numeric ids.\n *\n * A few surfaces key on id rather than uuid — the query-engine IR is the main\n * one (`member.labelId` takes label ids). Without this a script would have to\n * apply once, read the ids back, and apply again just to write one filter.\n *\n * Returns `unknown` deliberately. A builder standing in a `number` slot is not\n * type-compatible with the payload it is going into, so the cast is real; a\n * generic `<T>(value: T): T` would only hide it, and would additionally claim a\n * `number` where an unresolved ref yields `undefined`. Callers cast at the one\n * place it matters, in view of the reader.\n */\nexport function resolveIdRefs(value: unknown): unknown {\n return resolveIdRefValue(value);\n}\n\nfunction resolveIdRefValue(value: unknown): unknown {\n // `.id` throws with a useful message when the ref has no id yet. Failing\n // here beats writing `undefined` into a payload: an id-keyed predicate that\n // silently loses a term matches everyone or no one, and looks fine doing it.\n if (value instanceof WorkspaceBuilderResource) return value.id;\n if (Array.isArray(value)) return value.map(resolveIdRefValue);\n if (!isPlainRecord(value)) return value;\n\n const out: AnyRecord = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n out[key] = resolveIdRefValue(nestedValue);\n }\n return out;\n}\n","import {\n EventRuleEventType,\n EventRuleObjectType,\n type CreateRoutineRequest,\n type EventRuleActionType,\n type MemberFilterFormData,\n type NotificationRuleCreate,\n} from '../types';\nimport type { QueryPredicate } from '../types/query-engine-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { resolveIdRefs, WorkspaceBuilderResource } from './resource';\nimport type { WorkflowBuilder } from './workflows';\n\nexport class MemberFilterBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n /** Query-engine predicate (JSON IR) authored on MemberFilter.query. */\n query: QueryPredicate | null = null;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.query = options.query ?? null;\n }\n\n /**\n * Set the filter's query-engine predicate (JSON IR).\n *\n * Anywhere the IR wants a numeric id you may pass the builder that will own\n * it (e.g. a label in a `member.labelId` value); refs resolve at apply time.\n */\n setQuery(query: QueryPredicate): MemberFilterBuilder {\n this.query = query;\n return this;\n }\n\n planLine(): string {\n return `MemberFilter: ${this.name}${this.query ? ' (query)' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: MemberFilterFormData = {\n name: this.name,\n description: this.description,\n // Builder refs inside the IR become ids here; see resolveIdRefs.\n query: resolveIdRefs(this.query) as QueryPredicate | null,\n };\n const result = await client.createMemberFilter(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\ninterface RoutineRuleDraft {\n actionType: EventRuleActionType | string;\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams: AnyRecord;\n}\n\nexport class RoutineBuilder extends WorkspaceBuilderResource {\n readonly active: boolean;\n readonly description: string;\n readonly rules: RoutineRuleDraft[] = [];\n\n constructor(\n readonly name: string,\n readonly cronSchedule = '',\n options: AnyRecord = {}\n ) {\n super();\n this.active = options.active ?? false;\n this.description = options.description ?? '';\n }\n\n addRule(\n actionType: string,\n options: {\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams?: AnyRecord;\n } = {}\n ): RoutineBuilder {\n this.rules.push({\n actionType,\n workflow: options.workflow,\n memberFilter: options.memberFilter,\n actionParams: options.actionParams ?? {},\n });\n return this;\n }\n\n planLine(): string {\n const parts = [\n ...(this.cronSchedule ? [`cron=${this.cronSchedule}`] : []),\n ...(this.rules.length ? [`${this.rules.length} rules`] : []),\n this.active ? 'active' : 'inactive',\n ];\n return `Routine: ${this.name} (${parts.join(', ')})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const eventRules = this.rules.map((rule) => {\n const actionParams = { ...rule.actionParams };\n if (rule.workflow?._id !== undefined) actionParams.workflowId = rule.workflow._id;\n if (rule.memberFilter?._id !== undefined)\n actionParams.memberFilterId = rule.memberFilter._id;\n return {\n uuid: crypto.randomUUID(),\n objectType: EventRuleObjectType.ROUTINE,\n eventType: EventRuleEventType.ROUTINE_TRIGGERED,\n actionType: rule.actionType as EventRuleActionType,\n actionParams,\n active: true,\n };\n });\n const payload: CreateRoutineRequest = {\n name: this.name,\n cronString: this.cronSchedule,\n scheduleMode: this.cronSchedule ? 'CRON' : undefined,\n scheduleEnabled: this.active,\n ...(this.description ? { description: this.description } : {}),\n ...(eventRules.length ? { eventRules } : {}),\n };\n const result = await client.createRoutine(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class NotificationRuleBuilder extends WorkspaceBuilderResource {\n readonly noticeType: string;\n readonly memberId: number;\n readonly workflow?: WorkflowBuilder;\n readonly prompt?: string;\n readonly notifySms: boolean;\n readonly notifyEmail: boolean;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.noticeType = options.noticeType ?? options.notice_type ?? name;\n this.memberId = options.memberId ?? options.member_id;\n this.workflow = options.workflow;\n this.prompt = options.prompt ?? options.message;\n this.notifySms = Boolean(options.notifySms ?? options.notify_sms);\n this.notifyEmail = Boolean(options.notifyEmail ?? options.notify_email);\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.memberId !== undefined) parts.push(`memberId=${this.memberId}`);\n if (this.workflow) parts.push(`workflow='${this.workflow.name}'`);\n return `NotificationRule: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n if (this.memberId === undefined) {\n throw new Error(`Notification rule '${this.name}' requires memberId`);\n }\n const payload: NotificationRuleCreate = {\n noticeType: this.noticeType,\n memberId: this.memberId,\n workflowId: this.workflow?._id,\n prompt: this.prompt ?? null,\n notifySms: this.notifySms,\n notifyEmail: this.notifyEmail,\n };\n const result = await client.createNotificationRule(payload);\n this._id = result.id;\n this._created = true;\n }\n}\n","import {\n DataFieldType,\n EventRuleEventType,\n type DataTypeFormData,\n type EnumOption,\n type EventRuleActionType,\n type MemberLabelFormData,\n type SchemaField,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport { type AnyRecord, isRecord, slugify, WorkspaceBuilderResource } from './resource';\n\n// The client DataFieldType enum and the generated SchemaField fieldType\n// literal union share the same string values, but TS string enums are\n// nominal — convert once at draft construction.\ntype WorkspaceFieldDraft = SchemaField;\n\nfunction normalizeOptions(options: any[]): EnumOption[] {\n if (options.length === 0) return [];\n const first = options[0];\n if (isRecord(first)) return options as EnumOption[];\n if (Array.isArray(first)) {\n return options.map((entry) => ({ label: String(entry[0]), value: entry[1] }));\n }\n return options.map((option) => ({ label: String(option), value: String(option) }));\n}\n\nfunction createFieldDraft(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: EnumOption[];\n cel?: string;\n } = {}\n): WorkspaceFieldDraft {\n return {\n name,\n slug,\n fieldType: fieldType as SchemaField['fieldType'],\n required: Boolean(options.required),\n order: options.order ?? 0,\n ...(options.description ? { description: options.description } : {}),\n ...(options.choices ? { options: options.choices } : {}),\n ...(options.cel ? { celFunction: options.cel } : {}),\n };\n}\n\nexport class FormBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly prompt: string;\n readonly collection: boolean;\n readonly fields: WorkspaceFieldDraft[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n\n constructor(name: string, slug?: string, options: AnyRecord = {}) {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.description = options.description ?? '';\n this.prompt = options.prompt ?? '';\n this.collection = options.collection ?? false;\n\n for (const field of options.fields ?? []) {\n if (!isRecord(field) || !field.name) continue;\n const choices = field.options ? normalizeOptions(field.options) : undefined;\n this.fields.push(\n createFieldDraft(\n (field.fieldType ?? field.field_type ?? DataFieldType.TEXT) as DataFieldType,\n field.name,\n field.slug ?? slugify(field.name),\n {\n required: Boolean(field.required ?? field.isRequired),\n order: field.order ?? 0,\n description: field.description,\n choices,\n }\n )\n );\n }\n }\n\n field(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: any[];\n cel?: string;\n } = {}\n ): FormBuilder {\n this.fields.push(createFieldDraft(fieldType, name, slug, options));\n return this;\n }\n\n enumField(name: string, slug: string, options: any[], settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ENUM, name, slug, {\n ...settings,\n choices: normalizeOptions(options),\n });\n }\n\n textField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TEXT, name, slug, settings);\n }\n\n numberField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.NUMBER, name, slug, settings);\n }\n\n dateField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATE, name, slug, settings);\n }\n\n booleanField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.BOOLEAN, name, slug, settings);\n }\n\n functionField(name: string, slug: string, cel: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.FUNCTION, name, slug, { ...settings, cel });\n }\n\n emailField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.EMAIL, name, slug, settings);\n }\n\n phoneField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.PHONE, name, slug, settings);\n }\n\n longtextField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.LONGTEXT, name, slug, settings);\n }\n\n integerField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.INTEGER, name, slug, settings);\n }\n\n datetimeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATETIME, name, slug, settings);\n }\n\n timeOfDayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TIME_OF_DAY, name, slug, settings);\n }\n\n usZipCodeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.US_ZIP_CODE, name, slug, settings);\n }\n\n arrayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ARRAY, name, slug, settings);\n }\n\n objectField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.OBJECT, name, slug, settings);\n }\n\n onRecordCreated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_CREATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n onRecordUpdated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_UPDATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n matchKey(): string {\n return this.slug;\n }\n\n planLine(): string {\n return `Form: ${this.name} (slug=${this.slug}, ${this.fields.length} fields)`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: DataTypeFormData = {\n name: this.name,\n slug: this.slug,\n description: this.description,\n prompt: this.prompt,\n isCollection: this.collection,\n fields: this.fields,\n };\n const result = await client.createDataType(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class MemberLabelBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly color: string;\n readonly description: string;\n\n constructor(name: string, slug?: string, color = '8b5cf6', description = '') {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.color = color;\n this.description = description;\n }\n\n matchKey(): string {\n return this.name;\n }\n\n planLine(): string {\n return `Label: ${this.name} (slug=${this.slug})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: MemberLabelFormData = {\n name: this.name,\n slug: this.slug,\n color: this.color,\n description: this.description,\n };\n const result = await client.createMemberLabel(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n","import {\n EventRuleEventType,\n EventRuleActionType,\n type EventRuleInput,\n type JourneyV2DefinitionFormData,\n type JourneyV2EndingInput,\n type JourneyV2GoalInput,\n type JourneyV2TouchInput,\n type JourneyV2WaitInput,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { type AnyRecord, resolveRefs, WorkspaceBuilderResource } from './resource';\n\n/** Options for a `JOURNEY_STEP_EXECUTE` outreach rule on a step. */\nexport interface StepRuleOptions {\n /** CEL guard — the action is skipped when this is false. */\n when?: string;\n /** Operator-facing rule name, shown in the journey editor. */\n name?: string;\n /** Delay the action this many seconds after the step activates. */\n delaySeconds?: number;\n active?: boolean;\n}\n\nexport interface StepRuleDraft {\n uuid: string;\n actionType: EventRuleActionType;\n actionParams: AnyRecord;\n options: StepRuleOptions;\n /**\n * The uuid the SERVER already stores for this rule, learned during\n * adoption. `uuid` above is minted by the script at authoring time and is\n * therefore different on every run of the same program; sending that as the\n * identity would make every re-run delete the live rule and create a\n * replacement, resetting its delivery bookkeeping. Preferred over `uuid`\n * when present.\n */\n adoptedUuid?: string;\n}\n\n/**\n * A uuid the action needs, either literal or as the builder that will own it.\n * Builders resolve at apply time, so a step can reference a Workflow created in\n * the same script without the author threading ids through by hand.\n */\nexport type UuidRef = string | WorkspaceBuilderResource;\n\n// ===========================================================================\n// Journey builder\n// ===========================================================================\n//\n// A Journey is one ordered timeline written atomically: touches in order, the\n// wait into each, exclusive branches, ordered Endings and goals.\n\n/** The wait on the edge INTO a touch. */\nexport interface WaitOptions {\n /**\n * Whole elapsed days since the previous touch's durable acceptance. The ONE\n * canonical shape the structured control round-trips — the server\n * regenerates the CEL from this number.\n */\n afterDays?: number;\n /**\n * Any other valid CEL, stored byte for byte. `duration(\"4h\")`, member-local\n * schedules, and everything else lives here; the editor evaluates it but\n * declines to reinterpret it. Mutually exclusive with `afterDays`.\n */\n when?: string;\n /** Hold the touch until the member matches this saved MemberFilter. */\n filterId?: number;\n // NOTE: there is no deadline option here. The evaluator implements no\n // deadline semantics, so the server's wait contract rejects the key rather\n // than accepting a setting that would never fire. Model \"stop waiting\" as\n // an Ending instead: it is evaluated on every tick and terminates the\n // enrollment explicitly.\n}\n\nexport interface TouchOptions {\n description?: string;\n wait?: WaitOptions;\n}\n\nexport interface EndingOptions {\n /**\n * The Ending's CEL condition. Optional ONLY when `filterId` is given —\n * an Ending with neither predicate would match every enrollment\n * (rule-filters plan §3.2).\n */\n when?: string;\n /**\n * A saved MemberFilter the member must be in. Given alongside `when` the two\n * are ANDed: the Ending claims a member only when both pass.\n */\n filterId?: number;\n}\n\nexport interface GoalOptions {\n description?: string;\n /** Touch or Ending whose completion satisfies the goal. */\n step?: TouchBuilder | EndingBuilder;\n completionCel?: string;\n value?: number;\n}\n\n/** One arm of an exclusive branch. */\nexport interface RouteOptions {\n /**\n * The route's CEL condition. Omit BOTH this and `filterId` to declare the\n * **Otherwise** route: an OPTIONAL fallback, taken immediately when nothing\n * above matched. At most one route per branch omits both, and it must be\n * declared last, because Otherwise matches immediately and anything after it\n * could never be reached.\n *\n * Declaring no Otherwise at all is the default shape, not an omission: the\n * branch is checked top to bottom on every pass and members WAIT at it until\n * a route matches. So there are two author intents, not one:\n *\n * - **wait for a match** — declare only conditional routes;\n * - **fall back immediately** — add a final route with no `when` and no\n * `filterId`.\n */\n when?: string;\n /**\n * A saved MemberFilter the member must be in (rule-filters plan §3.2).\n *\n * A route carrying only this is CONDITIONAL, not the fallback — that is the\n * whole reason `when` alone can no longer answer \"is this Otherwise?\".\n * Given alongside `when` the two are ANDed.\n */\n filterId?: number;\n /**\n * The touch this arm continues to after its own touches — the per-arm\n * terminus. Omit it and the arm ENDS: the enrollment completes after the\n * arm's last touch, or — for an arm with no touches at all — as soon as the\n * route is taken. An Ending still applies first. Absence is meaningful, so\n * there is no separate \"stop\" option to get out of step with it.\n */\n continueAt?: TouchBuilder;\n}\n\n/**\n * One route of a branch. Declaration order IS precedence — routes are checked\n * top to bottom and the first match wins.\n */\nexport class RouteBuilder {\n readonly touches: TouchBuilder[] = [];\n /**\n * The DECISION RULE uuid. Adopted for the same reason an Ending's is:\n * `MemberJourneyStep.entry_decision_rule_id` points at this row with\n * `ON DELETE SET NULL`, so recreating it on a re-run would erase which arm\n * every already-routed enrollment is on — invisibly, since both rules\n * \"exist\" afterwards.\n */\n _ruleUuid?: string;\n\n constructor(\n readonly name: string,\n readonly options: RouteOptions = {}\n ) {}\n\n /** Append a touch to this arm. Order is call order. */\n touch(name: string, options: TouchOptions = {}): TouchBuilder {\n const touch = new TouchBuilder(name, options);\n this.touches.push(touch);\n return touch;\n }\n}\n\n/**\n * The ordered route set attached to one touch.\n *\n * There is no branch ENTITY on the server and none is created here — a branch\n * is its rules, and its header is derived from the source touch. This class\n * exists only to group the routes with the touch that owns them.\n *\n * A branch needs at least one CONDITIONAL route. It does not need an Otherwise:\n * with none, members wait at the branch source and the routes are re-checked on\n * every pass until one matches. See {@link RouteOptions.when} for the two\n * fallback intents and how each is expressed.\n */\nexport class BranchBuilder {\n readonly routes: RouteBuilder[] = [];\n\n /** Append a route. Declaration order is evaluation order. */\n route(name: string, options: RouteOptions = {}): RouteBuilder {\n const route = new RouteBuilder(name, options);\n this.routes.push(route);\n return route;\n }\n}\n\n/** One ordinary touch in a timeline, plus the wait that leads into it. */\nexport class TouchBuilder {\n readonly rules: StepRuleDraft[] = [];\n /** Filled in from the server's response so a re-run keeps this touch. */\n _uuid?: string;\n\n /**\n * The exclusive branch that follows this touch, when it has one. A touch\n * carrying a branch gets NO ordinary outgoing connection: its routes are\n * the only way out, so touches declared after it are reached only by an arm\n * naming them in `continueAt`.\n */\n _branch?: BranchBuilder;\n\n readonly name: string;\n\n /**\n * The name is CANONICALIZED here, once, and everything downstream reads it:\n * the `key:<name>` address, the payload, adoption's name lookup, and the\n * uniqueness gate. The API trims it before storing\n * (`JourneyV2TouchInput`/`JourneyV2EndingInput` name validators), so a\n * builder holding `\" Welcome \"` would send an address for a name the server\n * does not have, fail to find its own step on the way back, and treat it as\n * new on the next run — archiving the live step and its history. One\n * representation at the boundary is the only way that cannot happen; a\n * second trim anywhere downstream would be a place for the two to drift.\n */\n constructor(\n name: string,\n readonly options: TouchOptions = {}\n ) {\n this.name = name.trim();\n }\n\n /**\n * Attach an exclusive branch after this touch, or return the existing one.\n *\n * Idempotent so a script can add routes in stages without accidentally\n * declaring two branches on one touch — which the server has no shape for,\n * since a touch owns exactly one ordered route set.\n */\n branch(): BranchBuilder {\n this._branch ??= new BranchBuilder();\n return this._branch;\n }\n\n /**\n * The request-local address this step answers to .\n *\n * A saved step is addressed by its uuid; an unsaved one by a `key` derived\n * from its authored name. Deriving from the NAME rather than minting a\n * uuid4 keeps the payload stable across re-runs of the same script — a\n * fresh random key on every run would make the request differ from itself\n * for no reason, and the server's EventRule sync matches on the uuids the\n * payload carries. Names are already asserted unique within a journey,\n * which is what makes a name-derived key unique.\n *\n * {@link EndingBuilder} INHERITS this rather than deriving its own: an\n * Ending's anchor key and a touch's key land in one server-side namespace\n * (`stepKey` is one field), so two derivations that drifted would produce\n * two spellings of the same address and a goal would 404 on the one its\n * step was not sent under.\n *\n * Two steps of one name therefore answer to one address. {@link preflight}\n * is the first enforcement point and refuses it before any write, counting\n * touches and Endings together and comparing names trimmed, as the API\n * stores them. Without that gate the collision surfaces twice and both\n * times too late: the server rejects the definition PUT after `apply()` has\n * created the Journey, and {@link indexStoredByName} rejects the SECOND run\n * of a script whose two stored steps make `adopt()` a coin flip.\n */\n get _address(): string {\n return this._uuid ?? `key:${this.name}`;\n }\n\n /**\n * Re-attach the EventRule uuids the server already stores for this touch.\n *\n * Identity is the operator-set rule NAME. `.sendsSms(...)` does not require\n * one, so an unnamed rule falls back to its actionType — but ONLY when that\n * answer is 1:1: exactly one unnamed draft of that actionType here, and\n * exactly one stored rule of it left unclaimed there. Anything else throws.\n *\n * The ordinal-within-actionType fallback this replaces was not a weaker\n * identity, it was the wrong one. Inserting a new unnamed rule ABOVE an\n * existing same-type rule shifts every position by one, so the new rule\n * adopted the existing rule's uuid — taking over its delivery bookkeeping —\n * and the existing rule was written as brand new and archived. Nothing in\n * the payload showed it: both rules \"exist\" afterwards. When the script\n * cannot say which rule is which, the honest answer is to ask the author to\n * name them, not to guess by position.\n */\n adoptRuleUuids(serverRules: AnyRecord[]): void {\n const namedDrafts = this.rules.filter((draft) => !!draft.options.name);\n const storedByName = indexStoredByName(\n serverRules,\n new Set(namedDrafts.map((draft) => draft.options.name as string)),\n `touch '${this.name}'`,\n 'action'\n );\n\n // A stored rule a named draft claims is out of the unnamed pool: it has\n // an owner, so it cannot also be the answer to an unnamed draft.\n const claimed = new Set<AnyRecord>();\n for (const draft of namedDrafts) {\n const match = storedByName.get(draft.options.name as string);\n // No stored rule of that name is an ordinary NEW rule — it keeps the\n // uuid the script minted and the server creates it. It must NOT fall\n // through to the unnamed path: a freshly named rule would there take\n // an existing rule's identity, and the existing rule would be\n // recreated and archived under it.\n if (!match) continue;\n draft.adoptedUuid = match.uuid as string;\n claimed.add(match);\n }\n\n const unnamedByActionType = new Map<string, StepRuleDraft[]>();\n for (const draft of this.rules) {\n if (draft.options.name) continue;\n const actionType = String(draft.actionType);\n unnamedByActionType.set(actionType, [\n ...(unnamedByActionType.get(actionType) ?? []),\n draft,\n ]);\n }\n for (const [actionType, drafts] of unnamedByActionType) {\n const candidates = serverRules.filter(\n (rule) => String(rule.actionType) === actionType && !claimed.has(rule)\n );\n // Nothing stored of this type: every draft is new, and creating them\n // is not a guess.\n if (!candidates.length) continue;\n if (drafts.length === 1 && candidates.length === 1) {\n drafts[0]!.adoptedUuid = candidates[0]!.uuid as string;\n continue;\n }\n throw new Error(\n `touch '${this.name}' has ${drafts.length} unnamed ${actionType} action(s) ` +\n `and the server has ${candidates.length} — so there is no way to tell ` +\n 'which stored action each one is. Adopting by position swaps their ' +\n 'identities the moment an action is inserted or removed, which moves ' +\n \"one action's delivery history onto another. Give these actions names \" +\n '(`{ name: ... }`) so each one can be matched to the right rule.'\n );\n }\n }\n\n /** Attach a `JOURNEY_STEP_EXECUTE` action. */\n onExecute(\n actionType: EventRuleActionType,\n params: AnyRecord = {},\n options: StepRuleOptions = {}\n ): TouchBuilder {\n this.rules.push({\n uuid: crypto.randomUUID(),\n actionType,\n actionParams: params,\n options,\n });\n return this;\n }\n\n sendsSms(\n params: {\n phoneNumberUUID: UuidRef;\n messageTemplate?: string;\n workflowUUID?: UuidRef;\n initialUserMessage?: string;\n },\n options: StepRuleOptions = {}\n ): TouchBuilder {\n return this.onExecute(EventRuleActionType.SMS_SEND, params, options);\n }\n\n callsMember(\n params: { phoneNumberUUID: UuidRef; workflowUUID: UuidRef },\n options: StepRuleOptions = {}\n ): TouchBuilder {\n return this.onExecute(EventRuleActionType.PHONE_CALL, params, options);\n }\n\n sendsEmail(\n params: {\n inboxUUID: UuidRef;\n subjectTemplate?: string;\n bodyTemplate?: string;\n workflowUUID?: UuidRef;\n },\n options: StepRuleOptions = {}\n ): TouchBuilder {\n return this.onExecute(EventRuleActionType.EMAIL_SEND, params, options);\n }\n\n get hasOutreach(): boolean {\n return this.rules.length > 0;\n }\n\n eventRuleInputs(): EventRuleInput[] {\n return this.rules.map((rule) => ({\n uuid: rule.adoptedUuid ?? rule.uuid,\n eventType: EventRuleEventType.JOURNEY_STEP_EXECUTE,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.options.name ? { name: rule.options.name } : {}),\n ...(rule.options.when ? { conditions: rule.options.when } : {}),\n ...(rule.options.delaySeconds ? { delay: rule.options.delaySeconds } : {}),\n active: rule.options.active ?? true,\n }));\n }\n}\n\n/** One ordered Ending. List position IS precedence — first match wins. */\nexport class EndingBuilder extends TouchBuilder {\n /**\n * The DECISION RULE uuid, distinct from `_uuid` (the anchor step's).\n *\n * An Ending is two rows: a `JourneyDecisionRule` carrying the condition and\n * precedence, and a `JourneyStep` anchor carrying its actions, goals, and\n * status history. Adopting only the anchor left the rule to be recreated on\n * every re-run — and `MemberJourney.latched_ending_rule_id` /\n * `JourneyStatusLog.journey_decision_rule_id` point at the RULE with\n * `ON DELETE SET NULL`, so every completed enrollment silently forgot which\n * Ending it took.\n */\n _ruleUuid?: string;\n\n constructor(\n name: string,\n readonly when: string | undefined,\n readonly filterId: number | undefined\n ) {\n super(name);\n }\n\n /**\n * An Ending cannot carry a branch, and saying so is the whole override.\n *\n * `EndingBuilder extends TouchBuilder` for the identity and addressing\n * an Ending's anchor shares with a touch, which also inherits every touch\n * method — `branch()` among them. Inherited unchanged it would set\n * `_branch` on an object nothing ever reads it from: the Ending serializer\n * writes `{uuid|key, name, celCondition, filterId, eventRules}` and no\n * `branch`, and `allTouches()` walks only the timeline, so the routes are\n * never numbered, validated, adopted or sent. The author gets no error and\n * a definition quietly missing what they asked for.\n *\n * An Ending is terminal by construction — it is the rule that ENDS an\n * enrollment — so there is no shape to serialize even if the payload had a\n * field for it. Refusing at the call is the only point where the author is\n * still holding the mistake.\n *\n * @see foreignAnchorProblem for why this names no Ending.\n */\n override branch(): never {\n throw new Error(\n 'an Ending cannot carry a branch. An Ending terminates an enrollment, ' +\n 'so there is nothing after it to route to, and the atomic definition ' +\n 'has no field to send one under — the routes would be silently ' +\n 'dropped. Put the branch on the touch that leads to this Ending ' +\n 'instead, and give each arm its own Ending.'\n );\n }\n}\n\nexport interface GoalDraft {\n name: string;\n description?: string;\n step?: TouchBuilder | EndingBuilder;\n completionCel?: string;\n value?: number;\n /** Server-assigned goal uuid, learned during adoption. */\n _uuid?: string;\n}\n\n/**\n * Build a Journey definition and write it through the ATOMIC endpoint.\n *\n * One create plus one `PUT /v2-definition`. That is not an optimization: a\n * definition is only valid as a whole, so a partial write would be rejected by\n * the publish validator anyway, and a half-applied timeline is exactly the\n * state the atomic endpoint exists to make impossible.\n */\nexport class JourneyBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly touches: TouchBuilder[] = [];\n readonly endings: EndingBuilder[] = [];\n readonly goals: GoalDraft[] = [];\n /** Activate after the definition is written and validated. */\n readonly activate: boolean;\n /** Optimistic-concurrency token, from create or adoption. */\n private _expectedUpdatedAt?: string;\n /** Server status at adoption — decides whether a re-run must pause first. */\n private _status?: string;\n /**\n * Server execution model at adoption. Only `'v2'` accepts the whole-definition\n * write `apply()` makes; anything else is refused at adoption, and `apply()`\n * re-checks it before its first write.\n */\n private _executionModel?: string;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.activate = options.activate ?? false;\n }\n\n /**\n * A definition write is idempotent, so an ADOPTED journey is written too.\n * That is the whole point of adopting one: the PUT is a full, uuid-keyed\n * replacement, so re-running a script is how an author expresses an edit.\n */\n get appliesWhenExisting(): boolean {\n return true;\n }\n\n /** Append a touch to the timeline. Order is call order. */\n touch(name: string, options: TouchOptions = {}): TouchBuilder {\n const touch = new TouchBuilder(name, options);\n this.touches.push(touch);\n return touch;\n }\n\n /**\n * Every touch in the timeline, arms included, depth first.\n *\n * Identity adoption, name-uniqueness and validation all have to see arm\n * touches — a walk over the top level alone would leave every arm touch\n * recreated on each re-run, silently archiving its member history.\n */\n allTouches(): TouchBuilder[] {\n const out: TouchBuilder[] = [];\n const walk = (touches: TouchBuilder[]): void => {\n for (const touch of touches) {\n out.push(touch);\n for (const route of touch._branch?.routes ?? []) walk(route.touches);\n }\n };\n walk(this.touches);\n return out;\n }\n\n /** Every route in the timeline, at every nesting depth, depth first. */\n allRoutes(): RouteBuilder[] {\n const out: RouteBuilder[] = [];\n for (const touch of this.allTouches()) {\n for (const route of touch._branch?.routes ?? []) out.push(route);\n }\n return out;\n }\n\n /** Append an Ending. Call order is evaluation order. */\n ending(name: string, options: EndingOptions): EndingBuilder {\n const ending = new EndingBuilder(name, options.when, options.filterId);\n this.endings.push(ending);\n return ending;\n }\n\n goal(name: string, options: GoalOptions = {}): JourneyBuilder {\n this.goals.push({\n name,\n description: options.description,\n step: options.step,\n completionCel: options.completionCel,\n value: options.value,\n });\n return this;\n }\n\n /**\n * Authoring problems the server's publish validator would reject.\n *\n * \"No incoming edge\" has no meaning in a timeline — position is the order —\n * so the checks here cover branch shape and Ending conditions. Touches\n * without actions pass through, with or without a wait.\n */\n validate(): string[] {\n const problems: string[] = [];\n if (!this.touches.length) {\n problems.push(\n `journey '${this.name}' has no touches — an empty timeline has nothing to execute.`\n );\n }\n for (const touch of this.allTouches()) {\n const branch = touch._branch;\n if (!branch) continue;\n // Otherwise is the route with NEITHER predicate. A filter-only route\n // is conditional, so counting it as a fallback here would report a\n // perfectly good branch as having two.\n const fallbacks = branch.routes.filter(\n (route) => !route.options.when?.trim() && route.options.filterId === undefined\n );\n // An Otherwise is OPTIONAL — a branch with only conditional routes\n // holds until one matches, and that is the default shape, so flagging\n // it would stop an author shipping the very thing the server prefers.\n // A CONDITIONAL route is still required: with nothing that can fail to\n // match, the first route takes every member and no decision is made.\n if (branch.routes.length - fallbacks.length < 1) {\n problems.push(\n `branch after touch '${touch.name}' needs at least one conditional ` +\n 'route — one declared with a `when`, a `filterId`, or both. ' +\n 'Members wait at the branch until a route matches, so an ' +\n 'Otherwise is optional.'\n );\n }\n if (fallbacks.length > 1) {\n problems.push(\n `branch after touch '${touch.name}' declares ${fallbacks.length} ` +\n 'Otherwise routes; a branch has at most one unconditional fallback.'\n );\n }\n if (fallbacks.length === 1 && branch.routes[branch.routes.length - 1] !== fallbacks[0]) {\n problems.push(\n `the Otherwise route of the branch after touch '${touch.name}' is ` +\n 'not last; it is taken immediately, so any route after it can ' +\n 'never be reached.'\n );\n }\n // A route with no touches and no `continueAt` is valid: nothing\n // follows it, so taking it ends the Journey.\n }\n for (const ending of this.endings) {\n if (!ending.when?.trim() && ending.filterId === undefined) {\n problems.push(\n `ending '${ending.name}' has no condition — an Ending that always ` +\n 'matches terminates every enrolment on evaluation order alone. ' +\n 'Give it a `when` expression, a `filterId`, or both.'\n );\n }\n }\n return problems;\n }\n\n /**\n * Shapes this definition cannot express, found BEFORE anything is written.\n *\n * A different list from {@link validate}, and a different consequence:\n * those are warnings the orchestrator prints and then writes anyway, these\n * are refusals. For each one the payload has no way to say what the script\n * asked for, so serializing past it would write a DIFFERENT program from\n * the one the script wrote, with nothing afterwards to say so.\n *\n * It has to run before the first write rather than during serialization,\n * because {@link apply} creates the Journey — or pauses a live one — before\n * it builds the payload. A refusal raised from `definitionPayload()` has\n * therefore already left an empty journey shell behind, or taken a\n * production program off the air.\n *\n * PURE: reads only what the script declared, never what the server holds,\n * so it is correct at any point — before adoption included — and\n * `WorkspaceBuilder.preflight()` can stay a synchronous, side-effect-free\n * check a caller may run directly. Nothing here needs adoption to have run:\n * an anchor the server has not seen is addressed by its request-local key,\n * so \"has this Ending been saved\" is no longer a question a refusal\n * depends on.\n */\n preflight(): string[] {\n const problems: string[] = [];\n this.allTouches().forEach((touch, index) => {\n const wait = touch.options.wait;\n if (wait?.afterDays !== undefined && wait.when) {\n problems.push(waitExclusivityProblem(index));\n }\n });\n const owned = this.ownedAnchors();\n this.goals.forEach((goal, index) => {\n const step = goal.step;\n if (step && !owned.has(step)) {\n problems.push(foreignAnchorProblem(index, anchorKind(step)));\n }\n });\n\n // Touches and Endings are ONE step-name namespace, and a repeat in it is\n // a defect whatever the save state. Unsaved, both address themselves\n // `key:<name>` and the definition resolves `stepKey` through a single\n // field, so two rows answer to one address — which the server refuses on\n // the definition PUT, i.e. after `apply()` has created the Journey or\n // paused a live one. Saved, they are two stored steps of one name, which\n // is what {@link indexStoredByName} refuses on the NEXT run.\n //\n // Names arrive canonical (`TouchBuilder` trims in its constructor, and\n // `EndingBuilder` inherits it), so `\"Welcome\"` and `\" Welcome \"` are\n // already one name here rather than two this gate would wave through.\n //\n // `assertUnambiguousNames()` checks each kind separately and runs from\n // `adopt()`, which a brand-new Journey never reaches — so it cannot be\n // this gate. It still owns routes and goals, whose namespaces are their\n // own.\n const stepNames = [\n ...this.allTouches().map((touch) => touch.name),\n ...this.endings.map((ending) => ending.name),\n ];\n const claims = new Map<string, number>();\n for (const name of stepNames) claims.set(name, (claims.get(name) ?? 0) + 1);\n const repeated = [...claims.values()].filter((count) => count > 1).length;\n if (repeated) problems.push(sharedStepNameProblem(repeated));\n\n // A name that is only whitespace canonicalizes to nothing, which the API\n // refuses (\"name cannot be empty\") — but on the definition PUT, after\n // `apply()` has created the Journey or paused a live one. It also has no\n // usable address: every empty name would claim `key:`. Refusing it here\n // is the same answer, before the first write.\n const nameless = stepNames.filter((name) => !name).length;\n if (nameless) problems.push(namelessStepProblem(nameless));\n return problems;\n }\n\n /**\n * Every step a goal in THIS journey can anchor to, compared by object\n * identity — touches AND Endings, which is why the element type names both\n * rather than leaning on `EndingBuilder extends TouchBuilder` to smuggle\n * Endings in under a touch-only annotation.\n *\n * A goal anchored to some other journey's builder is not a near miss the\n * server can catch: an unsaved one sends a `stepKey` this definition never\n * declares (a 404 whose cause is invisible), and a SAVED one sends a real\n * `stepUuid` belonging to a live step somewhere else.\n */\n private ownedAnchors(): ReadonlySet<TouchBuilder | EndingBuilder> {\n return new Set<TouchBuilder | EndingBuilder>([...this.allTouches(), ...this.endings]);\n }\n\n planLine(): string {\n const parts: string[] = [];\n const touchCount = this.allTouches().length;\n const routeCount = this.allRoutes().length;\n if (touchCount) parts.push(`${touchCount} touches`);\n if (routeCount) parts.push(`${routeCount} routes`);\n if (this.endings.length) parts.push(`${this.endings.length} endings`);\n if (this.goals.length) parts.push(`${this.goals.length} goals`);\n return `Journey: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n /**\n * Re-attach every stable child identity the server already holds.\n *\n * The atomic endpoint is a FULL REPLACEMENT keyed on uuids: an omitted\n * uuid does not mean \"unchanged\", it means \"create a new one and archive\n * whatever the old one was\". So anything this misses is silently recreated\n * on every re-run of the same script — and a script is normally re-run,\n * because a program is built in stages. Each identity has a different thing\n * hanging off it, and losing it costs something specific:\n *\n * | identity | what re-creating it destroys |\n * |---|---|\n * | touch step uuid | the touch's `MemberJourneyStep` history |\n * | EventRule uuid | that action's delivery bookkeeping |\n * | Ending RULE uuid | which Ending completed enrollments latched |\n * | Ending anchor uuid | the Ending's status history and goal anchor |\n * | goal uuid | every member's satisfaction row for that goal |\n *\n * `existing` is the journey DETAIL or AUTHORING projection. Both carry\n * `steps[].eventRules`, `goals`, and `decisionRules` —\n * the read projection redacts CEL, not identity — so one fetch is enough\n * and no second round trip is needed. (The orchestrator asks for the\n * authoring projection anyway: this builder holds `journeys:write` because\n * it is about to PUT, and the superset costs nothing.)\n *\n * Names are the only key available on a FIRST adoption, and a duplicate\n * name makes adoption a coin flip between two live resources. That throws\n * rather than guessing: silently attaching a touch to the wrong step\n * archives real member history.\n */\n adopt(existing: AnyRecord): void {\n // First, before any builder state changes: the definition write this\n // builder makes is refused for any other execution model, and `apply()`\n // may PAUSE a live Journey before that write. A missing value means\n // legacy (see `Journey.executionModel`), so it is refused too.\n if (existing.executionModel !== 'v2') {\n throw new UnadoptableJourneyError(this.name, existing.id);\n }\n super.adopt(existing);\n this._expectedUpdatedAt = existing.updatedAt as string | undefined;\n this._status = existing.status as string | undefined;\n this._executionModel = existing.executionModel;\n this.assertUnambiguousNames();\n this.adoptChildIdentities(existing);\n }\n\n /** Reject a script whose own names cannot identify a resource. */\n private assertUnambiguousNames(): void {\n assertUniqueNames(\n this.allTouches().map((touch) => touch.name),\n `journey '${this.name}'`,\n 'touch'\n );\n // Route names are the adoption key for a route's DECISION RULE, exactly\n // as an Ending's name is, so they must be unique across the whole\n // journey rather than only within their own branch — two branches each\n // with a route called \"Escalate\" would make adoption a coin flip\n // between two live rules.\n assertUniqueNames(\n this.allRoutes().map((route) => route.name),\n `journey '${this.name}'`,\n 'route'\n );\n assertUniqueNames(\n this.endings.map((ending) => ending.name),\n `journey '${this.name}'`,\n 'ending'\n );\n assertUniqueNames(\n this.goals.map((goal) => goal.name),\n `journey '${this.name}'`,\n 'goal'\n );\n for (const touch of [...this.allTouches(), ...this.endings]) {\n const names = touch.rules.map((rule) => rule.options.name).filter(Boolean) as string[];\n assertUniqueNames(names, `touch '${touch.name}'`, 'action name');\n }\n }\n\n private adoptChildIdentities(payload: AnyRecord): void {\n const steps = (payload.steps ?? []) as AnyRecord[];\n // The step names this script will actually look up. Everything below\n // matches STORED rows by name, and neither the table nor the publish\n // validator makes those names unique — so a plain `new Map(...)` would\n // quietly keep the last row of a duplicated name and adopt an arbitrary\n // one of two live identities, archiving the other's member history on\n // the next save. A duplicate the script never names is nobody's problem\n // and is left alone.\n const referencedStepNames = new Set([\n ...this.allTouches().map((touch) => touch.name),\n ...this.endings.map((ending) => ending.name),\n ]);\n const stepsByName = indexStoredByName(\n steps,\n referencedStepNames,\n `journey '${this.name}'`,\n 'step'\n );\n const stepsById = new Map(steps.map((step) => [step.id as number, step]));\n\n for (const touch of this.allTouches()) {\n const match = stepsByName.get(touch.name);\n if (!match) continue;\n touch._uuid = match.uuid as string;\n touch.adoptRuleUuids((match.eventRules ?? []) as AnyRecord[]);\n }\n\n // Branch ROUTES are the complement of the Ending filter below: same\n // table, same identity argument, different product. Indexed by name for\n // the same reason Endings are — a route's uuid is the only thing that\n // survives a re-run, and nothing else in the payload identifies it.\n const routeRules = ((payload.decisionRules ?? []) as AnyRecord[]).filter(\n (rule) => rule.sourceStepId !== null && rule.sourceStepId !== undefined\n );\n const declaredRoutes = this.allRoutes();\n const routesByName = indexStoredByName(\n routeRules,\n new Set(declaredRoutes.map((route) => route.name)),\n `journey '${this.name}'`,\n 'route'\n );\n for (const route of declaredRoutes) {\n const stored = routesByName.get(route.name);\n if (stored) route._ruleUuid = stored.uuid as string;\n }\n\n // An Ending's identity is its decision RULE; the anchor is reached\n // through the rule's target rather than by name, so an adopted Ending\n // never picks up a touch's step. (An Ending and a touch DECLARED under\n // one name are still two stored steps sharing a name, which the step\n // index above refuses — from the touch's side, where the ambiguity is\n // real.)\n const endingRules = ((payload.decisionRules ?? []) as AnyRecord[]).filter(\n (rule) => rule.sourceStepId === null || rule.sourceStepId === undefined\n );\n const rulesByName = indexStoredByName(\n endingRules,\n new Set(this.endings.map((ending) => ending.name)),\n `journey '${this.name}'`,\n 'ending'\n );\n for (const ending of this.endings) {\n const rule = rulesByName.get(ending.name);\n const anchor = rule\n ? stepsById.get(rule.targetStepId as number)\n : stepsByName.get(ending.name);\n if (rule) ending._ruleUuid = rule.uuid as string;\n if (!anchor) continue;\n ending._uuid = anchor.uuid as string;\n ending.adoptRuleUuids((anchor.eventRules ?? []) as AnyRecord[]);\n }\n\n const goalsByName = indexStoredByName(\n (payload.goals ?? []) as AnyRecord[],\n new Set(this.goals.map((goal) => goal.name)),\n `journey '${this.name}'`,\n 'goal'\n );\n for (const goal of this.goals) {\n const match = goalsByName.get(goal.name);\n if (match) goal._uuid = match.uuid as string;\n }\n }\n\n /** The atomic request body. Exposed so a test can assert it without HTTP. */\n definitionPayload(): JourneyV2DefinitionFormData {\n const owned = this.ownedAnchors();\n // Depth-first position, numbered exactly as `preflight()` numbers it, so\n // a refusal raised down in the serializer names the same touch the\n // pre-write gate would have named.\n const positions: ReadonlyMap<TouchBuilder, number> = new Map(\n this.allTouches().map((touch, index) => [touch, index])\n );\n return {\n expectedUpdatedAt: this._expectedUpdatedAt ?? '',\n touches: this.touches.map((touch) => serializeTouch(touch, positions)),\n endings: this.endings.map((ending): JourneyV2EndingInput => ({\n ...(ending._ruleUuid ? { uuid: ending._ruleUuid } : {}),\n // Anchor address, exactly as `serializeTouch` sends a touch's:\n // the saved anchor's uuid, or the request-local `key` a goal in\n // this same save names it by. Both come from `_address`, so the\n // Ending and the goal cannot be sent under two spellings.\n ...(ending._uuid ? { anchorUuid: ending._uuid } : { key: ending._address }),\n name: ending.name,\n // The two predicates are sent INDEPENDENTLY (rule-filters plan\n // §3.2). A filter-only Ending carries no `celCondition` at all\n // rather than an empty one the server would have to normalize.\n ...(ending.when ? { celCondition: ending.when } : {}),\n ...(ending.filterId !== undefined ? { filterId: ending.filterId } : {}),\n eventRules: ending.eventRuleInputs(),\n })),\n // ALWAYS sent, `[]` included. The field distinguishes omitted (leave\n // goals alone) from empty (delete them), and this builder owns the\n // goal list — so omitting an empty list would make goal REMOVAL the\n // one edit a script cannot express: delete the `.goal(...)` call, re-run,\n // and the goal stays live forever.\n goals: this.goals.map((goal, index): JourneyV2GoalInput => ({\n ...(goal._uuid ? { uuid: goal._uuid } : {}),\n name: goal.name,\n ...(goal.description ? { description: goal.description } : {}),\n ...serializeGoalAnchor(goal.step, index, owned),\n ...(goal.completionCel ? { completionCel: goal.completionCel } : {}),\n ...(goal.value !== undefined ? { value: goal.value } : {}),\n })),\n };\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n // `WorkspaceBuilder.apply()` gates this, but the class is exported and a\n // direct caller gets no gate at all — while the first statements below\n // are writes. Refuse here too, so an invalid plan never leaves an empty\n // shell behind or pauses a production Journey.\n const problems = this.preflight();\n if (problems.length) {\n throw new Error(\n `Journey has ${problems.length} problem(s) and was not applied:\\n` +\n problems.map((problem) => ` - ${problem}`).join('\\n')\n );\n }\n\n // The class is exported and `_existed` is a public field, so a caller can\n // reach here without `adopt()`. An existing Journey whose execution model\n // is not known to accept the definition write is refused before the\n // pause below — pausing and then having the write refused would leave a\n // live program off.\n if (this._existed && this._executionModel !== 'v2') {\n throw new UnadoptableJourneyError(this.name, this._id);\n }\n\n if (!this._existed) {\n const created = await client.createJourney({\n name: this.name,\n description: this.description,\n });\n this._id = created.id;\n this._uuid = created.uuid;\n this._created = true;\n this._expectedUpdatedAt = created.updatedAt;\n } else if (this._status === 'active' && this.activate) {\n // A live Journey's topology is immutable, so a re-run has to pause\n // before it can write, and re-read for a fresh concurrency token.\n //\n // Only when the script ASKED for an active Journey. Pausing one it\n // did not ask to activate would take a production program off the air\n // as a side effect of re-running a script; without `activate` the\n // server's stable `journey_v2_structural_edit_not_allowed` refusal is\n // the right answer, and it tells the operator exactly what to do.\n const paused = await client.updateJourney(this.id, { status: 'paused' });\n this._expectedUpdatedAt = paused.updatedAt;\n }\n\n const saved = await client.putJourneyDefinition(this.id, this.definitionPayload());\n this._expectedUpdatedAt = saved.updatedAt;\n this.adoptWrittenUuids(saved);\n\n if (this.activate) {\n await client.updateJourney(this.id, { status: 'active' });\n }\n }\n\n /**\n * Re-attach the uuids the server assigned, so a follow-up write matches.\n *\n * The PUT returns the AUTHORING projection, which is the same shape\n * `adopt` reads — so this is the same operation against a payload we just\n * caused, and it uses the same code path rather than a second, thinner\n * copy that would drift.\n */\n private adoptWrittenUuids(saved: AnyRecord): void {\n this.adoptChildIdentities(saved);\n }\n}\n\n/**\n * Index STORED rows by name, refusing a name the script matches that more than\n * one stored row answers to.\n *\n * The mirror image of {@link assertUniqueNames}: that one rejects a script\n * whose own names are ambiguous, this one rejects a SERVER state the script's\n * names cannot resolve. Both halves are needed, because nothing makes a\n * journey's step, Ending, goal, or action names unique — not the tables, not\n * the publish validator — so the ambiguity can arrive from the editor long\n * after a clean script was written.\n *\n * `referenced` is the set of names the script will look up. A stored duplicate\n * outside it is harmless: nothing in this script will ever choose between\n * those two rows, and refusing to run because of a resource the script does\n * not touch would be a gate the author cannot act on.\n */\nfunction indexStoredByName(\n rows: AnyRecord[],\n referenced: Set<string>,\n owner: string,\n kind: string\n): Map<string, AnyRecord> {\n const byName = new Map<string, AnyRecord>();\n const counts = new Map<string, number>();\n for (const row of rows) {\n const name = row.name;\n if (typeof name !== 'string' || !name) continue;\n counts.set(name, (counts.get(name) ?? 0) + 1);\n if (!byName.has(name)) byName.set(name, row);\n }\n for (const [name, count] of counts) {\n if (count < 2 || !referenced.has(name)) continue;\n throw new Error(\n `${owner} already has ${count} ${kind}s named '${name}'. This script adopts ` +\n `by name, so it cannot tell which ${kind} it owns — and the one it does ` +\n 'not pick is archived on the next save, taking its history with it. ' +\n `Rename them so each name identifies one ${kind}.`\n );\n }\n return byName;\n}\n\n/**\n * The refusal for an existing Journey the builder cannot write: its definition\n * write is a whole replacement, which only a current Journey accepts. Thrown\n * before any write, so nothing on the server has changed.\n */\nexport class UnadoptableJourneyError extends Error {\n readonly journeyId: unknown;\n readonly journeyName: string;\n\n constructor(name: string, id: unknown) {\n super(\n `Journey ${String(id)} ('${name}') is a Journey the builder cannot adopt: the ` +\n \"script replaces a Journey's whole definition on save, and this Journey was \" +\n 'built with the older Journey editor, which does not accept that write. ' +\n 'Nothing was changed. Rebuild it as a current Journey, or rename the ' +\n 'journey in the script so the builder creates a new one.'\n );\n this.name = 'UnadoptableJourneyError';\n this.journeyId = id;\n this.journeyName = name;\n }\n}\n\n/** Throw when a builder's own names cannot identify a resource. */\nfunction assertUniqueNames(names: string[], owner: string, kind: string): void {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n throw new Error(\n `${owner} has two ${kind}s named '${name}'. The builder adopts an ` +\n 'existing journey by name, so duplicates would attach a builder to ' +\n \"either one at random — archiving the other's history on the next \" +\n 'save. Rename one.'\n );\n }\n seen.add(name);\n }\n}\n\n/** Translate builder wait options into the server's structured wait. */\n/**\n * Serialize one touch and, recursively, the branch it owns.\n *\n * A free function rather than a method so the recursion reads as one shape:\n * touch -> branch -> routes -> arm touches -> … . `key` is sent whenever the\n * touch has no server uuid yet, because an arm can only name an unsaved\n * rejoin target through the request-local address .\n */\nfunction serializeTouch(\n touch: TouchBuilder,\n positions: ReadonlyMap<TouchBuilder, number>\n): JourneyV2TouchInput {\n return {\n ...(touch._uuid ? { uuid: touch._uuid } : { key: touch._address }),\n name: touch.name,\n ...(touch.options.description ? { description: touch.options.description } : {}),\n ...(touch.options.wait ? { wait: buildWait(touch.options.wait, positions.get(touch)) } : {}),\n eventRules: touch.eventRuleInputs(),\n ...(touch._branch\n ? {\n branch: {\n routes: touch._branch.routes.map((route) => ({\n ...(route._ruleUuid ? { uuid: route._ruleUuid } : {}),\n name: route.name,\n // Omitted, not null, and INDEPENDENT of each other: a route\n // with neither predicate IS the Otherwise marker, one with\n // either is conditional, and one with both is ANDed\n // (rule-filters plan §3.2). The server normalizes \"\" to the\n // same thing as omitted.\n ...(route.options.when ? { celCondition: route.options.when } : {}),\n ...(route.options.filterId !== undefined\n ? { filterId: route.options.filterId }\n : {}),\n touches: route.touches.map((armTouch) => serializeTouch(armTouch, positions)),\n ...(route.options.continueAt\n ? { continueAt: route.options.continueAt._address }\n : {}),\n })),\n },\n }\n : {}),\n };\n}\n\n/**\n * How a goal names its anchor step in the atomic payload.\n *\n * A saved anchor is named by `stepUuid`. An unsaved one — a touch or an\n * Ending's anchor alike — is named by `stepKey`, carrying the same\n * request-local address the step itself is sent under, because on the FIRST\n * save of a timeline nothing has a uuid yet and a client cannot mint one.\n * Sending nothing there is not a missing decoration: an anchored goal is\n * satisfied only when its step is reached AND its CEL holds, so the goal that\n * reached the server would be a different rule from the one the script wrote.\n *\n * `owned` is the set of steps this journey declares, compared by object\n * identity: a goal anchored to another builder's step would otherwise send a\n * `stepKey` this definition never declares, or a live `stepUuid` belonging to\n * a step in some other journey. That is the one thing this cannot express, and\n * it THROWS rather than serializing to nothing — dropping an anchor is silent,\n * the payload is valid, the write succeeds, and nothing afterwards says so.\n *\n * The refusal is the LAST line of defence. `WorkspaceBuilder.apply()` gates on\n * {@link JourneyBuilder.preflight} before it writes anything; this fires\n * only for a caller that reached `definitionPayload()` directly, and it raises\n * the identical sentence so the two paths cannot drift.\n */\nfunction serializeGoalAnchor(\n step: TouchBuilder | EndingBuilder | undefined,\n goalIndex: number,\n owned: ReadonlySet<TouchBuilder | EndingBuilder>\n): Pick<JourneyV2GoalInput, 'stepUuid' | 'stepKey'> {\n if (!step) return {};\n if (!owned.has(step)) throw new Error(foreignAnchorProblem(goalIndex, anchorKind(step)));\n if (step._uuid) return { stepUuid: step._uuid };\n return { stepKey: step._address };\n}\n\n/**\n * The two refusals, worded once.\n *\n * Both the pre-write gate and the serializer raise these, so an author who\n * trips the last line of defence reads the sentence the gate would have\n * printed. Each names the offender by POSITION and the anchor by KIND, never\n * by the name the script gave it: these strings reach operator terminals, CI\n * logs and exception trackers, and an authored touch, goal or Ending name is\n * workspace content that has no business in any of them.\n */\nfunction foreignAnchorProblem(goalIndex: number, kind: 'touch' | 'Ending'): string {\n return (\n `goal at index ${goalIndex} is anchored to ${kind === 'Ending' ? 'an' : 'a'} ` +\n `${kind} that belongs to a different journey builder. A goal anchor is ` +\n 'part of the same atomic definition as its step, so it can only name a ' +\n 'touch or Ending this journey declares.'\n );\n}\n\n/**\n * `touchIndex` is the touch's depth-first position, absent only for a direct\n * caller of {@link buildWait} that has no timeline to position it in.\n *\n * @see foreignAnchorProblem for why these carry positions and not names.\n */\nfunction waitExclusivityProblem(touchIndex: number | undefined): string {\n const where = touchIndex === undefined ? 'this touch' : `touch at index ${touchIndex}`;\n return (\n `${where} sets both afterDays and when; fold the day count into \\`when\\`. ` +\n 'A wait is either a whole-day count or Advanced CEL, not both.'\n );\n}\n\n/**\n * Step names claimed more than once, counted across touches AND Endings.\n *\n * @see foreignAnchorProblem for why this counts them and does not name them.\n */\nfunction sharedStepNameProblem(count: number): string {\n return (\n `${count} step name(s) are claimed more than once. Touches and Endings ` +\n 'are one namespace: until a save mints their uuids they address ' +\n 'themselves by name and the definition resolves those keys through one ' +\n 'field, and once saved they are stored steps the next run cannot tell ' +\n 'apart. Names are canonical (trimmed), as the API stores them. Rename one.'\n );\n}\n\n/**\n * Steps whose canonical name is empty.\n *\n * @see foreignAnchorProblem for why this counts them and does not name them.\n */\nfunction namelessStepProblem(count: number): string {\n return (\n `${count} step(s) have an empty name once trimmed. A step's name is its ` +\n 'request-local address until a save mints its uuid, so a nameless one ' +\n 'has nothing to be addressed by, and the API refuses it. Name them.'\n );\n}\n\n/** How a refusal names an anchor: by what it IS, never by what it is called. */\nfunction anchorKind(step: TouchBuilder | EndingBuilder): 'touch' | 'Ending' {\n return step instanceof EndingBuilder ? 'Ending' : 'touch';\n}\n\nexport function buildWait(wait: WaitOptions, touchIndex?: number): JourneyV2WaitInput {\n if (wait.afterDays !== undefined && wait.when) {\n throw new Error(waitExclusivityProblem(touchIndex));\n }\n const extras = {\n ...(wait.filterId !== undefined ? { filterId: wait.filterId } : {}),\n };\n if (wait.afterDays !== undefined) {\n return { kind: 'wholeDays', days: wait.afterDays, ...extras };\n }\n if (wait.when) {\n return { kind: 'advanced', cel: wait.when, ...extras };\n }\n return { kind: 'none', ...extras };\n}\n","import { EventRuleEventType, type EventRuleActionType, type WorkflowFormData } from '../types';\nimport type { Ability } from '../types/ability-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport type { FormBuilder } from './forms';\nimport { type AnyRecord, WorkspaceBuilderResource } from './resource';\n\nconst PERM_KEYS: Record<string, string> = {\n canRead: 'canRead',\n canCreate: 'canCreate',\n canEdit: 'canEdit',\n can_read: 'canRead',\n can_create: 'canCreate',\n can_edit: 'canEdit',\n};\n\nconst ABILITY_TYPE_MAP: Record<string, string> = {\n data_access: 'integration:data_access',\n file_access: 'integration:file_access',\n escalation: 'oversight:escalation',\n};\n\nclass AbilityDef {\n readonly uuid = crypto.randomUUID();\n readonly config: AnyRecord;\n readonly enabled: boolean;\n readonly celCondition?: string;\n readonly form?: FormBuilder;\n readonly perms: AnyRecord = {};\n\n constructor(\n readonly abilityType: string,\n options: AnyRecord = {}\n ) {\n this.config = options.config ?? {};\n this.enabled = options.enabled ?? true;\n this.celCondition = options.celCondition ?? options.cel_condition;\n this.form = options.form;\n for (const [inputKey, outputKey] of Object.entries(PERM_KEYS)) {\n if (inputKey in options) this.perms[outputKey] = options[inputKey];\n }\n }\n\n toAbility(): Ability {\n const config = { ...this.config };\n if (this.form?._uuid) {\n config.dataTypeUuid = this.form._uuid;\n Object.assign(config, this.perms);\n }\n return {\n uuid: this.uuid,\n abilityType: ABILITY_TYPE_MAP[this.abilityType] ?? this.abilityType,\n config,\n enabled: this.enabled,\n ...(this.celCondition ? { celCondition: this.celCondition } : {}),\n };\n }\n}\n\n/** Compatibility transport for transitionsTo; CEL is Path availability, flags select automatically. */\nexport interface TaskTransition {\n parent: TaskBuilder;\n child: TaskBuilder;\n when: string;\n autoNext: boolean;\n required: boolean;\n celCondition?: string;\n}\n\nexport interface WorkflowBuilderOptions {\n description?: string;\n prompt?: string;\n}\n\nexport class TaskBuilder extends WorkspaceBuilderResource {\n readonly transitions: TaskTransition[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n /** Child task ids the server already has, recorded when this task is adopted. */\n readonly existingChildIds = new Set<number>();\n\n /** Record the edges an adopted task already carries, so a re-run adds only what is missing. */\n adopt(existing: AnyRecord): void {\n super.adopt(existing);\n for (const child of (existing.childTasks ?? []) as AnyRecord[]) {\n const id = child.taskId ?? child.id;\n if (typeof id === 'number') this.existingChildIds.add(id);\n }\n }\n\n constructor(\n readonly name: string,\n readonly workflow: WorkflowBuilder,\n readonly prompt = '',\n readonly start = false,\n readonly description = ''\n ) {\n super();\n }\n\n transitionsTo(\n child: TaskBuilder,\n when: string,\n autoNext = false,\n required = false,\n celCondition?: string\n ): TaskBuilder {\n if (child === this) {\n throw new Error(`Task '${this.name}' cannot transition to itself`);\n }\n this.transitions.push({\n parent: this,\n child,\n when,\n autoNext,\n required,\n celCondition,\n });\n return this;\n }\n\n onEnter(action: string, params: AnyRecord = {}, name?: string): TaskBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.TASK_EXECUTE,\n actionType: action as EventRuleActionType,\n actionParams: params,\n name,\n });\n return this;\n }\n\n initialMessage(message: string, suggestions?: string[]): TaskBuilder {\n return this.onEnter('assistant:message', {\n message,\n ...(suggestions ? { suggestions } : {}),\n });\n }\n\n planLine(): string {\n return `Task: ${this.name}${this.start ? ' [start]' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed || this.workflow._id === undefined) return;\n if (this.workflow._draftRevisionId === undefined) {\n // Root id without a draft revision id means the workflow was\n // created/adopted through a path that skipped revision resolution —\n // creating the task would attach it to whatever revision happens to\n // share the number (cross-workflow corruption). Fail loudly.\n throw new Error(\n `Workflow '${this.workflow.name}' has no draft revision id; ` +\n 'cannot create tasks. Tasks attach to a WorkflowRevision, ' +\n 'not the stable workflow root.'\n );\n }\n // Tasks belong to a revision graph — target the DRAFT revision\n // explicitly (edits always land on the draft; publish makes them live).\n const result = await client.createTask({\n workflowRevisionId: this.workflow._draftRevisionId,\n name: this.name,\n prompt: this.prompt,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class WorkflowBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly prompt?: string;\n readonly tasks: TaskBuilder[] = [];\n readonly abilities: AbilityDef[] = [];\n /** The DRAFT revision's id — where tasks and graph edits attach.\n * `_id` is the STABLE workflow root id; the two are different entities\n * and (after any publish) different numbers. */\n _draftRevisionId?: number;\n\n constructor(\n readonly name: string,\n options: WorkflowBuilderOptions = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.prompt = options.prompt;\n }\n\n task(name: string, options: AnyRecord = {}): TaskBuilder {\n const task = new TaskBuilder(\n name,\n this,\n options.prompt ?? '',\n options.start ?? false,\n options.description ?? ''\n );\n this.tasks.push(task);\n return task;\n }\n\n ability(abilityType: string, options: AnyRecord = {}): WorkflowBuilder {\n this.abilities.push(new AbilityDef(abilityType, options));\n return this;\n }\n\n get startTask(): TaskBuilder | undefined {\n return this.tasks.find((task) => task.start) ?? this.tasks[0];\n }\n\n matchKey(): string {\n return this.name;\n }\n\n adopt(existing: AnyRecord): void {\n // Accepts the WorkflowDetail composition ({ workflow, draftRevision,\n // activeRevision }) — the orchestrator fetches it per matched name.\n // Root facts (id/uuid) live on `workflow`; graph facts (startTaskId)\n // live on the draft revision.\n const root = (existing.workflow ?? existing) as AnyRecord;\n super.adopt(root);\n const draft = existing.draftRevision as AnyRecord | undefined;\n this._draftRevisionId = (draft?.id ?? root.draftRevisionId) as number | undefined;\n const start = this.startTask;\n const startTaskId = draft?.startTaskId as number | undefined;\n if (start && startTaskId) {\n start._id = startTaskId;\n start._existed = true;\n }\n }\n\n planLine(): string {\n const details: string[] = [];\n if (this.tasks.length) details.push(`${this.tasks.length} tasks`);\n if (this.abilities.length) details.push(`${this.abilities.length} abilities`);\n return `Workflow: ${this.name}${details.length ? ` (${details.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: WorkflowFormData = {\n name: this.name,\n description: this.description,\n createMode: 'taskless',\n ...(this.prompt ? { prompt: this.prompt } : {}),\n ...(this.abilities.length\n ? { abilities: this.abilities.map((ability) => ability.toAbility()) }\n : {}),\n };\n const result = await client.createWorkflow(payload);\n this._id = result.workflow.id;\n this._uuid = result.workflow.uuid;\n // Tasks attach to the draft revision, never the root — keep its id.\n this._draftRevisionId = result.draftRevision.id;\n this._created = true;\n }\n}\n","import {\n EventRuleObjectType,\n type EventRule,\n type EventRuleFormData,\n type UpdateEventRuleFormData,\n} from '../types';\nimport { ApiError } from '../api/base';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { MemberFilterBuilder, NotificationRuleBuilder, RoutineBuilder } from './automation';\nimport { FormBuilder, MemberLabelBuilder } from './forms';\nimport { JourneyBuilder } from './journeys';\nimport {\n type AnyRecord,\n type ResourceSummary,\n resolveRefs,\n WorkspaceBuilderResource,\n} from './resource';\nimport {\n TaskBuilder,\n type TaskTransition,\n WorkflowBuilder,\n type WorkflowBuilderOptions,\n} from './workflows';\n\nconst PHASES = new Map<Function, number>([\n [FormBuilder, 0],\n [MemberLabelBuilder, 0],\n [WorkflowBuilder, 2],\n [TaskBuilder, 3],\n [MemberFilterBuilder, 5],\n [RoutineBuilder, 6],\n [NotificationRuleBuilder, 6],\n // A Journey is written whole by its own apply(), so it has no child\n // resources to sequence after it.\n [JourneyBuilder, 7],\n]);\n\n/**\n * Page size for the adoption sweeps.\n *\n * Adoption has to see every resource of a type, not the first screenful — the\n * list routes default to 10 per page, so a workspace with a dozen routines\n * would leave the eleventh undiscovered and duplicated on every re-run. 100 is\n * the max these routes allow; `collectPages` walks the rest.\n */\nconst LIST_PAGE_SIZE = 100;\n\n/**\n * Read every page of a paginated list endpoint.\n *\n * `totalPages` is trusted for the bound but the walk also stops on an empty\n * page, so a backend that reports the count differently cannot spin here.\n */\nasync function collectPages<T>(\n fetchPage: (page: number) => Promise<{ items: T[]; totalPages?: number }>\n): Promise<T[]> {\n const first = await fetchPage(1);\n const all = [...first.items];\n const totalPages = first.totalPages ?? 1;\n for (let page = 2; page <= totalPages; page++) {\n const next = await fetchPage(page);\n if (!next.items.length) break;\n all.push(...next.items);\n }\n return all;\n}\n\nfunction notificationRuleKey(\n noticeType: string,\n memberId: number,\n workflowId: number | null\n): string {\n return JSON.stringify([noticeType, memberId, workflowId]);\n}\n\n/**\n * Resolve a resource's build phase, walking the prototype chain.\n *\n * Keyed on the exact constructor a subclass (e.g. the journey `Start` step)\n * misses every entry and silently sorts to the end — applying its edges after\n * everything else and hiding ordering bugs behind an accident.\n */\nfunction phaseFor(resource: WorkspaceBuilderResource): number {\n let ctor: Function | null = resource.constructor;\n while (ctor) {\n const phase = PHASES.get(ctor);\n if (phase !== undefined) return phase;\n ctor = Object.getPrototypeOf(ctor) as Function | null;\n }\n return 99;\n}\n\nexport class WorkspaceBuilder {\n readonly resources: WorkspaceBuilderResource[] = [];\n\n constructor(readonly client: GravityRailWorkspaceClient) {}\n\n form(name: string, options: AnyRecord & { slug?: string } = {}): FormBuilder {\n const form = new FormBuilder(name, options.slug, options);\n this.resources.push(form);\n return form;\n }\n\n workflow(name: string, options: WorkflowBuilderOptions = {}): WorkflowBuilder {\n const workflow = new WorkflowBuilder(name, options);\n this.resources.push(workflow);\n return workflow;\n }\n\n label(\n name: string,\n options: { slug?: string; color?: string; description?: string } = {}\n ): MemberLabelBuilder {\n const label = new MemberLabelBuilder(\n name,\n options.slug,\n options.color,\n options.description ?? ''\n );\n this.resources.push(label);\n return label;\n }\n\n /**\n * A Journey timeline: ordered touches, structured waits, exclusive branches\n * and ordered Endings, written through the atomic definition endpoint.\n *\n * The Journey is adopted by exact name when the workspace already holds one;\n * the write then replaces its definition whole.\n */\n journey(name: string, options: AnyRecord = {}): JourneyBuilder {\n const journey = new JourneyBuilder(name, options);\n this.resources.push(journey);\n return journey;\n }\n\n routine(name: string, cronSchedule = '', options: AnyRecord = {}): RoutineBuilder {\n const routine = new RoutineBuilder(name, cronSchedule, options);\n this.resources.push(routine);\n return routine;\n }\n\n memberFilter(name: string, options: AnyRecord = {}): MemberFilterBuilder {\n const filter = new MemberFilterBuilder(name, options);\n this.resources.push(filter);\n return filter;\n }\n\n notificationRule(name: string, options: AnyRecord = {}): NotificationRuleBuilder {\n const rule = new NotificationRuleBuilder(name, options);\n this.resources.push(rule);\n return rule;\n }\n\n plan(): void {\n const resources = this.sortedResources();\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Plan');\n writeLine('='.repeat(50));\n const declared = resources.filter((resource) => !resource.isImplicit);\n for (const resource of declared) {\n writeLine(` + ${resource.planLine()}`);\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n this.reportJourneyWarnings();\n writeLine(`\\n Total: ${declared.length} resources, ${wiring.length} connections`);\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n async preview(): Promise<void> {\n const resources = this.sortedResources();\n await this.resolveExisting(resources);\n\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Preview');\n writeLine('='.repeat(50));\n const declared = resources.filter((resource) => !resource.isImplicit);\n for (const resource of declared) {\n if (resource._existed) {\n writeLine(` = ${resource.planLine()} (exists, id=${resource._id})`);\n } else {\n writeLine(` + ${resource.planLine()}`);\n }\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n this.reportJourneyWarnings();\n const toCreate = declared.filter((resource) => !resource._existed);\n const existing = declared.filter((resource) => resource._existed);\n writeLine(\n `\\n Total: ${toCreate.length} to create, ${existing.length} existing, ${wiring.length} connections`\n );\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n /**\n * Print journey authoring problems that only bite at runtime — a touch with\n * no action does nothing at all. It looks fine in the editor, so it is\n * surfaced before the write rather than discovered from a member's phone.\n */\n private reportJourneyWarnings(): void {\n const problems = this.resources\n .filter((resource): resource is JourneyBuilder => resource instanceof JourneyBuilder)\n .flatMap((journey) => journey.validate());\n if (!problems.length) return;\n writeLine('\\n Journey warnings:');\n for (const problem of problems) writeLine(` ! ${problem}`);\n }\n\n /**\n * Problems that make the plan unwritable, found before the first write.\n *\n * The API validates each CEL when you save it, and its diagnosis is right —\n * but it fires per-write, so a plan whose edges reference a non-collection\n * form gets four labels, two forms, a workflow and six tasks created before\n * the seventh call rejects it. The operator is left with a half-built\n * program to hand-repair. Checking here costs nothing and writes nothing.\n *\n * Deliberately narrow: only cross-resource facts the builder can see with\n * certainty. Per-field CEL schema checking stays server-side, where the\n * real validator lives — duplicating it here would drift.\n *\n * Pure: reads only what the plan declares, never what the server holds, so\n * it is correct before adoption and safe for a caller to run directly. It\n * is also the WHOLE gate: every anchor a v2 definition can name has a\n * request-local address whether or not the server has seen it, so no\n * refusal has to wait for adoption to decide it.\n */\n preflight(): string[] {\n const problems: string[] = [];\n const forms = this.resources.filter(\n (resource): resource is FormBuilder => resource instanceof FormBuilder\n );\n const collectionBySlug = new Map(forms.map((form) => [form.slug, form.collection]));\n\n // `assignment.collections.<slug>` requires <slug> to be a COLLECTION\n // form. This is the exact defect that shipped: the edges were right, the\n // form was declared without `collection: true`, and nothing said so\n // until fourteen resources existed.\n const reference = /assignment\\.collections\\.([A-Za-z0-9_]+)/g;\n for (const resource of this.sortedResources()) {\n if (!(resource instanceof TaskBuilder)) continue;\n for (const transition of resource.transitions) {\n const cel = transition.celCondition;\n if (!cel) continue;\n for (const [, slug] of cel.matchAll(reference)) {\n if (!collectionBySlug.has(slug)) continue; // server resolves it\n if (!collectionBySlug.get(slug)) {\n problems.push(\n `task '${transition.parent.name}' → '${transition.child.name}': CEL reads ` +\n `assignment.collections.${slug}, but this plan creates '${slug}' as a ` +\n `non-collection form. Declare it with { collection: true }.`\n );\n }\n }\n }\n }\n\n // A Journey is written as ONE atomic PUT, and `JourneyBuilder.apply()`\n // has to create the Journey — or pause a live one — before it can build\n // that payload. So a definition the builder cannot express has to be\n // refused here or the refusal lands after those writes, leaving an empty\n // journey shell or a production program off the air.\n for (const resource of this.resources) {\n if (resource instanceof JourneyBuilder) problems.push(...resource.preflight());\n }\n return [...new Set(problems)];\n }\n\n /** The plan-rejection shape: every problem printed, nothing written. */\n private rejectIfProblems(problems: string[]): void {\n if (!problems.length) return;\n writeLine('\\nPlan rejected — nothing was created:');\n for (const problem of problems) writeLine(` ! ${problem}`);\n throw new Error(\n `Plan has ${problems.length} problem(s) and was not applied:\\n` +\n problems.map((problem) => ` - ${problem}`).join('\\n')\n );\n }\n\n async apply(): Promise<ResourceSummary> {\n const resources = this.sortedResources();\n\n // Refuse before writing anything, rather than failing part-way through.\n // One gate, and it is pure: nothing it decides depends on which\n // resources the server already holds, so adoption (reads only) can run\n // after it.\n this.rejectIfProblems(this.preflight());\n await this.resolveExisting(resources);\n\n const summary: ResourceSummary = {};\n\n writeLine('Applying...');\n for (const resource of resources) {\n try {\n // The server already made it (a journey's Start step) — it is here\n // only so edges can point at it.\n if (resource.isImplicit) continue;\n // Most builders are create-only: an adopted resource is left\n // exactly as the server has it, because their `apply()` knows only\n // how to CREATE and re-running it would duplicate. A resource that\n // declares `appliesWhenExisting` writes idempotently — its apply()\n // is a full, uuid-keyed replacement that handles the adopted case\n // itself — so skipping it here would make adoption pointless: the\n // second run of a script would read the journey, resolve every\n // identity, and then write nothing.\n if (resource._existed && !resource.appliesWhenExisting) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n writeLine(` Exists ${resource.planLine()} -> id=${resource._id}`);\n continue;\n }\n\n const updating = resource._existed;\n await resource.apply(this.client);\n if (resource._created || resource._id !== undefined) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n const startTag = resource instanceof TaskBuilder && resource.start ? ' [start]' : '';\n const verb = updating ? 'Updated' : 'Created';\n writeLine(` ${verb} ${resource.planLine()}${startTag} -> id=${resource._id}`);\n } else {\n writeLine(` Skipped: ${resource.planLine()}`);\n }\n } catch (err) {\n writeLine(formatApplyFailureLine(resource, err));\n throw new ApplyError(resource, err, summary);\n }\n }\n\n await this.applyTransitions();\n await this.applyEventRules(resources);\n\n const count = Object.values(summary).reduce((total, ids) => total + ids.length, 0);\n writeLine(`\\nDone! Created ${count} resources.`);\n return summary;\n }\n\n private async resolveExisting(resources: WorkspaceBuilderResource[]): Promise<void> {\n // Before the first server call: a journey name is the ONLY key adoption\n // has, and two builders declared under one name collapse into a single\n // entry of the name→builder map below — so one of them is silently never\n // adopted and never applied, while the other inherits whatever the\n // server holds under that name and replaces it whole.\n assertUniqueJourneyNames(\n resources.filter(\n (resource): resource is JourneyBuilder => resource instanceof JourneyBuilder\n )\n );\n\n const formSlugs = new Map(\n resources\n .filter((resource): resource is FormBuilder => resource instanceof FormBuilder)\n .map((resource) => [resource.slug, resource])\n );\n const labelNames = new Map(\n resources\n .filter(\n (resource): resource is MemberLabelBuilder => resource instanceof MemberLabelBuilder\n )\n .map((resource) => [resource.name, resource])\n );\n const workflowNames = new Map(\n resources\n .filter((resource): resource is WorkflowBuilder => resource instanceof WorkflowBuilder)\n .map((resource) => [resource.name, resource])\n );\n\n if (formSlugs.size) {\n for (const existing of await this.client.getDataTypes()) {\n if (existing.slug && formSlugs.has(existing.slug)) {\n formSlugs.get(existing.slug)!.adopt(existing);\n }\n }\n }\n if (labelNames.size) {\n for (const existing of await this.client.getMemberLabels()) {\n if (existing.name && labelNames.has(existing.name)) {\n labelNames.get(existing.name)!.adopt(existing);\n }\n }\n }\n\n const filterNames = new Map(\n resources\n .filter(\n (resource): resource is MemberFilterBuilder =>\n resource instanceof MemberFilterBuilder\n )\n .map((resource) => [resource.name, resource])\n );\n if (filterNames.size) {\n for (const existing of await this.client.getMemberFilters()) {\n if (existing.name && filterNames.has(existing.name)) {\n filterNames.get(existing.name)!.adopt(existing);\n }\n }\n }\n\n // Journeys adopt by name and pull the AUTHORING projection per journey,\n // because a journey's identity for re-run purposes is its touch, rule and\n // goal uuids, and the list rows carry none of them. The write is a full\n // atomic REPLACEMENT, so an absent rule uuid would silently recreate the\n // Ending. The builder already holds `journeys:write`; it is about to PUT.\n const journeyNames = new Map(\n resources\n .filter((resource): resource is JourneyBuilder => resource instanceof JourneyBuilder)\n .map((resource) => [resource.name, resource])\n );\n if (journeyNames.size) {\n // Every page, not just the first: the default page holds 25 rows, so\n // a match on page 2 would be silently duplicated — and worse, two\n // same-name journeys SPLIT across pages would dodge the ambiguity\n // refusal below and adopt the first one destructively. Max page size,\n // walk totalPages (review round 10).\n const pageSize = 500;\n const firstPage = await this.client.getJourneys(false, { page: 1, pageSize });\n const allJourneys = [...firstPage.items];\n for (let page = 2; page <= firstPage.totalPages; page++) {\n const nextPage = await this.client.getJourneys(false, { page, pageSize });\n allJourneys.push(...nextPage.items);\n }\n // Group first, adopt second. Adopting inside the scan would attach the\n // builder to the FIRST stored journey of that name and then attach it\n // again to the second — each adoption a full, destructive replacement\n // of a different live journey. Only an unambiguous 1:1 match is\n // adoptable; zero matches is the ordinary create path.\n const storedByName = new Map<string, (typeof allJourneys)[number][]>();\n for (const existing of allJourneys) {\n if (!existing.name || !journeyNames.has(existing.name)) continue;\n storedByName.set(existing.name, [...(storedByName.get(existing.name) ?? []), existing]);\n }\n for (const [name, matches] of storedByName) {\n if (matches.length > 1) {\n throw new Error(\n `This workspace has ${matches.length} journeys named '${name}', and ` +\n 'the script adopts an existing journey by name — so it cannot tell ' +\n 'which one it owns. Adopting the wrong one replaces that journey ' +\n 'whole on the next save. Rename the others in the app, or rename ' +\n 'the journey in the script.'\n );\n }\n const existing = matches[0]!;\n const builder = journeyNames.get(name)!;\n // `adopt()` refuses a Journey whose execution model does not\n // accept the whole-definition write. It throws here, during these\n // reads, so nothing has been created or paused yet.\n builder.adopt(await this.client.getJourneyAuthoring(existing.id));\n }\n }\n\n const routineNames = new Map(\n resources\n .filter((resource): resource is RoutineBuilder => resource instanceof RoutineBuilder)\n .map((resource) => [resource.name, resource])\n );\n if (routineNames.size) {\n for (const existing of await collectPages((page) =>\n this.client.getRoutines({ page, pageSize: LIST_PAGE_SIZE })\n )) {\n if (existing.name && routineNames.has(existing.name)) {\n routineNames.get(existing.name)!.adopt(existing);\n }\n }\n }\n\n await this.resolveExistingWorkflows(resources, workflowNames);\n // Last, because a notification rule's identity includes the workflow it\n // notifies about, and that id is only known once workflows are adopted.\n await this.resolveExistingNotificationRules(resources);\n }\n\n /**\n * Adopt notification rules the server already has.\n *\n * There is no name on the server row — `NotificationRule` is keyed by what\n * it does — so identity is the composite the API enforces uniqueness on in\n * practice: notice type, recipient, and subject workflow.\n */\n private async resolveExistingNotificationRules(\n resources: WorkspaceBuilderResource[]\n ): Promise<void> {\n const rules = resources.filter(\n (resource): resource is NotificationRuleBuilder =>\n resource instanceof NotificationRuleBuilder\n );\n if (!rules.length) return;\n\n const identified = rules.flatMap((rule) => {\n // memberId absent: apply() rejects it, so there is nothing to match.\n if (rule.memberId === undefined) return [];\n // A declared workflow with no id yet is a workflow this run will\n // create, so no server rule can be pointing at it. Matching on\n // \"workflow unset\" here would adopt an unrelated global rule.\n if (rule.workflow && rule.workflow._id === undefined) return [];\n return [\n [\n notificationRuleKey(rule.noticeType, rule.memberId, rule.workflow?._id ?? null),\n rule,\n ] as const,\n ];\n });\n if (!identified.length) return;\n\n const byKey = new Map(identified);\n for (const existing of await this.client.getNotificationRules()) {\n // A shared-destination rule names no Member; the builder declares\n // Member rules only, so it never adopts one.\n if (existing.memberId == null) continue;\n const key = notificationRuleKey(\n existing.noticeType,\n existing.memberId,\n existing.workflowId ?? null\n );\n byKey.get(key)?.adopt(existing);\n }\n }\n\n private async resolveExistingWorkflows(\n resources: WorkspaceBuilderResource[],\n workflowNames: Map<string, WorkflowBuilder>\n ): Promise<void> {\n if (!workflowNames.size) return;\n\n const existingWorkflows = await this.client.getWorkflows();\n for (const { workflow: existing } of existingWorkflows.items) {\n if (existing.name && workflowNames.has(existing.name)) {\n // List rows carry only the root + active-revision summary. Tasks\n // and startTaskId live on the DRAFT revision, so fetch the detail\n // composition for adoption (root ids and revision ids are\n // different entities — matching tasks by root id attaches them to\n // the wrong workflow once any workflow has been published).\n const detail = await this.client.getWorkflow(existing.id);\n workflowNames.get(existing.name)!.adopt(detail);\n }\n }\n\n const adoptedWorkflows = resources.filter(\n (resource): resource is WorkflowBuilder =>\n resource instanceof WorkflowBuilder && resource._existed && resource._id !== undefined\n );\n if (!adoptedWorkflows.length) return;\n\n const existingTasks = await this.client.getTasks();\n for (const workflow of adoptedWorkflows) {\n // Tasks belong to a revision graph — match against the adopted\n // workflow's DRAFT revision id (task.workflowRevisionId), falling\n // back to the legacy field for older payloads.\n const workflowTasks = existingTasks.filter(\n (task) =>\n ((task as { workflowRevisionId?: number }).workflowRevisionId ?? task.workflowId) ===\n workflow._draftRevisionId\n );\n const taskByName = new Map(workflowTasks.map((task) => [task.name, task]));\n for (const taskBuilder of workflow.tasks) {\n const match = taskByName.get(taskBuilder.name);\n if (match) taskBuilder.adopt(match);\n }\n\n const ids = new Map<number, TaskBuilder[]>();\n for (const taskBuilder of workflow.tasks) {\n if (taskBuilder._id !== undefined) {\n ids.set(taskBuilder._id, [...(ids.get(taskBuilder._id) ?? []), taskBuilder]);\n }\n }\n for (const builders of ids.values()) {\n if (builders.length <= 1) continue;\n const nameAdopted = builders.filter((task) => taskByName.has(task.name));\n for (const task of builders.filter((builder) => !nameAdopted.includes(builder))) {\n task._id = undefined;\n task._existed = false;\n }\n }\n }\n }\n\n private sortedResources(): WorkspaceBuilderResource[] {\n const all: WorkspaceBuilderResource[] = [];\n for (const resource of this.resources) {\n all.push(resource);\n if (resource instanceof WorkflowBuilder) {\n const start = resource.startTask;\n const tasks =\n start === undefined\n ? resource.tasks\n : [start, ...resource.tasks.filter((task) => task !== start)];\n all.push(...tasks);\n }\n }\n return all.sort((a, b) => phaseFor(a) - phaseFor(b));\n }\n\n private collectWiringSummary(resources: WorkspaceBuilderResource[]): string[] {\n const lines: string[] = [];\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const transition of resource.transitions) {\n lines.push(`${transition.parent.name} -> ${transition.child.name}`);\n }\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on enter '${resource.name}'`);\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on ${rule.eventType} '${resource.name}'`);\n }\n } else if (resource instanceof RoutineBuilder) {\n for (const rule of resource.rules)\n lines.push(`${rule.actionType} rule on '${resource.name}'`);\n } else if (resource instanceof JourneyBuilder) {\n // A timeline has no edges to name — position IS the order — so\n // the preview shows the sequence itself, then the Endings in the\n // precedence they will be evaluated in.\n resource.touches.forEach((touch, index) => {\n lines.push(`${index + 1}. ${touch.name}`);\n });\n for (const ending of resource.endings) lines.push(`Ending: ${ending.name}`);\n for (const goal of resource.goals) lines.push(`Goal: ${goal.name}`);\n }\n }\n return lines;\n }\n\n private async applyTransitions(): Promise<void> {\n const parentChildren = new Map<TaskBuilder, TaskTransition[]>();\n for (const resource of this.sortedResources()) {\n if (!(resource instanceof TaskBuilder)) continue;\n for (const transition of resource.transitions) {\n parentChildren.set(transition.parent, [\n ...(parentChildren.get(transition.parent) ?? []),\n transition,\n ]);\n }\n }\n\n for (const [parent, transitions] of parentChildren) {\n if (parent._id === undefined) continue;\n const childTasks = transitions.flatMap((transition) => {\n const taskId = transition.child._id;\n if (taskId === undefined || taskId === parent._id) return [];\n // Already wired on a previous run — re-sending it makes the API\n // reject the whole update as a conflict, which reads as \"the\n // template half-worked\" and sends the operator hand-repairing.\n if (parent.existingChildIds.has(taskId)) return [];\n return [\n {\n taskId,\n choicePrompt: transition.when,\n celCondition: transition.celCondition ?? null,\n autoNext: transition.autoNext,\n required: transition.required,\n },\n ];\n });\n if (!childTasks.length) continue;\n await this.client.updateTask(parent._id, { childTasks });\n writeLine(\n ` Wired: ${parent.name} -> [${transitions.map((tr) => tr.child.name).join(', ')}]`\n );\n }\n }\n\n private async applyEventRules(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.TASK,\n taskId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on enter '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.DATA_RECORD,\n dataTypeId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.condition ? { conditions: rule.condition } : {}),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on ${rule.eventType} '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n }\n }\n }\n\n private async applyEventRule(payload: EventRuleFormData, label: string): Promise<void> {\n const existing = await this.findMatchingEventRule(payload);\n if (!existing) {\n await this.client.createEventRule(payload);\n writeLine(` Wired: ${label}`);\n return;\n }\n\n const update = eventRuleUpdate(existing, payload);\n if (Object.keys(update).length) {\n await this.client.updateEventRule(existing.id, update);\n writeLine(` Updated: ${label}`);\n } else {\n writeLine(` Exists: ${label}`);\n }\n }\n\n private async findMatchingEventRule(payload: EventRuleFormData): Promise<EventRule | undefined> {\n const sourceFilter = eventRuleSourceFilter(payload);\n const candidates = await this.client.searchEventRules({\n objectType: payload.objectType,\n eventType: payload.eventType,\n actionType: payload.actionType,\n includeDisabled: true,\n ...sourceFilter,\n });\n return candidates.find((candidate) => eventRulesMatch(candidate, payload));\n }\n}\n\nexport class ApplyError extends Error {\n readonly createdSoFar: ResourceSummary;\n readonly #resource: WorkspaceBuilderResource;\n readonly #cause: unknown;\n\n constructor(resource: WorkspaceBuilderResource, cause: unknown, createdSoFar: ResourceSummary) {\n super(formatApplyErrorMessage(resource, cause, createdSoFar));\n this.name = 'ApplyError';\n this.createdSoFar = createdSoFar;\n this.#resource = resource;\n this.#cause = cause;\n }\n\n get resource(): WorkspaceBuilderResource {\n return this.#resource;\n }\n\n get cause(): unknown {\n return this.#cause;\n }\n}\n\n/**\n * Refuse a script that declares two journeys under one name.\n *\n * A journey has no slug and no author-supplied key, so its NAME is the whole\n * of its identity for adoption. Two builders sharing one collapse into a\n * single map entry, which is silent: the plan prints both, one of them is\n * simply never adopted or applied, and the other inherits whatever the server\n * had under that name.\n */\nfunction assertUniqueJourneyNames(journeys: JourneyBuilder[]): void {\n const seen = new Set<string>();\n for (const journey of journeys) {\n if (seen.has(journey.name)) {\n throw new Error(\n `This script declares two journeys named '${journey.name}'. A journey is ` +\n 'adopted and re-applied by name, so only one of them could ever be ' +\n 'written — and an apply replaces the journey it adopted whole. ' +\n 'Rename one.'\n );\n }\n seen.add(journey.name);\n }\n}\n\nfunction resourceKey(resource: WorkspaceBuilderResource): string {\n if (resource instanceof FormBuilder) return 'forms';\n if (resource instanceof MemberLabelBuilder) return 'labels';\n if (resource instanceof WorkflowBuilder) return 'workflows';\n if (resource instanceof TaskBuilder) return 'tasks';\n if (resource instanceof MemberFilterBuilder) return 'memberFilters';\n if (resource instanceof RoutineBuilder) return 'routines';\n if (resource instanceof NotificationRuleBuilder) return 'notificationRules';\n if (resource instanceof JourneyBuilder) return 'journeys';\n return 'resources';\n}\n\nconst SEARCHABLE_EVENT_RULE_SOURCE_FIELDS = [\n 'taskId',\n 'dataTypeId',\n 'routineId',\n 'workflowRevisionId',\n 'journeyStepId',\n] as const;\n\nconst EVENT_RULE_SOURCE_FIELDS = [\n ...SEARCHABLE_EVENT_RULE_SOURCE_FIELDS,\n 'calendarId',\n 'calendarEventTypeId',\n] as const;\n\ntype SearchableEventRuleSourceField = (typeof SEARCHABLE_EVENT_RULE_SOURCE_FIELDS)[number];\n\nfunction eventRuleSourceFilter(\n payload: EventRuleFormData\n): Partial<Record<SearchableEventRuleSourceField, number>> {\n const filter: Partial<Record<SearchableEventRuleSourceField, number>> = {};\n for (const field of SEARCHABLE_EVENT_RULE_SOURCE_FIELDS) {\n const value = payload[field];\n if (value !== undefined && value !== null) {\n filter[field] = value;\n }\n }\n return filter;\n}\n\nfunction eventRulesMatch(existing: EventRule, payload: EventRuleFormData): boolean {\n if (normalizeString(existing.name) !== normalizeString(payload.name)) return false;\n if (existing.objectType !== payload.objectType) return false;\n if (existing.eventType !== payload.eventType) return false;\n if (existing.actionType !== payload.actionType) return false;\n\n for (const field of EVENT_RULE_SOURCE_FIELDS) {\n if ((existing[field] ?? null) !== (payload[field] ?? null)) return false;\n }\n\n if (normalizeString(payload.name)) return true;\n if (normalizeString(existing.conditions) !== normalizeString(payload.conditions)) return false;\n if (!eventRuleValueEqual(existing.actionParams, payload.actionParams ?? null)) return false;\n if (!eventRuleValueEqual(existing.triggerParams, payload.triggerParams ?? null)) return false;\n return true;\n}\n\nfunction eventRuleUpdate(existing: EventRule, payload: EventRuleFormData): UpdateEventRuleFormData {\n const update: UpdateEventRuleFormData = {};\n const conditions = payload.conditions ?? null;\n if (normalizeString(existing.conditions) !== normalizeString(conditions)) {\n update.conditions = conditions;\n }\n const actionParams = payload.actionParams ?? null;\n if (!eventRuleValueEqual(existing.actionParams, actionParams)) {\n update.actionParams = payload.actionParams;\n }\n const triggerParams = payload.triggerParams ?? null;\n if (!eventRuleValueEqual(existing.triggerParams, triggerParams)) {\n update.triggerParams = payload.triggerParams;\n }\n const active = payload.active ?? true;\n if (existing.active !== active) {\n update.active = active;\n }\n const delay = payload.delay ?? 0;\n if (existing.delay !== delay) {\n update.delay = delay;\n }\n const order = payload.order ?? 0;\n if (existing.order !== order) {\n update.order = order;\n }\n return update;\n}\n\nfunction normalizeString(value: string | null | undefined): string {\n return value ?? '';\n}\n\nfunction eventRuleValueEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(stableValue(left)) === JSON.stringify(stableValue(right));\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (!value || typeof value !== 'object') return value;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, nested]) => [key, stableValue(nested)])\n );\n}\n\nfunction writeLine(message = ''): void {\n process.stdout.write(`${message}\\n`);\n}\n\nfunction handleEventRuleApplyFailure(resourceName: string, err: unknown): void {\n if (hasStatus(err, 403)) {\n writeLine(\n ` WARNING: Event rule on '${resourceName}' failed (retry exec() with scopes=['automations:admin'])`\n );\n return;\n }\n const summary = summarizeError(err);\n writeLine(` FAILED: Event rule on '${resourceName}': ${summary}`);\n throw new Error(`Failed wiring event rule on '${resourceName}': ${summary}`);\n}\n\nfunction writeScopeForResource(resource: WorkspaceBuilderResource): string | null {\n if (resource instanceof FormBuilder) return 'datatypes:write';\n if (resource instanceof WorkflowBuilder || resource instanceof TaskBuilder) {\n return 'workflows:write';\n }\n if (resource instanceof MemberLabelBuilder || resource instanceof MemberFilterBuilder) {\n return 'members:write';\n }\n if (resource instanceof RoutineBuilder || resource instanceof NotificationRuleBuilder) {\n return 'automations:admin';\n }\n if (resource instanceof JourneyBuilder) return 'journeys:write';\n return null;\n}\n\nfunction scopeRetryHint(resource: WorkspaceBuilderResource): string {\n const scope = writeScopeForResource(resource);\n return scope ? ` (retry exec with scopes=['${scope}'])` : '';\n}\n\nfunction formatApplyFailureLine(resource: WorkspaceBuilderResource, err: unknown): string {\n const line = ` FAILED: ${resource.planLine()}: ${summarizeError(err)}`;\n return hasStatus(err, 403) ? `${line}${scopeRetryHint(resource)}` : line;\n}\n\nfunction formatApplyErrorMessage(\n resource: WorkspaceBuilderResource,\n cause: unknown,\n createdSoFar: ResourceSummary\n): string {\n let message = `Failed creating ${resource.planLine()}: ${summarizeError(cause)}`;\n if (hasStatus(cause, 403)) {\n const scope = writeScopeForResource(resource);\n if (scope) {\n message += `\\nRetry exec with scopes=['${scope}']`;\n }\n }\n const createdKeys = Object.keys(createdSoFar);\n if (createdKeys.length > 0) {\n message += `\\nAlready created: ${JSON.stringify(createdSoFar)}`;\n }\n return message;\n}\n\nfunction summarizeError(err: unknown): string {\n if (hasStatus(err, 403)) {\n return 'Insufficient permissions for this operation';\n }\n if (err instanceof ApiError) {\n const msg = err.message.trim();\n const availableTypesIdx = msg.indexOf('Available types:');\n if (availableTypesIdx !== -1) {\n const head = msg.slice(0, availableTypesIdx).trim().replace(/\\.$/, '');\n return head ? `${head}.` : 'Request failed';\n }\n return msg.length > 240 ? `${msg.slice(0, 237)}...` : msg;\n }\n if (err instanceof Error) {\n // Name only, deliberately. A non-ApiError can still carry a message the\n // backend supplied, and this string is surfaced to the operator — see the\n // \"backend returned sensitive detail\" tests. Do not widen this.\n return err.name || 'Error';\n }\n return typeof err;\n}\n\nfunction hasStatus(err: unknown, status: number): boolean {\n if (typeof err === 'object' && err !== null) {\n const candidate = err as { status?: unknown; statusCode?: unknown };\n if (candidate.status === status || candidate.statusCode === status) return true;\n }\n const message = err instanceof Error ? err.message : typeof err === 'string' ? err : '';\n return message.includes(String(status));\n}\n\nexport async function runWorkspaceScript(\n client: GravityRailWorkspaceClient,\n build: (workspace: WorkspaceBuilder) => void | Promise<void>,\n mode = 'plan'\n): Promise<ResourceSummary | void> {\n const workspace = new WorkspaceBuilder(client);\n await build(workspace);\n if (mode === 'plan') return workspace.plan();\n if (mode === 'preview') return workspace.preview();\n if (mode === 'apply') return workspace.apply();\n throw new Error(`Unknown mode '${mode}'. Use plan, preview, or apply.`);\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: event_type\n */\n\n\n/**\n * Scope-class capabilities that unlock event types in the feed.\n *\n * These are existing platform scope strings. A grant carries scope-class\n * capabilities and nothing finer, and they decide which event rows a viewer\n * may read. The workspace schemas' second tier (per-object authorization:\n * admin-only Forms, folder ACLs, object-level grants) is never copied into the grants\n * projection: it applies live, per object, when a ref is hydrated into a name\n * (:mod:`lib.activity.ref_readers`).\n */\nexport type ActivityCapability = typeof ActivityCapability[keyof typeof ActivityCapability];\n\n\nexport const ActivityCapability = {\n 'apps:read': 'apps:read',\n 'assignments:read': 'assignments:read',\n 'chats:read': 'chats:read',\n 'journeys:read': 'journeys:read',\n 'members:read': 'members:read',\n 'operator:read': 'operator:read',\n 'org:read': 'org:read',\n 'phones:read': 'phones:read',\n 'records:read': 'records:read',\n 'workflows:read': 'workflows:read',\n 'workspace:read': 'workspace:read',\n} as const;\n\n/**\n * Every occurrence kind the spine records. Closed; grows by review.\n */\nexport type ActivityEventType = typeof ActivityEventType[keyof typeof ActivityEventType];\n\n\nexport const ActivityEventType = {\n membercreated: 'member.created',\n memberremoved: 'member.removed',\n memberrole_changed: 'member.role_changed',\n memberlabels_changed: 'member.labels_changed',\n memberattributes_changed: 'member.attributes_changed',\n importstarted: 'import.started',\n importcompleted: 'import.completed',\n assignmentstarted: 'assignment.started',\n assignmentconcluded: 'assignment.concluded',\n assignmenttask_entered: 'assignment.task_entered',\n journeyenrolled: 'journey.enrolled',\n journeyunenrolled: 'journey.unenrolled',\n journeycompleted: 'journey.completed',\n journeystep_transitioned: 'journey.step_transitioned',\n journeyactivated: 'journey.activated',\n chatstarted: 'chat.started',\n chatawaiting_human: 'chat.awaiting_human',\n chathuman_replied: 'chat.human_replied',\n chatcall_ended: 'chat.call_ended',\n chatauto_replied: 'chat.auto_replied',\n chatsummary: 'chat.summary',\n messagesent: 'message.sent',\n messagesend_failed: 'message.send_failed',\n membermessage_received: 'member.message_received',\n escalationopened: 'escalation.opened',\n escalationresolved: 'escalation.resolved',\n callstarted: 'call.started',\n callcompleted: 'call.completed',\n callmissed: 'call.missed',\n callsummary: 'call.summary',\n callqueued: 'call.queued',\n callnot_placed: 'call.not_placed',\n presencewent_online: 'presence.went_online',\n presencewent_offline: 'presence.went_offline',\n operator_groupmember_added: 'operator_group.member_added',\n operator_groupmember_removed: 'operator_group.member_removed',\n operatorinteraction_declined: 'operator.interaction_declined',\n voicemailreceived: 'voicemail.received',\n voicemailtranscribed: 'voicemail.transcribed',\n voicemaillistened: 'voicemail.listened',\n routinestarted: 'routine.started',\n routinecompleted: 'routine.completed',\n routinefailed: 'routine.failed',\n workflowpublished: 'workflow.published',\n subscriptionstarted: 'subscription.started',\n subscriptionupdated: 'subscription.updated',\n subscriptioncanceled: 'subscription.canceled',\n member_subscriptionstarted: 'member_subscription.started',\n member_subscriptioncanceled: 'member_subscription.canceled',\n purchasecompleted: 'purchase.completed',\n phone_numberprovisioned: 'phone_number.provisioned',\n phone_numberarchived: 'phone_number.archived',\n domainlinked: 'domain.linked',\n domainverified: 'domain.verified',\n configupdated: 'config.updated',\n connectionauthorization_lost: 'connection.authorization_lost',\n connectionauthorization_restored: 'connection.authorization_restored',\n data_recordcreated: 'data_record.created',\n data_recordupdated: 'data_record.updated',\n notificationdelivered: 'notification.delivered',\n} as const;\n\n/**\n * The visibility class an event is *born* with.\n *\n * ``ACCOUNT_PRIVATE`` is structural privacy: such an event is only ever\n * visible to the account named in ``account_uuid``, regardless of any scope a\n * viewer holds, and it never enters a workspace or org rollup. This is how\n * manager and agent-job chat privacy survives aggregation.\n */\nexport type ActivityVisibility = typeof ActivityVisibility[keyof typeof ActivityVisibility];\n\n\nexport const ActivityVisibility = {\n workspace: 'workspace',\n org: 'org',\n account_private: 'account_private',\n} as const;\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: ref\n */\n\n\n/**\n * Who or what caused an occurrence.\n *\n * ``AGENT`` is an Agent, recorded as itself even when it acts through a\n * member-shaped session; every emitter derives it through\n * :mod:`lib.activity.attribution`, never by building an actor inline.\n *\n * ``SYSTEM`` means no principal was involved — a Temporal schedule, an\n * inbound carrier or Stripe event with no member attribution. It is never a\n * placeholder for \"did not bother to look\".\n *\n * ``UNATTRIBUTED`` means a principal may well have acted but the event does\n * not name which one. The event backfill writes it: it synthesizes rows from\n * canonical tables and, by operator ruling, derives no principal from them,\n * so claiming ``system`` there would assert that nobody acted. Rows\n * written before this kind existed keep the ``system`` they were written\n * with — the log is append-only.\n *\n * Additive by contract: a reader must treat a kind it does not know as\n * unnamed rather than fail (the feed serves it as ``null``).\n */\nexport type ActorKind = typeof ActorKind[keyof typeof ActorKind];\n\n\nexport const ActorKind = {\n account: 'account',\n agent: 'agent',\n connection: 'connection',\n member: 'member',\n org_account: 'org_account',\n system: 'system',\n unattributed: 'unattributed',\n} as const;\n\n/**\n * Closed vocabulary of entity kinds a spine ref may name.\n *\n * Adding a kind is a code change with review — the same gate the event-type\n * vocabulary gets. Kinds name *entities*, never fields or values.\n */\nexport type EntityKind = typeof EntityKind[keyof typeof EntityKind];\n\n\nexport const EntityKind = {\n account: 'account',\n org: 'org',\n org_account: 'org_account',\n workspace: 'workspace',\n agent: 'agent',\n connection: 'connection',\n member: 'member',\n assignment: 'assignment',\n journey: 'journey',\n journey_step: 'journey_step',\n routine: 'routine',\n task: 'task',\n workflow: 'workflow',\n workflow_revision: 'workflow_revision',\n call: 'call',\n chat: 'chat',\n escalation: 'escalation',\n inbox: 'inbox',\n phone_number: 'phone_number',\n recording: 'recording',\n voicemail: 'voicemail',\n domain: 'domain',\n import: 'import',\n invoice: 'invoice',\n member_label: 'member_label',\n member_subscription: 'member_subscription',\n operator_group: 'operator_group',\n purchase: 'purchase',\n subscription: 'subscription',\n data_type: 'data_type',\n workspace_config: 'workspace_config',\n data_record: 'data_record',\n} as const;\n\n/**\n * A typed reference to one entity, with the scope chain it was observed in.\n *\n * Stored in ``activity_events.refs`` (and in ``activity_open_items``'s\n * ``responsible``) as JSON. Never used for a join: the activities database\n * holds no foreign keys, and a ref whose entity was deleted renders as its\n * kind — the same behavior as a ref the viewer may not resolve.\n *\n * **Two names for one field, on purpose.** This class is a *storage* shape —\n * the JSON the recorder writes and the drain reads — and, since the serving\n * API returns typed detail payloads, it is also a *wire* shape. Storage wants\n * the snake_case names already committed to rows; the API contract requires\n * lowerCamelCase keys (root ``CLAUDE.md``). A serialization-only alias gives\n * both without a mapping layer: validation still reads ``workspace_uuid``, so\n * every stored row and every emitter is untouched, while ``by_alias=True`` —\n * which FastAPI uses to serialize a response, and which nothing on the write\n * path passes — emits ``workspaceUuid``.\n * :class:`lib.activity.details.ActivityDetailBase` carries the same config for\n * the same reason.\n */\nexport interface EntityRef {\n kind: EntityKind;\n uuid: string;\n workspaceUuid?: string | null;\n orgUuid?: string | null;\n accountUuid?: string | null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoJO,IAAM,gCAAgC;AAAA,EAC3C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,MAAM;AACR;AA4CO,IAAM,mCAAmC;AAAA,EAC9C,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS;AACX;;;ACxKO,IAAM,qBAAqB;AAAA,EAChC,KAAK;AAAA,EACL,UAAU;AAAA,EACV,MAAM;AACR;;;ACCO,IAAM,gCAAgC;AAAA,EAC3C,cAAc;AAAA,EACd,QAAQ;AACV;AA8UO,IAAM,4BAA4B;AAAA,EACvC,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,WAAW;AACb;;;AC7VO,IAAM,0BAA0B;AAAA,EACrC,OAAO;AAAA,EACP,SAAS;AAAA,EACT,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,WAAW;AACb;AA4BO,IAAM,0BAA0B;AAAA,EACr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