Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

workflow publishing terminology updates (#1468)

Anshul sharma4c808ee0ec45
diff --git a/.ai/plans/2026-08-24-workflow-publish-unpublish.md b/.ai/plans/2026-08-24-workflow-publish-unpublish.md
new file mode 100644
index 0000000000..255e539d3b
--- /dev/null
+++ b/.ai/plans/2026-08-24-workflow-publish-unpublish.md
@@ -0,0 +1,678 @@
+# Workflows: one switch — Publish / Unpublish — implementation plan
+
+**Spec / source:** `.ai/specs/2026-08-24-workflow-publish-unpublish.md`
+**Research:** `.ai/research/2026-08-24-workflow-version-terminology.md`
+**Branch:** `fix/workflow-version-copy-changes`
+
+Goal: delete `workflow.active`, rename `workflow.activeVersionId` →
+`workflow.publishedVersionId`, and make Publish/Unpublish the only on-off switch.
+"Published"/"Draft" is the only state vocabulary; the words "Active" and "Live" leave the
+product entirely.
+
+## Progress
+- [x] Task 1: Write and apply the migration
+- [x] Task 2: Regenerate database types
+- [x] Task 3: Gate `syncWorkflowTriggers` on `publishedVersionId` alone
+- [x] Task 4: Drop the `active` predicates from the scheduler
+- [x] Task 5: Rename the engine's run-context gate to `workflowPublished`
+- [ ] Task 6: Replace `setWorkflowActive` with `unpublishWorkflow`
+- [ ] Task 7: Swap the column in the service and list loader
+- [ ] Task 8: Turn the toggle route into an unpublish route
+- [ ] Task 9: List page — drop the Active column, add Unpublish to the row menu
+- [ ] Task 10: Builder — Publish/Unpublish button and Published tag
+- [ ] Task 11: Update the trigger-drift SQL invariant
+- [x] Task 12: Update the demo datasets
+- [ ] Task 13: Update AGENTS.md, rules, and the docs site
+- [ ] Task 14: Extract i18n strings
+- [ ] Task 15: End-to-end verification
+
+## Dependencies
+
+- Task 2 needs Task 1. Everything else needs Task 2 (the generated types are what make the
+ new column name typecheck).
+- Tasks 3, 4, 5, 6, 7, 8, 11, 12 are independent of each other — safe to run in parallel.
+- Task 9 needs Tasks 7 and 8. Task 10 needs Task 8.
+- Task 14 needs Tasks 9 and 10. Task 15 needs everything.
+
+---
+
+## Task 1: Write and apply the migration
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_workflow-publish-unpublish.sql` (the command below generates the name)
+- Read for context: `packages/database/supabase/migrations/20260810100100_workflows-foundation.sql` — lines 32–52 (table), 76–81 (FK), 183–185 (the partial index)
+
+**Steps:**
+
+1. Create the migration file:
+ ```bash
+ pnpm db:migrate:new workflow-publish-unpublish
+ ```
+2. Put exactly this in it:
+ ```sql
+ -- Publishing is now the only on-off switch: workflow."publishedVersionId" set means the
+ -- workflow runs that version, NULL means it is a draft and nothing fires.
+
+ -- A workflow that was published but switched OFF is deliberately paused. Collapsing the
+ -- two flags would silently resume it, so unpublish it while "active" still records intent.
+ UPDATE "workflow" SET "activeVersionId" = NULL WHERE "active" = FALSE;
+
+ -- ...and its dispatch rows with it, matching what syncWorkflowTriggers does on unpublish.
+ -- Must run BEFORE the column is dropped.
+ DELETE FROM "workflowTriggerEvent" te
+ USING "workflow" w
+ WHERE te."workflowId" = w."id"
+ AND te."companyId" = w."companyId"
+ AND w."active" = FALSE;
+
+ -- Postgres silently drops any index whose predicate names a dropped column, and
+ -- "workflow_due_idx" is partial on "active" = TRUE. Rebuild it, or the scheduler loses
+ -- its index with no error anywhere.
+ DROP INDEX IF EXISTS "workflow_due_idx";
+
+ ALTER TABLE "workflow" DROP COLUMN "active";
+ ALTER TABLE "workflow" RENAME COLUMN "activeVersionId" TO "publishedVersionId";
+ ALTER TABLE "workflow"
+ RENAME CONSTRAINT "workflow_activeVersionId_fkey" TO "workflow_publishedVersionId_fkey";
+
+ CREATE INDEX "workflow_due_idx" ON "workflow" ("nextRunAt")
+ WHERE "nextRunAt" IS NOT NULL AND "publishedVersionId" IS NOT NULL;
+ ```
+3. Do NOT drop and re-add the FK. Its `ON DELETE SET NULL ("activeVersionId")` clause names
+ its column explicitly on purpose (a bare `SET NULL` would also null `companyId`, which is
+ `NOT NULL`, making the parent row undeletable — see `.ai/lessons.md`). `RENAME COLUMN`
+ carries that clause across intact.
+4. Apply it:
+ ```bash
+ pnpm db:migrate
+ ```
+ If the local database is not running, STOP and report — do not rebuild or reset the
+ database.
+
+**Verify:**
+```bash
+psql "$SUPABASE_DB_URL" -c '\d "workflow"' -c "SELECT indexdef FROM pg_indexes WHERE indexname = 'workflow_due_idx';"
+# Expected: the column list shows "publishedVersionId" and NO "active" column;
+# the constraint is named workflow_publishedVersionId_fkey;
+# indexdef contains: WHERE ((("nextRunAt" IS NOT NULL) AND ("publishedVersionId" IS NOT NULL)))
+```
+
+**Out of scope:** `eventSystemSubscription.active` (a different table, correctly named);
+`workflowRun_active_idx` (an index on `workflowRun`, unrelated to this column); every
+`workflowVersion` column.
+
+---
+
+## Task 2: Regenerate database types
+
+**Depends on:** Task 1
+**Files:**
+- Modify (generated, never hand-edited): `packages/database/src/types.ts`,
+ `packages/database/src/swagger-docs-schema.ts`,
+ `packages/database/supabase/functions/lib/types.ts`
+
+**Steps:**
+1. Run:
+ ```bash
+ pnpm run generate:types
+ ```
+2. These three files already carry uncommitted regeneration drift on this branch. That is
+ expected — the regen absorbs it, so the diff is wider than this feature. Do not try to
+ revert or narrow it, and do not hand-edit any of them.
+
+**Verify:**
+```bash
+grep -c 'publishedVersionId' packages/database/src/types.ts
+grep -n '"active"' packages/database/src/types.ts | grep -i workflow
+# Expected: the first prints a number >= 3 (Row/Insert/Update);
+# the second prints nothing for the `workflow` table (eventSystemSubscription hits are fine)
+```
+
+**Out of scope:** hand-editing any generated file.
+
+---
+
+## Task 3: Gate `syncWorkflowTriggers` on `publishedVersionId` alone
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `packages/workflows/src/sync.ts` — the select and gate inside `syncWorkflowTriggers` (around lines 166–188)
+- Modify: `packages/workflows/src/seed-workflows.test.ts` — any `active` reference
+
+**Steps:**
+1. Change the select from `["active", "activeVersionId"]` to `["publishedVersionId"]`.
+2. Change the gate `if (workflow?.active && workflow.activeVersionId) {` to
+ `if (workflow?.publishedVersionId) {`, and the `.where("id", "=", workflow.activeVersionId)`
+ below it to `workflow.publishedVersionId`.
+3. Update the doc comment above `CompanyLock` and the `nextRunAt` comment: "a promote or
+ toggle" becomes "a publish or unpublish".
+4. Leave everything else in the transaction alone — the `lockCompany` first statement, the
+ delete-then-insert of `workflowTriggerEvent`, the `eventSystemSubscription`
+ reconciliation, and the `nextRunAt` write are all unchanged.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/workflows test && pnpm exec turbo run typecheck --filter=@carbon/workflows
+# Expected: all tests pass; no TypeScript errors
+```
+
+**Out of scope:** `deriveWorkflowSubscriptions`, `deriveWorkflowTriggerRows`,
+`findTriggerSchedule` — none of them read the workflow row.
+
+---
+
+## Task 4: Drop the `active` predicates from the scheduler
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `packages/jobs/src/workflows/scheduler.ts` — lines ~26, 39, 46, 50–51, 60–61, 70–71, 253
+- Modify: `packages/jobs/src/workflows/scheduler.test.ts`
+
+**Steps:**
+1. Delete both `.where("w.active", "=", true)` lines. The
+ `.where("w.activeVersionId", "is not", null)` beside each one already expresses the whole
+ condition once the flag is gone.
+2. Rename `activeVersionId` → `publishedVersionId` everywhere in the file: the row type field,
+ the `onRef("v.id", "=", "w.activeVersionId")` join, the select list, the remaining
+ `is not null` predicates, the type-narrowing predicate function, and
+ `workflowVersionId: row.activeVersionId`.
+3. Update the test fixtures/inserts to drop `active` and use the new column name.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs test -- scheduler && pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: scheduler tests pass; no TypeScript errors
+```
+
+**Out of scope:** `activeRunKeys` / `activeKeys` / `workflowRun_active_idx` — those describe
+in-flight RUNS, not the publish state. Do not rename them.
+
+---
+
+## Task 5: Rename the engine's run-context gate to `workflowPublished`
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `packages/jobs/src/workflows/engine/log.ts` — the context type (line ~15), the select (line ~54), the mapping (line ~76)
+- Modify: `packages/jobs/src/workflows/engine/execute.ts` — `SWITCHED_OFF` (line 72) and the guard (line ~378)
+- Modify: `packages/jobs/src/workflows/engine/execute.test.ts`, `end-to-end.test.ts`, `batch.test.ts` — the `workflowActive: true` fixtures
+
+**Steps:**
+1. In `log.ts`: rename the type field `workflowActive: boolean` → `workflowPublished: boolean`;
+ change the select from `"w.active as workflowActive"` to
+ ``sql`w."publishedVersionId" IS NOT NULL`.as("workflowPublished")`` (import `sql` from
+ `kysely` if it is not already imported in that file); change the mapping to
+ `workflowPublished: row.workflowPublished === true`.
+2. In `execute.ts`: change the guard to `if (!context.workflowPublished) {` and change the
+ constant to:
+ ```typescript
+ const SWITCHED_OFF = "This workflow was unpublished before the run started.";
+ ```
+ Rename the constant itself to `UNPUBLISHED` so the name matches the string, and update its
+ single other use at the `statusReason` line.
+3. Update the three test fixtures to `workflowPublished: true`.
+4. The guard deliberately asks "is the workflow published at all", NOT "is this run's version
+ still the published one". A run already in flight keeps the version it started with even
+ after a newer version is published — that is existing documented behaviour. If you find
+ yourself comparing `publishedVersionId` to the run's `workflowVersionId`, STOP and report.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs test && pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: all @carbon/jobs tests pass; no TypeScript errors
+```
+
+**Out of scope:** `matcher.ts` — it never read `workflow.active`; its gate is the presence of
+`workflowTriggerEvent` rows, which Task 3 already controls.
+
+---
+
+## Task 6: Replace `setWorkflowActive` with `unpublishWorkflow`
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/workflows.server.ts` — `publishWorkflowVersion` (~line 136), `setWorkflowActive` (~line 154), and the `syncAfterWorkflowDelete` doc comment (~line 197)
+- Modify: `apps/erp/app/modules/workflows/workflows.models.ts` — delete `workflowToggleValidator` (~line 69)
+
+**Steps:**
+1. In `publishWorkflowVersion`, change the update payload from
+ `{ activeVersionId: versionId, active: true, ... }` to
+ `{ publishedVersionId: versionId, ... }`. Keep the `updatedBy` / `updatedAt` fields and the
+ `datetime.timestamp()` call exactly as they are.
+2. Replace `setWorkflowActive` with:
+ ```typescript
+ export async function unpublishWorkflow(
+ client: SupabaseClient<Database>,
+ {
+ workflowId,
+ companyId,
+ userId
+ }: {
+ workflowId: string;
+ companyId: string;
+ userId: string;
+ }
+ ): Promise<WorkflowSyncResult> {
+ const updated = await client
+ .from("workflow")
+ .update({
+ publishedVersionId: null,
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .eq("id", workflowId)
+ .eq("companyId", companyId);
+
+ if (updated.error) {
+ return { ok: false, issues: [], message: updated.error.message };
+ }
+
+ // Unpublishing must still sync — that is what deletes the trigger rows and clears
+ // nextRunAt, which is what actually stops the workflow firing.
+ return syncAndWake(companyId, workflowId);
+ }
+ ```
+ There is no boolean parameter: publishing needs a version id and runs validation, so it
+ cannot share an entry point with unpublishing.
+3. Delete `workflowToggleValidator` from `workflows.models.ts`.
+4. In the `syncAfterWorkflowDelete` comment, change "the next publish or toggle" to "the next
+ publish or unpublish".
+
+**Verify:**
+```bash
+grep -rn "setWorkflowActive\|workflowToggleValidator" apps/erp/app
+# Expected: only the not-yet-updated route hit from Task 8; zero after Task 8 lands
+```
+
+**Out of scope:** `validateDefinition`, `readWorkflowVersion`, `syncAndWake` internals.
+
+---
+
+## Task 7: Swap the column in the service and list loader
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/workflows.service.ts` — `getWorkflows` (~lines 18, 29–42), `getWorkflow` (~line 62), and the embed at ~line 489
+- Modify: `apps/erp/app/routes/x+/workflows+/_index.tsx` — lines ~37–46
+
+**Steps:**
+1. In `getWorkflows`, change the select string from
+ `"id, name, description, ownerId, active, activeVersionId, createdAt, updatedAt"` to
+ `"id, name, description, ownerId, publishedVersionId, createdAt, updatedAt"` — `active` is
+ dropped entirely, not renamed.
+2. Update the derived-status comment to say `publishedVersionId`, and change the two filter
+ branches to `.not("publishedVersionId", "is", null)` and
+ `.is("publishedVersionId", null)`. The `"Published"` / `"Draft"` filter VALUES are
+ unchanged — they are what the UI sends and what saved views already store.
+3. In `getWorkflow` (~line 62), drop `active,` and rename `activeVersionId` in the select
+ string.
+4. At ~line 489, change `"workflowId, workflow(activeVersionId)"` to
+ `"workflowId, workflow(publishedVersionId)"` and update whatever reads that field.
+5. In `_index.tsx`, rename the local `activeVersionIds` → `publishedVersionIds` and read
+ `row.publishedVersionId`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors mentioning `active` or `activeVersionId`.
+# NOTE: the filter is `erp`, NOT `@carbon/erp` — a wrong filter silently passes.
+# If turbo returns a cached pass, re-run with --force before trusting it.
+```
+
+**Out of scope:** the `GenericQueryFilters` pipeline; `getWorkflowVersionNumbers`;
+`getWorkflowLastRuns`.
+
+---
+
+## Task 8: Turn the toggle route into an unpublish route
+
+**Depends on:** Tasks 2, 6
+**Files:**
+- Create: `apps/erp/app/routes/x+/workflow+/$id.unpublish.tsx`
+- Delete: `apps/erp/app/routes/x+/workflow+/$id.toggle.tsx`
+- Modify: `apps/erp/app/utils/path.ts` — line ~2201
+- Copy from (precedent): `apps/erp/app/routes/x+/workflow+/$id.toggle.tsx` (the file being replaced) and `$id.publish.tsx` for the permission + plan gate shape
+
+**Steps:**
+1. Create the new route with the same imports, `assertIsPost`, `requirePermissions({ update: "workflows" })` and `requirePlan({ feature: "WORKFLOWS" })` blocks as the toggle route. Drop the
+ validator entirely — unpublish carries no fields — and call:
+ ```typescript
+ const unpublished = await unpublishWorkflow(client, {
+ workflowId: id,
+ companyId,
+ userId
+ });
+
+ if (!unpublished.ok) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(null, unpublished.message ?? "Failed to unpublish")
+ )
+ );
+ }
+
+ return data(
+ { success: true },
+ await flash(request, success("Workflow unpublished"))
+ );
+ ```
+2. Keep the header comment's intent, updated: this is the one route both the list menu and the
+ builder button post to, so there is exactly one place that re-syncs the trigger rows.
+3. Delete `$id.toggle.tsx`.
+4. In `path.ts`, replace the `workflowToggle` entry with:
+ ```typescript
+ workflowUnpublish: (id: string) =>
+ generatePath(`${x}/workflow/${id}/unpublish`),
+ ```
+ Keep the alphabetical ordering of the surrounding keys (it sits after `workflowTestRun`).
+
+**Verify:**
+```bash
+grep -rn "workflowToggle\|toggle.tsx" apps/erp/app | grep -i workflow
+# Expected: no output
+```
+
+**Out of scope:** `$id.publish.tsx` — its path, validator and gates do not change.
+
+---
+
+## Task 9: List page — drop the Active column, add Unpublish to the row menu
+
+**Depends on:** Tasks 7, 8
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx`
+- Delete: `apps/erp/app/modules/workflows/ui/WorkflowActiveCheckbox.tsx`
+- Delete: `apps/erp/app/modules/workflows/ui/WorkflowActiveSwitch.tsx` (already unused — nothing imports it)
+- Modify: `apps/erp/app/modules/workflows/ui/index.ts` (or whichever barrel re-exports those two, if any)
+- Modify: `apps/erp/app/modules/workflows/ui/WorkflowsUpgradeOverlay.tsx` — its fake sample rows carry an `active` field (lines ~20–32)
+- Copy from (precedent): the existing `ConfirmDelete` usage at the bottom of `WorkflowsTable.tsx` (~lines 281–297) for the disclosure + selected-row + modal pattern, and `apps/erp/app/components/Modals/Confirm/Confirm.tsx` for the dialog itself
+
+**Steps:**
+1. Delete the whole `accessorKey: "active"` column object (~lines 117–130) and the
+ `WorkflowActiveCheckbox` import.
+2. Leave the `status` column exactly as it is — it already renders
+ `Published` / `Draft` badges and the same static filter. Only its `isPublished` derivation
+ changes source: `Boolean(row.original.publishedVersionId)`, and `exportValue` likewise.
+3. Add an `unpublishDisclosure = useDisclosure()` beside the existing `renameDisclosure` /
+ `deleteDisclosure`.
+4. In `renderContextMenu`, add between Rename and Delete:
+ ```tsx
+ <MenuItem
+ disabled={
+ !permissions.can("update", "workflows") || !row.publishedVersionId
+ }
+ onClick={() => {
+ flushSync(() => setSelectedWorkflow(row));
+ unpublishDisclosure.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuCircleStop />} />
+ {t`Unpublish`}
+ </MenuItem>
+ ```
+ Import `LuCircleStop` from `react-icons/lu` alongside the existing `Lu*` imports. Add
+ `unpublishDisclosure` to the `renderContextMenu` dependency array.
+5. Render the confirm beside the existing modals:
+ ```tsx
+ {unpublishDisclosure.isOpen && selectedWorkflow && (
+ <Confirm
+ action={path.to.workflowUnpublish(selectedWorkflow.id)}
+ isOpen
+ title={t`Unpublish ${selectedWorkflow.name}?`}
+ text={t`It will stop running until you publish a version again. Nothing is deleted.`}
+ confirmText={t`Unpublish`}
+ onCancel={() => {
+ setSelectedWorkflow(null);
+ unpublishDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ setSelectedWorkflow(null);
+ unpublishDisclosure.onClose();
+ }}
+ />
+ )}
+ ```
+ Import `Confirm` from `~/components/Modals` (it is exported from that barrel alongside
+ `ConfirmDelete`).
+6. In `WorkflowsUpgradeOverlay.tsx`, remove the `active` field from every sample row and
+ whatever renders it, so the marketing preview matches the real table's columns.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp && pnpm exec biome check apps/erp/app/modules/workflows
+# Expected: no TypeScript errors; biome reports no NEW errors
+# (the repo has ~419 pre-existing warnings — leave those alone)
+```
+
+**Out of scope:** the `status` column's badge copy and filter values (unchanged by design);
+the `Table` component; saved views.
+
+---
+
+## Task 10: Builder — Publish/Unpublish button and Published tag
+
+**Depends on:** Task 8
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/WorkflowVersionStatus.tsx`
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx` — lines ~139–156, ~196–270
+- Modify: `apps/erp/app/modules/workflows/ui/WorkflowLockModal.tsx` — verify the copy at line ~104 still reads correctly
+- Copy from (precedent): the existing `confirmPublish` disclosure + `Modal` block in `BuilderHeader.tsx` (~lines 238–270) for the second confirm dialog
+
+**Steps:**
+1. `WorkflowVersionStatus.tsx`: rename the prop `isLive` → `isPublished`, the early return
+ `if (!isPublished) return null;`, and the badge text from `<Trans>Live</Trans>` to
+ `<Trans>Published</Trans>`. Keep `variant="green"`.
+2. `BuilderHeader.tsx`:
+ - Rename the locals: `live` → `published`, `isLiveVersion` → `isPublishedVersion`, both
+ reading `workflow.publishedVersionId`.
+ - Update the lock-glyph comment and the tooltip text to
+ `<Trans>This version is published. Create a new version to edit.</Trans>`.
+ - `renderStatus` passes `isPublished={v.id === workflow.publishedVersionId}`.
+ - Replace the single Publish button with a conditional. When `isPublishedVersion` is true,
+ render an **Unpublish** button (`variant="secondary"`) that opens a new
+ `confirmUnpublish` disclosure; otherwise render the existing **Publish** button. The
+ Publish button keeps its `isDisabled` on `!permissions.can("update", "workflows")` and
+ the in-flight fetcher state, but DROPS `isLiveVersion` from that condition — the
+ published version now shows Unpublish rather than a permanently disabled Publish.
+ - The Unpublish confirm posts to `path.to.workflowUnpublish(workflow.id)`. Reuse
+ `Confirm` from `~/components/Modals` (same component as Task 9) rather than hand-rolling
+ a second inline `Modal`: title `` t`Unpublish this workflow?` ``, text
+ `` t`It will stop running until you publish a version again. Nothing is deleted.` ``,
+ confirmText `` t`Unpublish` ``.
+ - Update the replace-confirm copy: title stays `` t`Publish Version ${current.versionNumber}?` ``,
+ body becomes `` t`Version ${published.versionNumber} is published now and will be replaced.` ``.
+3. Check `WorkflowLockModal.tsx` line ~104 ("Branch an editable copy of this version that you
+ can change and publish.") — already correct, leave it unless it mentions Live or Active.
+
+**Verify:**
+```bash
+grep -rn "isLive\|Trans>Live<\|is live" apps/erp/app/modules/workflows
+# Expected: no output
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no TypeScript errors
+```
+
+**Out of scope:** the builder store's `isVersionLocked` / `canChangeDefinition` /
+`canMoveNodes` logic — the locking model does not change; `IssuesPanel.tsx` ("N problems —
+not published") is already correct.
+
+---
+
+## Task 11: Update the trigger-drift SQL invariant
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `packages/checks/src/invariants/workflow-trigger-event-drift.sql`
+
+**Steps:**
+1. Rename the `active` CTE to `published`, and update the three `FROM active a` /
+ `FROM declared` references accordingly.
+2. Replace `WHERE w."active" = TRUE` with `WHERE w."publishedVersionId" IS NOT NULL`, and
+ rename `w."activeVersionId"` → `w."publishedVersionId"` in the CTE select and in the final
+ `t."workflowVersionId" <> d."activeVersionId"` comparison.
+3. Reword the three violation strings and the header comment: "an active workflow's" →
+ "a published workflow's"; "an active, promoted version" → "a published version"; "points at
+ a version that is no longer the active one" → "…no longer the published one".
+
+**Verify:**
+```bash
+pnpm --filter @carbon/checks invariants
+# Expected: workflow-trigger-event-drift reports zero violating rows
+pnpm --filter @carbon/checks workflow-events
+# Expected: passes
+```
+If the local database is unreachable these two cannot run — say so explicitly in the report
+rather than marking the task verified.
+
+**Out of scope:** every other file in `packages/checks/src/invariants/`.
+
+---
+
+## Task 12: Update the demo datasets
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `packages/database/src/datasets/tiers/workflow-definitions.ts` — `SeedWorkflow.active` at lines 63–70
+- Modify: `packages/database/src/datasets/tiers/11-workflows.ts` — lines ~83–109
+- Modify: `packages/database/src/datasets/data/satellite/workflows.ts`,
+ `data/robotics/workflows.ts`, `data/precision/workflows.ts`, `data/motor/workflows.ts` —
+ each has one `active: true` and six `active: false`
+
+**Steps:**
+1. Rename the `SeedWorkflow` field `active: boolean` → `published: boolean` and update its doc
+ comment ("Only the simplest one ships published; the rest are there to read and publish
+ deliberately.").
+2. Rename `active:` → `published:` in all four data files (7 occurrences each).
+3. In `11-workflows.ts`:
+ - The log line becomes ``ctx.log(`workflow — ${workflow.name}${workflow.published ? "" : " (draft)"}`)``.
+ - Drop `active: workflow.active` from the `insertId(ctx, "workflow", {...})` payload.
+ - The `UPDATE "workflow" SET "activeVersionId" = $1` statement becomes
+ `SET "publishedVersionId" = $1` and now runs **only when `workflow.published`** — replace
+ the old comment (which explained why it was set even when off) with: an unpublished
+ seeded workflow is a draft, so it gets no pointer and no trigger rows.
+ - Keep the `if (!workflow.published) continue;` guard that skips the trigger rows.
+4. Do NOT touch `reconcileSubscriptions`'s `active: true` — that is an
+ `eventSystemSubscription` column.
+
+**Verify:**
+```bash
+pnpm db:check:datasets
+# Expected: all four datasets apply and roll back cleanly, no errors
+```
+Row counts per table must be unchanged (same workflows, same versions, one published workflow
+with trigger rows per dataset), so `.ai/runs/*-baseline.txt` stays valid. If a count moves,
+STOP and report — do not update the baselines.
+
+**Out of scope:** the workflow definitions themselves (nodes/edges); every other tier.
+
+---
+
+## Task 13: Update AGENTS.md, rules, and the docs site
+
+**Depends on:** Tasks 3–12
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/AGENTS.md` — the Vocabulary entry (line ~9), the Publish entry (line ~13), the validation-command comment (line ~42), the file-tree comment (line ~51), the server-function bullet (line ~72)
+- Modify: `packages/workflows/AGENTS.md` — the if-and-only-if rule (~line 302)
+- Modify: `.claude/rules/workflow-matcher.md` — the `syncWorkflowTriggers` bullet ("Call it on promote, on trigger edit, and on activate/deactivate") and the surrounding `active`/pointer wording
+- Modify: `.claude/rules/workflow-engine.md` — the skipped-run reason string, if it quotes it
+- Modify: `docs/content/docs/reference/workflows.mdx` — lines ~113–117 and ~129
+
+**Steps:**
+1. `apps/erp/app/modules/workflows/AGENTS.md`: the Vocabulary entry currently explains that
+ the pointer and the boolean are separate columns *on purpose*. That reasoning is now wrong.
+ Replace it: a workflow carries `ownerId` and `publishedVersionId`; the pointer IS the on-off
+ switch — set means published and running that version, `NULL` means draft. The Publish
+ entry loses its "set `active`" step (validate → set `publishedVersionId` →
+ `syncWorkflowTriggers` → wake the scheduler) and gains Unpublish as the inverse. Replace
+ `setWorkflowActive` with `unpublishWorkflow` in the server-function bullet, and "publish/toggle"
+ with "publish/unpublish" in the command comment.
+2. `packages/workflows/AGENTS.md` ~line 302: a `workflowTriggerEvent` row exists if and only if
+ the workflow HAS A PUBLISHED VERSION and that version's trigger node lists the event; the
+ third rewrite trigger becomes "unpublishing" instead of "toggling `active`".
+3. `.claude/rules/workflow-matcher.md`: "Call it on publish, on trigger edit, and on
+ unpublish." Fix the `active`/`activeVersionId` wording in the same section.
+4. `.claude/rules/workflow-engine.md`: update the skipped reason string if quoted.
+5. `docs/content/docs/reference/workflows.mdx`:
+ - **Delete** the entire `<Callout type="warn" title="“Published” and “Active” are different switches">` block (lines ~113–115). It documents a distinction that no longer exists.
+ - Rewrite the publishing paragraph: publishing a version makes it the one that runs;
+ **"Unpublish"** stops the workflow and leaves every version intact, and publishing again
+ starts it. There is no separate on/off switch.
+ - Change *"This version is live. Create a new version to edit."* to *"This version is
+ published…"* (line ~117) and "promote another one mid-run" wording if it says "live".
+ - Line ~129: the Update permission row's "toggle active" becomes "unpublish".
+
+**Verify:**
+```bash
+grep -rn -i "active switch\|activeVersionId\|are different switches" docs/content/docs/reference/workflows.mdx apps/erp/app/modules/workflows/AGENTS.md packages/workflows/AGENTS.md .claude/rules/workflow-matcher.md
+# Expected: no output
+pnpm --filter docs build
+# Expected: build succeeds (MDX must still parse after the callout removal)
+```
+
+**Out of scope:** every other docs page; `.claude/rules/workflow-event-system.md` (its
+`active` references are `eventSystemSubscription`, correctly named).
+
+---
+
+## Task 14: Extract i18n strings
+
+**Depends on:** Tasks 9, 10
+**Files:**
+- Modify: `packages/locale/locales/*/erp.po` (generated by the commands below)
+
+**Steps:**
+1. Run:
+ ```bash
+ pnpm lingui:extract && pnpm lingui:clean
+ ```
+2. Fill the new strings in the other locales with the `/translate` skill (it fans the work out
+ to cheap models and merges deterministically). Do not hand-translate.
+3. Expect churn: on this branch `lingui:extract` rewrites large parts of the catalogs. Keep the
+ commit for this task separate from the code tasks so review stays readable.
+
+**Verify:**
+```bash
+grep -c 'msgid "Published"' packages/locale/locales/en/erp.po
+# Expected: at least 1
+```
+
+**Out of scope:** the `mes` catalog (nothing in `apps/mes` touches workflows); adding locales.
+
+---
+
+## Task 15: End-to-end verification
+
+**Depends on:** all previous tasks
+**Files:** none (verification only)
+
+**Steps:**
+1. Run the full scoped gate set:
+ ```bash
+ pnpm exec turbo run typecheck --filter=erp --filter=@carbon/jobs --filter=@carbon/workflows --filter=@carbon/database
+ pnpm exec biome check
+ pnpm --filter @carbon/jobs test
+ pnpm --filter @carbon/workflows test
+ pnpm db:check:datasets
+ pnpm --filter @carbon/checks workflow-events
+ ```
+2. Confirm the words are gone:
+ ```bash
+ grep -rn "workflow.active\|activeVersionId" apps/erp/app packages/workflows/src packages/jobs/src packages/checks/src
+ # Expected: no output
+ ```
+3. Browser pass with the `/auth` then `/test` skills, against `/x/workflows`, covering spec
+ acceptance criteria 4–8: publish a version (tag appears, list flips to Published),
+ unpublish from the builder (tag gone, list reads Draft), unpublish from the list row menu,
+ republish the same version, and confirm the Active checkbox column is gone from the table.
+ Ask the user before driving the browser.
+4. Report which acceptance criteria are proven by an actual command or browser run and which
+ are not. Do not claim a criterion passed without output to back it.
+
+**Verify:** every command above exits zero; every criterion in the spec's Acceptance criteria
+list is either demonstrated or explicitly reported as not demonstrated.
+
+**Out of scope:** `pnpm run build` (full repo build) unless something above fails in a way that
+suggests a build-only breakage; whole-repo `turbo run typecheck --filter='*'` (it OOMs).
diff --git a/.ai/research/2026-08-24-workflow-version-terminology.md b/.ai/research/2026-08-24-workflow-version-terminology.md
new file mode 100644
index 0000000000..1696142c0e
--- /dev/null
+++ b/.ai/research/2026-08-24-workflow-version-terminology.md
@@ -0,0 +1,85 @@
+# How other workflow builders name version states
+
+Research date: 2026-08-24. Question: Carbon shows three words — **Published**, **Live**,
+**Active** — for what a user experiences as two ideas. Should they become "Finalized"?
+
+## What Carbon has today
+
+| Surface | Label | Backing field |
+|---|---|---|
+| `WorkflowsTable.tsx:98` | `Published` / `Draft` badge | `workflow.activeVersionId != null` |
+| `WorkflowVersionStatus.tsx:12` | `Live` badge on a version | version id == `activeVersionId` |
+| `WorkflowActiveCheckbox.tsx` / `WorkflowActiveSwitch.tsx` | `Active` toggle | `workflow.active` boolean |
+| `BuilderHeader.tsx:234` | `Publish` button | sets `activeVersionId` |
+
+So **Published** and **Live** are the *same fact* seen from two levels (the workflow has a
+chosen version / this version is the chosen one), and **Active** is a genuinely separate
+on-off switch. The DB column is even named `activeVersionId`, which is why "active" leaked
+into two unrelated meanings.
+
+## Competitor scan
+
+**n8n 2.0 (shipped Jan 2026) — the most direct precedent.** n8n *deleted* the
+active/inactive toggle and replaced it with Publish / Unpublish. Autosave writes a new
+saved version on every edit; only the **published** version responds to triggers. Two
+words total: *saved* (draft) and *published*. They hit exactly Carbon's confusion and
+resolved it by collapsing "active" into "published", not by inventing a third word.
+
+**Retool Workflows.** Draft is the "current working version"; publishing creates a
+numbered release. The Releases list tags the running one **Live**. Note the shape: `Live`
+is a *marker on the published version*, not a separate state — the same relationship
+Carbon's `Live` badge actually has. Retool has no separate active toggle.
+
+**Zapier.** A Zap is a **draft** until you **Publish**; each publish makes a new version;
+the previously published Zap stays running while you edit the draft. Zapier does keep a
+separate **on/off** switch, but it is described as turning the Zap on or off — never
+"active version".
+
+**Salesforce Flow.** Version statuses are **Active**, **Draft**, **Obsolete**,
+**InvalidDraft**. Activating a new version makes the previous one *Obsolete*. Salesforce
+uses "Active" for the version and has no separate enable toggle, so there is no collision.
+
+**Workato.** Versions are labelled **current**; the running/stopped concept is
+**Start recipe / Stop recipe**. Again: one word per concept.
+
+**HubSpot.** Draft vs published (version history), no on/off toggle; users have been
+asking for the Zapier-style draft-over-live model.
+
+## Findings
+
+1. **Nobody ships the word "Finalized".** Zero of the six use it. It reads as an
+ approval/document term (Carbon itself uses Finalized-ish language for quotes and
+ documents), and it does not tell the user the version is *the one that runs*. Changing
+ Published → Finalized would trade a term customers already know from Zapier/n8n/HubSpot
+ for one they know from nowhere.
+2. **The real bug is three labels for two concepts, not the choice of label.** Every tool
+ surveyed keeps exactly one word per concept: one for "this is the definition that runs"
+ (published / active / current) and, if it exists at all, one for "the whole thing is
+ switched on".
+3. **Two words dominate: Draft and Published.** Zapier, Retool, n8n and HubSpot all landed
+ there independently. That is the safe, recognisable vocabulary.
+4. **"Live" is a tag, not a state.** Retool proves the pattern is fine *as long as* it only
+ ever decorates the published version in a version list — which is what Carbon's badge
+ already does.
+
+## Recommended direction (not yet implemented)
+
+- Keep **Draft / Published** as the version vocabulary. Keep the **Publish** button.
+- Either drop the `Live` badge in favour of `Published`, or keep `Live` *only* in the
+ version-history list as Retool does — never alongside a second "Published" badge on the
+ same screen.
+- Rename the `Active` toggle so it stops competing: **Enabled / Paused** (or **On / Off**),
+ or follow n8n and remove it entirely, making Unpublish the way to stop a workflow.
+ Whichever is chosen, "active" should disappear from user-facing copy even though
+ `activeVersionId` stays in the schema.
+
+## Sources
+
+- https://docs.n8n.io/build/understand-workflows/save-and-publish-workflows
+- https://support.n8n.io/article/understanding-workflow-publishing-in-n-8-n-2-0
+- https://docs.retool.com/workflows/guides/version-and-publish
+- https://help.zapier.com/hc/en-us/articles/9693520498445-Create-Zap-drafts-and-versions
+- https://zapier.com/blog/introducing-drafts/
+- https://gearset.com/blog/flows-and-flow-definitions/
+- https://docs.workato.com/recipes/version-management.html
+- https://knowledge.hubspot.com/website-pages/restore-a-previous-version-of-content
diff --git a/.ai/reviews/2026-08-24-workflow-publish-unpublish-review.md b/.ai/reviews/2026-08-24-workflow-publish-unpublish-review.md
new file mode 100644
index 0000000000..58b59497cd
--- /dev/null
+++ b/.ai/reviews/2026-08-24-workflow-publish-unpublish-review.md
@@ -0,0 +1,292 @@
+# Thermo-nuclear review — workflow publish/unpublish
+
+Branch `fix/workflow-version-copy-changes`, working tree vs `main`.
+34 files, +344 / −266, plus one migration and one new route; three files deleted.
+
+Verified green before reviewing: `pnpm exec turbo run typecheck --filter=erp` (17.8s, clean),
+`pnpm exec biome check` on every touched path (3 formatter errors found and fixed — see
+finding 7), 490 `@carbon/jobs` tests, 431 `@carbon/workflows` tests, all four demo datasets.
+
+**Verdict: do not merge as-is.** The change itself is the right shape — replacing two switches
+with one pointer genuinely deletes concepts rather than rearranging them, and the migration is
+careful. But it leaves the version-lock rule implemented four times, ships the same confirm
+dialog twice, and strips the cover from a load-bearing WHERE clause with no comment. Findings
+1–4 are each a few lines and should land before merge.
+
+---
+
+## 1. The version-lock rule now has four implementations, and its own helper is an identity wrapper
+
+**Structural / single-source-of-truth. High conviction.**
+
+`apps/erp/app/modules/workflows/workflows.server.ts:25`
+
+```typescript
+export function getWorkflowLockFlags({
+ versionId,
+ publishedVersionId
+}: {
+ versionId: string;
+ publishedVersionId: string | null;
+}) {
+ const isPublished =
+ publishedVersionId !== null && versionId === publishedVersionId;
+ return { isPublished, isVersionLocked: isPublished };
+}
+```
+
+Three problems stacked in nine lines:
+
+- It returns **one boolean under two names**, and `isPublished` is never read from it by any
+ caller (grep confirms: the only destructure anywhere is `const { isVersionLocked } = ...`).
+- Its **only** caller is `checkWorkflowVersionLock`, twenty lines below it in the same file.
+- `publishedVersionId !== null &&` is dead. `versionId` is a non-empty `string` at both call
+ sites (`params.id` guarded by `if (!id) throw`, and `z.string().min(1)` in
+ `workflowPublishValidator`), so `versionId === null` is unreachable and the bare equality
+ already yields `false` when the pointer is null.
+
+Meanwhile the same rule is re-derived inline in two other layers:
+
+- `apps/erp/app/routes/x+/workflow+/$id.tsx:149` — `isVersionLocked: versionId === workflow.publishedVersionId`
+- `apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx:158` — `const isPublishedVersion = versionId === workflow.publishedVersionId;`
+
+Under the old two-switch model (`active` boolean AND `activeVersionId` pointer) a named helper
+earned its keep, because "is this version locked" was a compound question. That is precisely
+what this PR deleted. The question is now a single equality, and a helper wrapping `a === b`
+in an object literal is indirection with nothing behind it.
+
+**Remedy — delete it.** In `checkWorkflowVersionLock`:
+
+```typescript
+ return versionId === workflow.publishedVersionId
+ ? { ok: false, message: LOCKED_VERSION_MESSAGE }
+ : { ok: true };
+```
+
+Drop `getWorkflowLockFlags` and its parameter type entirely; keep `LOCKED_VERSION_MESSAGE`
+exported. Net −13 lines, one fewer module export, one fewer name for one idea, and the two
+inline call sites stop looking like they are bypassing a canonical helper — because there
+isn't one to bypass.
+
+(If you would rather keep a shared predicate, then it must be used by all three call sites and
+should be a plain `isVersionPublished(versionId, publishedVersionId): boolean` — not a flags
+object. The current shape is the one option that is strictly worse than both alternatives.)
+
+---
+
+## 2. The Unpublish confirm dialog is built twice
+
+**Duplication / SSOT. High conviction.**
+
+`apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx:283`
+
+```tsx
+ <Confirm
+ action={path.to.workflowUnpublish(selectedWorkflow.id)}
+ isOpen
+ title={t`Unpublish ${selectedWorkflow.name}?`}
+ text={t`It will stop running until you publish a version again. Nothing is deleted.`}
+ confirmText={t`Unpublish`}
+```
+
+`apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx:253`
+
+```tsx
+ <Confirm
+ action={path.to.workflowUnpublish(workflow.id)}
+ isOpen
+ title={t`Unpublish this workflow?`}
+ text={t`It will stop running until you publish a version again. Nothing is deleted.`}
+ confirmText={t`Unpublish`}
+```
+
+Same route builder, same body copy, same button label — and already drifting on the title. Two
+call sites appearing in the same PR is the moment to extract, not the moment to copy. The
+consequence of leaving it: the next copy edit lands in one of the two and the product says two
+different things about the same action, which is the exact class of bug this PR exists to fix.
+
+**Remedy.** `apps/erp/app/modules/workflows/ui/ConfirmUnpublishWorkflow.tsx`:
+
+```tsx
+export function ConfirmUnpublishWorkflow({
+ workflowId,
+ name,
+ onClose
+}: {
+ workflowId: string;
+ name: string;
+ onClose: () => void;
+}) {
+ const { t } = useLingui();
+ return (
+ <Confirm
+ action={path.to.workflowUnpublish(workflowId)}
+ isOpen
+ title={t`Unpublish ${name}?`}
+ text={t`It will stop running until you publish a version again. Nothing is deleted.`}
+ confirmText={t`Unpublish`}
+ onCancel={onClose}
+ onSubmit={onClose}
+ />
+ );
+}
+```
+
+Take the named title in both places — a confirm dialog should name what it is about to change,
+and the builder has `workflow.name` right there. That also collapses three Lingui message ids
+to two.
+
+---
+
+## 3. `scanDue`'s "redundant" WHERE is load-bearing, and now nothing says so
+
+**Legibility of a non-obvious invariant. High conviction — this one is a future outage.**
+
+`packages/jobs/src/workflows/scheduler.ts:38`
+
+```typescript
+ .innerJoin("workflowVersion as v", (join) =>
+ join
+ .onRef("v.id", "=", "w.publishedVersionId")
+ .onRef("v.companyId", "=", "w.companyId")
+ )
+ ...
+ .where("w.publishedVersionId", "is not", null)
+```
+
+To any reader this WHERE is obviously dead: an inner join on `v.id = w.publishedVersionId`
+cannot match a NULL. It is not dead. The scheduler's index, created by this PR's own migration,
+is **partial**:
+
+```sql
+CREATE INDEX "workflow_due_idx" ON "workflow" ("nextRunAt")
+ WHERE "nextRunAt" IS NOT NULL AND "publishedVersionId" IS NOT NULL;
+```
+
+Postgres proves a partial-index predicate from that relation's own restriction clauses, not
+from join quals, so deleting the WHERE drops the scan to a seq scan over `workflow` on every
+scheduler wake. Before this PR the clause was camouflaged as `.where("w.active", "=", true)`
+next to a not-null test and looked purposeful; the rename stripped the camouflage and left an
+apparently-pointless line sitting next to the join, one cleanup PR away from deletion.
+
+**Remedy.** A comment naming the index, e.g. above the WHERE:
+
+```typescript
+ // Reads as redundant next to the join, but it is what lets the planner match the partial
+ // `workflow_due_idx` — a join qual cannot prove that predicate.
+```
+
+Related, lower stakes: the narrowing `.filter((r): r is typeof r & { publishedVersionId: string } => r.publishedVersionId !== null)`
+at `scheduler.ts:66` is now purely a type device with no runtime effect (the join guarantees
+it). Fine to keep as cast-avoidance, but it is the second thing in this function that reads as
+a runtime guard and isn't.
+
+Also adjacent, not introduced here: `scanDue` awaits its `due` query and its `futureRow` query
+sequentially although they are independent. `Promise.all` would be both faster and no less
+readable. Optional.
+
+---
+
+## 4. `log.ts` reaches for raw SQL to compute a boolean the query could just select
+
+**Boundary / type cleanliness. Medium-high conviction.**
+
+`packages/jobs/src/workflows/engine/log.ts:55`
+
+```typescript
+ sql<boolean>`w."publishedVersionId" IS NOT NULL`.as("workflowPublished"),
+```
+
+and then in the mapper:
+
+```typescript
+ workflowPublished: row.workflowPublished === true,
+```
+
+Two things worth undoing. The hand-written SQL fragment is the only raw string in an otherwise
+fully typed Kysely select, so the compiler stops checking that column name — a future rename of
+`publishedVersionId` typechecks clean here and fails at runtime, which is exactly the failure
+mode a migration-and-rename PR should be closing. And `=== true` is a defensive coercion for a
+nullable boolean column that no longer exists; the expression above it cannot be null.
+
+**Remedy.** Select the column and derive the flag in TypeScript:
+
+```typescript
+ "w.publishedVersionId as publishedVersionId",
+ ...
+ workflowPublished: row.publishedVersionId !== null,
+```
+
+Same `RunContext` shape, no raw SQL, no dead coercion, and "the pointer means published" lives
+in the language where the field's doc comment already explains it.
+
+---
+
+## 5. Consider lifting the publish/unpublish cluster out of `BuilderHeader`
+
+**Decomposition. Medium conviction — optional, but it is the natural home for finding 2.**
+
+`BuilderHeader.tsx` is 300 lines and now holds: layout, inline rename (own fetcher + a
+`settled` ref to defeat blur-after-Enter), the save marker, the version menu, a publish fetcher,
+an issues `useEffect` that writes to the builder store, two disclosures, and two dialogs. Well
+under the 1k threshold, so this is not a blocker — but the publish/unpublish block is a
+self-contained unit with its own state, and extracting `PublishControls.tsx` would leave the
+header reading as layout plus title.
+
+One thing to preserve if you do: the asymmetry where **unpublish uses the canonical `Confirm`
+while publish hand-rolls a `Modal`** is correct, not sloppy. Publish must post `versionId` in
+the body and read `issues` back off its own fetcher to drive the node outlines, and `Confirm`
+owns its form and gives the caller no response. That deserves a one-line comment, or a reader
+will "unify" the two and silently break the issues panel.
+
+---
+
+## 6. Checked and deliberately not flagged
+
+- `packages/database/src/datasets/tiers/11-workflows.ts` — the new `if (!workflow.published) continue;`
+ sits after the version insert and before both the pointer UPDATE and the trigger rows, so a
+ draft seed gets a readable version and no dispatch rows. Correct, and the comment earns its place.
+- `packages/jobs/src/workflows/engine/execute.ts` — testing workflow-level publication rather
+ than "is this run's version still the published one" is the documented decision (in-flight
+ runs keep their version). Right call, and the const rename is faithful.
+- `variant="gray"` exists in `packages/react/src/Badge.tsx`. `WorkflowsUpgradeOverlay`'s badges
+ now match the real table's green/gray Published/Draft instead of outline/secondary
+ Active/Inactive — a small consistency win the PR gets for free.
+- `packages/workflows/src/sync.ts` — the gate collapsing from `workflow?.active && workflow.activeVersionId`
+ to `workflow?.publishedVersionId` is the cleanest edit in the diff. One condition, one comment,
+ and unpublish stops the workflow through the existing empty-desired-set path rather than a new branch.
+- Comment audit: the new comments are sparse and answer real questions (why sync on unpublish,
+ why the tier skips, why the route carries no body, what the pointer means). No narration found.
+ The one comment that should go is the *code* it documents — see finding 1.
+
+## 7. Fixed during the review
+
+`pnpm exec biome check` reported three formatter errors on files this PR touched
+(`WorkflowsTable.tsx`, `WorkflowsUpgradeOverlay.tsx`, `tiers/11-workflows.ts`). Applied
+`biome check --write` on exactly those three; re-check is clean. The remaining `noConsole` /
+`noEmptyBlockStatements` hits under `packages/database/src/datasets` are pre-existing warnings
+in files this PR did not touch.
+
+## Resolution
+
+Findings 1–4 applied, plus finding 5's comment (the extraction itself deferred):
+
+- `getWorkflowLockFlags` deleted; `checkWorkflowVersionLock` compares directly. `AGENTS.md`
+ updated, since it named the helper.
+- New `apps/erp/app/modules/workflows/ui/ConfirmUnpublishWorkflow.tsx` is the single copy of
+ the dialog; both `WorkflowsTable` and `BuilderHeader` render it, and both now name the workflow.
+- Comment added above `scanDue`'s WHERE naming `workflow_due_idx`.
+- `log.ts` selects `w.publishedVersionId` and derives the boolean in TypeScript; the raw `sql`
+ tag and the `=== true` are gone.
+- Comment on the publish modal explaining why it is not a `Confirm`.
+
+Re-verified after the fixes: `pnpm exec turbo run typecheck --filter=erp` clean,
+`pnpm exec turbo run test typecheck --filter=@carbon/jobs` 490 tests pass,
+`pnpm exec biome check` clean on both trees.
+
+## Still outstanding on the branch (not review findings)
+
+- `pnpm --filter @carbon/checks invariants` and `... workflow-events`
+- `pnpm --filter docs build` (the MDX callout removal must still parse)
+- `pnpm lingui:extract && pnpm lingui:clean`, then the other locales
+- browser pass over acceptance criteria 4–8
diff --git a/.ai/specs/2026-08-24-workflow-publish-unpublish.md b/.ai/specs/2026-08-24-workflow-publish-unpublish.md
new file mode 100644
index 0000000000..37a7793bc7
--- /dev/null
+++ b/.ai/specs/2026-08-24-workflow-publish-unpublish.md
@@ -0,0 +1,316 @@
+# Workflows: one switch — Publish / Unpublish
+
+- **Status:** Approved (pending user sign-off)
+- **Date:** 2026-08-24
+- **Author:** aashu (with Claude)
+- **Research:** [.ai/research/2026-08-24-workflow-version-terminology.md](../research/2026-08-24-workflow-version-terminology.md)
+
+## Problem
+
+A workflow today has three user-facing words for what a customer experiences as two
+ideas, and one of them is a lie:
+
+| Surface | Word | Backing data |
+|---|---|---|
+| `WorkflowsTable` status column | **Published** / Draft | `workflow.activeVersionId != null` |
+| Version menu, in the builder | **Live** | version id `== workflow.activeVersionId` |
+| List column + builder switch | **Active** | `workflow.active` (a separate boolean) |
+
+"Published" and "Live" are the *same fact* seen from two levels. "Active" is a genuinely
+separate kill switch, and it stole the word "active" from the pointer column
+(`activeVersionId`) that means something else entirely. Our own documentation has a warning
+callout about it — `docs/content/docs/reference/workflows.mdx:113`, *"'Published' and
+'Active' are different switches"* — which is the tell that the model is too complicated to
+explain. A workflow only runs when it is active **and** has a live version, and nothing on
+screen says so.
+
+## Goals
+
+- One concept, one word. **Publishing is the on switch. Unpublishing is the off switch.**
+- The word for the running state is **Published**, everywhere: badge, version tag, docs, code.
+- "Active" and "Live" disappear from every user-facing string and from the workflow schema.
+- No customer's workflow silently starts or stops running because of this change.
+
+## Non-goals
+
+- No change to how workflows are authored, validated, executed, scheduled, retried, or logged.
+- No change to the version-locking model (publishing still freezes a version; editing still
+ means creating a new one).
+- No approval/review step before publishing. Not asked for.
+- No rename of `eventSystemSubscription.active` — a different table, a different concept,
+ correctly named. Leave it alone.
+
+## Design
+
+### 1. Data model
+
+One migration, in this order:
+
+```sql
+-- A workflow that was published but switched OFF is deliberately paused. Collapsing the
+-- two flags into one would silently resume it, so unpublish it first, before the column
+-- that records the user's intent is gone.
+UPDATE "workflow" SET "activeVersionId" = NULL WHERE "active" = FALSE;
+
+-- ...and its trigger rows with it, to stay consistent with syncWorkflowTriggers, the only
+-- other writer of that table. Must run BEFORE the column is dropped.
+DELETE FROM "workflowTriggerEvent" te
+ USING "workflow" w
+ WHERE te."workflowId" = w."id" AND te."companyId" = w."companyId"
+ AND w."active" = FALSE;
+
+-- Postgres SILENTLY DROPS any index whose predicate names a dropped column, so
+-- "workflow_due_idx" (partial on "active" = TRUE) has to be rebuilt, not just left alone.
+DROP INDEX IF EXISTS "workflow_due_idx";
+
+ALTER TABLE "workflow" DROP COLUMN "active";
+ALTER TABLE "workflow" RENAME COLUMN "activeVersionId" TO "publishedVersionId";
+ALTER TABLE "workflow"
+ RENAME CONSTRAINT "workflow_activeVersionId_fkey" TO "workflow_publishedVersionId_fkey";
+
+CREATE INDEX "workflow_due_idx" ON "workflow" ("nextRunAt")
+ WHERE "nextRunAt" IS NOT NULL AND "publishedVersionId" IS NOT NULL;
+```
+
+Three details that are easy to get wrong here:
+
+- **`workflow_due_idx` is a partial index on `"active" = TRUE`** — this is the scheduler's
+ due-workflow index. Dropping the column takes the index with it *without an error*, so the
+ scheduler would quietly fall back to a sequential scan. Rebuilding it is not optional. Its
+ predicate loses the `active` half and keeps the other two, which is exactly the collapse
+ this change is about.
+- **A column rename does not rename its constraint.** `workflow_activeVersionId_fkey` has to
+ be renamed explicitly or the schema keeps the old word in the place people read it from.
+- The FK's `ON DELETE SET NULL ("activeVersionId")` names its column explicitly on purpose
+ (see `.ai/lessons.md` — a bare `SET NULL` would null `companyId` too and make the parent
+ row undeletable). `RENAME COLUMN` carries that clause across intact; do **not** drop and
+ re-add the constraint.
+
+After this, `workflow.publishedVersionId` is the single source of truth:
+
+- `NULL` → the workflow is a **Draft**. Nothing fires. No `workflowTriggerEvent` rows exist.
+- set → the workflow is **Published**. That version is the one that runs.
+
+In practice the trigger rows the `DELETE` targets should already be absent (turning a
+workflow off syncs them away), so it is belt-and-braces against historical drift — but it is
+exactly what the `workflow-trigger-event-drift` invariant checks, so a stale row would
+otherwise fail CI right after the migration lands.
+
+`nextRunAt`, `canvasState`, and every `workflowVersion` column are untouched.
+
+Then `pnpm run generate:types`. Note that `packages/database/src/types.ts`,
+`swagger-docs-schema.ts` and `supabase/functions/lib/types.ts` already carry uncommitted
+regeneration drift on this branch — regenerating will absorb it, which is correct, but the
+diff will be wider than this feature.
+
+**No new column to remember the last published version.** Resuming means opening the
+builder, picking a version and pressing Publish — the version menu is already the place
+you choose a version, and every version now carries a Publish button when nothing is
+published. Adding a `lastPublishedVersionId` would put a second version pointer on the same
+row, which is the duplication this whole change exists to remove.
+
+### 2. Runtime — three gates, all narrowing to one condition
+
+Every place that reads `workflow.active` today is reading "is this workflow on". After the
+change that question is `publishedVersionId IS NOT NULL`.
+
+**`packages/workflows/src/sync.ts`** — `syncWorkflowTriggers` selects
+`["active", "activeVersionId"]` and gates on `workflow?.active && workflow.activeVersionId`.
+It becomes a select of `["publishedVersionId"]` gated on `workflow?.publishedVersionId`.
+Everything downstream (trigger-row rewrite, `eventSystemSubscription` reconciliation,
+`nextRunAt`) is unchanged, including the required `lockCompany` first statement. This one
+edit is what makes unpublish actually stop a workflow: no trigger rows, no dispatch.
+
+**`packages/jobs/src/workflows/scheduler.ts`** — drop the two `.where("w.active", "=", true)`
+predicates; the existing `.where("w.publishedVersionId", "is not", null)` beside each of them
+already expresses the whole condition.
+
+**`packages/jobs/src/workflows/engine/execute.ts`** — the last-moment guard
+(`if (!context.workflowActive) → Skipped`) becomes `if (!context.workflowPublished)`, fed by
+`log.ts` selecting `w."publishedVersionId" IS NOT NULL` instead of `w.active`. This
+deliberately tests *"is the workflow published at all"*, not *"is this run's version still
+the published one"* — a run already in flight keeps using the version it started with even
+if a newer one is promoted mid-run, which is documented behaviour we are not changing. The
+`SWITCHED_OFF` reason string becomes:
+
+> `"This workflow was unpublished before the run started."`
+
+That string is written into `workflowRun.statusReason` and shown in run history, so it is
+user-facing copy, not a comment.
+
+### 3. Server + service layer
+
+- `publishWorkflowVersion` (`workflows.server.ts`) drops `active: true` from its update and
+ sets `publishedVersionId`. Validation, the `syncAndWake` call, and the issue-return shape
+ are unchanged.
+- `setWorkflowActive` becomes **`unpublishWorkflow(client, { workflowId, companyId, userId })`**
+ — sets `publishedVersionId: null` and calls the same `syncAndWake`. It takes no boolean:
+ there is only one direction, because publishing needs a version id and validation.
+- `getWorkflows` / `getWorkflow` (`workflows.service.ts`) swap the column in their `select`
+ lists, and the `Published`/`Draft` static filter switches to
+ `.not("publishedVersionId", "is", null)` / `.is("publishedVersionId", null)`. The
+ translation comment there stays accurate and gets the new column name.
+- `workflowToggleValidator` is deleted from `workflows.models.ts` — unpublish carries no
+ fields.
+
+### 4. Routes
+
+| Before | After |
+|---|---|
+| `x+/workflow+/$id.toggle.tsx` (reads `active` checkbox) | `x+/workflow+/$id.unpublish.tsx` (no body) |
+| `path.to.workflowToggle(id)` | `path.to.workflowUnpublish(id)` |
+
+`$id.publish.tsx` keeps its path, validator and permission gate (`update: "workflows"`).
+The unpublish route gates on the same permission. Both remain the only authorization gate
+in front of `syncWorkflowTriggers`, which bypasses RLS via Kysely.
+
+### 5. UI
+
+**List page (`WorkflowsTable.tsx`)**
+
+- The `active` column and `WorkflowActiveCheckbox` are removed; `WorkflowActiveCheckbox.tsx`
+ and the unused `WorkflowActiveSwitch.tsx` are deleted.
+- The Status column keeps its `Published` / `Draft` badges and its static filter exactly as
+ they read today — the copy customers already see does not change.
+- The row context menu gains **Unpublish** between *Rename Workflow* and *Delete Workflow*,
+ disabled unless `permissions.can("update", "workflows")` **and** the row is published. It
+ posts to `path.to.workflowUnpublish(row.id)` and shows a confirm modal
+ (*"Unpublish {name}? It will stop running until you publish a version again."*) because it
+ stops production automation. Publishing is not offered from the list: it needs a version
+ choice and can fail validation with issues only the canvas can show.
+
+**Builder (`BuilderHeader.tsx`)**
+
+- `live` / `isLiveVersion` become `published` / `isPublishedVersion`.
+- The primary button is **Publish** when the open version is not the published one, and
+ **Unpublish** when it is — replacing today's dead disabled-Publish state on the published
+ version. So: nothing published → every version offers Publish; something published → the
+ published version offers Unpublish. Unpublish gets the same confirm modal as the list.
+- The replace-confirm modal copy: *"Version N is published now and will be replaced."*
+- The lock tooltip: *"This version is published. Create a new version to edit."*
+
+**Version menu (`WorkflowVersionStatus.tsx`)** — prop `isLive` → `isPublished`, badge text
+`Live` → `Published`. Still renders nothing for every other version, so exactly one version
+in the menu ever carries a tag.
+
+**Also** `WorkflowLockModal.tsx` (*"…change and publish"* — already correct, verify),
+`WorkflowsUpgradeOverlay.tsx` (its fake sample rows carry an `active` field that must match
+the real table's new shape), and `IssuesPanel.tsx` (*"N problems — not published"* — already
+correct).
+
+Unrelated `active` identifiers in `TriggerForm.tsx` (weekday toggles), `catalog.ts` /
+`recordPickers.tsx` / `NodePalette.tsx` (custom-field `active`) are **not** touched.
+
+New and changed strings are marked with Lingui macros as the surrounding code does, then
+`pnpm lingui:extract` and the `/translate` skill fill the catalogs.
+
+### 6. Demo datasets
+
+`packages/database/src/datasets/tiers/11-workflows.ts` sets `activeVersionId` for every
+seeded workflow and then skips trigger rows for the off ones. That two-step exists only
+because the two flags were separate. It collapses:
+
+- `SeedWorkflow.active` → `SeedWorkflow.published` (type + the four
+ `data/{satellite,robotics,precision,motor}/workflows.ts` files, one `active: true` and six
+ `active: false` each).
+- Set `publishedVersionId` **only** when `published`; keep the `continue` that skips trigger
+ rows for the rest. The log line becomes `(draft)` instead of `(off)`.
+- `reconcileSubscriptions`'s `active: true` is an `eventSystemSubscription` column — untouched.
+
+Row counts per table are unchanged (same workflows, same versions, same one published
+workflow with trigger rows), so the `.ai/runs/*-baseline.txt` files stay valid.
+`pnpm db:check:datasets` is the gate.
+
+### 7. Conformance + docs
+
+- `packages/checks/src/invariants/workflow-trigger-event-drift.sql` — the `active` CTE drops
+ its `WHERE w."active" = TRUE` and filters `w."publishedVersionId" IS NOT NULL` instead;
+ three violation strings mentioning "active" are reworded to "published". Rename the CTE to
+ `published` so the SQL reads honestly.
+- `apps/erp/app/modules/workflows/AGENTS.md` — the Vocabulary entry that explains *why* the
+ boolean and the pointer are separate columns is now wrong and must be replaced with the
+ single-pointer model; the Publish bullet loses its "set `active`" step.
+- `packages/workflows/AGENTS.md` (~line 302) — the if-and-only-if rule loses "is active".
+- `.claude/rules/workflow-matcher.md` — `syncWorkflowTriggers` is called "on publish, on
+ trigger edit, and on unpublish"; the `active`/pointer wording in the sync section.
+- `.claude/rules/workflow-engine.md` — the skipped-run reason string.
+- `docs/content/docs/reference/workflows.mdx` — **delete** the *"'Published' and 'Active' are
+ different switches"* callout, rewrite the publish paragraph as one switch, change *"This
+ version is live"* to *"…is published"*, and drop "toggle active" from the Update-permission
+ row.
+
+## Design decisions
+
+| Decision | Choice | Why |
+|---|---|---|
+| Model | Publish/Unpublish is the only on-off switch; published version = the running version | n8n 2.0 removed its active/inactive toggle for exactly this reason; Zapier, Retool and HubSpot all ship a single publish switch |
+| State word | **Published** everywhere (badge, version tag, docs) | Shares a root word with the Publish button, which is the easiest pairing to learn; also leaves today's list badge copy unchanged |
+| "Live" | Removed from all copy | It was a second word for the same fact as the Published badge — the original confusion |
+| Column | `activeVersionId` → `publishedVersionId`, in the same migration | "Active" leaked from this column into the UI in the first place; leaving it keeps the trap set. Mechanical and typechecker-enforced |
+| Re-arm after unpublish | Nothing stored; publish a version from the version menu | A second version pointer would reintroduce the duplication being removed |
+| Paused workflows at migration time | `UPDATE … SET activeVersionId = NULL WHERE active = FALSE` before the drop | A deliberately-paused workflow must not silently resume. This is the one irreversible-feeling step and it fails safe (stopped, not started) |
+| `workflow_due_idx` | Dropped and recreated without the `active` half of its predicate | Postgres drops a partial index whose predicate names a dropped column, silently — the scheduler would lose its index with no error anywhere |
+| Engine guard | `publishedVersionId IS NOT NULL`, not "is this run's version still published" | Faithful translation of the old `active` guard; in-flight runs keep their version, which is documented behaviour |
+| List page | Status badge + **Unpublish** in the row context menu; no toggle column | Keeps a one-click stop reachable from the list. A toggle would lie: publishing can fail validation and needs a version choice |
+| Unpublish confirmation | Confirm modal on both list and builder | It stops live automation; a misclick has production consequences |
+| `eventSystemSubscription.active` | Untouched | Different table, different concept, correctly named |
+
+## Acceptance criteria
+
+1. **Schema** — `workflow` has no `active` column and has `publishedVersionId`;
+ `pnpm exec turbo run typecheck --filter=erp --filter=@carbon/jobs --filter=@carbon/workflows`
+ passes with no reference to `workflow.active` anywhere outside generated types.
+2. **Index survived** — after `pnpm db:migrate`,
+ `SELECT indexdef FROM pg_indexes WHERE indexname = 'workflow_due_idx'` returns one row and
+ its predicate names `publishedVersionId` and `nextRunAt` only.
+3. **Migration safety** — on a database seeded with the `satellite` dataset plus a workflow
+ manually set to `active = false, activeVersionId = <v>`, after `pnpm db:migrate` that
+ workflow has `publishedVersionId IS NULL`, has zero `workflowTriggerEvent` rows, and shows
+ **Draft** in the list.
+4. **Publish** — in the builder on an unpublished workflow, every version's primary button
+ reads **Publish**; no version carries a tag. Pressing Publish on a valid version writes
+ `publishedVersionId`, tags that version **Published**, creates its `workflowTriggerEvent`
+ rows, and the list row flips to **Published**.
+5. **Unpublish from the builder** — on the published version the button reads **Unpublish**;
+ confirming clears `publishedVersionId`, removes every `workflowTriggerEvent` row for that
+ workflow, drops the **Published** tag, and the list row reads **Draft**. Triggering the
+ workflow's event afterwards creates no `workflowRun`.
+6. **Unpublish from the list** — the row menu's Unpublish is disabled on a Draft row and on a
+ user without `workflows_update`; on a Published row it produces the same end state as (4).
+7. **Republish** — after (4), publishing the same version again restores the trigger rows and
+ the Published tag. A schedule-triggered workflow gets a non-null `workflow.nextRunAt`; an
+ event-triggered one gets `NULL`.
+8. **In-flight run** — a run queued for version 1 and then unpublished before it executes
+ settles `Skipped` with reason *"This workflow was unpublished before the run started."*
+9. **No "Active"/"Live"** — `grep -rn "Live\|Active" apps/erp/app/modules/workflows/ui` returns
+ no user-facing workflow-state string, and `docs/content/docs/reference/workflows.mdx` has no
+ "Active switch" callout.
+10. **Gates green** — `pnpm exec biome check`, the workflow unit tests
+ (`packages/jobs/src/workflows/*.test.ts`, `packages/workflows/src/seed-workflows.test.ts`),
+ `pnpm db:check:datasets`, and `pnpm --filter @carbon/checks workflow-events` all pass.
+
+## Open questions (resolved before writing)
+
+- [x] **How do we remember which version to re-publish after an unpublish?** — **Answer:**
+ Don't. When nothing is published, every version in the menu offers Publish and no version
+ carries a tag; when something is published, that version carries the tag and offers
+ Unpublish. No new column. (User, 2026-08-24.)
+- [x] **Which single word means "this is the version that runs"?** — **Answer:** **Published**,
+ everywhere — badge, version tag, code, docs. The button stays Publish/Unpublish, so the verb
+ and the state share a root word. "Live" is removed. (User, 2026-08-24.)
+- [x] **Rename `workflow.activeVersionId` → `publishedVersionId`?** — **Answer:** Yes, in the
+ same migration. The word "active" leaked from that column into the UI, so leaving it keeps
+ the trap set for the next engineer. (User, 2026-08-24.)
+- [x] **What replaces the Active checkbox column on the list page?** — **Answer:** Nothing in
+ the grid; the Published/Draft badge is the indicator, and **Unpublish** joins the row context
+ menu so an emergency stop stays one click from the list. Publishing stays in the builder.
+ (User, 2026-08-24.)
+
+## Changelog
+
+- **2026-08-24** — Written after the four questions above were resolved with the user.
+ Grounded in `20260810100100_workflows-foundation.sql`, `packages/workflows/src/sync.ts`,
+ `packages/jobs/src/workflows/{scheduler,matcher}.ts`,
+ `packages/jobs/src/workflows/engine/{execute,log}.ts`, the ERP workflows module, and
+ `docs/content/docs/reference/workflows.mdx`. Terminology grounded in the competitor scan at
+ `.ai/research/2026-08-24-workflow-version-terminology.md`.
diff --git a/.claude/rules/workflow-matcher.md b/.claude/rules/workflow-matcher.md
index 3d6b41635d..4ab426bb82 100644
--- a/.claude/rules/workflow-matcher.md
+++ b/.claude/rules/workflow-matcher.md
@@ -127,14 +127,18 @@ replay can never double-fire:
- `syncWorkflowTriggers(db, companyId, workflowId, lockCompany)` — rewrite one workflow's trigger rows
(delete-then-insert; the table has no UPDATE policy by design), **write `workflow.nextRunAt`**
(the scheduler's bookmark, or null for event-triggered workflows), and reconcile the company's
- subscriptions. Returns `{ eventIds, tables, scheduled }`. Call it on promote, on trigger edit,
- and on activate/deactivate.
+ subscriptions. Returns `{ eventIds, tables, scheduled }`. Call it on publish, on trigger edit,
+ and on unpublish.
- `syncWorkflowSubscriptions(db, companyId)` — standalone repair from existing rows.
Reconciliation is surgical: only `handlerType = 'WORKFLOW'` rows are touched, matched by
exact `(companyId, name, table)`, and a row with the wrong `operations` is deleted and
re-inserted. It never resets a company's WEBHOOK/SEARCH/AUDIT subscriptions.
+The gate inside it is `workflow.publishedVersionId` alone — set means published, `NULL` means
+draft and an empty desired set. The old `active` boolean was removed in migration
+`20260824163808_workflow-publish-unpublish.sql`.
+
**Why this lives in `@carbon/workflows` and not `@carbon/database`:** it must read
`WORKFLOW_EVENTS`, and `@carbon/workflows` already dev-depends on `@carbon/database` — the
reverse edge is a package cycle Turborepo rejects. Kysely is imported **type-only** here
@@ -150,7 +154,7 @@ The caller owns it because `@carbon/workflows` imports Kysely **type-only** (the
for the browser) and cannot run raw SQL; `workflows.server.ts` supplies
`` sql`SELECT pg_advisory_xact_lock(hashtext(${companyId}))` ``.
-Kysely bypasses RLS. **The caller authorizes first** — phase 7's activation route gates on
+Kysely bypasses RLS. **The caller authorizes first** — the publish and unpublish routes gate on
`workflows_update` before calling.
## Gotchas
diff --git a/apps/erp/app/modules/agent/kb/docs/platform/architecture.md b/apps/erp/app/modules/agent/kb/docs/platform/architecture.md
index 59b6fca304..6a891d97b7 100644
--- a/apps/erp/app/modules/agent/kb/docs/platform/architecture.md
+++ b/apps/erp/app/modules/agent/kb/docs/platform/architecture.md
@@ -16,8 +16,9 @@ Any term you might not know is marked with a number the first time it appears, l
Postgres [[17]](#g17). The number links to a one-line definition in the [Glossary](#glossary) at the
end. Nothing is assumed.
-The file paths, line numbers and counts throughout are accurate as of August 2026. They will drift as
-the repository moves; the ideas they illustrate outlast them.
+ The file paths, line numbers and counts throughout are accurate as of August
+ 2026. They will drift as the repository moves; the ideas they illustrate
+ outlast them.
---
@@ -492,8 +493,7 @@ describing every table, view, function and enum. App code imports from it:
```ts
import type { Database } from "@carbon/database";
-type PurchaseOrderRow =
- Database["public"]["Tables"]["purchaseOrder"]["Row"];
+type PurchaseOrderRow = Database["public"]["Tables"]["purchaseOrder"]["Row"];
```
**Run `pnpm run generate:types` after pulling migrations or writing one, before you
@@ -630,33 +630,33 @@ refuses to start without it.
**Libraries** (`packages/`). The ones you will actually touch are near the top:
-| Package | What it does |
-| --------------- | ---------------------------------------------------------------------------------------- |
-| `react` | The design system. **Check here before writing any UI.** |
-| `database` | Generated types, migrations, edge functions, database clients. |
-| `auth` | Login, sessions, `requirePermissions`, API keys, permission caching. |
-| `form` | `ValidatedForm`, field components, zod helpers. |
-| `jobs` | Every Inngest background function, plus the workflow runtime. |
-| `lib` | Shared server utilities: the Inngest client, `trigger()`, email, Slack. |
-| `utils` | Pure helpers: dates, money, arrays, strings, BOM maths. |
-| `workflows` | Customer workflow schema, validation and pure runtime. No I/O. |
-| `documents` | PDF generation, email templates, barcode and label rendering. |
-| `locale` | Lingui setup and language switching. |
+| Package | What it does |
+| --------------- | ---------------------------------------------------------------------------------------------------------------- |
+| `react` | The design system. **Check here before writing any UI.** |
+| `database` | Generated types, migrations, edge functions, database clients. |
+| `auth` | Login, sessions, `requirePermissions`, API keys, permission caching. |
+| `form` | `ValidatedForm`, field components, zod helpers. |
+| `jobs` | Every Inngest background function, plus the workflow runtime. |
+| `lib` | Shared server utilities: the Inngest client, `trigger()`, email, Slack. |
+| `utils` | Pure helpers: dates, money, arrays, strings, BOM maths. |
+| `workflows` | Customer workflow schema, validation and pure runtime. No I/O. |
+| `documents` | PDF generation, email templates, barcode and label rendering. |
+| `locale` | Lingui setup and language switching. |
| `env` | The one place `docs/platform/self-hosting/environment-variables` are read and validated. |
-| `logger` | Structured logging, with request-id correlation. |
-| `notifications` | The notification event taxonomy (enums only). |
-| `printing` | Printer registry, label queue, physical print delivery. |
-| `onboarding` | New-company setup, the "Implementation Hub". |
-| `kv` | Redis client plus rate limiting. |
-| `stripe` | Billing. Cloud edition only. |
-| `ee` | Enterprise-only code: Xero, Slack, Jira, Linear, Onshape, plan gating. |
-| `viewer` | 3D model and assembly-instruction rendering. |
-| `tiptap` | Rich text editor. |
-| `dev` | The `crbn` CLI that runs your local stack. |
-| `checks` | Repo conformance rules enforced in CI. |
-| `config` | Shared tsconfig, Tailwind theme, vitest preset. No runtime code. |
-| `glossary` | Canonical manufacturing term definitions used in field help. |
-| `harness` | Internal AI-agent tooling. Not shipped. |
+| `logger` | Structured logging, with request-id correlation. |
+| `notifications` | The notification event taxonomy (enums only). |
+| `printing` | Printer registry, label queue, physical print delivery. |
+| `onboarding` | New-company setup, the "Implementation Hub". |
+| `kv` | Redis client plus rate limiting. |
+| `stripe` | Billing. Cloud edition only. |
+| `ee` | Enterprise-only code: Xero, Slack, Jira, Linear, Onshape, plan gating. |
+| `viewer` | 3D model and assembly-instruction rendering. |
+| `tiptap` | Rich text editor. |
+| `dev` | The `crbn` CLI that runs your local stack. |
+| `checks` | Repo conformance rules enforced in CI. |
+| `config` | Shared tsconfig, Tailwind theme, vitest preset. No runtime code. |
+| `glossary` | Canonical manufacturing term definitions used in field help. |
+| `harness` | Internal AI-agent tooling. Not shipped. |
**Inside an ERP module** (there are eighteen, under `apps/erp/app/modules/{module}/`):
@@ -833,120 +833,126 @@ Typechecking the whole repo at once runs out of memory, so always use `--filter`
Numbered so the body can point at them. Alphabetical.
<a id="g1"></a>
-**1. Action:** the function a route file exports to handle a form submission. Runs on the
-server only, never shipped to the browser.
+**1. Action:** the function a route file exports to handle a form submission.
+Runs on the server only, never shipped to the browser.
<a id="g2"></a>
-**2. Deno:** an alternative JavaScript runtime to Node.js. Our edge functions are written
-for it, which is why they use `https://` imports instead of `node_modules`.
+**2. Deno:** an alternative JavaScript runtime to Node.js. Our edge functions
+are written for it, which is why they use `https://` imports instead of
+`node_modules`.
<a id="g3"></a>
-**3. ECS Fargate:** Amazon's service for running Docker containers without managing the
-servers underneath. The ERP and MES run here in production.
+**3. ECS Fargate:** Amazon's service for running Docker containers without
+managing the servers underneath. The ERP and MES run here in production.
<a id="g4"></a>
-**4. Edge function:** a small server-side program deployed next to the database, called
-over HTTP and awaited like a normal function. Ours are written for Deno.
+**4. Edge function:** a small server-side program deployed next to the database,
+called over HTTP and awaited like a normal function. Ours are written for Deno.
<a id="g5"></a>
-**5. Inngest:** the background job runner. Send it an event; it calls your function over
-HTTP and remembers each completed step, so a retry resumes rather than restarts.
+**5. Inngest:** the background job runner. Send it an event; it calls your
+function over HTTP and remembers each completed step, so a retry resumes rather
+than restarts.
<a id="g6"></a>
-**6. Kysely:** a TypeScript SQL query builder. Unlike `supabase-js` it holds a real
-database connection, so it can run real transactions. It also bypasses RLS.
+**6. Kysely:** a TypeScript SQL query builder. Unlike `supabase-js` it holds a
+real database connection, so it can run real transactions. It also bypasses RLS.
<a id="g7"></a>
-**7. Lingui:** the translation library. You mark strings in code; it extracts them into
-per-language files for translators.
+**7. Lingui:** the translation library. You mark strings in code; it extracts
+them into per-language files for translators.
<a id="g8"></a>
-**8. Loader:** the function a route file exports to fetch the data its page needs. Runs
-on the server only.
+**8. Loader:** the function a route file exports to fetch the data its page
+needs. Runs on the server only.
<a id="g9"></a>
-**9. Migration:** one timestamped SQL file describing a schema change. The full ordered
-set of them _is_ the schema; there is no separate schema file.
+**9. Migration:** one timestamped SQL file describing a schema change. The full
+ordered set of them _is_ the schema; there is no separate schema file.
<a id="g10"></a>
-**10. Monorepo:** one Git repository holding several applications and shared libraries
-that are versioned and released together.
+**10. Monorepo:** one Git repository holding several applications and shared
+libraries that are versioned and released together.
<a id="g11"></a>
-**11. MRP:** Material Requirements Planning. Works out what to buy and make, and when,
-given demand and current stock. Runs as an edge function.
+**11. MRP:** Material Requirements Planning. Works out what to buy and make, and
+when, given demand and current stock. Runs as an edge function.
<a id="g12"></a>
-**12. Multi-tenancy:** one database and one running application serving many separate
-customer companies, with each company's data invisible to the others.
+**12. Multi-tenancy:** one database and one running application serving many
+separate customer companies, with each company's data invisible to the others.
<a id="g13"></a>
-**13. nanostores:** a very small state library. We use it for reference lists (items,
-customers, suppliers) that many screens read and Realtime keeps fresh.
+**13. nanostores:** a very small state library. We use it for reference lists
+(items, customers, suppliers) that many screens read and Realtime keeps fresh.
<a id="g14"></a>
-**14. pg_cron:** a Postgres extension that runs SQL on a schedule, inside the database.
-Used for cache refreshes and queue sweeping.
+**14. pg_cron:** a Postgres extension that runs SQL on a schedule, inside the
+database. Used for cache refreshes and queue sweeping.
<a id="g15"></a>
-**15. pg_net:** a Postgres extension that lets the database make outbound HTTP calls. We
-use it for exactly one thing: pinging the event queue awake after a commit.
+**15. pg_net:** a Postgres extension that lets the database make outbound HTTP
+calls. We use it for exactly one thing: pinging the event queue awake after a
+commit.
<a id="g16"></a>
-**16. PGMQ:** a message queue implemented in ordinary Postgres tables. Lets a database
-trigger enqueue work inside the same transaction as the write that caused it.
+**16. PGMQ:** a message queue implemented in ordinary Postgres tables. Lets a
+database trigger enqueue work inside the same transaction as the write that
+caused it.
<a id="g17"></a>
-**17. Postgres:** the relational database everything in Carbon is built on. Version 15.
+**17. Postgres:** the relational database everything in Carbon is built on.
+Version 15.
<a id="g18"></a>
-**18. PostgREST:** a service that exposes Postgres tables and views as a REST API. Every
-`client.from(...).select(...)` is a PostgREST call, not raw SQL.
+**18. PostgREST:** a service that exposes Postgres tables and views as a REST
+API. Every `client.from(...).select(...)` is a PostgREST call, not raw SQL.
<a id="g19"></a>
-**19. Radix UI:** an unstyled, accessible React component library. Our design system adds
-Tailwind styling on top of it.
+**19. Radix UI:** an unstyled, accessible React component library. Our design
+system adds Tailwind styling on top of it.
<a id="g20"></a>
**20. RLS (Row Level Security):** a Postgres feature where a per-table rule is
-automatically added to every query. It is what keeps one company's data invisible to
-another.
+automatically added to every query. It is what keeps one company's data
+invisible to another.
<a id="g21"></a>
-**21. RPC:** here, calling a function defined inside Postgres from application code, via
-`client.rpc("name", args)`.
+**21. RPC:** here, calling a function defined inside Postgres from application
+code, via `client.rpc("name", args)`.
<a id="g22"></a>
**22. Service role:** a database credential that bypasses all RLS. Powerful; use
carefully.
<a id="g23"></a>
-**23. SST:** infrastructure-as-code for AWS, written in TypeScript. `sst.config.ts`
-defines our production cluster.
+**23. SST:** infrastructure-as-code for AWS, written in TypeScript.
+`sst.config.ts` defines our production cluster.
<a id="g24"></a>
-**24. Supabase:** an open-source bundle around Postgres: REST API, auth, storage,
-realtime and edge functions. We run its containers locally and use the managed version in
-production.
+**24. Supabase:** an open-source bundle around Postgres: REST API, auth,
+storage, realtime and edge functions. We run its containers locally and use the
+managed version in production.
<a id="g25"></a>
-**25. Turborepo:** the build orchestrator that knows which packages depend on which, so
-`pnpm build` only rebuilds what changed.
+**25. Turborepo:** the build orchestrator that knows which packages depend on
+which, so `pnpm build` only rebuilds what changed.
<a id="g26"></a>
-**26. View:** a saved query that behaves like a read-only table. Carbon writes to tables
-and reads from views; computed values like order totals live in the view.
+**26. View:** a saved query that behaves like a read-only table. Carbon writes
+to tables and reads from views; computed values like order totals live in the
+view.
<a id="g27"></a>
**27. Vite:** the build tool and dev server behind all our React apps.
<a id="g28"></a>
-**28. zod:** a schema library. Describe data once, get validation and a TypeScript type
-from the same definition.
+**28. zod:** a schema library. Describe data once, get validation and a
+TypeScript type from the same definition.
<a id="g29"></a>
-**29. zustand:** a small React state library. We use it only for throwaway UI state, like
-whether a modal is open.
+**29. zustand:** a small React state library. We use it only for throwaway UI
+state, like whether a modal is open.
---
diff --git a/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md b/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md
index b2fb3a7a63..2abd312dcd 100644
--- a/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md
+++ b/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md
@@ -57,6 +57,7 @@ Resend API key for transactional email.
Verified sending domain.
Stripe secret key, Cloud / Enterprise billing.
Verifies inbound Stripe webhooks.
+Verifies inbound Stripe Connect webhooks (connected-account events, signed with a separate secret).
## AI & analytics
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.md b/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.md
index 0e72f99302..7bd0c1f82b 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.md
@@ -44,7 +44,7 @@ If a condition matches none of its paths and has no **"Otherwise"**, that step *
- **Succeeded**: Every step that ran finished without error.
- **Failed**: At least one step failed, or the run was stopped by the 500-step ceiling.
- **Blocked**: A loop guard stopped it before any step ran. The reason is on the run.
- - **Skipped**: It never started — the workflow was switched off, or a scheduled run came due too late, or its previous run was still going.
+ - **Skipped**: It never started — the workflow was unpublished, or a scheduled run came due too late, or its previous run was still going.
Individual steps use a shorter list: **Running**, **Succeeded**, **Failed**, **Skipped**. There is no blocked or queued step — those are decisions about the run as a whole.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/workflows.md b/apps/erp/app/modules/agent/kb/docs/reference/workflows.md
index 5428a9334a..1b58d1d504 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/workflows.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/workflows.md
@@ -94,9 +94,9 @@ There is no Save button. The builder saves as you work and reports its state nex
**"Publish"** is all-or-nothing. Carbon validates the whole workflow — a trigger exists, no step loops back, every step is reachable, every required field is filled, every variable resolves and comes from upstream, every type lines up — and if anything is wrong, **nothing is written**. The problems appear in a panel headed **"3 problems — not published"**, and clicking one pans the canvas to the step it belongs to.
-Publishing promotes a version to live **and** turns the workflow on. The **"Active"** switch, on the list and in the builder, is a separate kill switch: turning it off removes the workflow's trigger registrations so nothing fires, while leaving the published version in place. A workflow only runs when it is active *and* has a live version.
+Publishing is also the only on/off switch there is. Whichever version you publish is the one that runs, and **"Unpublish"** — on the published version in the builder, or from a workflow's row menu on the list — stops the workflow entirely: its trigger registrations are removed so nothing fires. Nothing is deleted, so publishing a version again starts it back up. A workflow with nothing published reads as **Draft**.
-Publishing also freezes that version. The builder locks with *"This version is live. Create a new version to edit."* — to keep working, use the version menu to create a new version, which copies the live one and numbers it one higher. Older versions stay readable, and a run that is already in flight keeps using the version it started with even if you promote another one mid-run.
+Publishing also freezes that version. The builder locks with *"This version is published. Create a new version to edit."* — to keep working, use the version menu to create a new version, which copies the published one and numbers it one higher. Older versions stay readable, and a run that is already in flight keeps using the version it started with even if you publish another one mid-run.
**Test run.** The trigger card has a **"Test run"** button, available to the workflow's owner. It executes for real, so anything it creates or sends actually happens, but the result is never written to run history: *"The result will not appear on the Runs page."*
@@ -108,7 +108,7 @@ Workflows have their own permission module, seeded from your existing settings a
| --- | --- |
| View | Open the list, the builder, and run history |
| Create | Add a workflow, or create a new version of one |
-| Update | Edit, publish, rename, toggle active, test run |
+| Update | Edit, publish, unpublish, rename, test run |
| Delete | Delete a workflow, its versions, and its run history |
Every step reads and writes with the owner's permissions, re-checked at each step rather than cached, and Carbon confirms the owner still has access to the relevant area before running. If the owner's access is revoked the run stops with a plain message naming the area, such as *"The owner of this workflow no longer has access to Purchasing."* Nothing a workflow does can reach outside the company it belongs to.
diff --git a/apps/erp/app/modules/workflows/AGENTS.md b/apps/erp/app/modules/workflows/AGENTS.md
index dd3c597da5..9642cc7462 100644
--- a/apps/erp/app/modules/workflows/AGENTS.md
+++ b/apps/erp/app/modules/workflows/AGENTS.md
@@ -6,18 +6,19 @@ The definition schema, validator, catalogs, matcher and engine all live outside
## Key Domain Concepts
-- **Workflow** — the `workflow` row. Carries `ownerId`, `active` (the on/off kill switch), and `activeVersionId` (the promoted version pointer). The pointer and the boolean are separate columns on purpose: turning a workflow off and back on restores whichever version was promoted.
+- **Workflow** — the `workflow` row. Carries `ownerId` and `publishedVersionId`. That pointer IS the on/off switch: set means the workflow runs that version, `NULL` means it is a draft and nothing fires. There is no separate `active` boolean — it was a second switch for the same idea and was removed (migration `20260824163808_workflow-publish-unpublish.sql`). Because the pointer names a version rather than carrying a flag, exactly one version can be published at a time by construction.
- **Version** — a `workflowVersion` row holding `nodes`, `edges` and `formatVersion`. Numbered, never named.
- **Canvas state** — `workflow.canvasState` JSONB: `{ x, y, zoom, panOnScroll }`. Per workflow (not per user, not per version), written by `$id.canvas.tsx` through `updateWorkflowCanvasState`, restored as `defaultViewport`. Node collapse is NOT here — `expanded` lives on each node in the definition and rides the autosave. `/save`, `/canvas` and `/positions` are all excluded from `shouldRevalidate`; revalidating on a canvas write would snap the viewport back to where it was on load, and revalidating on a positions write would remount the builder store mid-drag.
- **Definition** — `{ formatVersion, nodes, edges }`, validated by `workflowDefinitionSchema` from `@carbon/workflows`. `CURRENT_DEFINITION_FORMAT_VERSION` is **3**; the SQL column default is a stale **1**, so the app always writes the constant explicitly.
-- **Publish** — validate → set `activeVersionId` → set `active` → `syncWorkflowTriggers` → wake the scheduler. One route does all five; splitting them leaves a workflow that looks active and never fires.
-- **The live version is read-only.** Editing a live workflow means creating a new version, the same rule released item revisions follow.
+- **Publish** — validate → set `publishedVersionId` → `syncWorkflowTriggers` → wake the scheduler. One route does all four; splitting them leaves a workflow that looks published and never fires.
+- **Unpublish** — the inverse and the only off switch: `publishedVersionId = NULL` → the same `syncWorkflowTriggers`, which is what deletes the trigger rows and clears `nextRunAt`. It takes no boolean, because publishing needs a version id and has to validate first.
+- **The published version is read-only.** Editing a published workflow means creating a new version, the same rule released item revisions follow.
## Safety
### Always
- MUST read a version through `readWorkflowVersion(row)` from `@carbon/workflows` — the only legal read path. On `{ ok: false }` render the failure and **do not mount the canvas**; a blank canvas would let an autosave overwrite a definition nobody could see.
-- MUST call `checkWorkflowVersionLock` in every mutating route. The live-version lock is enforced server-side, not only in the UI. The ONE deliberate exception is `$id.positions.tsx` — node positions carry no behaviour, and `updateWorkflowNodePositions` writes only `position`, only onto node ids that already exist, so that route cannot change what a workflow does even when called by hand.
+- MUST call `checkWorkflowVersionLock` in every mutating route. The published-version lock is enforced server-side, not only in the UI. The ONE deliberate exception is `$id.positions.tsx` — node positions carry no behaviour, and `updateWorkflowNodePositions` writes only `position`, only onto node ids that already exist, so that route cannot change what a workflow does even when called by hand.
- MUST write `formatVersion: CURRENT_DEFINITION_FORMAT_VERSION` on every definition write.
- MUST scope every query by `companyId`.
- MUST build version insert/update objects with every key explicitly present — PostgREST writes `NULL` for a present-but-`undefined` key, which would null `nodes`/`edges` past their `'[]'` defaults.
@@ -39,7 +40,7 @@ The definition schema, validator, catalogs, matcher and engine all live outside
pnpm exec turbo run typecheck --filter=erp # the app package is named `erp`, not @carbon/erp
pnpm --filter erp exec vitest run app/modules/workflows/ui/Builder/graph.test.ts
pnpm exec biome check apps/erp/app/modules/workflows apps/erp/app/routes/x+/workflow+ apps/erp/app/routes/x+/workflows+
-pnpm --filter @carbon/checks workflow-events # trigger-row drift after a publish/toggle
+pnpm --filter @carbon/checks workflow-events # trigger-row drift after a publish/unpublish
```
## Layout
@@ -48,12 +49,12 @@ pnpm --filter @carbon/checks workflow-events # trigger-row drift after a publi
modules/workflows/
├── workflows.models.ts # zod validators
├── workflows.service.ts # Supabase reads/writes for workflow + workflowVersion
-├── workflows.server.ts # lock predicates, publish, toggle — server only
+├── workflows.server.ts # lock predicates, publish, unpublish — server only
├── types.ts # BuilderNode / BuilderEdge React Flow aliases
├── index.ts # barrel (does NOT export workflows.server)
└── ui/
├── WorkflowsTable.tsx, WorkflowForm.tsx, WorkflowLockModal.tsx,
- │ WorkflowActiveSwitch.tsx, WorkflowActiveCheckbox.tsx, WorkflowsUpgradeOverlay.tsx
+ │ ConfirmUnpublishWorkflow.tsx, WorkflowsUpgradeOverlay.tsx
├── useWorkflowsSubmodules.tsx
└── Builder/ # canvas, store, node cards, palette, versions, issues
```
@@ -67,15 +68,15 @@ Routes split in two trees: `x+/workflows+/` (list, create, rename, delete, with
- `insertWorkflow` / `updateWorkflow` — separate rather than one `upsert*`
- `insertWorkflowVersion` / `updateWorkflowDefinition` / `deleteWorkflowVersion`
- `updateWorkflowOwner` — takes the session user, never a submitted id
-- `getWorkflowLockFlags` / `checkWorkflowVersionLock` (server) — the live-version lock
+- `checkWorkflowVersionLock` (server) — the published-version lock; the rule is one equality against `publishedVersionId`, so there is no helper wrapping it
- `updateWorkflowNodePositions` (service) — the positions-only writer behind `$id.positions.tsx`
-- `publishWorkflowVersion` / `setWorkflowActive` (server) — both call `syncWorkflowTriggers`, which uses Kysely and **bypasses RLS**; the route's `requirePermissions` is the only authorization gate
+- `publishWorkflowVersion` / `unpublishWorkflow` (server) — both call `syncWorkflowTriggers`, which uses Kysely and **bypasses RLS**; the route's `requirePermissions` is the only authorization gate
## Builder Notes
- One zustand store per builder instance, vanilla `createStore` in a ref behind a context — the `DocumentTemplateEditor` idiom. React Flow keeps viewport and interaction state.
- **No undo.** Deliberate; recovery is via versions.
-- Autosave is a 1s debounce with two modes. An editable version posts the whole definition to `$id.save.tsx`; a LIVE version posts positions only, to `$id.positions.tsx`. The route exports `shouldRevalidate` returning false for both — without it every autosave re-seeds the canvas from server state mid-edit.
+- Autosave is a 1s debounce with two modes. An editable version posts the whole definition to `$id.save.tsx`; a PUBLISHED version posts positions only, to `$id.positions.tsx`. The route exports `shouldRevalidate` returning false for both — without it every autosave re-seeds the canvas from server state mid-edit.
- The builder store has TWO read-only reasons, not one: `canChangeDefinition` (`canEdit && !isVersionLocked`) gates config, nodes, edges and `expanded`; `canMoveNodes` (`canEdit` alone) gates dragging and auto-arrange. Movement follows PERMISSION, not the lock, so a published workflow can still be tidied. Every store mutator is gated on one of them — `updateNodeData` in particular, since every node config form funnels through it.
- **A draft saves half-filled; only publishing demands completeness.** `clauseSchema.right` and `lookupMatchSchema.value` are optional and `lookupMatchSchema.field` may be `""`, so a node the user is still filling in round-trips through `workflowDefinitionSchema` (and therefore `readWorkflowVersion`) instead of failing autosave. `validateDefinition`'s config layer is what reports each gap as `INCOMPLETE_CONFIG` and blocks publish. Never re-tighten those three fields to make a runtime path simpler — the runtime skips with a reason (`compare.ts`, `lookup.ts`) precisely so it does not have to. When `/save` does return `ok: false`, `Autosave.tsx` raises the server's `error` string as a toast and the route logs the zod issues.
- Drawn loops are blocked at connection time by `isValidConnection` + `wouldCreateCycle`. The validator's `CYCLE` check stays as the backstop.
diff --git a/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx b/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
index d0d6cd78e9..5c8355b81f 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
@@ -24,6 +24,7 @@ import type {
WorkflowDetail,
WorkflowVersionSummary
} from "../../workflows.service";
+import { ConfirmUnpublishWorkflow } from "../ConfirmUnpublishWorkflow";
import { useBuilderStore, useBuilderStoreApi } from "./context";
import { WorkflowVersionStatus } from "./WorkflowVersionStatus";
@@ -52,7 +53,7 @@ function SaveMarker() {
}
// Renaming is a property of the workflow, not of the version being viewed, so a
-// live (read-only) version is still renameable — only the permission gates it.
+// published (read-only) version is still renameable — only the permission gates it.
function WorkflowTitle({ workflow }: { workflow: WorkflowDetail }) {
const { t } = useLingui();
const permissions = usePermissions();
@@ -136,7 +137,7 @@ export function BuilderHeader({
const { t } = useLingui();
const permissions = usePermissions();
const store = useBuilderStoreApi();
- // The lock glyph means "this is the live version"; the tooltip below distinguishes
+ // The lock glyph means "this is the published version"; the tooltip below distinguishes
// that from simply lacking permission.
const isVersionLocked = useBuilderStore((state) => state.isVersionLocked);
const canEdit = useBuilderStore((state) => state.canEdit);
@@ -148,12 +149,13 @@ export function BuilderHeader({
}>();
const versionFetcher = useFetcher();
const confirmPublish = useDisclosure();
+ const confirmUnpublish = useDisclosure();
const current = versions.find((version) => version.id === versionId);
- const live = versions.find(
- (version) => version.id === workflow.activeVersionId
+ const published = versions.find(
+ (version) => version.id === workflow.publishedVersionId
);
- const isLiveVersion = versionId === workflow.activeVersionId;
+ const isPublishedVersion = versionId === workflow.publishedVersionId;
// Publish issues drive the node outlines and the panel.
useEffect(() => {
@@ -184,8 +186,10 @@ export function BuilderHeader({
</span>
</TooltipTrigger>
<TooltipContent>
- {isLiveVersion ? (
- <Trans>This version is live. Create a new version to edit.</Trans>
+ {isPublishedVersion ? (
+ <Trans>
+ This version is published. Create a new version to edit.
+ </Trans>
) : (
<Trans>You do not have permission to edit workflows</Trans>
)}
@@ -203,7 +207,9 @@ export function BuilderHeader({
label={current && <span>Version {current.versionNumber}</span>}
renderLabel={(v) => <span>Version {v.versionNumber}</span>}
renderStatus={(v) => (
- <WorkflowVersionStatus isLive={v.id === workflow.activeVersionId} />
+ <WorkflowVersionStatus
+ isPublished={v.id === workflow.publishedVersionId}
+ />
)}
onNewVersion={
permissions.can("create", "workflows")
@@ -218,24 +224,43 @@ export function BuilderHeader({
: undefined
}
/>
- <Button
- isDisabled={
- !permissions.can("update", "workflows") ||
- isLiveVersion ||
- publishFetcher.state !== "idle"
- }
- isLoading={publishFetcher.state !== "idle"}
- onClick={() => {
- // Replacing a live version is worth asking about; a first publish is not.
- if (live) confirmPublish.onOpen();
- else publish();
- }}
- >
- <Trans>Publish</Trans>
- </Button>
+ {isPublishedVersion ? (
+ <Button
+ variant="secondary"
+ isDisabled={!permissions.can("update", "workflows")}
+ onClick={confirmUnpublish.onOpen}
+ >
+ <Trans>Unpublish</Trans>
+ </Button>
+ ) : (
+ <Button
+ isDisabled={
+ !permissions.can("update", "workflows") ||
+ publishFetcher.state !== "idle"
+ }
+ isLoading={publishFetcher.state !== "idle"}
+ onClick={() => {
+ // Replacing a published version is worth asking about; a first publish is not.
+ if (published) confirmPublish.onOpen();
+ else publish();
+ }}
+ >
+ <Trans>Publish</Trans>
+ </Button>
+ )}
</div>
- {confirmPublish.isOpen && current && live && (
+ {confirmUnpublish.isOpen && (
+ <ConfirmUnpublishWorkflow
+ workflowId={workflow.id}
+ name={workflow.name}
+ onClose={confirmUnpublish.onClose}
+ />
+ )}
+
+ {/* Hand-rolled rather than `Confirm`: publish posts `versionId` and reads the returned
+ issues back off its own fetcher to outline the failing nodes. */}
+ {confirmPublish.isOpen && current && published && (
<Modal
open
onOpenChange={(open) => {
@@ -249,7 +274,7 @@ export function BuilderHeader({
</ModalHeader>
<ModalBody>
<p className="text-sm text-muted-foreground">
- {t`Version ${live.versionNumber} is live now and will be replaced.`}
+ {t`Version ${published.versionNumber} is published now and will be replaced.`}
</p>
</ModalBody>
<ModalFooter>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/WorkflowVersionStatus.tsx b/apps/erp/app/modules/workflows/ui/Builder/WorkflowVersionStatus.tsx
index b707636780..fc44173e24 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/WorkflowVersionStatus.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/WorkflowVersionStatus.tsx
@@ -2,14 +2,14 @@ import { Badge } from "@carbon/react";
import { Trans } from "@lingui/react/macro";
type Props = {
- isLive: boolean;
+ isPublished: boolean;
};
-export function WorkflowVersionStatus({ isLive }: Props) {
- if (!isLive) return null;
+export function WorkflowVersionStatus({ isPublished }: Props) {
+ if (!isPublished) return null;
return (
<Badge variant="green">
- <Trans>Live</Trans>
+ <Trans>Published</Trans>
</Badge>
);
}
diff --git a/apps/erp/app/modules/workflows/ui/ConfirmUnpublishWorkflow.tsx b/apps/erp/app/modules/workflows/ui/ConfirmUnpublishWorkflow.tsx
new file mode 100644
index 0000000000..8825979858
--- /dev/null
+++ b/apps/erp/app/modules/workflows/ui/ConfirmUnpublishWorkflow.tsx
@@ -0,0 +1,34 @@
+import { useLingui } from "@lingui/react/macro";
+import { Confirm } from "~/components/Modals";
+import { path } from "~/utils/path";
+
+type ConfirmUnpublishWorkflowProps = {
+ workflowId: string;
+ name: string;
+ onClose: () => void;
+};
+
+/**
+ * The one copy of the unpublish confirmation, shared by the list row menu and the builder
+ * header. Both post to the same bodyless route, so the only thing to keep in one place is
+ * what the dialog says.
+ */
+export function ConfirmUnpublishWorkflow({
+ workflowId,
+ name,
+ onClose
+}: ConfirmUnpublishWorkflowProps) {
+ const { t } = useLingui();
+
+ return (
+ <Confirm
+ action={path.to.workflowUnpublish(workflowId)}
+ isOpen
+ title={t`Unpublish ${name}?`}
+ text={t`It will stop running until you publish a version again. Nothing is deleted.`}
+ confirmText={t`Unpublish`}
+ onCancel={onClose}
+ onSubmit={onClose}
+ />
+ );
+}
diff --git a/apps/erp/app/modules/workflows/ui/WorkflowActiveCheckbox.tsx b/apps/erp/app/modules/workflows/ui/WorkflowActiveCheckbox.tsx
deleted file mode 100644
index d7eea00073..0000000000
--- a/apps/erp/app/modules/workflows/ui/WorkflowActiveCheckbox.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { Checkbox } from "@carbon/react";
-import { useLingui } from "@lingui/react/macro";
-import { useFetcher } from "react-router";
-import { usePermissions } from "~/hooks";
-import { path } from "~/utils/path";
-
-/**
- * Checkbox variant of {@link WorkflowActiveSwitch} used in the workflows table.
- * Posts to the same toggle route that re-syncs the trigger rows, and reads its
- * checked state from the in-flight submission so it does not snap back while saving.
- */
-export function WorkflowActiveCheckbox({
- workflowId,
- active
-}: {
- workflowId: string;
- active: boolean;
-}) {
- const { t } = useLingui();
- const fetcher = useFetcher<{ success?: boolean }>();
- const permissions = usePermissions();
-
- const checked = fetcher.formData
- ? fetcher.formData.get("active") === "on"
- : active;
-
- // The toggle route performs an unconditional update, so block further clicks
- // until the in-flight submission settles — rapid clicks could otherwise reach
- // the server out of order and leave the workflow with the wrong active value.
- const isUpdating = fetcher.state !== "idle";
-
- return (
- <Checkbox
- aria-label={t`Active`}
- isChecked={checked}
- disabled={!permissions.can("update", "workflows") || isUpdating}
- onCheckedChange={(next) => {
- const formData = new FormData();
- if (next === true) formData.set("active", "on");
- fetcher.submit(formData, {
- method: "post",
- action: path.to.workflowToggle(workflowId)
- });
- }}
- />
- );
-}
diff --git a/apps/erp/app/modules/workflows/ui/WorkflowActiveSwitch.tsx b/apps/erp/app/modules/workflows/ui/WorkflowActiveSwitch.tsx
deleted file mode 100644
index 652362846b..0000000000
--- a/apps/erp/app/modules/workflows/ui/WorkflowActiveSwitch.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Switch } from "@carbon/react";
-import { useFetcher } from "react-router";
-import { usePermissions } from "~/hooks";
-import { path } from "~/utils/path";
-
-/**
- * The on/off kill switch, shared by the list and the builder header so both post
- * to the one toggle route that re-syncs the trigger rows. Reads its checked state
- * from the in-flight submission so the switch does not snap back while saving.
- */
-export function WorkflowActiveSwitch({
- workflowId,
- active
-}: {
- workflowId: string;
- active: boolean;
-}) {
- const fetcher = useFetcher<{ success?: boolean }>();
- const permissions = usePermissions();
-
- const checked = fetcher.formData
- ? fetcher.formData.get("active") === "on"
- : active;
-
- return (
- <Switch
- checked={checked}
- disabled={!permissions.can("update", "workflows")}
- onCheckedChange={(next) => {
- const formData = new FormData();
- if (next) formData.set("active", "on");
- fetcher.submit(formData, {
- method: "post",
- action: path.to.workflowToggle(workflowId)
- });
- }}
- />
- );
-}
diff --git a/apps/erp/app/modules/workflows/ui/WorkflowLockModal.tsx b/apps/erp/app/modules/workflows/ui/WorkflowLockModal.tsx
index a68346cf63..93e50e5553 100644
--- a/apps/erp/app/modules/workflows/ui/WorkflowLockModal.tsx
+++ b/apps/erp/app/modules/workflows/ui/WorkflowLockModal.tsx
@@ -22,7 +22,7 @@ type WorkflowLockModalProps = {
};
/**
- * Shown when the open version is the live one. Replaces the old inline warning banner:
+ * Shown when the open version is the published one. Replaces the old inline warning banner:
* opening a published version is a fork in the road, so we ask once which way to go —
* keep reading the read-only canvas, or branch a version you can edit. Dismissing (the X,
* the overlay, or "View the workflow") lands on the read-only canvas; the header lock glyph
@@ -60,7 +60,7 @@ const WorkflowLockModal = ({
<ModalContent size="small">
<ModalHeader>
<ModalTitle>
- <Trans>This version is live</Trans>
+ <Trans>This version is published</Trans>
</ModalTitle>
<ModalDescription>
<Trans>
@@ -83,7 +83,7 @@ const WorkflowLockModal = ({
<span className="flex flex-1 flex-col gap-0.5">
<span className="text-sm font-medium">{t`View the workflow`}</span>
<span className="text-xs leading-snug text-muted-foreground">
- {t`Browse the live version read-only. You can still rearrange steps to tidy the layout.`}
+ {t`Browse the published version read-only. You can still rearrange steps to tidy the layout.`}
</span>
</span>
<LuChevronRight className="size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
diff --git a/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx b/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx
index c9b93333c4..790983aeed 100644
--- a/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx
+++ b/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx
@@ -17,11 +17,11 @@ import {
LuBadgeCheck,
LuCalendar,
LuCirclePlus,
+ LuCircleStop,
LuHistory,
LuPencil,
LuTag,
LuText,
- LuToggleLeft,
LuTrash,
LuUser,
LuWorkflow
@@ -33,8 +33,8 @@ import { usePermissions } from "~/hooks";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
import type { Workflow, WorkflowLastRun } from "../workflows.service";
+import { ConfirmUnpublishWorkflow } from "./ConfirmUnpublishWorkflow";
import { RunStatus } from "./Runs/RunStatus";
-import { WorkflowActiveCheckbox } from "./WorkflowActiveCheckbox";
import WorkflowForm from "./WorkflowForm";
type WorkflowsTableProps = {
@@ -53,6 +53,7 @@ const WorkflowsTable = memo(
const newDisclosure = useDisclosure();
const renameDisclosure = useDisclosure();
const deleteDisclosure = useDisclosure();
+ const unpublishDisclosure = useDisclosure();
const [selectedWorkflow, setSelectedWorkflow] = useState<Workflow | null>(
null
);
@@ -93,7 +94,7 @@ const WorkflowsTable = memo(
id: "status",
header: t`Status`,
cell: ({ row }) => {
- const isPublished = Boolean(row.original.activeVersionId);
+ const isPublished = Boolean(row.original.publishedVersionId);
return isPublished ? (
<Badge variant="green">{t`Published`}</Badge>
) : (
@@ -111,27 +112,7 @@ const WorkflowsTable = memo(
]
},
exportValue: (row: Workflow) =>
- row.activeVersionId ? "Published" : "Draft"
- }
- },
- {
- accessorKey: "active",
- header: t`Active`,
- cell: ({ row }) => (
- <WorkflowActiveCheckbox
- workflowId={row.original.id}
- active={row.original.active}
- />
- ),
- meta: {
- icon: <LuToggleLeft />,
- filter: {
- type: "static",
- options: [
- { value: "true", label: t`Active` },
- { value: "false", label: t`Inactive` }
- ]
- }
+ row.publishedVersionId ? "Published" : "Draft"
}
},
{
@@ -152,10 +133,10 @@ const WorkflowsTable = memo(
}
},
{
- accessorKey: "activeVersionId",
- header: t`Live Version`,
+ accessorKey: "publishedVersionId",
+ header: t`Published Version`,
cell: ({ row }) => {
- const versionId = row.original.activeVersionId;
+ const versionId = row.original.publishedVersionId;
const versionNumber = versionId
? versionNumbers[versionId]
: undefined;
@@ -224,6 +205,18 @@ const WorkflowsTable = memo(
<MenuIcon icon={<LuPencil />} />
{t`Rename Workflow`}
</MenuItem>
+ <MenuItem
+ disabled={
+ !permissions.can("update", "workflows") || !row.publishedVersionId
+ }
+ onClick={() => {
+ flushSync(() => setSelectedWorkflow(row));
+ unpublishDisclosure.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuCircleStop />} />
+ {t`Unpublish`}
+ </MenuItem>
<MenuItem
destructive
disabled={!permissions.can("delete", "workflows")}
@@ -237,7 +230,14 @@ const WorkflowsTable = memo(
</MenuItem>
</>
),
- [navigate, permissions, renameDisclosure, deleteDisclosure, t]
+ [
+ navigate,
+ permissions,
+ renameDisclosure,
+ unpublishDisclosure,
+ deleteDisclosure,
+ t
+ ]
);
return (
@@ -280,6 +280,16 @@ const WorkflowsTable = memo(
}}
/>
)}
+ {unpublishDisclosure.isOpen && selectedWorkflow && (
+ <ConfirmUnpublishWorkflow
+ workflowId={selectedWorkflow.id}
+ name={selectedWorkflow.name}
+ onClose={() => {
+ setSelectedWorkflow(null);
+ unpublishDisclosure.onClose();
+ }}
+ />
+ )}
{deleteDisclosure.isOpen && selectedWorkflow && (
<ConfirmDelete
action={path.to.workflowDelete(selectedWorkflow.id)}
diff --git a/apps/erp/app/modules/workflows/ui/WorkflowsUpgradeOverlay.tsx b/apps/erp/app/modules/workflows/ui/WorkflowsUpgradeOverlay.tsx
index 6d38ceb5dc..4bc8f4fbe8 100644
--- a/apps/erp/app/modules/workflows/ui/WorkflowsUpgradeOverlay.tsx
+++ b/apps/erp/app/modules/workflows/ui/WorkflowsUpgradeOverlay.tsx
@@ -17,19 +17,19 @@ const mockRows = [
{
name: "New Order Notification",
event: "sales.order.created",
- active: true
+ published: true
},
{
name: "Low Stock Alert",
event: "inventory.stock.below-minimum",
- active: true
+ published: true
},
{
name: "Invoice Overdue",
event: "accounting.invoice.overdue",
- active: false
+ published: false
},
- { name: "Supplier PO Sent", event: "purchasing.order.sent", active: true }
+ { name: "Supplier PO Sent", event: "purchasing.order.sent", published: true }
];
export default function WorkflowsUpgradeOverlay() {
@@ -66,8 +66,12 @@ export default function WorkflowsUpgradeOverlay() {
<span className="text-muted-foreground text-xs font-mono">
{row.event}
</span>
- <Badge variant={row.active ? "outline" : "secondary"}>
- {row.active ? <Trans>Active</Trans> : <Trans>Inactive</Trans>}
+ <Badge variant={row.published ? "green" : "gray"}>
+ {row.published ? (
+ <Trans>Published</Trans>
+ ) : (
+ <Trans>Draft</Trans>
+ )}
</Badge>
</div>
))}
diff --git a/apps/erp/app/modules/workflows/workflows.models.ts b/apps/erp/app/modules/workflows/workflows.models.ts
index b3e7ba8d2d..036a0c5d05 100644
--- a/apps/erp/app/modules/workflows/workflows.models.ts
+++ b/apps/erp/app/modules/workflows/workflows.models.ts
@@ -14,7 +14,7 @@ export const workflowDefinitionSaveValidator = z.object({
formatVersion: zfd.numeric(z.number().int())
});
-/** Layout only. The one payload a live version accepts — see `$id.positions.tsx`. */
+/** Layout only. The one payload a published version accepts — see `$id.positions.tsx`. */
export const workflowNodePositionsValidator = z.object({
versionId: z.string().min(1, { message: "Version is required" }),
positions: z.string().min(1)
@@ -66,10 +66,6 @@ export const workflowPublishValidator = z.object({
versionId: z.string().min(1, { message: "Version is required" })
});
-export const workflowToggleValidator = z.object({
- active: zfd.checkbox()
-});
-
export const workflowVersionValidator = z.object({
copyFromVersionId: z.string().min(1, { message: "Version is required" })
});
diff --git a/apps/erp/app/modules/workflows/workflows.server.ts b/apps/erp/app/modules/workflows/workflows.server.ts
index a0913f58aa..a72a256df3 100644
--- a/apps/erp/app/modules/workflows/workflows.server.ts
+++ b/apps/erp/app/modules/workflows/workflows.server.ts
@@ -20,22 +20,11 @@ import {
const logger = getLogger("erp", "workflows");
export const LOCKED_VERSION_MESSAGE =
- "This version is live. Create a new version to make changes.";
-
-export function getWorkflowLockFlags({
- versionId,
- activeVersionId
-}: {
- versionId: string;
- activeVersionId: string | null;
-}) {
- const isLive = activeVersionId !== null && versionId === activeVersionId;
- return { isLive, isVersionLocked: isLive };
-}
+ "This version is published. Create a new version to make changes.";
/**
- * The promoted version is read-only; every mutating route calls this. An id that
- * resolves to nothing returns `{ ok: true }` — it cannot be the active version —
+ * The published version is read-only; every mutating route calls this. An id that
+ * resolves to nothing returns `{ ok: true }` — it cannot be the published version —
* matching `checkRevisionLock`'s unresolvable-is-unlocked rule.
*/
export async function checkWorkflowVersionLock(
@@ -46,16 +35,11 @@ export async function checkWorkflowVersionLock(
if (state.error || !state.data) return { ok: true };
const workflow = state.data.workflow as {
- activeVersionId: string | null;
+ publishedVersionId: string | null;
} | null;
if (!workflow) return { ok: true };
- const { isVersionLocked } = getWorkflowLockFlags({
- versionId,
- activeVersionId: workflow.activeVersionId
- });
-
- return isVersionLocked
+ return versionId === workflow.publishedVersionId
? { ok: false, message: LOCKED_VERSION_MESSAGE }
: { ok: true };
}
@@ -74,7 +58,7 @@ const lockCompany: CompanyLock = (trx, companyId) =>
sql`SELECT pg_advisory_xact_lock(hashtext(${companyId}))`.execute(trx);
/**
- * Rewrites the workflow's trigger rows to match whatever is now promoted, and
+ * Rewrites the workflow's trigger rows to match whatever is now published, and
* wakes the scheduler chain so a scheduled workflow starts within minutes rather
* than waiting for the hourly backstop.
*
@@ -136,8 +120,7 @@ export async function publishWorkflowVersion(
const promoted = await client
.from("workflow")
.update({
- activeVersionId: versionId,
- active: true,
+ publishedVersionId: versionId,
updatedBy: userId,
updatedAt: datetime.timestamp()
})
@@ -151,24 +134,28 @@ export async function publishWorkflowVersion(
return syncAndWake(companyId, workflowId);
}
-export async function setWorkflowActive(
+/**
+ * The inverse of {@link publishWorkflowVersion}, and the only way to switch a workflow off.
+ *
+ * Takes no boolean: publishing needs a version id and has to pass validation first, so the
+ * two directions cannot share one entry point.
+ */
+export async function unpublishWorkflow(
client: SupabaseClient<Database>,
{
workflowId,
companyId,
- userId,
- active
+ userId
}: {
workflowId: string;
companyId: string;
userId: string;
- active: boolean;
}
): Promise<WorkflowSyncResult> {
const updated = await client
.from("workflow")
.update({
- active,
+ publishedVersionId: null,
updatedBy: userId,
updatedAt: datetime.timestamp()
})
@@ -179,7 +166,8 @@ export async function setWorkflowActive(
return { ok: false, issues: [], message: updated.error.message };
}
- // Turning a workflow off must still sync — that is what deletes its trigger rows.
+ // Unpublishing must still sync — that is what deletes the trigger rows and clears
+ // nextRunAt, which is what actually stops the workflow firing.
return syncAndWake(companyId, workflowId);
}
@@ -194,7 +182,7 @@ export async function setWorkflowActive(
*
* Never throws: the row is already deleted, so failing here must not present the
* delete as failed. The orphan is wasted work, not incorrect behaviour, and the
- * next publish or toggle in the company reconciles it away.
+ * next publish or unpublish in the company reconciles it away.
*/
export async function syncAfterWorkflowDelete(
companyId: string,
diff --git a/apps/erp/app/modules/workflows/workflows.service.ts b/apps/erp/app/modules/workflows/workflows.service.ts
index 7e21de570a..9e245f741b 100644
--- a/apps/erp/app/modules/workflows/workflows.service.ts
+++ b/apps/erp/app/modules/workflows/workflows.service.ts
@@ -15,7 +15,7 @@ export async function getWorkflows(
let query = client
.from("workflow")
.select(
- "id, name, description, ownerId, active, activeVersionId, createdAt, updatedAt",
+ "id, name, description, ownerId, publishedVersionId, createdAt, updatedAt",
{ count: "exact" }
)
.eq("companyId", companyId);
@@ -25,9 +25,9 @@ export async function getWorkflows(
}
if (args) {
- // "status" is a derived filter — Published means a live version is promoted
- // (activeVersionId set), Draft means none. There is no status column, so
- // translate it into an activeVersionId null test and keep it out of the
+ // "status" is a derived filter — Published means a version is published
+ // (publishedVersionId set), Draft means none. There is no status column, so
+ // translate it into a publishedVersionId null test and keep it out of the
// generic column-filter pipeline (which can only emit eq/in/etc.).
const statusFilters: Filter[] = [];
const columnFilters: Filter[] = [];
@@ -37,9 +37,9 @@ export async function getWorkflows(
for (const filter of statusFilters) {
if (filter.value === "Published") {
- query = query.not("activeVersionId", "is", null);
+ query = query.not("publishedVersionId", "is", null);
} else if (filter.value === "Draft") {
- query = query.is("activeVersionId", null);
+ query = query.is("publishedVersionId", null);
}
}
@@ -59,7 +59,7 @@ export async function getWorkflow(
return client
.from("workflow")
.select(
- "id, name, description, ownerId, active, activeVersionId, nextRunAt, canvasState, createdAt, updatedAt"
+ "id, name, description, ownerId, publishedVersionId, nextRunAt, canvasState, createdAt, updatedAt"
)
.eq("id", id)
.eq("companyId", companyId)
@@ -124,8 +124,7 @@ export async function insertWorkflow(
description: workflow.description ?? null,
companyId: workflow.companyId,
ownerId: workflow.createdBy,
- createdBy: workflow.createdBy,
- active: false
+ createdBy: workflow.createdBy
})
.select("id")
.single();
@@ -203,7 +202,7 @@ export async function updateWorkflowDefinition(
}
/**
- * The one writer allowed on a live version. It reads the version's nodes and re-writes
+ * The one writer allowed on a published version. It reads the version's nodes and re-writes
* only `position`, only for node ids that already exist — `edges`, `data`, `expanded`,
* `name` and `type` are never touched, and an unknown id is ignored. The endpoint is
* therefore incapable of changing behaviour even when called by hand.
@@ -486,7 +485,7 @@ export async function getWorkflowVersionOwnership(
) {
return client
.from("workflowVersion")
- .select("workflowId, workflow(activeVersionId)")
+ .select("workflowId, workflow(publishedVersionId)")
.eq("id", versionId)
.eq("companyId", companyId)
.maybeSingle();
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 83807a262e..1b2ca4248a 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-08-22T01:32:58.017Z",
+ "generated": "2026-08-24T17:18:07.184Z",
"totalTools": 1443,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/workflow+/$id.tsx b/apps/erp/app/routes/x+/workflow+/$id.tsx
index 37cafb81f7..ffe1f6f04e 100644
--- a/apps/erp/app/routes/x+/workflow+/$id.tsx
+++ b/apps/erp/app/routes/x+/workflow+/$id.tsx
@@ -146,7 +146,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
definition: read.definition,
failure: null,
message: null,
- isVersionLocked: versionId === workflow.activeVersionId
+ isVersionLocked: versionId === workflow.publishedVersionId
};
}
diff --git a/apps/erp/app/routes/x+/workflow+/$id.toggle.tsx b/apps/erp/app/routes/x+/workflow+/$id.unpublish.tsx
similarity index 55%
rename from apps/erp/app/routes/x+/workflow+/$id.toggle.tsx
rename to apps/erp/app/routes/x+/workflow+/$id.unpublish.tsx
index 7d2d0a0d19..dc363e1c54 100644
--- a/apps/erp/app/routes/x+/workflow+/$id.toggle.tsx
+++ b/apps/erp/app/routes/x+/workflow+/$id.unpublish.tsx
@@ -2,15 +2,14 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { requirePlan } from "@carbon/ee/plan.server";
-import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import { workflowToggleValidator } from "~/modules/workflows";
-import { setWorkflowActive } from "~/modules/workflows/workflows.server";
+import { unpublishWorkflow } from "~/modules/workflows/workflows.server";
import { path } from "~/utils/path";
-// The one route both the list switch and the header switch post to, so there is
-// exactly one place that has to remember to re-sync the trigger rows.
+// The one route both the list row menu and the builder button post to, so there is
+// exactly one place that has to remember to re-sync the trigger rows. It carries no
+// body: clearing the published version is the whole operation.
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
@@ -27,34 +26,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id } = params;
if (!id) throw new Error("id is not found");
- const formData = await request.formData();
- const validation = await validator(workflowToggleValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const toggled = await setWorkflowActive(client, {
+ const unpublished = await unpublishWorkflow(client, {
workflowId: id,
companyId,
- userId,
- active: validation.data.active
+ userId
});
- if (!toggled.ok) {
+ if (!unpublished.ok) {
return data(
{ success: false },
- await flash(request, error(null, toggled.message ?? "Failed to update"))
+ await flash(
+ request,
+ error(null, unpublished.message ?? "Failed to unpublish")
+ )
);
}
return data(
{ success: true },
- await flash(
- request,
- success(validation.data.active ? "Workflow is on" : "Workflow is off")
- )
+ await flash(request, success("Workflow unpublished"))
);
}
diff --git a/apps/erp/app/routes/x+/workflows+/_index.tsx b/apps/erp/app/routes/x+/workflows+/_index.tsx
index 0ae5362ff2..e9f246cdd5 100644
--- a/apps/erp/app/routes/x+/workflows+/_index.tsx
+++ b/apps/erp/app/routes/x+/workflows+/_index.tsx
@@ -34,15 +34,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
const rows = workflows.data ?? [];
- const activeVersionIds = rows
- .map((row) => row.activeVersionId)
+ const publishedVersionIds = rows
+ .map((row) => row.publishedVersionId)
.filter((id): id is string => id !== null);
const versionNumbers: Record<string, number> = {};
- if (activeVersionIds.length) {
+ if (publishedVersionIds.length) {
const versions = await getWorkflowVersionNumbers(
client,
- activeVersionIds,
+ publishedVersionIds,
companyId
);
for (const version of versions.data ?? []) {
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 321fdf1d92..b49b719c12 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -2198,7 +2198,8 @@ export const path = {
workflows: `${x}/workflows`,
workflowTestRun: (id: string) =>
generatePath(`${x}/workflow/${id}/test-run`),
- workflowToggle: (id: string) => generatePath(`${x}/workflow/${id}/toggle`),
+ workflowUnpublish: (id: string) =>
+ generatePath(`${x}/workflow/${id}/unpublish`),
workflowVersionNew: (id: string) =>
generatePath(`${x}/workflow/${id}/version/new`)
}
diff --git a/docs/content/docs/reference/workflow-runs.mdx b/docs/content/docs/reference/workflow-runs.mdx
index ba80c50029..de39a83f20 100644
--- a/docs/content/docs/reference/workflow-runs.mdx
+++ b/docs/content/docs/reference/workflow-runs.mdx
@@ -49,7 +49,7 @@ If a condition matches none of its paths and has no **"Otherwise"**, that step *
<Status name="Succeeded" accent>Every step that ran finished without error.</Status>
<Status name="Failed" terminal>At least one step failed, or the run was stopped by the 500-step ceiling.</Status>
<Status name="Blocked" terminal>A loop guard stopped it before any step ran. The reason is on the run.</Status>
- <Status name="Skipped" terminal>It never started — the workflow was switched off, or a scheduled run came due too late, or its previous run was still going.</Status>
+ <Status name="Skipped" terminal>It never started — the workflow was unpublished, or a scheduled run came due too late, or its previous run was still going.</Status>
</StatusFlow>
Individual steps use a shorter list: **Running**, **Succeeded**, **Failed**, **Skipped**. There is no blocked or queued step — those are decisions about the run as a whole.
diff --git a/docs/content/docs/reference/workflows.mdx b/docs/content/docs/reference/workflows.mdx
index 5481388a02..16e6117794 100644
--- a/docs/content/docs/reference/workflows.mdx
+++ b/docs/content/docs/reference/workflows.mdx
@@ -110,11 +110,9 @@ There is no Save button. The builder saves as you work and reports its state nex
**"Publish"** is all-or-nothing. Carbon validates the whole workflow — a trigger exists, no step loops back, every step is reachable, every required field is filled, every variable resolves and comes from upstream, every type lines up — and if anything is wrong, **nothing is written**. The problems appear in a panel headed **"3 problems — not published"**, and clicking one pans the canvas to the step it belongs to.
-<Callout type="warn" title="“Published” and “Active” are different switches">
-Publishing promotes a version to live **and** turns the workflow on. The **"Active"** switch, on the list and in the builder, is a separate kill switch: turning it off removes the workflow's trigger registrations so nothing fires, while leaving the published version in place. A workflow only runs when it is active *and* has a live version.
-</Callout>
+Publishing is also the only on/off switch there is. Whichever version you publish is the one that runs, and **"Unpublish"** — on the published version in the builder, or from a workflow's row menu on the list — stops the workflow entirely: its trigger registrations are removed so nothing fires. Nothing is deleted, so publishing a version again starts it back up. A workflow with nothing published reads as **Draft**.
-Publishing also freezes that version. The builder locks with *"This version is live. Create a new version to edit."* — to keep working, use the version menu to create a new version, which copies the live one and numbers it one higher. Older versions stay readable, and a run that is already in flight keeps using the version it started with even if you promote another one mid-run.
+Publishing also freezes that version. The builder locks with *"This version is published. Create a new version to edit."* — to keep working, use the version menu to create a new version, which copies the published one and numbers it one higher. Older versions stay readable, and a run that is already in flight keeps using the version it started with even if you publish another one mid-run.
**Test run.** The trigger card has a **"Test run"** button, available to the workflow's owner. It executes for real, so anything it creates or sends actually happens, but the result is never written to run history: *"The result will not appear on the Runs page."*
@@ -126,7 +124,7 @@ Workflows have their own permission module, seeded from your existing settings a
| --- | --- |
| View | Open the list, the builder, and run history |
| Create | Add a workflow, or create a new version of one |
-| Update | Edit, publish, rename, toggle active, test run |
+| Update | Edit, publish, unpublish, rename, test run |
| Delete | Delete a workflow, its versions, and its run history |
<Callout type="note" title="A workflow runs as its owner, not as whoever triggered it">
diff --git a/packages/checks/src/invariants/workflow-trigger-event-drift.sql b/packages/checks/src/invariants/workflow-trigger-event-drift.sql
index 75311ea07f..8fff88e7bf 100644
--- a/packages/checks/src/invariants/workflow-trigger-event-drift.sql
+++ b/packages/checks/src/invariants/workflow-trigger-event-drift.sql
@@ -1,22 +1,22 @@
--- invariant: an active workflow's workflowTriggerEvent rows equal the event ids
--- on its active version's trigger nodes; returns violating rows (none = healthy)
-WITH active AS (
+-- invariant: a published workflow's workflowTriggerEvent rows equal the event ids
+-- on its published version's trigger nodes; returns violating rows (none = healthy)
+WITH published AS (
SELECT w."id" AS "workflowId",
w."companyId",
- w."activeVersionId",
+ w."publishedVersionId",
v."nodes"
FROM "workflow" w
JOIN "workflowVersion" v
- ON v."id" = w."activeVersionId"
+ ON v."id" = w."publishedVersionId"
AND v."companyId" = w."companyId"
- WHERE w."active" = TRUE
+ WHERE w."publishedVersionId" IS NOT NULL
),
declared AS (
SELECT a."workflowId",
a."companyId",
- a."activeVersionId",
+ a."publishedVersionId",
e AS "eventId"
- FROM active a,
+ FROM published a,
LATERAL jsonb_array_elements(a."nodes") n,
LATERAL jsonb_array_elements_text(n -> 'data' -> 'events') e
WHERE n ->> 'type' = 'trigger'
@@ -33,7 +33,7 @@ WHERE t."eventId" IS NULL
UNION ALL
SELECT t."workflowId", t."companyId", t."eventId",
- 'dispatch row with no matching trigger node on an active, promoted version' AS "violation"
+ 'dispatch row with no matching trigger node on a published version' AS "violation"
FROM "workflowTriggerEvent" t
LEFT JOIN declared d
ON d."workflowId" = t."workflowId"
@@ -44,10 +44,10 @@ WHERE d."eventId" IS NULL
UNION ALL
SELECT t."workflowId", t."companyId", t."eventId",
- 'dispatch row points at a version that is no longer the active one' AS "violation"
+ 'dispatch row points at a version that is no longer the published one' AS "violation"
FROM "workflowTriggerEvent" t
JOIN declared d
ON d."workflowId" = t."workflowId"
AND d."companyId" = t."companyId"
AND d."eventId" = t."eventId"
-WHERE t."workflowVersionId" <> d."activeVersionId";
+WHERE t."workflowVersionId" <> d."publishedVersionId";
diff --git a/packages/checks/src/scripts/check-workflow-events.ts b/packages/checks/src/scripts/check-workflow-events.ts
index 373ba93e6f..45e74de420 100644
--- a/packages/checks/src/scripts/check-workflow-events.ts
+++ b/packages/checks/src/scripts/check-workflow-events.ts
@@ -39,7 +39,7 @@ async function main() {
FROM "workflowTriggerEvent" t
JOIN "workflow" w
ON w."id" = t."workflowId" AND w."companyId" = t."companyId"
- WHERE w."active" = TRUE
+ WHERE w."publishedVersionId" IS NOT NULL
ORDER BY t."eventId"`
);
diff --git a/packages/database/src/datasets/data/motor/workflows.ts b/packages/database/src/datasets/data/motor/workflows.ts
index 4fbb0b3a42..251cacedff 100644
--- a/packages/database/src/datasets/data/motor/workflows.ts
+++ b/packages/database/src/datasets/data/motor/workflows.ts
@@ -46,7 +46,7 @@ export function buildMotorWorkflows(refs: {
name: "Assign new sales orders",
description:
"Puts every incoming motor order on someone's desk the moment it is created.",
- active: true,
+ published: true,
nodes: [
{
id: "trigger_order",
@@ -78,7 +78,7 @@ export function buildMotorWorkflows(refs: {
name: "Escalate high-priority issues",
description:
"Notifies the quality owner when an issue is raised to High or Critical.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_priority",
@@ -161,7 +161,7 @@ export function buildMotorWorkflows(refs: {
name: "Flag large purchase orders",
description:
"Works out a purchase order's total when its status changes and flags anything over 10,000.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_po_status",
@@ -243,7 +243,7 @@ export function buildMotorWorkflows(refs: {
name: "Chase jobs that have not started producing",
description:
"Every weekday morning, finds in-progress jobs with nothing completed yet and puts each one back on the owner's desk.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_morning",
@@ -325,7 +325,7 @@ export function buildMotorWorkflows(refs: {
name: "Announce a released job",
description:
"Tells whoever released a job that it is now on the floor. Fires on the business moment, not on a column change.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_released",
@@ -372,7 +372,7 @@ export function buildMotorWorkflows(refs: {
name: "Open an issue when a shipment is voided",
description:
"A voided shipment usually means something went wrong in the warehouse — this raises the paperwork for it automatically.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_shipment",
@@ -444,7 +444,7 @@ export function buildMotorWorkflows(refs: {
name: "Tell an outside system a supplier was approved",
description:
"Posts to a URL of your choosing when a supplier turns Active. Point the webhook at your own endpoint before switching this on.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_supplier",
diff --git a/packages/database/src/datasets/data/precision/workflows.ts b/packages/database/src/datasets/data/precision/workflows.ts
index ae38da4d92..d58433ba87 100644
--- a/packages/database/src/datasets/data/precision/workflows.ts
+++ b/packages/database/src/datasets/data/precision/workflows.ts
@@ -46,7 +46,7 @@ export function buildPrecisionWorkflows(refs: {
name: "Assign new sales orders",
description:
"Puts every incoming job on an estimator's desk the moment the order is created.",
- active: true,
+ published: true,
nodes: [
{
id: "trigger_order",
@@ -78,7 +78,7 @@ export function buildPrecisionWorkflows(refs: {
name: "Escalate high-priority issues",
description:
"Notifies the quality owner when an issue is raised to High or Critical.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_priority",
@@ -161,7 +161,7 @@ export function buildPrecisionWorkflows(refs: {
name: "Flag large purchase orders",
description:
"Works out a purchase order's total when its status changes and flags anything over 10,000.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_po_status",
@@ -243,7 +243,7 @@ export function buildPrecisionWorkflows(refs: {
name: "Chase jobs that have not started producing",
description:
"Every weekday morning, finds in-progress jobs with nothing completed yet and puts each one back on the owner's desk.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_morning",
@@ -325,7 +325,7 @@ export function buildPrecisionWorkflows(refs: {
name: "Announce a released job",
description:
"Tells whoever released a job that it is now on the floor. Fires on the business moment, not on a column change.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_released",
@@ -372,7 +372,7 @@ export function buildPrecisionWorkflows(refs: {
name: "Open an issue when a shipment is voided",
description:
"A voided shipment usually means something went wrong in the warehouse — this raises the paperwork for it automatically.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_shipment",
@@ -444,7 +444,7 @@ export function buildPrecisionWorkflows(refs: {
name: "Tell an outside system a supplier was approved",
description:
"Posts to a URL of your choosing when a supplier turns Active. Point the webhook at your own endpoint before switching this on.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_supplier",
diff --git a/packages/database/src/datasets/data/robotics/workflows.ts b/packages/database/src/datasets/data/robotics/workflows.ts
index bf6121c7a1..d32e287d3e 100644
--- a/packages/database/src/datasets/data/robotics/workflows.ts
+++ b/packages/database/src/datasets/data/robotics/workflows.ts
@@ -46,7 +46,7 @@ export function buildRoboticsWorkflows(refs: {
name: "Assign new sales orders",
description:
"Puts every incoming arm order on someone's desk the moment it is created.",
- active: true,
+ published: true,
nodes: [
{
id: "trigger_order",
@@ -78,7 +78,7 @@ export function buildRoboticsWorkflows(refs: {
name: "Escalate high-priority issues",
description:
"Notifies the quality owner when an issue is raised to High or Critical.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_priority",
@@ -161,7 +161,7 @@ export function buildRoboticsWorkflows(refs: {
name: "Flag large purchase orders",
description:
"Works out a purchase order's total when its status changes and flags anything over 10,000.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_po_status",
@@ -243,7 +243,7 @@ export function buildRoboticsWorkflows(refs: {
name: "Chase jobs that have not started producing",
description:
"Every weekday morning, finds in-progress jobs with nothing completed yet and puts each one back on the owner's desk.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_morning",
@@ -325,7 +325,7 @@ export function buildRoboticsWorkflows(refs: {
name: "Announce a released job",
description:
"Tells whoever released a job that it is now on the floor. Fires on the business moment, not on a column change.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_released",
@@ -372,7 +372,7 @@ export function buildRoboticsWorkflows(refs: {
name: "Open an issue when a shipment is voided",
description:
"A voided shipment usually means something went wrong in the warehouse — this raises the paperwork for it automatically.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_shipment",
@@ -444,7 +444,7 @@ export function buildRoboticsWorkflows(refs: {
name: "Tell an outside system a supplier was approved",
description:
"Posts to a URL of your choosing when a supplier turns Active. Point the webhook at your own endpoint before switching this on.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_supplier",
diff --git a/packages/database/src/datasets/data/satellite/workflows.ts b/packages/database/src/datasets/data/satellite/workflows.ts
index 39b3aa20f2..6d0faa4570 100644
--- a/packages/database/src/datasets/data/satellite/workflows.ts
+++ b/packages/database/src/datasets/data/satellite/workflows.ts
@@ -46,7 +46,7 @@ export function buildSeedWorkflows(refs: {
name: "Assign new sales orders",
description:
"Puts every incoming sales order on someone's desk the moment it is created.",
- active: true,
+ published: true,
nodes: [
{
id: "trigger_order",
@@ -78,7 +78,7 @@ export function buildSeedWorkflows(refs: {
name: "Escalate high-priority issues",
description:
"Notifies the quality owner when an issue is raised to High or Critical.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_priority",
@@ -161,7 +161,7 @@ export function buildSeedWorkflows(refs: {
name: "Flag large purchase orders",
description:
"Works out a purchase order's total when its status changes and flags anything over 10,000.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_po_status",
@@ -243,7 +243,7 @@ export function buildSeedWorkflows(refs: {
name: "Chase jobs that have not started producing",
description:
"Every weekday morning, finds in-progress jobs with nothing completed yet and puts each one back on the owner's desk.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_morning",
@@ -325,7 +325,7 @@ export function buildSeedWorkflows(refs: {
name: "Announce a released job",
description:
"Tells whoever released a job that it is now on the floor. Fires on the business moment, not on a column change.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_released",
@@ -372,7 +372,7 @@ export function buildSeedWorkflows(refs: {
name: "Open an issue when a shipment is voided",
description:
"A voided shipment usually means something went wrong in the warehouse — this raises the paperwork for it automatically.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_shipment",
@@ -444,7 +444,7 @@ export function buildSeedWorkflows(refs: {
name: "Tell an outside system a supplier was approved",
description:
"Posts to a URL of your choosing when a supplier turns Active. Point the webhook at your own endpoint before switching this on.",
- active: false,
+ published: false,
nodes: [
{
id: "trigger_supplier",
diff --git a/packages/database/src/datasets/tiers/11-workflows.ts b/packages/database/src/datasets/tiers/11-workflows.ts
index 5d7e6b052d..915f9aa26b 100644
--- a/packages/database/src/datasets/tiers/11-workflows.ts
+++ b/packages/database/src/datasets/tiers/11-workflows.ts
@@ -80,13 +80,14 @@ export async function runTier11(ctx: Ctx): Promise<void> {
ownerId: userId,
issueTypeId: issueType.id
})) {
- ctx.log(`workflow — ${workflow.name}${workflow.active ? "" : " (off)"}`);
+ ctx.log(
+ `workflow — ${workflow.name}${workflow.published ? "" : " (draft)"}`
+ );
const workflowId = await insertId(ctx, "workflow", {
name: workflow.name,
description: workflow.description,
- ownerId: userId,
- active: workflow.active
+ ownerId: userId
});
const versionId = await insertId(ctx, "workflowVersion", {
@@ -97,17 +98,16 @@ export async function runTier11(ctx: Ctx): Promise<void> {
edges: JSON.stringify(workflow.edges)
});
- // Set even when the workflow is off: deactivating in the app keeps the promoted
- // version and only drops the trigger rows, so switching one on has to just work.
+ // The pointer IS the on/off switch, so an unpublished seeded workflow is a draft: no
+ // pointer, and no trigger rows either — exactly what `syncWorkflowTriggers` leaves
+ // behind when a user unpublishes one.
+ if (!workflow.published) continue;
+
await ctx.client.query(
- `UPDATE "workflow" SET "activeVersionId" = $1 WHERE "id" = $2 AND "companyId" = $3`,
+ `UPDATE "workflow" SET "publishedVersionId" = $1 WHERE "id" = $2 AND "companyId" = $3`,
[versionId, workflowId, ctx.companyId]
);
- // Trigger rows are what make a workflow fire, so an inactive one gets none —
- // the same thing `syncWorkflowTriggers` does when a user turns one off.
- if (!workflow.active) continue;
-
for (const row of triggerRowsFor(workflow.nodes)) {
await insertRow(ctx, "workflowTriggerEvent", {
workflowId,
diff --git a/packages/database/src/datasets/tiers/workflow-definitions.ts b/packages/database/src/datasets/tiers/workflow-definitions.ts
index a4972794e0..f8a3a11fa1 100644
--- a/packages/database/src/datasets/tiers/workflow-definitions.ts
+++ b/packages/database/src/datasets/tiers/workflow-definitions.ts
@@ -63,8 +63,8 @@ export type Edge = {
export type SeedWorkflow = {
name: string;
description: string;
- /** Only the simplest one ships on; the rest are there to read and switch on deliberately. */
- active: boolean;
+ /** Only the simplest one ships published; the rest are there to read and publish deliberately. */
+ published: boolean;
nodes: Node[];
edges: Edge[];
};
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index c02dfbbcf2..d61b35c23a 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -1869,6 +1869,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterialStep.jobOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.quantity"
+ },
{
$ref: "#/parameters/select"
},
@@ -1934,6 +1937,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterialStep.jobOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.quantity"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -1953,6 +1959,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterialStep.jobOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.quantity"
+ },
{
$ref: "#/parameters/body.jobMaterialStep"
},
@@ -6106,10 +6115,7 @@ export default {
$ref: "#/parameters/rowFilter.workflow.ownerId"
},
{
- $ref: "#/parameters/rowFilter.workflow.active"
- },
- {
- $ref: "#/parameters/rowFilter.workflow.activeVersionId"
+ $ref: "#/parameters/rowFilter.workflow.publishedVersionId"
},
{
$ref: "#/parameters/rowFilter.workflow.nextRunAt"
@@ -6204,10 +6210,7 @@ export default {
$ref: "#/parameters/rowFilter.workflow.ownerId"
},
{
- $ref: "#/parameters/rowFilter.workflow.active"
- },
- {
- $ref: "#/parameters/rowFilter.workflow.activeVersionId"
+ $ref: "#/parameters/rowFilter.workflow.publishedVersionId"
},
{
$ref: "#/parameters/rowFilter.workflow.nextRunAt"
@@ -6256,10 +6259,7 @@ export default {
$ref: "#/parameters/rowFilter.workflow.ownerId"
},
{
- $ref: "#/parameters/rowFilter.workflow.active"
- },
- {
- $ref: "#/parameters/rowFilter.workflow.activeVersionId"
+ $ref: "#/parameters/rowFilter.workflow.publishedVersionId"
},
{
$ref: "#/parameters/rowFilter.workflow.nextRunAt"
@@ -10320,6 +10320,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodMaterialStep.methodOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.quantity"
+ },
{
$ref: "#/parameters/select"
},
@@ -10385,6 +10388,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodMaterialStep.methodOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.quantity"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -10404,6 +10410,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodMaterialStep.methodOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.quantity"
+ },
{
$ref: "#/parameters/body.methodMaterialStep"
},
@@ -71376,6 +71385,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterialStep.quoteOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quantity"
+ },
{
$ref: "#/parameters/select"
},
@@ -71441,6 +71453,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterialStep.quoteOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quantity"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -71460,6 +71475,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterialStep.quoteOperationStepId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quantity"
+ },
{
$ref: "#/parameters/body.quoteMaterialStep"
},
@@ -99560,6 +99578,10 @@ export default {
"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `jobOperationStep.id`.<fk table='jobOperationStep' column='id'/>",
format: "text",
type: "string"
+ },
+ quantity: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -101330,7 +101352,6 @@ export default {
"companyId",
"name",
"ownerId",
- "active",
"createdBy",
"createdAt"
],
@@ -101361,12 +101382,7 @@ export default {
format: "text",
type: "string"
},
- active: {
- default: false,
- format: "boolean",
- type: "boolean"
- },
- activeVersionId: {
+ publishedVersionId: {
format: "text",
type: "string"
},
@@ -103419,6 +103435,10 @@ export default {
"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `methodOperationStep.id`.<fk table='methodOperationStep' column='id'/>",
format: "text",
type: "string"
+ },
+ quantity: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -104720,7 +104740,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -104769,7 +104789,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -132288,6 +132308,10 @@ export default {
"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `quoteOperationStep.id`.<fk table='quoteOperationStep' column='id'/>",
format: "text",
type: "string"
+ },
+ quantity: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -141117,6 +141141,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobMaterialStep.quantity": {
+ name: "quantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.consumables": {
name: "consumables",
description: "consumables",
@@ -143187,14 +143217,8 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.workflow.active": {
- name: "active",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.workflow.activeVersionId": {
- name: "activeVersionId",
+ "rowFilter.workflow.publishedVersionId": {
+ name: "publishedVersionId",
required: false,
in: "query",
type: "string"
@@ -145478,6 +145502,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.methodMaterialStep.quantity": {
+ name: "quantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.inspectionSample": {
name: "inspectionSample",
description: "inspectionSample",
@@ -177665,6 +177695,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.quoteMaterialStep.quantity": {
+ name: "quantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.nonConformanceSupplier": {
name: "nonConformanceSupplier",
description: "nonConformanceSupplier",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index ee15a312b7..3b2e81474a 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -59171,8 +59171,6 @@ export type Database = {
}
workflow: {
Row: {
- active: boolean
- activeVersionId: string | null
canvasState: Json | null
companyId: string
createdAt: string
@@ -59182,12 +59180,11 @@ export type Database = {
name: string
nextRunAt: string | null
ownerId: string
+ publishedVersionId: string | null
updatedAt: string | null
updatedBy: string | null
}
Insert: {
- active?: boolean
- activeVersionId?: string | null
canvasState?: Json | null
companyId: string
createdAt?: string
@@ -59197,12 +59194,11 @@ export type Database = {
name: string
nextRunAt?: string | null
ownerId: string
+ publishedVersionId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
- active?: boolean
- activeVersionId?: string | null
canvasState?: Json | null
companyId?: string
createdAt?: string
@@ -59212,17 +59208,11 @@ export type Database = {
name?: string
nextRunAt?: string | null
ownerId?: string
+ publishedVersionId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
Relationships: [
- {
- foreignKeyName: "workflow_activeVersionId_fkey"
- columns: ["activeVersionId", "companyId"]
- isOneToOne: false
- referencedRelation: "workflowVersion"
- referencedColumns: ["id", "companyId"]
- },
{
foreignKeyName: "workflow_companyId_fkey"
columns: ["companyId"]
@@ -59321,6 +59311,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "workflow_publishedVersionId_fkey"
+ columns: ["publishedVersionId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workflowVersion"
+ referencedColumns: ["id", "companyId"]
+ },
{
foreignKeyName: "workflow_updatedBy_fkey"
columns: ["updatedBy"]
@@ -68515,14 +68512,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71948,14 +71945,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -72502,14 +72499,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index ee15a312b7..3b2e81474a 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -59171,8 +59171,6 @@ export type Database = {
}
workflow: {
Row: {
- active: boolean
- activeVersionId: string | null
canvasState: Json | null
companyId: string
createdAt: string
@@ -59182,12 +59180,11 @@ export type Database = {
name: string
nextRunAt: string | null
ownerId: string
+ publishedVersionId: string | null
updatedAt: string | null
updatedBy: string | null
}
Insert: {
- active?: boolean
- activeVersionId?: string | null
canvasState?: Json | null
companyId: string
createdAt?: string
@@ -59197,12 +59194,11 @@ export type Database = {
name: string
nextRunAt?: string | null
ownerId: string
+ publishedVersionId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
- active?: boolean
- activeVersionId?: string | null
canvasState?: Json | null
companyId?: string
createdAt?: string
@@ -59212,17 +59208,11 @@ export type Database = {
name?: string
nextRunAt?: string | null
ownerId?: string
+ publishedVersionId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
Relationships: [
- {
- foreignKeyName: "workflow_activeVersionId_fkey"
- columns: ["activeVersionId", "companyId"]
- isOneToOne: false
- referencedRelation: "workflowVersion"
- referencedColumns: ["id", "companyId"]
- },
{
foreignKeyName: "workflow_companyId_fkey"
columns: ["companyId"]
@@ -59321,6 +59311,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "workflow_publishedVersionId_fkey"
+ columns: ["publishedVersionId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workflowVersion"
+ referencedColumns: ["id", "companyId"]
+ },
{
foreignKeyName: "workflow_updatedBy_fkey"
columns: ["updatedBy"]
@@ -68515,14 +68512,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71948,14 +71945,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -72502,14 +72499,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20260824163808_workflow-publish-unpublish.sql b/packages/database/supabase/migrations/20260824163808_workflow-publish-unpublish.sql
new file mode 100644
index 0000000000..e6d6475fa9
--- /dev/null
+++ b/packages/database/supabase/migrations/20260824163808_workflow-publish-unpublish.sql
@@ -0,0 +1,32 @@
+-- Publishing is now the only on-off switch: workflow."publishedVersionId" set means the
+-- workflow runs that version, NULL means it is a draft and nothing fires. The old "active"
+-- boolean was a second switch for the same idea, and it is what leaked the word "active"
+-- into the UI beside the pointer column that means something else.
+
+-- A workflow that was published but switched OFF is deliberately paused. Collapsing the two
+-- flags would silently resume it, so unpublish it while "active" still records that intent.
+UPDATE "workflow" SET "activeVersionId" = NULL WHERE "active" = FALSE;
+
+-- ...and its dispatch rows with it, matching what syncWorkflowTriggers does on unpublish.
+-- Must run BEFORE the column is dropped.
+DELETE FROM "workflowTriggerEvent" te
+ USING "workflow" w
+ WHERE te."workflowId" = w."id"
+ AND te."companyId" = w."companyId"
+ AND w."active" = FALSE;
+
+-- Postgres silently drops any index whose predicate names a dropped column, and
+-- "workflow_due_idx" is partial on "active" = TRUE. Rebuild it below, or the scheduler
+-- loses its due-workflow index with no error anywhere.
+DROP INDEX IF EXISTS "workflow_due_idx";
+
+ALTER TABLE "workflow" DROP COLUMN "active";
+ALTER TABLE "workflow" RENAME COLUMN "activeVersionId" TO "publishedVersionId";
+
+-- A column rename does not rename its constraint.
+ALTER TABLE "workflow"
+ RENAME CONSTRAINT "workflow_activeVersionId_fkey" TO "workflow_publishedVersionId_fkey";
+
+-- Both predicate halves still matter: deleting the published version leaves "nextRunAt" set.
+CREATE INDEX "workflow_due_idx" ON "workflow" ("nextRunAt")
+ WHERE "nextRunAt" IS NOT NULL AND "publishedVersionId" IS NOT NULL;
diff --git a/packages/jobs/src/workflows/engine/batch.test.ts b/packages/jobs/src/workflows/engine/batch.test.ts
index b7eb31a30a..ddaa2eaa1f 100644
--- a/packages/jobs/src/workflows/engine/batch.test.ts
+++ b/packages/jobs/src/workflows/engine/batch.test.ts
@@ -184,7 +184,7 @@ beforeEach(() => {
eventId: "job.status.changed",
status: "Queued"
},
- workflowActive: true,
+ workflowPublished: true,
companyGroupId: "cg1",
version: definition
});
diff --git a/packages/jobs/src/workflows/engine/end-to-end.test.ts b/packages/jobs/src/workflows/engine/end-to-end.test.ts
index b4d1242853..2b10450006 100644
--- a/packages/jobs/src/workflows/engine/end-to-end.test.ts
+++ b/packages/jobs/src/workflows/engine/end-to-end.test.ts
@@ -72,7 +72,7 @@ function seed(eventId: string, definition: SeedDefinition): void {
eventId,
status: "Queued"
},
- workflowActive: true,
+ workflowPublished: true,
companyGroupId: "cg1",
version: definition
});
diff --git a/packages/jobs/src/workflows/engine/execute.test.ts b/packages/jobs/src/workflows/engine/execute.test.ts
index 68435e2bf6..a7fc3f1af0 100644
--- a/packages/jobs/src/workflows/engine/execute.test.ts
+++ b/packages/jobs/src/workflows/engine/execute.test.ts
@@ -138,7 +138,7 @@ beforeEach(() => {
eventId: "purchaseOrder.status.changed",
status: "Queued"
},
- workflowActive: true,
+ workflowPublished: true,
companyGroupId: "cg1",
version: definition
});
diff --git a/packages/jobs/src/workflows/engine/execute.ts b/packages/jobs/src/workflows/engine/execute.ts
index 59e75f59b4..d8d8644170 100644
--- a/packages/jobs/src/workflows/engine/execute.ts
+++ b/packages/jobs/src/workflows/engine/execute.ts
@@ -69,7 +69,7 @@ export interface EngineLogger {
error(message: string, ...rest: unknown[]): void;
}
-const SWITCHED_OFF = "This workflow was switched off before the run started.";
+const UNPUBLISHED = "This workflow was unpublished before the run started.";
const NO_PERMISSIONS =
"The permissions for the owner of this workflow could not be read.";
const NOT_AVAILABLE = "This kind of step is not available yet.";
@@ -375,12 +375,12 @@ export async function executeWorkflowRun(params: {
const startedAt = datetime.timestamp();
- if (!context.workflowActive) {
+ if (!context.workflowPublished) {
await finishRun(db, {
runId: payload.runId,
companyId: payload.companyId,
status: "Skipped",
- statusReason: SWITCHED_OFF,
+ statusReason: UNPUBLISHED,
startedAt
});
return { settled: "Skipped" as const };
diff --git a/packages/jobs/src/workflows/engine/log.ts b/packages/jobs/src/workflows/engine/log.ts
index 5252f8bb98..5f47f8ab03 100644
--- a/packages/jobs/src/workflows/engine/log.ts
+++ b/packages/jobs/src/workflows/engine/log.ts
@@ -12,7 +12,8 @@ export interface RunContext {
eventId: string;
status: string;
};
- workflowActive: boolean;
+ /** The workflow has a published version at all — the pointer IS the on/off switch. */
+ workflowPublished: boolean;
/** The company's group, which service functions need. Falls back to the company. */
companyGroupId: string;
version: {
@@ -51,7 +52,7 @@ export async function loadRunContext(
"r.workflowVersionId as workflowVersionId",
"r.eventId as eventId",
"r.status as status",
- "w.active as workflowActive",
+ "w.publishedVersionId as publishedVersionId",
"c.companyGroupId as companyGroupId",
"v.formatVersion as formatVersion",
"v.nodes as nodes",
@@ -73,7 +74,7 @@ export async function loadRunContext(
eventId: row.eventId,
status: row.status
},
- workflowActive: row.workflowActive === true,
+ workflowPublished: row.publishedVersionId !== null,
companyGroupId: row.companyGroupId ?? row.companyId,
version:
row.nodes === null
diff --git a/packages/jobs/src/workflows/scheduler.test.ts b/packages/jobs/src/workflows/scheduler.test.ts
index 3b740f2e25..ee051f62fb 100644
--- a/packages/jobs/src/workflows/scheduler.test.ts
+++ b/packages/jobs/src/workflows/scheduler.test.ts
@@ -122,7 +122,7 @@ describe("planClaims", () => {
id,
companyId: "cmp_1",
ownerId: "usr_1",
- activeVersionId: "wfv_1",
+ publishedVersionId: "wfv_1",
nextRunAt: new Date("2026-08-01T09:00:00Z"),
nodes
});
diff --git a/packages/jobs/src/workflows/scheduler.ts b/packages/jobs/src/workflows/scheduler.ts
index 797ccbdfc9..b9667af439 100644
--- a/packages/jobs/src/workflows/scheduler.ts
+++ b/packages/jobs/src/workflows/scheduler.ts
@@ -23,7 +23,7 @@ export type DueWorkflow = {
id: string;
companyId: string;
ownerId: string;
- activeVersionId: string;
+ publishedVersionId: string;
nextRunAt: Date;
nodes: unknown;
};
@@ -36,19 +36,20 @@ export async function scanDue(
.selectFrom("workflow as w")
.innerJoin("workflowVersion as v", (join) =>
join
- .onRef("v.id", "=", "w.activeVersionId")
+ .onRef("v.id", "=", "w.publishedVersionId")
.onRef("v.companyId", "=", "w.companyId")
)
.select([
"w.id",
"w.companyId",
"w.ownerId",
- "w.activeVersionId",
+ "w.publishedVersionId",
"w.nextRunAt",
"v.nodes"
])
- .where("w.active", "=", true)
- .where("w.activeVersionId", "is not", null)
+ // Reads as redundant beside the join, but it is what lets the planner match the partial
+ // `workflow_due_idx` — a join qual cannot prove that index's predicate. Do not delete.
+ .where("w.publishedVersionId", "is not", null)
.where("w.nextRunAt", "<=", now.toISOString())
.orderBy("w.nextRunAt", "asc")
.limit(MAX_DUE_PER_WAKE)
@@ -57,8 +58,7 @@ export async function scanDue(
const futureRow = await db
.selectFrom("workflow as w")
.select("w.nextRunAt")
- .where("w.active", "=", true)
- .where("w.activeVersionId", "is not", null)
+ .where("w.publishedVersionId", "is not", null)
.where("w.nextRunAt", ">", now.toISOString())
.orderBy("w.nextRunAt", "asc")
.limit(1)
@@ -67,8 +67,8 @@ export async function scanDue(
return {
due: due
.filter(
- (r): r is typeof r & { activeVersionId: string } =>
- r.activeVersionId !== null
+ (r): r is typeof r & { publishedVersionId: string } =>
+ r.publishedVersionId !== null
)
.map((r) => ({
...r,
@@ -250,7 +250,7 @@ export async function dispatchDue(
const planned: PlannedRun[] = [
{
workflowId: row.id,
- workflowVersionId: row.activeVersionId,
+ workflowVersionId: row.publishedVersionId,
eventId: SCHEDULE_EVENT_ID,
ownerId: row.ownerId,
status,
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index e7a9a42e41..8171cb2721 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Importieren Sie Ihre Teile, Stücklisten, Fertigungsprozesse und Kostenk
msgid "Browse library"
msgstr "Bibliothek durchsuchen"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Durchsuchen Sie die Live-Version schreibgeschützt. Sie können die Schritte trotzdem neu anordnen, um das Layout aufzuräumen."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Bucket"
@@ -8099,6 +8099,9 @@ msgstr "Ausstellungsdatum"
msgid "Issues"
msgstr "Probleme"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "ITAR-Zertifikationen"
@@ -8564,18 +8567,12 @@ msgstr "Listenparameter"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listen sind an beide {0} und {1} angebunden, daher kann dieser Schritt nicht erkennen, welche wiederholt werden soll. Behalten Sie eine Liste nur auf einer von ihnen."
-msgid "Live"
-msgstr "Live"
-
msgid "Live on Carbon"
msgstr "Live auf Carbon"
msgid "Live reloading"
msgstr "Live-Neuladen"
-msgid "Live Version"
-msgstr "Live-Version"
-
msgid "Load newer"
msgstr "Neuere laden"
@@ -11592,6 +11589,9 @@ msgstr "Veröffentlicht"
msgid "Published by Carbon"
msgstr "Veröffentlicht von Carbon"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Veröffentlichte Versionen können nicht bearbeitet werden. Schauen Sie sich die Version schreibgeschützt an, oder erstellen Sie einen Branch einer neuen Version, um Änderungen vorzunehmen."
@@ -15714,11 +15714,11 @@ msgstr "Diese Version gehört zur Änderungsmitteilung <0>{0}</0>. Bearbeiten Si
msgid "This version cannot be opened"
msgstr "Diese Version kann nicht geöffnet werden"
-msgid "This version is live"
-msgstr "Diese Version ist live"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Diese Version ist aktiv. Erstellen Sie eine neue Version zum Bearbeiten."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "Die Definition dieser Version konnte nicht gelesen werden."
@@ -16305,6 +16305,12 @@ msgstr "Abheften {0}"
msgid "Unposted Documents"
msgstr "Unveröffentlichte Dokumente"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "Nicht eingegangene Bestellungen"
@@ -16662,9 +16668,9 @@ msgstr "Überprüfen Sie Ihre E-Mail"
msgid "Version"
msgstr "Version"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "Version {0} ist jetzt live und wird ersetzt."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Version:"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 2d72c6cc5f..feb7180110 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Bring in your parts, BOMs, Bill of Process, and costing — with Carbon'
msgid "Browse library"
msgstr "Browse library"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Browse the live version read-only. You can still rearrange steps to tidy the layout."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgid "Bucket"
msgstr "Bucket"
@@ -8099,6 +8099,9 @@ msgstr "Issued Date"
msgid "Issues"
msgstr "Issues"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr "It will stop running until you publish a version again. Nothing is deleted."
+
msgid "ITAR Certifications"
msgstr "ITAR Certifications"
@@ -8564,18 +8567,12 @@ msgstr "List Parameters"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
-msgid "Live"
-msgstr "Live"
-
msgid "Live on Carbon"
msgstr "Live on Carbon"
msgid "Live reloading"
msgstr "Live reloading"
-msgid "Live Version"
-msgstr "Live Version"
-
msgid "Load newer"
msgstr "Load newer"
@@ -11592,6 +11589,9 @@ msgstr "Published"
msgid "Published by Carbon"
msgstr "Published by Carbon"
+msgid "Published Version"
+msgstr "Published Version"
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
@@ -15714,11 +15714,11 @@ msgstr "This version belongs to change notice <0>{0}</0>. Edit it there."
msgid "This version cannot be opened"
msgstr "This version cannot be opened"
-msgid "This version is live"
-msgstr "This version is live"
+msgid "This version is published"
+msgstr "This version is published"
-msgid "This version is live. Create a new version to edit."
-msgstr "This version is live. Create a new version to edit."
+msgid "This version is published. Create a new version to edit."
+msgstr "This version is published. Create a new version to edit."
msgid "This version's definition could not be read."
msgstr "This version's definition could not be read."
@@ -16305,6 +16305,12 @@ msgstr "Unpin {0}"
msgid "Unposted Documents"
msgstr "Unposted Documents"
+msgid "Unpublish"
+msgstr "Unpublish"
+
+msgid "Unpublish {name}?"
+msgstr "Unpublish {name}?"
+
msgid "Unreceived POs"
msgstr "Unreceived POs"
@@ -16662,9 +16668,9 @@ msgstr "Verify your email"
msgid "Version"
msgstr "Version"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "Version {0} is live now and will be replaced."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr "Version {0} is published now and will be replaced."
msgid "Version:"
msgstr "Version:"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index e3c688b466..003b5bebe1 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Importa tus piezas, BOMs, Bill of Process y costos — con las herramien
msgid "Browse library"
msgstr "Examinar biblioteca"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Examina la versión en directo en solo lectura. Aún puedes reorganizar los pasos para limpiar el diseño."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Depósito"
@@ -8099,6 +8099,9 @@ msgstr "Fecha de Emisión"
msgid "Issues"
msgstr "Problemas"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "Certificaciones ITAR"
@@ -8564,18 +8567,12 @@ msgstr "Parámetros de Lista"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Las listas están conectadas tanto a {0} como a {1}, por lo que este paso no puede determinar cuál repetir. Mantén una lista solo en una de ellas."
-msgid "Live"
-msgstr "Activo"
-
msgid "Live on Carbon"
msgstr "En vivo en Carbon"
msgid "Live reloading"
msgstr "Recarga en vivo"
-msgid "Live Version"
-msgstr "Versión activa"
-
msgid "Load newer"
msgstr "Cargar más recientes"
@@ -11592,6 +11589,9 @@ msgstr "Publicado"
msgid "Published by Carbon"
msgstr "Publicado por Carbon"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Las versiones publicadas no se pueden editar. Explora en solo lectura, o crea una nueva versión para hacer cambios."
@@ -15714,11 +15714,11 @@ msgstr "Esta versión pertenece al aviso de cambio <0>{0}</0>. Edítala allí."
msgid "This version cannot be opened"
msgstr "Esta versión no se puede abrir"
-msgid "This version is live"
-msgstr "Esta versión está en vivo"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Esta versión está activa. Crea una nueva versión para editar."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "La definición de esta versión no se pudo leer."
@@ -16305,6 +16305,12 @@ msgstr "Desfijar {0}"
msgid "Unposted Documents"
msgstr "Documentos No Contabilizados"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "POs no recibidas"
@@ -16662,9 +16668,9 @@ msgstr "Verifica tu correo electrónico"
msgid "Version"
msgstr "Versión"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "La versión {0} está activa ahora y será reemplazada."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Versión:"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 3327c543c7..16051fe806 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Importez vos pièces, nomenclatures, processus de fabrication et coûts
msgid "Browse library"
msgstr "Parcourir la bibliothèque"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Parcourir la version active en lecture seule. Vous pouvez toujours réorganiser les étapes pour nettoyer la mise en page."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Compartiment"
@@ -8099,6 +8099,9 @@ msgstr "Date d'émission"
msgid "Issues"
msgstr "Problèmes"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "Certifications ITAR"
@@ -8564,18 +8567,12 @@ msgstr "Paramètres de liste"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Les listes sont connectées à la fois à {0} et {1}, donc cette étape ne peut pas savoir sur laquelle répéter. Laissez une liste sur une seule d'entre elles."
-msgid "Live"
-msgstr "Actif"
-
msgid "Live on Carbon"
msgstr "En direct sur Carbon"
msgid "Live reloading"
msgstr "Rechargement en direct"
-msgid "Live Version"
-msgstr "Version active"
-
msgid "Load newer"
msgstr "Charger les plus récents"
@@ -11592,6 +11589,9 @@ msgstr "Publié"
msgid "Published by Carbon"
msgstr "Publié par Carbon"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Les versions publiées ne peuvent pas être modifiées. Consultez en lecture seule, ou créez une branche d'une nouvelle version pour apporter des modifications."
@@ -15714,11 +15714,11 @@ msgstr "Cette version appartient au change notice <0>{0}</0>. Modifiez-le là."
msgid "This version cannot be opened"
msgstr "Cette version ne peut pas être ouverte"
-msgid "This version is live"
-msgstr "Cette version est en direct"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Cette version est en direct. Créez une nouvelle version pour modifier."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "La définition de cette version n'a pas pu être lue."
@@ -16305,6 +16305,12 @@ msgstr "Dépingler {0}"
msgid "Unposted Documents"
msgstr "Documents non comptabilisés"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "Bons de commande non reçus"
@@ -16662,9 +16668,9 @@ msgstr "Vérifiez votre email"
msgid "Version"
msgstr "Version"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "La version {0} est active maintenant et sera remplacée."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Version :"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 46ee8c79fa..a841f0f852 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -2589,8 +2589,8 @@ msgstr "अपने पार्ट्स, BOMs, Bill of Process, और को
msgid "Browse library"
msgstr "लाइब्रेरी ब्राउज़ करें"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "लाइव संस्करण को केवल-पठन के लिए ब्राउज़ करें। आप अभी भी लेआउट को व्यवस्थित करने के लिए चरणों को पुनः व्यवस्थित कर सकते हैं।"
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "बकेट"
@@ -8099,6 +8099,9 @@ msgstr "जारी तारीख"
msgid "Issues"
msgstr "समस्याएं"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "ITAR प्रमाणपत्र"
@@ -8564,18 +8567,12 @@ msgstr "सूची पैरामीटर"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "सूचियां दोनों {0} और {1} में वायर्ड हैं, इसलिए यह चरण नहीं बता सकता कि किस पर दोहराना है। एक सूची को केवल एक पर छोड़ें।"
-msgid "Live"
-msgstr "लाइव"
-
msgid "Live on Carbon"
msgstr "Carbon पर लाइव"
msgid "Live reloading"
msgstr "लाइव रीलोडिंग"
-msgid "Live Version"
-msgstr "लाइव संस्करण"
-
msgid "Load newer"
msgstr "नया लोड करें"
@@ -11592,6 +11589,9 @@ msgstr "प्रकाशित"
msgid "Published by Carbon"
msgstr "Carbon द्वारा प्रकाशित"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "प्रकाशित संस्करणों को संपादित नहीं किया जा सकता। केवल-पठन के लिए देखें, या परिवर्तन करने के लिए एक नया संस्करण शाखा करें।"
@@ -15714,11 +15714,11 @@ msgstr "यह संस्करण परिवर्तन सूचना <0
msgid "This version cannot be opened"
msgstr "यह version खोला नहीं जा सकता"
-msgid "This version is live"
-msgstr "यह संस्करण लाइव है"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "यह version live है। संपादित करने के लिए एक नया version बनाएं।"
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "इस version की परिभाषा को पढ़ा नहीं जा सका।"
@@ -16305,6 +16305,12 @@ msgstr "{0} को अनपिन करें"
msgid "Unposted Documents"
msgstr "अपोस्ट किए गए दस्तावेज़"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "अप्राप्त POs"
@@ -16662,9 +16668,9 @@ msgstr "अपनी ईमेल सत्यापित करें"
msgid "Version"
msgstr "संस्करण"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "संस्करण {0} अब लाइव है और इसे बदल दिया जाएगा।"
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "संस्करण:"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index a7c1d07751..7fc29918fe 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Importa i tuoi componenti, distinte base, ciclo di lavorazione e costi
msgid "Browse library"
msgstr "Sfoglia libreria"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Sfoglia la versione live in sola lettura. Puoi comunque riorganizzare i passaggi per ordinare il layout."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Bucket"
@@ -8099,6 +8099,9 @@ msgstr "Data di Emissione"
msgid "Issues"
msgstr "Problemi"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "Certificazioni ITAR"
@@ -8564,18 +8567,12 @@ msgstr "Parametri Elenco"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Gli elenchi sono collegati sia a {0} che a {1}, quindi questo passaggio non può dire quale ripetere. Lascia un elenco su uno solo di essi."
-msgid "Live"
-msgstr "In diretta"
-
msgid "Live on Carbon"
msgstr "Live su Carbon"
msgid "Live reloading"
msgstr "Ricaricamento in tempo reale"
-msgid "Live Version"
-msgstr "Versione in diretta"
-
msgid "Load newer"
msgstr "Carica più recenti"
@@ -11592,6 +11589,9 @@ msgstr "Pubblicato"
msgid "Published by Carbon"
msgstr "Pubblicato da Carbon"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Le versioni pubblicate non possono essere modificate. Sfoglia in sola lettura o crea una nuova versione per apportare modifiche."
@@ -15714,11 +15714,11 @@ msgstr "Questa versione appartiene all'avviso di modifica <0>{0}</0>. Modificalo
msgid "This version cannot be opened"
msgstr "Questa versione non può essere aperta"
-msgid "This version is live"
-msgstr "Questa versione è in diretta"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Questa versione è in tempo reale. Crea una nuova versione per modificare."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "La definizione di questa versione non potrebbe essere letta."
@@ -16305,6 +16305,12 @@ msgstr "Rimuovi {0}"
msgid "Unposted Documents"
msgstr "Documenti Non Registrati"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "PO non ricevuti"
@@ -16662,9 +16668,9 @@ msgstr "Verifica la tua email"
msgid "Version"
msgstr "Versione"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "La versione {0} è ora live e sarà sostituita."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Versione:"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 11905bbcfb..c94a4a02e0 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -2589,8 +2589,8 @@ msgstr "パーツ、BOM、Bill of Process、原価計算をインポートして
msgid "Browse library"
msgstr "ライブラリを参照"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "ライブバージョンを読み取り専用で参照できます。ステップを並べ替えてレイアウトを整理することもできます。"
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "バケット"
@@ -8099,6 +8099,9 @@ msgstr "発行日"
msgid "Issues"
msgstr "問題"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "ITAR認定"
@@ -8564,18 +8567,12 @@ msgstr "リストパラメータ"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "リストが{0}と{1}の両方に接続されています。そのため、このステップはどちらを繰り返すべきかを判断できません。リストはそのうちの1つにのみ残してください。"
-msgid "Live"
-msgstr "ライブ"
-
msgid "Live on Carbon"
msgstr "Carbonで稼働中"
msgid "Live reloading"
msgstr "ライブリロード中"
-msgid "Live Version"
-msgstr "ライブバージョン"
-
msgid "Load newer"
msgstr "新しいものを読み込む"
@@ -11592,6 +11589,9 @@ msgstr "公開済み"
msgid "Published by Carbon"
msgstr "Carbonによって公開"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "公開済みバージョンは編集できません。読み取り専用で参照するか、新しいバージョンをブランチして変更してください。"
@@ -15714,11 +15714,11 @@ msgstr "このバージョンは変更通知<0>{0}</0>に属しています。
msgid "This version cannot be opened"
msgstr "このバージョンは開くことができません"
-msgid "This version is live"
-msgstr "このバージョンはライブです"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "このバージョンはライブです。編集するには新しいバージョンを作成してください。"
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "このバージョンの定義を読み取ることができませんでした。"
@@ -16305,6 +16305,12 @@ msgstr "{0}をピン留め解除"
msgid "Unposted Documents"
msgstr "未転記書類"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "未受領PO"
@@ -16662,9 +16668,9 @@ msgstr "メールアドレスを確認"
msgid "Version"
msgstr "バージョン"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "バージョン {0} は現在ライブであり、置き換えられます。"
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "バージョン:"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index c36e5a11d3..b00aeaca1e 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Carbon의 가져오기 도구, CSV, 또는 LLM의 도움으로 품목, B
msgid "Browse library"
msgstr "라이브러리 둘러보기"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "라이브 버전을 읽기 전용으로 탐색하세요. 여전히 단계를 재정렬하여 레이아웃을 정리할 수 있습니다."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "버킷"
@@ -8099,6 +8099,9 @@ msgstr "출고일"
msgid "Issues"
msgstr "이슈"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "ITAR 인증"
@@ -8564,18 +8567,12 @@ msgstr "목록 파라미터"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "{0}과 {1} 모두에 목록이 연결되어 있어서 이 단계에서 어느 것을 반복할지 알 수 없습니다. 목록을 하나에만 남기세요."
-msgid "Live"
-msgstr "실시간"
-
msgid "Live on Carbon"
msgstr "Carbon 도입 완료"
msgid "Live reloading"
msgstr "실시간 새로고침"
-msgid "Live Version"
-msgstr "실시간 버전"
-
msgid "Load newer"
msgstr "최신 항목 불러오기"
@@ -11592,6 +11589,9 @@ msgstr "게시됨"
msgid "Published by Carbon"
msgstr "Carbon에서 게시함"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "게시된 버전은 편집할 수 없습니다. 읽기 전용으로 둘러보거나 새 버전을 분기하여 변경하세요."
@@ -15714,11 +15714,11 @@ msgstr "이 버전은 변경 공지 <0>{0}</0>에 속합니다. 거기서 편집
msgid "This version cannot be opened"
msgstr "이 버전을 열 수 없습니다."
-msgid "This version is live"
-msgstr "이 버전은 활성화되어 있습니다"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "이 버전은 활성입니다. 편집할 새 버전을 만드십시오."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "이 버전의 정의를 읽을 수 없습니다."
@@ -16305,6 +16305,12 @@ msgstr "{0} 고정 해제"
msgid "Unposted Documents"
msgstr "미전기 문서"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "미입고 구매주문"
@@ -16662,9 +16668,9 @@ msgstr "이메일을 인증하세요"
msgid "Version"
msgstr "버전"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "버전 {0}이(가) 현재 라이브이며 대체될 예정입니다."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "버전:"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index ca327b8f8e..a8dfd15d5d 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Zaimportuj swoje części, BOM-y, Bill of Process i wycenę — za pomoc
msgid "Browse library"
msgstr "Przeglądaj bibliotekę"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Przeglądaj aktywną wersję tylko do odczytu. Możesz nadal zmienić kolejność kroków, aby posprzątać układ."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Zasobnik"
@@ -8099,6 +8099,9 @@ msgstr "Data wystawienia"
msgid "Issues"
msgstr "Problemy"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "Certyfikacje ITAR"
@@ -8564,18 +8567,12 @@ msgstr "Parametry listy"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listy są podłączone do obu {0} i {1}, więc ten krok nie może określić, którą z nich powtarzać. Pozostaw listę tylko w jednej z nich."
-msgid "Live"
-msgstr "Aktywny"
-
msgid "Live on Carbon"
msgstr "Na żywo w Carbon"
msgid "Live reloading"
msgstr "Odświeżanie na żywo"
-msgid "Live Version"
-msgstr "Wersja aktywna"
-
msgid "Load newer"
msgstr "Załaduj nowsze"
@@ -11592,6 +11589,9 @@ msgstr "Opublikowano"
msgid "Published by Carbon"
msgstr "Opublikowano przez Carbon"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Opublikowane wersje nie mogą być edytowane. Przeglądaj tylko do odczytu lub utwórz nową wersję, aby wprowadzić zmiany."
@@ -15714,11 +15714,11 @@ msgstr "Ta wersja należy do zmiany powiadomienia <0>{0}</0>. Edytuj tam."
msgid "This version cannot be opened"
msgstr "Ta wersja nie może być otwarta"
-msgid "This version is live"
-msgstr "Ta wersja jest na żywo"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Ta wersja jest aktywna. Utwórz nową wersję do edycji."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "Definicję tej wersji nie można było odczytać."
@@ -16305,6 +16305,12 @@ msgstr "Odepnij {0}"
msgid "Unposted Documents"
msgstr "Nieopublikowane dokumenty"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "Nieprzyjęte zamówienia"
@@ -16662,9 +16668,9 @@ msgstr "Zweryfikuj swój email"
msgid "Version"
msgstr "Wersja"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "Wersja {0} jest teraz dostępna i zostanie zastąpiona."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Wersja:"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 0103031be3..1e2e80df61 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Importe suas peças, BOMs, Bill of Process e custos — com as ferrament
msgid "Browse library"
msgstr "Procurar biblioteca"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Procure a versão ao vivo somente para leitura. Você ainda pode reorganizar os passos para organizar o layout."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Bucket"
@@ -8099,6 +8099,9 @@ msgstr "Data de Emissão"
msgid "Issues"
msgstr "Problemas"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "Certificações ITAR"
@@ -8564,18 +8567,12 @@ msgstr "Parâmetros de Lista"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listas estão conectadas em ambos {0} e {1}, então esta etapa não pode saber qual repetir. Deixe uma lista em apenas um deles."
-msgid "Live"
-msgstr "Ativo"
-
msgid "Live on Carbon"
msgstr "Ao vivo no Carbon"
msgid "Live reloading"
msgstr "Recarregamento ao vivo"
-msgid "Live Version"
-msgstr "Versão ativa"
-
msgid "Load newer"
msgstr "Carregar mais recentes"
@@ -11592,6 +11589,9 @@ msgstr "Publicado"
msgid "Published by Carbon"
msgstr "Publicado pela Carbon"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "As versões publicadas não podem ser editadas. Procure somente para leitura ou ramifique uma nova versão para fazer alterações."
@@ -15714,11 +15714,11 @@ msgstr "Esta versão pertence ao aviso de alteração <0>{0}</0>. Edite-a lá."
msgid "This version cannot be opened"
msgstr "Esta versão não pode ser aberta"
-msgid "This version is live"
-msgstr "Esta versão está ativa"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Esta versão está ativa. Crie uma nova versão para editar."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "A definição desta versão não pôde ser lida."
@@ -16305,6 +16305,12 @@ msgstr "Desafixar {0}"
msgid "Unposted Documents"
msgstr "Documentos Não Lançados"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "POs não recebidas"
@@ -16662,9 +16668,9 @@ msgstr "Verifique seu email"
msgid "Version"
msgstr "Versão"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "A versão {0} está ao vivo agora e será substituída."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Versão:"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 99ff2152fc..3b71bf4344 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Импортируйте ваши детали, спецификации
msgid "Browse library"
msgstr "Обзор библиотеки"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Просмотрите активную версию в режиме только для чтения. Вы все еще можете переставлять шаги для улучшения расположения."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Хранилище"
@@ -8099,6 +8099,9 @@ msgstr "Дата выпуска"
msgid "Issues"
msgstr "Проблемы"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "Сертификации ITAR"
@@ -8564,18 +8567,12 @@ msgstr "Параметры списка"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Списки привязаны к обоим {0} и {1}, поэтому этот шаг не может определить, какой из них повторить. Оставьте список только в одном из них."
-msgid "Live"
-msgstr "Активный"
-
msgid "Live on Carbon"
msgstr "Работает на Carbon"
msgid "Live reloading"
msgstr "Живая перезагрузка"
-msgid "Live Version"
-msgstr "Активная версия"
-
msgid "Load newer"
msgstr "Загрузить новые"
@@ -11592,6 +11589,9 @@ msgstr "Опубликовано"
msgid "Published by Carbon"
msgstr "Опубликовано Carbon"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Опубликованные версии нельзя редактировать. Просмотрите их в режиме только для чтения или создайте ветвь новой версии для внесения изменений."
@@ -15714,11 +15714,11 @@ msgstr "Эта версия принадлежит уведомлению об
msgid "This version cannot be opened"
msgstr "Эта версия не может быть открыта"
-msgid "This version is live"
-msgstr "Эта версия активна"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Эта версия активна. Создайте новую версию для редактирования."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "Определение этой версии не удалось прочитать."
@@ -16305,6 +16305,12 @@ msgstr "Открепить {0}"
msgid "Unposted Documents"
msgstr "Неопубликованные документы"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "Неполученные ПО"
@@ -16662,9 +16668,9 @@ msgstr "Подтвердите вашу электронную почту"
msgid "Version"
msgstr "Версия"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "Версия {0} сейчас в эфире и будет заменена."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Версия:"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 0c428d89c1..fbe2c6fb71 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -2589,8 +2589,8 @@ msgstr "Parçalarınızı, BOM'larınızı, İşlem Faturasını ve maliyetlendi
msgid "Browse library"
msgstr "Kütüphaneyi göz at"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "Canlı sürümü salt okunur şekilde inceleyin. Yine de adımları düzenlenecek şekilde yeniden düzenleyebilirsiniz."
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "Kova"
@@ -8099,6 +8099,9 @@ msgstr "Düzenlenme Tarihi"
msgid "Issues"
msgstr "Sorunlar"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "ITAR Sertifikaları"
@@ -8564,18 +8567,12 @@ msgstr "Liste Parametreleri"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listeler hem {0} hem de {1} öğelerine bağlıdır, bu nedenle bu adım hangisinin üzerinde tekrarlanacağını belirleyemez. Listeyi yalnızca birine bırakın."
-msgid "Live"
-msgstr "Canlı"
-
msgid "Live on Carbon"
msgstr "Carbon'da Canlı"
msgid "Live reloading"
msgstr "Canlı yeniden yükleniyor"
-msgid "Live Version"
-msgstr "Canlı Sürüm"
-
msgid "Load newer"
msgstr "Daha yenisini yükle"
@@ -11592,6 +11589,9 @@ msgstr "Yayımlandı"
msgid "Published by Carbon"
msgstr "Carbon tarafından yayınlandı"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "Yayımlanmış sürümler düzenlenemez. Salt okunur şekilde inceleyin veya değişiklik yapmak için yeni bir sürüm oluşturun."
@@ -15714,11 +15714,11 @@ msgstr "Bu sürüm değişiklik bildirimi <0>{0}</0> ile ilgilidir. Orada düzen
msgid "This version cannot be opened"
msgstr "Bu sürüm açılamıyor"
-msgid "This version is live"
-msgstr "Bu versiyon yayında"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "Bu sürüm canlı. Düzenlemek için yeni bir sürüm oluşturun."
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "Bu sürümün tanımı okunamadı."
@@ -16305,6 +16305,12 @@ msgstr "Sabitlemeyi Kaldır {0}"
msgid "Unposted Documents"
msgstr "Deftere Geçmemiş Belgeler"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "Alınmamış PO'lar"
@@ -16662,9 +16668,9 @@ msgstr "E-posta adresinizi doğrulayın"
msgid "Version"
msgstr "Sürüm"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "Sürüm {0} şimdi yayında ve değiştirilecektir."
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "Sürüm:"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 9ec300d667..b697c8f2c5 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -2589,8 +2589,8 @@ msgstr "导入您的零件、物料清单、工艺流程和成本——使用 Ca
msgid "Browse library"
msgstr "浏览库"
-msgid "Browse the live version read-only. You can still rearrange steps to tidy the layout."
-msgstr "以只读方式浏览实时版本。您仍然可以重新排列步骤以整理布局。"
+msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgstr ""
msgid "Bucket"
msgstr "存储桶"
@@ -8099,6 +8099,9 @@ msgstr "签发日期"
msgid "Issues"
msgstr "问题"
+msgid "It will stop running until you publish a version again. Nothing is deleted."
+msgstr ""
+
msgid "ITAR Certifications"
msgstr "ITAR 认证"
@@ -8564,18 +8567,12 @@ msgstr "列表参数"
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "列表同时连接到{0}和{1},因此此步骤无法判断要在哪一个上重复。仅在其中一个上保留列表。"
-msgid "Live"
-msgstr "实时"
-
msgid "Live on Carbon"
msgstr "在 Carbon 上线"
msgid "Live reloading"
msgstr "实时重新加载"
-msgid "Live Version"
-msgstr "实时版本"
-
msgid "Load newer"
msgstr "加载更新"
@@ -11592,6 +11589,9 @@ msgstr "已发布"
msgid "Published by Carbon"
msgstr "由 Carbon 发布"
+msgid "Published Version"
+msgstr ""
+
msgid "Published versions can't be edited. Look around read-only, or branch a new version to make changes."
msgstr "已发布的版本无法编辑。以只读方式浏览,或创建新版本以进行更改。"
@@ -15714,11 +15714,11 @@ msgstr "此版本属于变更通知<0>{0}</0>。请在那里编辑。"
msgid "This version cannot be opened"
msgstr "无法打开此版本"
-msgid "This version is live"
-msgstr "此版本已上线"
+msgid "This version is published"
+msgstr ""
-msgid "This version is live. Create a new version to edit."
-msgstr "此版本处于实时状态。创建新版本进行编辑。"
+msgid "This version is published. Create a new version to edit."
+msgstr ""
msgid "This version's definition could not be read."
msgstr "无法读取此版本的定义。"
@@ -16305,6 +16305,12 @@ msgstr "取消固定{0}"
msgid "Unposted Documents"
msgstr "未过账单据"
+msgid "Unpublish"
+msgstr ""
+
+msgid "Unpublish {name}?"
+msgstr ""
+
msgid "Unreceived POs"
msgstr "未收到的采购订单"
@@ -16662,9 +16668,9 @@ msgstr "验证您的电子邮件"
msgid "Version"
msgstr "版本"
-#. placeholder {0}: live.versionNumber
-msgid "Version {0} is live now and will be replaced."
-msgstr "版本 {0} 现已上线,将被替换。"
+#. placeholder {0}: published.versionNumber
+msgid "Version {0} is published now and will be replaced."
+msgstr ""
msgid "Version:"
msgstr "版本:"
diff --git a/packages/workflows/AGENTS.md b/packages/workflows/AGENTS.md
index 528809d1ca..f1bd8ab695 100644
--- a/packages/workflows/AGENTS.md
+++ b/packages/workflows/AGENTS.md
@@ -299,9 +299,9 @@ every other check compares declared types only.
## The `workflowTriggerEvent` invariant
-A `workflowTriggerEvent` row exists **if and only if** the workflow is active, has a promoted
-version, and that version's trigger nodes list that event id. Promoting a version, editing the
-active version's trigger, and toggling `active` must all rewrite the workflow's rows —
+A `workflowTriggerEvent` row exists **if and only if** the workflow has a published version and
+that version's trigger nodes list that event id. Publishing a version, editing the published
+version's trigger, and unpublishing must all rewrite the workflow's rows —
delete-then-insert **in the same transaction** as the change. If these drift, a workflow silently
stops firing or fires when it should not.
diff --git a/packages/workflows/src/seed-workflows.test.ts b/packages/workflows/src/seed-workflows.test.ts
index 0d3873252d..1062c59a4d 100644
--- a/packages/workflows/src/seed-workflows.test.ts
+++ b/packages/workflows/src/seed-workflows.test.ts
@@ -20,8 +20,8 @@ const everyDataset = Object.entries(SEED_WORKFLOW_BUILDERS).flatMap(
);
describe("dev seed workflows", () => {
- it("ships exactly one active workflow", () => {
- expect(workflows.filter((w) => w.active).map((w) => w.name)).toEqual([
+ it("ships exactly one published workflow", () => {
+ expect(workflows.filter((w) => w.published).map((w) => w.name)).toEqual([
"Assign new sales orders"
]);
});
diff --git a/packages/workflows/src/sync.ts b/packages/workflows/src/sync.ts
index fe2f94b115..dbeb72070b 100644
--- a/packages/workflows/src/sync.ts
+++ b/packages/workflows/src/sync.ts
@@ -160,12 +160,12 @@ export async function syncWorkflowTriggers(
): Promise<{ eventIds: string[]; tables: string[]; scheduled: boolean }> {
return db.transaction().execute(async (trx) => {
// First statement in the transaction — everything below reads company-wide
- // state and must not interleave with another publish or toggle.
+ // state and must not interleave with another publish or unpublish.
await lockCompany(trx, companyId);
const workflow = await trx
.selectFrom("workflow")
- .select(["active", "activeVersionId"])
+ .select(["publishedVersionId"])
.where("id", "=", workflowId)
.where("companyId", "=", companyId)
.executeTakeFirst();
@@ -173,11 +173,13 @@ export async function syncWorkflowTriggers(
let versionId: string | null = null;
let desired: DesiredTriggerRow[] = [];
let schedule: Schedule | null = null;
- if (workflow?.active && workflow.activeVersionId) {
+ // The pointer IS the on/off switch: unpublishing nulls it, so everything below
+ // computes an empty desired set and the workflow stops firing.
+ if (workflow?.publishedVersionId) {
const version = await trx
.selectFrom("workflowVersion")
.select(["id", "nodes"])
- .where("id", "=", workflow.activeVersionId)
+ .where("id", "=", workflow.publishedVersionId)
.where("companyId", "=", companyId)
.executeTakeFirst();
if (version) {
@@ -208,7 +210,7 @@ export async function syncWorkflowTriggers(
.execute();
}
- // Sole writer of workflow.nextRunAt. Folded in here so a promote or toggle cannot wire
+ // Sole writer of workflow.nextRunAt. Folded in here so a publish or unpublish cannot wire
// trigger rows and forget the due time — the failure would be silent (workflow never runs).
const nextRunAt =
schedule && versionId