@gravity-rail/sdk 0.18.1 → 0.21.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.
Files changed (39) hide show
  1. package/dist/{chunk-PUIYXJSZ.js → chunk-24L4RD4Z.js} +479 -39
  2. package/dist/chunk-24L4RD4Z.js.map +1 -0
  3. package/dist/{chunk-2YLKG4TT.js → chunk-3HAV5XUJ.js} +1 -1
  4. package/dist/chunk-3HAV5XUJ.js.map +1 -0
  5. package/dist/{chunk-PJFEGUHM.js → chunk-7OLBLLV7.js} +6 -2
  6. package/dist/{chunk-PJFEGUHM.js.map → chunk-7OLBLLV7.js.map} +1 -1
  7. package/dist/{client-B-jmQ4UA.d.cts → client-B0eh2BEY.d.cts} +1315 -285
  8. package/dist/{client-CatNn6FD.d.ts → client-CFz-BGmY.d.ts} +1315 -285
  9. package/dist/helpers.cjs +141 -0
  10. package/dist/helpers.cjs.map +1 -1
  11. package/dist/helpers.d.cts +17 -3
  12. package/dist/helpers.d.ts +17 -3
  13. package/dist/helpers.js +127 -1
  14. package/dist/helpers.js.map +1 -1
  15. package/dist/index.cjs +578 -39
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +28 -5
  18. package/dist/index.d.ts +28 -5
  19. package/dist/index.js +123 -5
  20. package/dist/index.js.map +1 -1
  21. package/dist/internal.cjs +485 -39
  22. package/dist/internal.cjs.map +1 -1
  23. package/dist/internal.d.cts +630 -551
  24. package/dist/internal.d.ts +630 -551
  25. package/dist/internal.js +9 -5
  26. package/dist/internal.js.map +1 -1
  27. package/dist/{revision-state-Fw1jsQOa.d.ts → revision-state-KfOztBkY.d.ts} +53 -172
  28. package/dist/{revision-state-CuESPYpi.d.cts → revision-state-fJ9PM15N.d.cts} +53 -172
  29. package/dist/schemas.cjs +31 -5
  30. package/dist/schemas.cjs.map +1 -1
  31. package/dist/schemas.d.cts +37 -14
  32. package/dist/schemas.d.ts +37 -14
  33. package/dist/schemas.js +31 -6
  34. package/dist/schemas.js.map +1 -1
  35. package/dist/{tasks-GVbVa_Lj.d.cts → tasks-WH_VfzMv.d.cts} +351 -16
  36. package/dist/{tasks-GVbVa_Lj.d.ts → tasks-WH_VfzMv.d.ts} +351 -16
  37. package/package.json +6 -6
  38. package/dist/chunk-2YLKG4TT.js.map +0 -1
  39. package/dist/chunk-PUIYXJSZ.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/workspace-builder/resource.ts","../src/workspace-builder/automation.ts","../src/workspace-builder/forms.ts","../src/workspace-builder/journeys.ts","../src/workspace-builder/role-update.ts","../src/workspace-builder/workflows.ts","../src/workspace-builder/orchestrator.ts"],"sourcesContent":["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 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 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.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 JourneyGoalFormData,\n type JourneyStepConnectionFormData,\n type JourneyStepFormData,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { type AnyRecord, resolveRefs, WorkspaceBuilderResource } from './resource';\n\n/** Options for a DAG edge between two journey steps. */\nexport interface StepConnectionOptions {\n /**\n * CEL guard evaluated once the parent step is terminal. The child only\n * becomes eligible while this is true. Journey-edge CEL sees `member.*`\n * (including `member.labels`), `journey.enrolled_at`, `journey.status`,\n * and `parent_step.{status,completed_at,activated_at,eligible_at,name}`.\n */\n when?: string;\n /**\n * Space this step N days after the parent completed. Sugar for the CEL\n * `days_since(parent_step.completed_at) >= N`, AND-ed with `when`.\n *\n * This is how you build a follow-up cadence — NOT `abandonAfterDays`,\n * which gives up rather than waits.\n */\n afterDays?: number;\n /**\n * Give up on this edge after N days of the CEL staying false: the child\n * moves to TIMED_OUT instead of waiting forever. A deadline, not a delay.\n */\n abandonAfterDays?: number;\n /** Raw seconds form of `abandonAfterDays`. `abandonAfterDays` wins. */\n timeoutSeconds?: number;\n /** The child waits for THIS parent specifically, not just any parent. */\n required?: boolean;\n /** Edge evaluation order among a parent's outgoing edges. */\n order?: number;\n /** Restrict the edge to members matching a saved MemberFilter. */\n filterId?: number;\n}\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\nexport interface StepConnectionDraft {\n parent: JourneyStepBuilder;\n child: JourneyStepBuilder;\n condition?: string;\n required: boolean;\n timeoutSeconds?: number;\n order?: number;\n filterId?: number;\n}\n\nexport interface JourneyGoalDraft {\n name: string;\n description: string;\n step?: JourneyStepBuilder;\n completionCel?: string;\n value?: number;\n order: number;\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\nconst SECONDS_PER_DAY = 86_400;\n\nfunction edgeKey(parentId: unknown, childId: unknown): string {\n return `${parentId}:${childId}`;\n}\n\n/** `days_since(parent_step.completed_at) >= N`, AND-ed onto any explicit CEL. */\nfunction edgeCondition(options: StepConnectionOptions): string | undefined {\n const clauses: string[] = [];\n if (options.afterDays !== undefined) {\n clauses.push(`days_since(parent_step.completed_at) >= ${options.afterDays}`);\n }\n if (options.when) clauses.push(`(${options.when})`);\n if (!clauses.length) return undefined;\n return clauses.join(' && ');\n}\n\nexport class JourneyStepBuilder extends WorkspaceBuilderResource {\n readonly connections: StepConnectionDraft[] = [];\n readonly rules: StepRuleDraft[] = [];\n readonly assigneeId?: number;\n readonly posX?: number;\n readonly posY?: number;\n\n // journey-decoupling Phase 7: a Journey step no longer links to a Workflow.\n // A step nudges via EventRule actions instead of running a Workflow, so the\n // builder no longer accepts or emits a workflow reference.\n constructor(\n readonly name: string,\n readonly journey: JourneyBuilder,\n readonly order = 0,\n readonly description = '',\n options: AnyRecord = {}\n ) {\n super();\n this.assigneeId = options.assigneeId;\n this.posX = options.posX;\n this.posY = options.posY;\n }\n\n /** Wire an edge to `child` and return the CHILD, so chains read linearly. */\n connectsTo(child: JourneyStepBuilder, options: StepConnectionOptions = {}): JourneyStepBuilder {\n if (child === this) {\n throw new Error(`Journey step '${this.name}' cannot connect to itself`);\n }\n const abandonSeconds =\n options.abandonAfterDays !== undefined\n ? options.abandonAfterDays * SECONDS_PER_DAY\n : options.timeoutSeconds;\n this.connections.push({\n parent: this,\n child,\n condition: edgeCondition(options),\n required: options.required ?? false,\n timeoutSeconds: abandonSeconds,\n order: options.order,\n filterId: options.filterId,\n });\n return child;\n }\n\n /**\n * Attach a `JOURNEY_STEP_EXECUTE` action — what this step actually DOES\n * when a member reaches it. A step with no rules is inert: the member\n * lands on it, nothing is sent, and the journey moves on.\n */\n onExecute(\n actionType: EventRuleActionType,\n params: AnyRecord = {},\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n this.rules.push({\n uuid: crypto.randomUUID(),\n actionType,\n actionParams: params,\n options,\n });\n return this;\n }\n\n /**\n * Text the member. `phoneNumberUUID` is a workspace PhoneNumber with SMS\n * enabled. Pass `workflowUUID` to start an SMS workflow chat, or\n * `messageTemplate` for a one-off send.\n */\n sendsSms(\n params: {\n phoneNumberUUID: UuidRef;\n messageTemplate?: string;\n workflowUUID?: UuidRef;\n initialUserMessage?: string;\n },\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(EventRuleActionType.SMS_SEND, params, options);\n }\n\n /**\n * Call the member. Both the workspace PhoneNumber uuid (voice enabled) and\n * the Workflow uuid that drives the call are required.\n */\n callsMember(\n params: { phoneNumberUUID: UuidRef; workflowUUID: UuidRef },\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(EventRuleActionType.PHONE_CALL, params, options);\n }\n\n /** Email the member from a workspace inbox. */\n sendsEmail(\n params: {\n inboxUUID: UuidRef;\n subjectTemplate?: string;\n bodyTemplate?: string;\n workflowUUID?: UuidRef;\n initialUserMessage?: string;\n contentType?: string;\n },\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(EventRuleActionType.EMAIL_SEND, params, options);\n }\n\n /** Label the member on arrival — pass label builders, not ids. */\n addsLabels(\n labels: WorkspaceBuilderResource[],\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(\n EventRuleActionType.MEMBER_LABEL_ACTION,\n { addLabelIds: labels },\n options\n );\n }\n\n /** True once this step has something to do when a member reaches it. */\n get hasOutreach(): boolean {\n return this.rules.length > 0;\n }\n\n eventRuleInputs(): EventRuleInput[] {\n return this.rules.map((rule) => ({\n uuid: 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 planLine(): string {\n const actions = this.rules.map((rule) => rule.actionType).join(' + ');\n return `Step: ${this.name}${actions ? ` (${actions})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n if (this.journey._id === undefined) return;\n const rules = this.eventRuleInputs();\n const payload: JourneyStepFormData = {\n name: this.name,\n description: this.description,\n order: this.order,\n ...(this.assigneeId !== undefined ? { assigneeId: this.assigneeId } : {}),\n ...(this.posX !== undefined ? { posX: this.posX } : {}),\n ...(this.posY !== undefined ? { posY: this.posY } : {}),\n // Saved atomically with the step, so a partial failure cannot leave\n // an inert step behind.\n ...(rules.length ? { eventRules: rules } : {}),\n };\n const result = await client.createStep(this.journey._id, payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\n/**\n * The auto-created `Start` step. `POST /journeys` always creates one and points\n * `journey.startStepId` at it, so the builder adopts it rather than creating a\n * second — and every real step hangs off it, directly or transitively.\n */\nclass StartStepBuilder extends JourneyStepBuilder {\n get isImplicit(): boolean {\n return true;\n }\n\n planLine(): string {\n return 'Step: Start (auto-created)';\n }\n\n async apply(): Promise<void> {\n // Adopted from the create-journey response; never created.\n }\n}\n\nexport class JourneyBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly steps: JourneyStepBuilder[] = [];\n readonly goals: JourneyGoalDraft[] = [];\n /** The auto-created `Start` step — connect the first real step to it. */\n readonly start: JourneyStepBuilder;\n /** `parentId:childId` for every edge the server already has (see `adopt`). */\n readonly existingEdges = new Set<string>();\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.start = new StartStepBuilder('Start', this, 0);\n this.steps.push(this.start);\n }\n\n step(name: string, options: AnyRecord = {}): JourneyStepBuilder {\n const step = new JourneyStepBuilder(\n name,\n this,\n options.order ?? this.steps.length,\n options.description ?? '',\n options\n );\n this.steps.push(step);\n return step;\n }\n\n /**\n * Declare a linear cadence: `Start → steps[0] → steps[1] → …`, each edge\n * carrying the matching entry from `spacing`.\n *\n * Chaining is not optional polish. A step created with no incoming edge is\n * a ROOT, and every root fires the moment a member enrols — a \"three\n * follow-ups over four days\" journey built without edges sends all three\n * at once.\n */\n sequence(steps: JourneyStepBuilder[], spacing: StepConnectionOptions[] = []): JourneyBuilder {\n let parent = this.start;\n steps.forEach((step, index) => {\n parent = parent.connectsTo(step, spacing[index] ?? {});\n });\n return this;\n }\n\n goal(name: string, options: AnyRecord = {}): JourneyBuilder {\n this.goals.push({\n name,\n description: options.description ?? '',\n step: options.step,\n completionCel: options.completionCel ?? options.completion_cel,\n value: options.value,\n order: options.order ?? this.goals.length,\n });\n return this;\n }\n\n /**\n * Authoring problems that make a journey silently misbehave at runtime.\n * Reported at plan/preview time, before anything is written.\n */\n validate(): string[] {\n const problems: string[] = [];\n const withParents = new Set<JourneyStepBuilder>();\n for (const step of this.steps) {\n for (const connection of step.connections) withParents.add(connection.child);\n }\n for (const step of this.steps) {\n if (step === this.start) continue;\n if (!withParents.has(step)) {\n problems.push(\n `step '${step.name}' has no incoming edge — it is a root and fires for ` +\n 'every member the moment they enrol. Connect it from journey.start or ' +\n 'a prior step.'\n );\n }\n if (!step.hasOutreach) {\n problems.push(\n `step '${step.name}' has no JOURNEY_STEP_EXECUTE action — a member ` +\n 'reaching it gets nothing. Add one with .sendsSms / .callsMember / ' +\n '.sendsEmail / .onExecute.'\n );\n }\n }\n if (!this.goals.length) {\n problems.push(`journey '${this.name}' has no goals — nothing measures whether it works.`);\n }\n return problems;\n }\n\n /**\n * Adopt an existing journey, its steps, and its EDGES, matched by name.\n *\n * Re-running a builder script is normal — a program is usually built in\n * stages as provisioning lands — and without adoption the second run would\n * create a duplicate journey and a duplicate set of steps beside the live\n * one, with members enrolled in neither.\n *\n * The edge set is recorded from the server's own `childConnections` rather\n * than inferred from \"both steps exist\". A first run that created the steps\n * and then failed before writing an edge leaves exactly that state, and\n * inferring would skip the missing edge on every subsequent run — leaving a\n * permanent root step that fires for every member at enrolment, silently.\n * The journey detail read eager-loads connections, so the real answer is\n * already in hand; there is no reason to guess.\n */\n adopt(existing: AnyRecord): void {\n super.adopt(existing);\n const existingSteps = (existing.steps ?? []) as AnyRecord[];\n const byName = new Map(existingSteps.map((step) => [step.name as string, step]));\n const startStep =\n existingSteps.find((step) => step.id === existing.startStepId) ?? byName.get('Start');\n if (startStep) this.start.adopt(startStep);\n for (const step of this.steps) {\n if (step === this.start) continue;\n const match = byName.get(step.name);\n if (match) step.adopt(match);\n }\n for (const step of existingSteps) {\n for (const edge of (step.childConnections ?? []) as AnyRecord[]) {\n this.existingEdges.add(edgeKey(edge.parentStepId, edge.childStepId));\n }\n }\n }\n\n /** True when the server already has this exact edge. */\n hasEdge(parent: JourneyStepBuilder, child: JourneyStepBuilder): boolean {\n if (parent._id === undefined || child._id === undefined) return false;\n return this.existingEdges.has(edgeKey(parent._id, child._id));\n }\n\n planLine(): string {\n const parts: string[] = [];\n const real = this.steps.filter((step) => step !== this.start);\n if (real.length) parts.push(`${real.length} steps`);\n if (this.goals.length) parts.push(`${this.goals.length} goals`);\n return `Journey: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const result = await client.createJourney({\n name: this.name,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n\n // Adopt the server's auto-created Start step so edges from\n // `journey.start` resolve to a real uuid instead of silently dropping.\n const startStep = (result.steps ?? []).find(\n (step) => step.id === result.startStepId || step.name === 'Start'\n );\n if (!startStep) {\n throw new Error(\n `Journey '${this.name}' was created without a Start step; ` +\n 'edges from journey.start cannot be wired.'\n );\n }\n this.start.adopt(startStep);\n }\n}\n\nexport function buildJourneyConnectionPayload(\n connection: StepConnectionDraft\n): JourneyStepConnectionFormData | undefined {\n if (!connection.parent._uuid || !connection.child._uuid) return undefined;\n return {\n parentStepUuid: connection.parent._uuid,\n childStepUuid: connection.child._uuid,\n ...(connection.condition ? { celCondition: connection.condition } : {}),\n ...(connection.required ? { required: true } : {}),\n ...(connection.timeoutSeconds ? { timeoutSeconds: connection.timeoutSeconds } : {}),\n ...(connection.order !== undefined ? { order: connection.order } : {}),\n ...(connection.filterId !== undefined ? { filterId: connection.filterId } : {}),\n };\n}\n\nexport function buildJourneyGoalPayload(goal: JourneyGoalDraft): JourneyGoalFormData {\n return {\n name: goal.name,\n description: goal.description,\n order: goal.order,\n ...(goal.step?._uuid ? { goalStepUuid: goal.step._uuid } : {}),\n ...(goal.completionCel ? { completionCel: goal.completionCel } : {}),\n ...(goal.value !== undefined ? { value: goal.value } : {}),\n };\n}\n","import type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\n\nexport class RoleUpdate extends WorkspaceBuilderResource {\n constructor(\n readonly roleId: number,\n readonly workflowIds?: number[],\n readonly dataTypeIds?: number[]\n ) {\n super();\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.workflowIds) parts.push(`workflows=${JSON.stringify(this.workflowIds)}`);\n if (this.dataTypeIds) parts.push(`dataTypes=${JSON.stringify(this.dataTypeIds)}`);\n return `RoleUpdate: roleId=${this.roleId}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const payload: AnyRecord = {};\n if (this.workflowIds) payload.workflowIds = this.workflowIds;\n if (this.dataTypeIds) payload.dataTypeIds = this.dataTypeIds;\n if (Object.keys(payload).length) await client.updateMemberRole(this.roleId, payload);\n this._id = this.roleId;\n this._created = true;\n }\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\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\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 }\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.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 };\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 {\n buildJourneyConnectionPayload,\n buildJourneyGoalPayload,\n JourneyBuilder,\n JourneyStepBuilder,\n} from './journeys';\nimport {\n type AnyRecord,\n type ResourceSummary,\n resolveRefs,\n WorkspaceBuilderResource,\n} from './resource';\nimport { RoleUpdate } from './role-update';\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 [RoleUpdate, 4],\n [MemberFilterBuilder, 5],\n [RoutineBuilder, 6],\n [NotificationRuleBuilder, 6],\n [JourneyBuilder, 7],\n [JourneyStepBuilder, 8],\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 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 roleUpdate(roleId: number, workflowIds?: number[], dataTypeIds?: number[]): RoleUpdate {\n const update = new RoleUpdate(roleId, workflowIds, dataTypeIds);\n this.resources.push(update);\n return update;\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 step with\n * no incoming edge fires for every member at enrolment, and a step with no\n * action does nothing at all. Both look fine in the editor, so they are\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 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 return [...new Set(problems)];\n }\n\n async apply(): Promise<ResourceSummary> {\n // Refuse before writing anything, rather than failing part-way through.\n const problems = this.preflight();\n if (problems.length) {\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 const resources = this.sortedResources();\n await this.resolveExisting(resources);\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 if (resource._existed) {\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 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 writeLine(` Created ${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 await this.applyJourneyConnections(resources);\n await this.applyJourneyGoals(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 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 DETAIL projection, because a\n // journey's identity for re-run purposes is its step graph, and the list\n // rows carry no steps.\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 const existingJourneys = await this.client.getJourneys();\n for (const existing of existingJourneys.items) {\n if (!existing.name || !journeyNames.has(existing.name)) continue;\n const detail = await this.client.getJourney(existing.id);\n journeyNames.get(existing.name)!.adopt(detail);\n }\n }\n\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 } else if (resource instanceof JourneyBuilder) {\n all.push(...resource.steps);\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 JourneyStepBuilder) {\n for (const connection of resource.connections) {\n const guard = connection.condition ? ` [${connection.condition}]` : '';\n lines.push(`${connection.parent.name} -> ${connection.child.name}${guard}`);\n }\n for (const rule of resource.rules) {\n lines.push(`${rule.actionType} on step '${resource.name}'`);\n }\n } else if (resource instanceof JourneyBuilder) {\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 private async applyJourneyConnections(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyStepBuilder)) continue;\n for (const connection of resource.connections) {\n if (resource.journey._id === undefined) continue;\n // Skip only an edge the SERVER actually reports (recorded during\n // adoption). \"Both steps exist\" is not the same fact: a first run\n // that created the steps and died before the edge leaves exactly\n // that state, and skipping there would strand a root step that\n // fires for every member at enrolment, on every future run.\n if (resource.journey.hasEdge(connection.parent, connection.child)) {\n writeLine(` Exists: ${connection.parent.name} -> ${connection.child.name}`);\n continue;\n }\n const payload = buildJourneyConnectionPayload(connection);\n if (!payload) continue;\n await this.client.createConnection(resource.journey._id, payload);\n writeLine(` Wired: ${connection.parent.name} -> ${connection.child.name}`);\n }\n }\n }\n\n private async applyJourneyGoals(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyBuilder) || resource._id === undefined) continue;\n // Goals have no natural key to match on, so an adopted journey keeps\n // the goals it already has rather than accumulating a duplicate set\n // on every re-run. Say so per goal — the plan already listed them, and\n // a silent skip reads as \"created\" to anyone watching the output.\n if (resource._existed) {\n for (const goal of resource.goals) {\n writeLine(` Skipped (journey already exists): Goal: ${goal.name}`);\n }\n continue;\n }\n for (const goal of resource.goals) {\n await this.client.createGoal(resource._id, buildJourneyGoalPayload(goal));\n writeLine(` Created goal: ${goal.name}`);\n }\n }\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\nfunction resourceKey(resource: WorkspaceBuilderResource): string {\n if (resource instanceof RoleUpdate) return 'roleUpdates';\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 JourneyStepBuilder) return 'journeySteps';\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 || resource instanceof JourneyStepBuilder) {\n return 'journeys:write';\n }\n if (resource instanceof RoleUpdate) return 'member_roles: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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKO,SAAS,SAAS,OAAoC;AAC1D,SAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACtE;AAEA,SAAS,cAAc,OAAoC;AACxD,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,QAAM,YAAY,OAAO,eAAe,KAAK;AAC7C,SAAO,cAAc,OAAO,aAAa,cAAc;AAC1D;AAEO,SAAS,QAAQ,MAAsB;AAC3C,SAAO,KAAK,YAAY,EAAE,WAAW,KAAK,GAAG,EAAE,WAAW,KAAK,GAAG;AACrE;AAEO,IAAe,2BAAf,MAAwC;AAAA,EAC5C;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,WAAW;AAAA;AAAA,EAGX,IAAI,KAAa;AACd,QAAI,KAAK,QAAQ,QAAW;AACzB,YAAM,IAAI;AAAA,QACP,GAAG,KAAK,YAAY,IAAI;AAAA,MAE3B;AAAA,IACH;AACA,WAAO,KAAK;AAAA,EACf;AAAA;AAAA,EAGA,IAAI,OAAe;AAChB,QAAI,KAAK,UAAU,QAAW;AAC3B,YAAM,IAAI;AAAA,QACP,GAAG,KAAK,YAAY,IAAI;AAAA,MAE3B;AAAA,IACH;AACA,WAAO,KAAK;AAAA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ation.ts","../src/workspace-builder/forms.ts","../src/workspace-builder/journeys.ts","../src/workspace-builder/role-update.ts","../src/workspace-builder/workflows.ts","../src/workspace-builder/orchestrator.ts"],"sourcesContent":["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 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 JourneyGoalFormData,\n type JourneyStepConnectionFormData,\n type JourneyStepFormData,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { type AnyRecord, resolveRefs, WorkspaceBuilderResource } from './resource';\n\n/** Options for a DAG edge between two journey steps. */\nexport interface StepConnectionOptions {\n /**\n * CEL guard evaluated once the parent step is terminal. The child only\n * becomes eligible while this is true. Journey-edge CEL sees `member.*`\n * (including `member.labels`), `journey.enrolled_at`, `journey.status`,\n * and `parent_step.{status,completed_at,activated_at,eligible_at,name}`.\n */\n when?: string;\n /**\n * Space this step N days after the parent completed. Sugar for the CEL\n * `days_since(parent_step.completed_at) >= N`, AND-ed with `when`.\n *\n * This is how you build a follow-up cadence — NOT `abandonAfterDays`,\n * which gives up rather than waits.\n */\n afterDays?: number;\n /**\n * Give up on this edge after N days of the CEL staying false: the child\n * moves to TIMED_OUT instead of waiting forever. A deadline, not a delay.\n */\n abandonAfterDays?: number;\n /** Raw seconds form of `abandonAfterDays`. `abandonAfterDays` wins. */\n timeoutSeconds?: number;\n /** The child waits for THIS parent specifically, not just any parent. */\n required?: boolean;\n /** Edge evaluation order among a parent's outgoing edges. */\n order?: number;\n /** Restrict the edge to members matching a saved MemberFilter. */\n filterId?: number;\n}\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\nexport interface StepConnectionDraft {\n parent: JourneyStepBuilder;\n child: JourneyStepBuilder;\n condition?: string;\n required: boolean;\n timeoutSeconds?: number;\n order?: number;\n filterId?: number;\n}\n\nexport interface JourneyGoalDraft {\n name: string;\n description: string;\n step?: JourneyStepBuilder;\n completionCel?: string;\n value?: number;\n order: number;\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\nconst SECONDS_PER_DAY = 86_400;\n\nfunction edgeKey(parentId: unknown, childId: unknown): string {\n return `${parentId}:${childId}`;\n}\n\n/** `days_since(parent_step.completed_at) >= N`, AND-ed onto any explicit CEL. */\nfunction edgeCondition(options: StepConnectionOptions): string | undefined {\n const clauses: string[] = [];\n if (options.afterDays !== undefined) {\n clauses.push(`days_since(parent_step.completed_at) >= ${options.afterDays}`);\n }\n if (options.when) clauses.push(`(${options.when})`);\n if (!clauses.length) return undefined;\n return clauses.join(' && ');\n}\n\nexport class JourneyStepBuilder extends WorkspaceBuilderResource {\n readonly connections: StepConnectionDraft[] = [];\n readonly rules: StepRuleDraft[] = [];\n readonly assigneeId?: number;\n readonly posX?: number;\n readonly posY?: number;\n\n // journey-decoupling Phase 7: a Journey step no longer links to a Workflow.\n // A step nudges via EventRule actions instead of running a Workflow, so the\n // builder no longer accepts or emits a workflow reference.\n constructor(\n readonly name: string,\n readonly journey: JourneyBuilder,\n readonly order = 0,\n readonly description = '',\n options: AnyRecord = {}\n ) {\n super();\n this.assigneeId = options.assigneeId;\n this.posX = options.posX;\n this.posY = options.posY;\n }\n\n /** Wire an edge to `child` and return the CHILD, so chains read linearly. */\n connectsTo(child: JourneyStepBuilder, options: StepConnectionOptions = {}): JourneyStepBuilder {\n if (child === this) {\n throw new Error(`Journey step '${this.name}' cannot connect to itself`);\n }\n const abandonSeconds =\n options.abandonAfterDays !== undefined\n ? options.abandonAfterDays * SECONDS_PER_DAY\n : options.timeoutSeconds;\n this.connections.push({\n parent: this,\n child,\n condition: edgeCondition(options),\n required: options.required ?? false,\n timeoutSeconds: abandonSeconds,\n order: options.order,\n filterId: options.filterId,\n });\n return child;\n }\n\n /**\n * Attach a `JOURNEY_STEP_EXECUTE` action — what this step actually DOES\n * when a member reaches it. A step with no rules is inert: the member\n * lands on it, nothing is sent, and the journey moves on.\n */\n onExecute(\n actionType: EventRuleActionType,\n params: AnyRecord = {},\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n this.rules.push({\n uuid: crypto.randomUUID(),\n actionType,\n actionParams: params,\n options,\n });\n return this;\n }\n\n /**\n * Text the member. `phoneNumberUUID` is a workspace PhoneNumber with SMS\n * enabled. Pass `workflowUUID` to start an SMS workflow chat, or\n * `messageTemplate` for a one-off send.\n */\n sendsSms(\n params: {\n phoneNumberUUID: UuidRef;\n messageTemplate?: string;\n workflowUUID?: UuidRef;\n initialUserMessage?: string;\n },\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(EventRuleActionType.SMS_SEND, params, options);\n }\n\n /**\n * Call the member. Both the workspace PhoneNumber uuid (voice enabled) and\n * the Workflow uuid that drives the call are required.\n */\n callsMember(\n params: { phoneNumberUUID: UuidRef; workflowUUID: UuidRef },\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(EventRuleActionType.PHONE_CALL, params, options);\n }\n\n /** Email the member from a workspace inbox. */\n sendsEmail(\n params: {\n inboxUUID: UuidRef;\n subjectTemplate?: string;\n bodyTemplate?: string;\n workflowUUID?: UuidRef;\n initialUserMessage?: string;\n contentType?: string;\n },\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(EventRuleActionType.EMAIL_SEND, params, options);\n }\n\n /** Label the member on arrival — pass label builders, not ids. */\n addsLabels(\n labels: WorkspaceBuilderResource[],\n options: StepRuleOptions = {}\n ): JourneyStepBuilder {\n return this.onExecute(\n EventRuleActionType.MEMBER_LABEL_ACTION,\n { addLabelIds: labels },\n options\n );\n }\n\n /** True once this step has something to do when a member reaches it. */\n get hasOutreach(): boolean {\n return this.rules.length > 0;\n }\n\n eventRuleInputs(): EventRuleInput[] {\n return this.rules.map((rule) => ({\n uuid: 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 planLine(): string {\n const actions = this.rules.map((rule) => rule.actionType).join(' + ');\n return `Step: ${this.name}${actions ? ` (${actions})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n if (this.journey._id === undefined) return;\n const rules = this.eventRuleInputs();\n const payload: JourneyStepFormData = {\n name: this.name,\n description: this.description,\n order: this.order,\n ...(this.assigneeId !== undefined ? { assigneeId: this.assigneeId } : {}),\n ...(this.posX !== undefined ? { posX: this.posX } : {}),\n ...(this.posY !== undefined ? { posY: this.posY } : {}),\n // Saved atomically with the step, so a partial failure cannot leave\n // an inert step behind.\n ...(rules.length ? { eventRules: rules } : {}),\n };\n const result = await client.createStep(this.journey._id, payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\n/**\n * The auto-created `Start` step. `POST /journeys` always creates one and points\n * `journey.startStepId` at it, so the builder adopts it rather than creating a\n * second — and every real step hangs off it, directly or transitively.\n */\nclass StartStepBuilder extends JourneyStepBuilder {\n get isImplicit(): boolean {\n return true;\n }\n\n planLine(): string {\n return 'Step: Start (auto-created)';\n }\n\n async apply(): Promise<void> {\n // Adopted from the create-journey response; never created.\n }\n}\n\nexport class JourneyBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly steps: JourneyStepBuilder[] = [];\n readonly goals: JourneyGoalDraft[] = [];\n /** The auto-created `Start` step — connect the first real step to it. */\n readonly start: JourneyStepBuilder;\n /** `parentId:childId` for every edge the server already has (see `adopt`). */\n readonly existingEdges = new Set<string>();\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.start = new StartStepBuilder('Start', this, 0);\n this.steps.push(this.start);\n }\n\n step(name: string, options: AnyRecord = {}): JourneyStepBuilder {\n const step = new JourneyStepBuilder(\n name,\n this,\n options.order ?? this.steps.length,\n options.description ?? '',\n options\n );\n this.steps.push(step);\n return step;\n }\n\n /**\n * Declare a linear cadence: `Start → steps[0] → steps[1] → …`, each edge\n * carrying the matching entry from `spacing`.\n *\n * Chaining is not optional polish. A step created with no incoming edge is\n * a ROOT, and every root fires the moment a member enrols — a \"three\n * follow-ups over four days\" journey built without edges sends all three\n * at once.\n */\n sequence(steps: JourneyStepBuilder[], spacing: StepConnectionOptions[] = []): JourneyBuilder {\n let parent = this.start;\n steps.forEach((step, index) => {\n parent = parent.connectsTo(step, spacing[index] ?? {});\n });\n return this;\n }\n\n goal(name: string, options: AnyRecord = {}): JourneyBuilder {\n this.goals.push({\n name,\n description: options.description ?? '',\n step: options.step,\n completionCel: options.completionCel ?? options.completion_cel,\n value: options.value,\n order: options.order ?? this.goals.length,\n });\n return this;\n }\n\n /**\n * Authoring problems that make a journey silently misbehave at runtime.\n * Reported at plan/preview time, before anything is written.\n */\n validate(): string[] {\n const problems: string[] = [];\n const withParents = new Set<JourneyStepBuilder>();\n for (const step of this.steps) {\n for (const connection of step.connections) withParents.add(connection.child);\n }\n for (const step of this.steps) {\n if (step === this.start) continue;\n if (!withParents.has(step)) {\n problems.push(\n `step '${step.name}' has no incoming edge — it is a root and fires for ` +\n 'every member the moment they enrol. Connect it from journey.start or ' +\n 'a prior step.'\n );\n }\n if (!step.hasOutreach) {\n problems.push(\n `step '${step.name}' has no JOURNEY_STEP_EXECUTE action — a member ` +\n 'reaching it gets nothing. Add one with .sendsSms / .callsMember / ' +\n '.sendsEmail / .onExecute.'\n );\n }\n }\n if (!this.goals.length) {\n problems.push(`journey '${this.name}' has no goals — nothing measures whether it works.`);\n }\n return problems;\n }\n\n /**\n * Adopt an existing journey, its steps, and its EDGES, matched by name.\n *\n * Re-running a builder script is normal — a program is usually built in\n * stages as provisioning lands — and without adoption the second run would\n * create a duplicate journey and a duplicate set of steps beside the live\n * one, with members enrolled in neither.\n *\n * The edge set is recorded from the server's own `childConnections` rather\n * than inferred from \"both steps exist\". A first run that created the steps\n * and then failed before writing an edge leaves exactly that state, and\n * inferring would skip the missing edge on every subsequent run — leaving a\n * permanent root step that fires for every member at enrolment, silently.\n * The journey detail read eager-loads connections, so the real answer is\n * already in hand; there is no reason to guess.\n */\n adopt(existing: AnyRecord): void {\n super.adopt(existing);\n const existingSteps = (existing.steps ?? []) as AnyRecord[];\n const byName = new Map(existingSteps.map((step) => [step.name as string, step]));\n const startStep =\n existingSteps.find((step) => step.id === existing.startStepId) ?? byName.get('Start');\n if (startStep) this.start.adopt(startStep);\n for (const step of this.steps) {\n if (step === this.start) continue;\n const match = byName.get(step.name);\n if (match) step.adopt(match);\n }\n for (const step of existingSteps) {\n for (const edge of (step.childConnections ?? []) as AnyRecord[]) {\n this.existingEdges.add(edgeKey(edge.parentStepId, edge.childStepId));\n }\n }\n }\n\n /** True when the server already has this exact edge. */\n hasEdge(parent: JourneyStepBuilder, child: JourneyStepBuilder): boolean {\n if (parent._id === undefined || child._id === undefined) return false;\n return this.existingEdges.has(edgeKey(parent._id, child._id));\n }\n\n planLine(): string {\n const parts: string[] = [];\n const real = this.steps.filter((step) => step !== this.start);\n if (real.length) parts.push(`${real.length} steps`);\n if (this.goals.length) parts.push(`${this.goals.length} goals`);\n return `Journey: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const result = await client.createJourney({\n name: this.name,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n\n // Adopt the server's auto-created Start step so edges from\n // `journey.start` resolve to a real uuid instead of silently dropping.\n const startStep = (result.steps ?? []).find(\n (step) => step.id === result.startStepId || step.name === 'Start'\n );\n if (!startStep) {\n throw new Error(\n `Journey '${this.name}' was created without a Start step; ` +\n 'edges from journey.start cannot be wired.'\n );\n }\n this.start.adopt(startStep);\n }\n}\n\nexport function buildJourneyConnectionPayload(\n connection: StepConnectionDraft\n): JourneyStepConnectionFormData | undefined {\n if (!connection.parent._uuid || !connection.child._uuid) return undefined;\n return {\n parentStepUuid: connection.parent._uuid,\n childStepUuid: connection.child._uuid,\n ...(connection.condition ? { celCondition: connection.condition } : {}),\n ...(connection.required ? { required: true } : {}),\n ...(connection.timeoutSeconds ? { timeoutSeconds: connection.timeoutSeconds } : {}),\n ...(connection.order !== undefined ? { order: connection.order } : {}),\n ...(connection.filterId !== undefined ? { filterId: connection.filterId } : {}),\n };\n}\n\nexport function buildJourneyGoalPayload(goal: JourneyGoalDraft): JourneyGoalFormData {\n return {\n name: goal.name,\n description: goal.description,\n order: goal.order,\n ...(goal.step?._uuid ? { goalStepUuid: goal.step._uuid } : {}),\n ...(goal.completionCel ? { completionCel: goal.completionCel } : {}),\n ...(goal.value !== undefined ? { value: goal.value } : {}),\n };\n}\n","import type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\n\nexport class RoleUpdate extends WorkspaceBuilderResource {\n constructor(\n readonly roleId: number,\n readonly workflowIds?: number[],\n readonly dataTypeIds?: number[]\n ) {\n super();\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.workflowIds) parts.push(`workflows=${JSON.stringify(this.workflowIds)}`);\n if (this.dataTypeIds) parts.push(`dataTypes=${JSON.stringify(this.dataTypeIds)}`);\n return `RoleUpdate: roleId=${this.roleId}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: AnyRecord = {};\n if (this.workflowIds) payload.workflowIds = this.workflowIds;\n if (this.dataTypeIds) payload.dataTypeIds = this.dataTypeIds;\n if (Object.keys(payload).length) await client.updateMemberRole(this.roleId, payload);\n this._id = this.roleId;\n this._created = true;\n }\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\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\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 }\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 };\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 {\n buildJourneyConnectionPayload,\n buildJourneyGoalPayload,\n JourneyBuilder,\n JourneyStepBuilder,\n} from './journeys';\nimport {\n type AnyRecord,\n type ResourceSummary,\n resolveRefs,\n WorkspaceBuilderResource,\n} from './resource';\nimport { RoleUpdate } from './role-update';\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 [RoleUpdate, 4],\n [MemberFilterBuilder, 5],\n [RoutineBuilder, 6],\n [NotificationRuleBuilder, 6],\n [JourneyBuilder, 7],\n [JourneyStepBuilder, 8],\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 sameIdSet(left: number[], right: number[]): boolean {\n const target = new Set(right);\n return target.size === new Set(left).size && left.every((id) => target.has(id));\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 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 roleUpdate(roleId: number, workflowIds?: number[], dataTypeIds?: number[]): RoleUpdate {\n const update = new RoleUpdate(roleId, workflowIds, dataTypeIds);\n this.resources.push(update);\n return update;\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 step with\n * no incoming edge fires for every member at enrolment, and a step with no\n * action does nothing at all. Both look fine in the editor, so they are\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 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 return [...new Set(problems)];\n }\n\n async apply(): Promise<ResourceSummary> {\n // Refuse before writing anything, rather than failing part-way through.\n const problems = this.preflight();\n if (problems.length) {\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 const resources = this.sortedResources();\n await this.resolveExisting(resources);\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 if (resource._existed) {\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 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 writeLine(` Created ${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 await this.applyJourneyConnections(resources);\n await this.applyJourneyGoals(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 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 DETAIL projection, because a\n // journey's identity for re-run purposes is its step graph, and the list\n // rows carry no steps.\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 const existingJourneys = await this.client.getJourneys();\n for (const existing of existingJourneys.items) {\n if (!existing.name || !journeyNames.has(existing.name)) continue;\n const detail = await this.client.getJourney(existing.id);\n journeyNames.get(existing.name)!.adopt(detail);\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.resolveExistingRoleUpdates(resources);\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 a role update whose grants the server already has.\n *\n * A role update is a replace-semantics PUT, not a create, so its identity is\n * the role id and \"already applied\" means the id sets match exactly. Subset\n * would be wrong: `roleUpdate(7, [])` asks to *clear* the role's workflow\n * access, and treating that as satisfied by a role that still has grants\n * would silently skip a real change.\n *\n * Only the fields this update declares are compared — an update that passes\n * `workflowIds` and omits `dataTypeIds` never touches data-type access, so\n * that access cannot make it stale.\n */\n private async resolveExistingRoleUpdates(resources: WorkspaceBuilderResource[]): Promise<void> {\n const updates = resources.filter(\n (resource): resource is RoleUpdate => resource instanceof RoleUpdate\n );\n if (!updates.length) return;\n\n const rolesById = new Map(\n (await this.client.getMemberRoles()).map((role) => [role.id, role])\n );\n for (const update of updates) {\n const role = rolesById.get(update.roleId);\n if (!role) continue;\n // Grants carry an accessMode the builder has no way to express, so\n // the ids are the whole of the comparable fact.\n const workflowsSettled =\n update.workflowIds === undefined ||\n sameIdSet(\n update.workflowIds,\n (role.workflowAccess ?? []).map((access) => access.workflowId)\n );\n const dataTypesSettled =\n update.dataTypeIds === undefined ||\n sameIdSet(\n update.dataTypeIds,\n (role.dataTypeAccess ?? []).map((access) => access.dataTypeId)\n );\n if (workflowsSettled && dataTypesSettled) update.adopt(role);\n }\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 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 } else if (resource instanceof JourneyBuilder) {\n all.push(...resource.steps);\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 JourneyStepBuilder) {\n for (const connection of resource.connections) {\n const guard = connection.condition ? ` [${connection.condition}]` : '';\n lines.push(`${connection.parent.name} -> ${connection.child.name}${guard}`);\n }\n for (const rule of resource.rules) {\n lines.push(`${rule.actionType} on step '${resource.name}'`);\n }\n } else if (resource instanceof JourneyBuilder) {\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 private async applyJourneyConnections(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyStepBuilder)) continue;\n for (const connection of resource.connections) {\n if (resource.journey._id === undefined) continue;\n // Skip only an edge the SERVER actually reports (recorded during\n // adoption). \"Both steps exist\" is not the same fact: a first run\n // that created the steps and died before the edge leaves exactly\n // that state, and skipping there would strand a root step that\n // fires for every member at enrolment, on every future run.\n if (resource.journey.hasEdge(connection.parent, connection.child)) {\n writeLine(` Exists: ${connection.parent.name} -> ${connection.child.name}`);\n continue;\n }\n const payload = buildJourneyConnectionPayload(connection);\n if (!payload) continue;\n await this.client.createConnection(resource.journey._id, payload);\n writeLine(` Wired: ${connection.parent.name} -> ${connection.child.name}`);\n }\n }\n }\n\n private async applyJourneyGoals(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyBuilder) || resource._id === undefined) continue;\n // Goals have no natural key to match on, so an adopted journey keeps\n // the goals it already has rather than accumulating a duplicate set\n // on every re-run. Say so per goal — the plan already listed them, and\n // a silent skip reads as \"created\" to anyone watching the output.\n if (resource._existed) {\n for (const goal of resource.goals) {\n writeLine(` Skipped (journey already exists): Goal: ${goal.name}`);\n }\n continue;\n }\n for (const goal of resource.goals) {\n await this.client.createGoal(resource._id, buildJourneyGoalPayload(goal));\n writeLine(` Created goal: ${goal.name}`);\n }\n }\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\nfunction resourceKey(resource: WorkspaceBuilderResource): string {\n if (resource instanceof RoleUpdate) return 'roleUpdates';\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 JourneyStepBuilder) return 'journeySteps';\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 || resource instanceof JourneyStepBuilder) {\n return 'journeys:write';\n }\n if (resource instanceof RoleUpdate) return 'member_roles: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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKO,SAAS,SAAS,OAAoC;AAC1D,SAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACtE;AAEA,SAAS,cAAc,OAAoC;AACxD,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,QAAM,YAAY,OAAO,eAAe,KAAK;AAC7C,SAAO,cAAc,OAAO,aAAa,cAAc;AAC1D;AAEO,SAAS,QAAQ,MAAsB;AAC3C,SAAO,KAAK,YAAY,EAAE,WAAW,KAAK,GAAG,EAAE,WAAW,KAAK,GAAG;AACrE;AAEO,IAAe,2BAAf,MAAwC;AAAA,EAC5C;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,WAAW;AAAA;AAAA,EAGX,IAAI,KAAa;AACd,QAAI,KAAK,QAAQ,QAAW;AACzB,YAAM,IAAI;AAAA,QACP,GAAG,KAAK,YAAY,IAAI;AAAA,MAE3B;AAAA,IACH;AACA,WAAO,K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