HiveCFM migrator · on-site operator guide

MSSQL → PostgreSQL Migration

Step-by-step guide for an operator migrating one HiveCFM client from legacy MSSQL to PostgreSQL, on the customer's site, with no outside help. Start at L0 Before you go on site, then follow L1 to L8 in order.

Updated 2026-09-30 · verified against branch fix/noref-tui-run3-operator-defects @ 4d6f7fe8e (base origin/AG-migration @ 14ec9e1c9) and the STC-BH run-3 rehearsal (2026-09-28/30) 11 lifecycle stages · one TUI screen · every step has its CLI equivalent
$ M="node --import tsx dist/cli.js" # 0. in <checkout>/packages/migrator
$ $M ui # 1. Environments → client → Menu → lifecycle (L1)
$ $M lifecycle --from-config <base.env> # or the same from a shell (L11)
$ $M lifecycle --from-config <base.env> --status # where is it now?
open-program is required on a database that has never been migrated into (the lifecycle runs it as its first stage). It creates the migration lease, the permission to put migration-owned schema into that database. A run without the lease fails fast with E-LEASE-01 before it writes anything. Older builds wrote Phases 1–2.6 first and then reported RETIRED: see 04b if that is what you see. The six older migrator branches (AG-hiveCoreMigrtorTool, feat/noref-shared-db-migration-lifecycle and four others) were deleted from the remote after their content was proved contained in AG-migration. Any command below that an older page called "not yet merged" is merged. Superset toolkit (4 subcommands) is wired in the CLI but every subcommand is a stub that prints an error and exits 1. No shipped behavior yet.
L0 – L11Migrate a client (recommended)
L0

Before you go on sitestart here · every customer

The recommended way to migrate a client is the Lifecycle screen of the TUI. It runs 11 stages, one per enter, and tells you what to press next. Sections L0 to L11 are the whole procedure. You should not need any other section unless a step here sends you there. Tick each line below before you start. Every item was a real stop on an earlier run.

One invocation for the whole guide

Every command in this guide runs from <checkout>/packages/migrator on the migration box, through the built CLI. Define it once per shell:

bash: set up the shell once
$cd <checkout>/packages/migrator
$M="node --import tsx dist/cli.js"
$$M lifecycle --help # must list --from-config; if not, the build is too old

Plain node dist/cli.js does not work: the CLI needs --import tsx. Older pages of this guide wrote pnpm migrate …; on a customer box use $M … instead.

.migrate/targets.json — the base entry (placeholders)
{
  "environments": [
    {
      "id": "<client id: lower-case, e.g. stcbh>",
      "label": "<Client> (base)",
      "tier": "prod",
      "configFile": "/home/<user>/.migrate-<client>-base.env",
      "environmentId": "<anchor env id>"
    }
  ]
}

The provision stage adds one entry per department to this same file. Do not add department entries by hand.

Bring the migrator to an offline box

The customer box has no internet, so git fetch, pnpm install and npm install -g pnpm (02) do not work there. Build before you travel, on a Linux machine with the same CPU type (x86-64 or arm64) and the same Node.js major version (20) as the customer box, and carry the built checkout.

  1. Build at the path it will have on site. Clone into the same absolute path you will use on the customer box, for example /opt/hivecfm/hivecfm-core, and follow 02 (install, generate, build). Some workspace links under node_modules are absolute paths, so a copy unpacked anywhere else can load the wrong files, or none.
  2. Pack it (tar keeps the links): tar -czf hivecfm-migrator-<build>.tgz -C /opt/hivecfm hivecfm-core. Leave out every .env file and the .migrate/ directory of your own machine.
  3. Copy and unpack at the same path: scp hivecfm-migrator-<build>.tgz <user>@<migration box>:, then on the box sudo mkdir -p /opt/hivecfm && sudo chown $USER /opt/hivecfm && tar -xzf hivecfm-migrator-<build>.tgz -C /opt/hivecfm.
  4. Check it with the commands below. Every line must give the expected answer before you go on.
bash: check a carried build on the customer box
$node -v # v20.x
$cd /opt/hivecfm/hivecfm-core/packages/migrator
$ls -l node_modules/@hivecfm/database # the link must point inside /opt/hivecfm/hivecfm-core
$M="node --import tsx dist/cli.js"
$$M --help # lists lifecycle and reset-client
$$M lifecycle --help # lists --from-config
L1

Start the TUI and select the client

Connect, start the TUI inside tmux, pick the client in Environments, then open Lifecycle from the Menu.

1. Connect and start

bash: start the TUI
$ssh -t <user>@<migration box>
$tmux new -s <client> # a dropped SSH session then leaves the TUI running
$cd <checkout>/packages/migrator # .migrate/ and relative paths resolve from here
$node --import tsx dist/cli.js ui
bash: SSH dropped? get back to the same screen
$ssh -t <user>@<migration box>
$tmux attach -t <client>
Never start a second TUI "to get the screen back"

A stage keeps running when SSH drops, when you close the TUI, and when you press q. Reattach with tmux attach. A second TUI cannot start a second lifecycle for the same client (it is refused with E-LIFECYCLE-LOCK-01), but reattaching is the only way to see the running screen.

tmux keys (press Ctrl+b, let go, then the key): c opens a new window (a shell beside the TUI); n goes to the next window, 0 / 1 to window 0 / 1; d detaches (everything keeps running; tmux attach -t <client> brings it back); [ lets you scroll back with the arrow keys or PgUp, and q leaves scroll mode. When a later step says "in a second tmux window", that is Ctrl+b c, then cd <checkout>/packages/migrator.

What you should see A full-screen UI with a breadcrumb at the top. If you see plain text and a prompt instead, the TUI refused the terminal: it printed the interactive UI needs a real terminal (TTY, >=80 columns, not CI, no --no-ui). Reconnect with ssh -t, widen the window, and unset CI.

2. Startup check

The first screen is Startup check. It looks for a run that stopped half-way.

  • No interrupted run detected — proceeding to the Dashboard. It does not move by itself. Press N (or esc).
  • Interrupted run detected in _MigrationCheckpoint with a table list. That is a single-environment run left over from the advanced path. For a lifecycle client, press N: the Lifecycle screen resumes its own stages. Press R only if you were running that environment by hand (single-environment flow).
  • This environment is still LIVE — its migrate-run lock is held. Something is still writing. Do not start anything. See L9.

3. Dashboard → Environments

On the Dashboard, e opens Environments and enter opens the Menu. Press e.

Environments reads .migrate/targets.json each time it opens. Before provision you see one row: the base entry. After provision the base entry and its departments fold into one client row, Client — <client> (N depts).

Environments after provision — text from the current build; screenshot to be captured on the next run
tier   label                                env-id      status
▸ ● DEV  Client — STC-BH (base) (4 depts)                   ✓ ready

DEV selected: Client — STC-BH (base) (4 depts). lifecycle / run-all-departments / provision use base entry STC-BH (base); [x] picks one department; esc → menu
[enter] select [x] expand|collapse [r] re-check all [n] new [l] reload
KeyWhat it does
↑ ↓Move the highlight.
rRe-check. On the client row it checks the base entry first, then every department. Each result reads ✓ ready, ✗ bad-env-id or ⚠ could not check — left as it was. A ✓ ready result is saved in .migrate/registry-status.json and comes back after a restart for 24 hours, while the entry and its config file are unchanged. On a single entry (before provision, the base entry is the only row) r opens the Environment re-check screen instead: wait until environmentId in Environment table (authoritative) shows ✓, press enter to accept (without the ✓ it says env-id check is not ✓ — accept is blocked.), then, back in Environments, enter on the row to select it.
enterSelect the highlighted row. It stays on this screen and says what the selection allows (the line under the table). A row marked ⚠ unverified needs a second enter: the first says ⚠ not yet verified — press [r] to re-check it, or enter again to select … anyway. Prefer r. A ✗ bad-env-id row cannot be selected.
xExpand or collapse the client row, to see or select one department. You do not need this for the lifecycle.
lReload .migrate/targets.json now, for example after an edit from a shell.
n / eAdd or edit an entry. The editor writes no .env file, and saving a department entry drops its department binding. Add the base entry by hand (L0) and let provision add the departments.
escGo back.

What you should see after enter … selected: Client — <client> (N depts). lifecycle / run-all-departments / provision use base entry <label> (or, before provision, the base entry marked ●). If you do not:

  • ✗ bad-env-id: …: the entry's environmentId is not in the target. Fix it in targets.json (or [x], then [e] on the entry), then [l] and [r].
  • ✗ targets.json could not be re-read — showing the list from <time>.: the file is not valid JSON or has no "environments" array. Fix the file, then press [l].
  • no base entry — lifecycle needs one: [n]: add the base entry (L0), then [l].

4. Menu → lifecycle

Press esc to return to the Dashboard, then enter for the Menu. The header reads <N> operations. Move to lifecycle (group Migrate) and press enter.

If lifecycle is grey, its hint says what is missing. enter on it repeats the hint.

Hint on the grey rowWhat to do
(select the client's base entry first)Nothing is selected. Go to Environments and select the client row or the base entry.
(select the client row in Environments)One department is selected. Select the client row instead.
(no base entry for this client — add it in Environments with [n])Add the base entry (L0).
(base entry ✗bad-env-id — [x], then [e] on it)The base entry's environment id is wrong. Fix it.
(base entry <id> unconfirmed — [x], then [e] on it)The base entry has no environment id or cannot be matched to the client. Fix it.
(this config's base entry is <id> — select that one)Two entries share the config file. Select the one named.

Other useful keys anywhere: g or : opens the Command palette (type part of an operation name). ? shows a fixed list of global keys; some keys on that list do nothing. q quits; if a child is still running it asks for a second q, and the child keeps running after the TUI closes.

CLI equivalent of this whole section (see what the lifecycle has done so far, without the TUI):

bash
$$M lifecycle --from-config <base.env> --status

It prints Lifecycle <base id>, one line per stage, one line per department and Next stage: <stage>. Before any stage has run it prints No lifecycle has run for this client yet. Next stage: open-program.

L2

The Lifecycle screen and every key

Read this once. Every later section says "press enter" and assumes you know what the screen shows.

About "quarantine pending not recorded" in the screenshots

The run-3 screenshots in this guide show a long yellow note on every department row: quarantine pending not recorded (…). That was an earlier build. The current build shows a dim quarantine ? on each row and one yellow line under the list: Quarantine counts not recorded for dept 1, 3, 4, 5 (their runs predate this build) — open Consolidate languages for a department and dry-run it to see its pending groups. What quarantine means, and what to do about it, is in L4.

screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Lifecycle screen for STC-BH with stages open-program to run marked done and verify running for department 1 of 4
The Lifecycle screen while a stage runs: ▸ marks the running stage, the step line names the department (k of M), the elapsed time and its log file, and the footer says ← leaves while the stage keeps running.

What is on the screen

  • Header: Lifecycle · <label> <env id>, then config <base.env> · tier <TIER> · state .migrate/lifecycle/<base id>.json. When a department has a higher tier than the base entry, the header adds (confirms at <TIER>: a department's tier).
  • One row per stage. ✓ done, ✗ failed, » skipped (it did not need to run), ○ pending. ▸ marks the stage enter runs next.
  • One row per department (after provision): dept N → <env id> run <pending|done|needs-verify|interrupted|failed> verified yes|no finalized yes|no, then, when they apply, pushed to the Hub at <time>, [failing: <checks>] and the quarantine count: quarantine N pending (yellow) or quarantine ? (dim, not recorded).
  • Under the departments: [a] accept survey_channel_coverage: [ ], the [o] options: … line (what the next stages will be given), and before provision [d] departments to provision: all ….
  • Footer: [enter] run next stage (<stage>) [a] accept [d] departments [o] options [h] re-run skipped hub-backfill [r] refresh [esc] back. [d] shows only before provision, [h] only while hub-backfill is skipped.

Keys

KeyWhat it does
enterRuns the next stage (the one marked ▸). Asks first for: open-program, provision, run, verify, hub-backfill, finalize, retire. Starts at once for: preflight, dry-run, export, census (they do not change customer data). provision, finalize and retire first run a preview that changes nothing; the confirm opens only if the preview succeeds. On a prod tier, run asks only after the dry-run stage is done.
aArms acceptance of the survey_channel_coverage parity check (source surveys that have no channel); the line shows [x]. A second a disarms it, but only until the next stage runs: that stage is given --accept-check survey_channel_coverage, the acceptance is saved in the state file, and from then on it stays accepted for the rest of this lifecycle, finalize's final parity included (a then answers … is already accepted for this lifecycle (…); it stays accepted.). Use it only when verify fails on that check alone and the gap is expected (L5).
dSets which departments to provision: digits and commas, e.g. 1,3,4,5; empty means all. After an interrupted provision, empty means the set recorded when provision started, shown on the line ([d] departments to provision: 1,3,4,5 (recorded when provision started; …)). Only before provision. After provision the list is fixed and [d] says so.
oOpens the options panel (next table).
hRe-runs a skipped hub-backfill (L6). Shown only while hub-backfill is skipped, also after the lifecycle is complete.
rRe-reads the state file and the lock.
escGoes back. Refused while a stage runs (A lifecycle command is running — wait for it to finish before leaving.).
←Leaves the screen while a stage runs. The stage keeps running; open Lifecycle again to see it.

The [o] options panel

Title: Lifecycle options — [up/down] move [enter] set [esc] close options. ↑ ↓ move, type a value, enter sets it or toggles the row, esc closes the panel and drops anything typed but not set. While it is open, every key goes into the panel (q does not quit). The panel opens with the cursor on the first row, --parity-retries, and the rows are in the order of the table below: --accept-check contact_target_extras is ↓ three times, --accept-live-tail is ↓ four times. On a checkbox row, enter toggles it ([x]); on a text row, enter with nothing typed does nothing. What is kept: --parity-retries, --approve-quarantine and --accept-live-tail live in the screen only; leaving the Lifecycle screen or restarting the TUI puts back their defaults. --accept-check contact_target_extras is saved in the state file once a stage has run with it, and then stays accepted for the rest of this lifecycle; it cannot be undone from the screen. Check the [o] options: … line before each enter.

RowMeaningDefault
--parity-retriesExtra delta + parity rounds per department before verify fails. 0 to 5. Sent to verify only.2
--approve-quarantineQUARANTINE language groups the run may merge, comma-separated, each spelled exactly as the consolidation report's group: line: <survey stem>|<dept> (e.g. Customer Survey|1) or v2:<name family>|<dept>|<interaction>|<8 hex>. Sent to dry-run and run; verify passes it on only if it must resume a run. Name only groups you have read in the report.none
fill --approve-quarantine…enter copies the QUARANTINE fingerprints from each department's newest reports/consolidation-<env>-*.md into the field above, for you to read. Nothing is set until you press enter on the field.—
--accept-check contact_target_extrasAccept migrated contacts the department no longer uses (the live source deleted or re-pointed their usage after migration). Applied only while a department has 50 or fewer. Check the ids in the parity report first (L5).[ ]
--accept-live-tailLet finalize go ahead although the source took new rows after its final delta. Those rows are never migrated. Prefer stopping source writes (L7). Sent to finalize only.[ ]

Confirms: what to type

Tier of the confirmWhat you see → what you do
prodType <TOKEN> exactly as shown, then press enter. The token looks like STCBH-4821 and is highlighted in the line. Type it exactly (capitals matter), then enter. A wrong attempt makes a new token: That did not match. A new token was generated: type <NEW TOKEN> exactly as shown (case-sensitive), then press enter.
uatType APPLY to authorize: → type APPLY, then enter.
dev / localProceed? [y/N] → press y. enter does nothing here. n or esc cancels.
retire (any tier)Always the prod token. On a non-prod client a yellow line says why: Tier PROD: retire drops the migration tables and columns for the whole database, not one environment, so it always asks for the production token, even for this <tier> client.

The confirm tier is the highest tier of the base entry and its departments. A customer base entry left as dev therefore gets y/N confirms and dev department entries: register the real tier (L0).

While a stage runs

  • A step line: <stage> · dept N (k of M) · elapsed 3m00s · log <path> (1h05m00s from an hour on), then the phase timeline (✓1 Lkp ●2 Ent ○2.5 Rep …, legend ✓ done ● active ○ pending » skipped ✗ failed) and up to 8 table rows with done / total, percent, rate and ETA.
  • Footer: running <stage>… — ← leaves this screen; the stage keeps running ….
  • Pressing enter twice starts only one child: A lifecycle command is already starting or running — this key was ignored.
  • Coming back to a running stage shows stage <s> is running (dept N (k of M), started <time>) — press [r] to refresh; enter is disabled until it finishes. That holder is the stage you started. Wait, or press r.

Stopping a stage

  • q, closing the TUI, or losing SSH does not stop the stage.
  • To stop it: find the lifecycle's pid (pgrep -af "dist/cli.js lifecycle") and send kill -INT <pid>. No new command or stage starts after that. The signal is passed on only to commands that stop safely (run, the dry-run's run, parity, hub-backfill); any other command (provision, delta, finalize-staging, retire, …) is left to finish first. It can take minutes.
  • A second kill -INT ends the running command at once, even in the middle of a write. Use it only if you accept that.
  • To resume: open Lifecycle again and press enter. A department run that was stopped continues with --resume by itself.

Where things are written

Path (under packages/migrator)What
.migrate/lifecycle/<base id>.jsonThe lifecycle state: each stage, each department, accepted checks, Hub push times. Reset (L10) needs it.
.migrate/lifecycle/<base id>.lockHeld while a lifecycle runs (pid, host, start time).
.migrate/lifecycle/logs/<base id>/One log per child command: <stage>[-dept<N>]-<command>-<time>.log, mode 0600, never deleted automatically.
reports/parity-<env>-<time>.html (with a sidecar the lifecycle reads) and consolidation-<env>-<time>.md.
provenance/<base id>/The provenance export and its manifest.json (L8).
L3

Stages 1–3: open-program · provision · preflight

Take the lease, create one environment per department, check each department. Set [d] before provision.

  1. 1open-program
  2. 2provision
  3. 3preflight
  4. 4dry-run
  5. 5run
  6. 6verify
  7. 7hub-backfill
  8. 8finalize
  9. 9export
  10. 10retire
  11. 11census
Lifecycle before the first stage — text from the current build; screenshot to be captured on the next run
Lifecycle · <Client> (base) <anchor env id>
config <base.env> · tier PROD · state .migrate/lifecycle/<client>.json

▸ ○ open-program   Takes the migration lease on the target DB so later stages may write; idempotent.
  ○ provision      Creates one project+environment per department and registers it; skipped if already registered.
  ○ preflight      Read-only readiness checks, one per department.
  ○ dry-run        Each department's run --dry-run: writes nothing; prints its plan and language-merge report.
  ○ run            Migrates every department and merges its language siblings, so no separate consolidate-languages is needed. QUARANTINE groups wait for Consolidate languages → [a]. The Hub push is its own stage (hub-backfill).
  ○ verify         Per dept: delta + parity, 1 + parity-retries rounds ([o]); [a] accepts survey_channel_coverage.
  ○ hub-backfill   Per department: hub-backfill pushes its responses; skipped where its config names no Hub.
  ○ finalize       Per department: finalize-staging preview, then --apply.
  ○ export         Writes the provenance manifest (retire needs it) to the export dir; skipped if one exists.
  ○ retire         Previews, then retires the migration program from the target database.
  ○ census         Read-only: confirms zero migration objects remain.

[a] accept survey_channel_coverage: [ ]
[o] options: parity retries 2 (CLI default; verify only) · approve-quarantine none (dry-run, run; verify only if it must resume a run) · accept contact_target_extras no · accept-live-tail no (finalize only)
[d] departments to provision: all (only used by the provision stage)

[enter] run next stage (open-program)  [a] accept  [d] departments  [o] options  [r] refresh  [esc] back

Stage 1 · open-programasks first

What it does Takes the migration lease on the target database. Nothing else may create migration tables without it. Safe to run twice.

Keys enter → confirm (Takes the migration lease: migration-owned tables may now be created in this database.) → token / APPLY / y.

What you should see ✓ open-program and ▸ on provision.

If not A refusal that says the database was retired means a program already ran and ended here; do not force it open, ask the migration owner. E-LEASE-… or a connection error: check TARGET_PG_* in the base config.

CLI $M open-program --config <base.env>

Stage 2 · provisionpreview, then asks

What it does Creates one project and environment per department, writes one .env.<base id>-<dept>-<name> file per department (a copy of the base config), and adds each department to .migrate/targets.json. The first department provisioned (the lowest id in the list) reuses the signup project and renames it.

  1. First press d, type the department list you decided in L0 (e.g. 1,3,4,5), enter. The line now reads [d] departments to provision: 1,3,4,5 …. Leaving it as all provisions every department the source reports, empty ones too.
  2. Press enter. The preview runs (provision-departments … --dry-run). Read it: Provisioning N department(s) into organization <org> — DRY RUN, nothing will be written, one line per department (reuse and rename, or WOULD create), and the Department → Environment map.
  3. The confirm opens: Writes to the target: one project and environment per department, their targets.json entries, and the anchor project is renamed. Type the token / APPLY / y.
  4. Check the files in a second tmux window (L1): ls -l .env.<base id>-*. Each must read -rw-------: provision writes them with mode 0600 because they hold the source and target passwords. A file that already existed is reported … already exists — left untouched. Delete it to regenerate. and keeps its old mode and contents: chmod 600 that one, and check it holds the same values as the base config.

What you should see ✓ provision, one department row per department (run pending), and in Environments the client row Client — <client> (N depts). The Lifecycle screen re-reads the registry after every stage, so no restart is needed.

If not

  • The preview refuses because the signup project already has a department's name: rename the project in the product to something neutral, then enter again.
  • Provision is incomplete for <cfg>: department(s) … have no registry entry … (after a forced stop): press enter again. Departments already made are found by project name; nothing is made twice.
  • … was most likely left half-created by an earlier provision-departments that was stopped part-way …: run the SELECT it prints (must return 0 surveys and 0 contacts), delete that project as it says (Delete Workspace in the product, or the guarded DELETE it prints), then enter. If the SELECT is not 0 and 0, stop and ask the owner.
  • A wrong department id in [d] fails the preview; nothing is saved. Fix [d] and press enter.

CLI The lifecycle passes the base entry's tier and id itself:

bash: provision by hand (preview, then real)
$$M provision-departments --client <anchor env id> --config <base.env> --write-config --tier <base tier> --id-prefix <base id> --departments 1,3,4,5 --dry-run
$$M provision-departments --client <anchor env id> --config <base.env> --write-config --tier <base tier> --id-prefix <base id> --departments 1,3,4,5

Stage 3 · preflightstarts at once · read-only

What it does The full read-only readiness check, once per department (source, target, schema, Hub reachability when configured). Writes nothing.

Keys enter (no confirm).

What you should see ✓ preflight.

If not The failure names the department, the check and Full log: …. A configured Hub that cannot be reached fails preflight: fix the Hub URL/key, or remove both Hub lines from that department's .env to skip the Hub for now (L6). Fix what the check says, then enter. Check codes are explained in 04 Preflight.

CLI $M preflight --client <dept env id> --config <dept .env> --department N

Any one stage from a shell

bash: one stage, the same command the screen runs
$$M lifecycle --from-config <base.env> --from-stage provision --until provision --preview # provision, finalize, retire only
$$M lifecycle --from-config <base.env> --departments 1,3,4,5 --from-stage provision --until provision
L4

Stages 4–5: dry-run · run

Rehearse every department, then migrate every department. The run also merges language siblings.

  1. 1open-program
  2. 2provision
  3. 3preflight
  4. 4dry-run
  5. 5run
  6. 6verify
  7. 7hub-backfill
  8. 8finalize
  9. 9export
  10. 10retire
  11. 11census

Stage 4 · dry-runstarts at once · writes nothing

What it does run --dry-run for each department. Writes nothing. Prints the plan and the language-merge report (reports/consolidation-<env>-<time>.md).

Keys enter (no confirm). Progress shows on the step line and phase timeline.

What you should see ✓ dry-run. The dry-run output says the real run will merge the AUTO_MERGE groups; you do not need a separate consolidate step for them.

If not

  • A department fails in Phase 3 with boundary 0: it has no customer surveys and should not have been provisioned. The lifecycle has no step that removes a provisioned department ([d] is fixed after provision), so the dry-run stage fails on it every time. Stop here: collect the escalation kit (L9) and wait for the migration owner. Waiting is safe: the source is only read, no customer data has been written to the target yet, and the program may stay open for days.
  • A long wait in the answered-GUID lookup is normal on a large department; watch the elapsed time and the log.
  • Warning, not the cause of the failure: N source channel name(s) have no channel mapping …: a warning only. Read the real error under it.

CLI $M run --client <dept env id> --config <dept .env> --department N --dry-run --consolidate-languages apply --skip-hub-backfill

Stage 5 · runasks first

What it does Migrates every department into its own environment, then merges its language siblings (AUTO_MERGE groups). The Hub is not pushed here; that is stage 7.

Keys enter → confirm Writes every department's data into its environment in the target database. → token / APPLY / y. On prod the confirm opens only after the dry-run stage is done.

What you should see Each department in turn, with phases 1 to 5 and table progress. At the end ✓ run, each department run done or run needs-verify (both are normal; verify is next).

If not

  • A department fails: read Reason/Full log, fix the cause, press enter. A department whose run was stopped continues with --resume by itself.
  • E-RUN-RESUME-01 (rows already exist without --resume): press enter again; the lifecycle marks a killed run as interrupted and resumes it. If it repeats, see L9.
  • Channel-mapping warnings are not the failure. See L9 for how to fix a wrong channel type.

CLI $M run --client <dept env id> --config <dept .env> --department N --consolidate-languages apply --skip-hub-backfill (add --resume to continue a stopped run).

After run: QUARANTINE language groups

The run merges only groups it is sure about (AUTO_MERGE). Groups that need a human decision are QUARANTINE. The department row shows quarantine N pending, or quarantine ? when the count was not recorded. If every row shows nothing, there is nothing to do.

For each department with a count above 0 or a ?:

  1. esc to the Menu. In Environments, x on the client row, select that department, esc.
  2. Menu → consolidate-languages. The first enter is a dry run: it shows AUTO_MERGE N, QUARANTINE N, UNMERGEABLE N.
  3. Read the QUARANTINE groups in reports/consolidation-<env>-<time>.md (less in a second tmux window). Each group has a group: line, its fingerprint. Decide for each group whether its surveys are the same survey in different languages.
  4. Only if every QUARANTINE group in the report should merge: press a, then enter. [a] arms all QUARANTINE groups of the report (this screen has no per-group choice), and enter applies at once, with no typed confirm. If any group must not merge, do not press a: run the CLI below with only the fingerprints you approve.
  5. Go back to the client row and Lifecycle.
Deadlines for QUARANTINE merges

Before hub-backfill (L6): a merge after a Hub push changes the ids the Hub keys records by, so a later push adds a second copy instead of correcting the first. Before retire (L8): after retire they can no longer be merged at all. The Lifecycle count is not updated by Consolidate languages → [a]; it keeps showing the old number until the department's next run.

Alternative before the run stage: put the fingerprints in [o] → --approve-quarantine (the fill row copies them from the dry-run reports). The run then merges them too.

CLI (per department) $M consolidate-languages --client <dept env id> --config <dept .env> (dry run), then $M consolidate-languages --client <dept env id> --config <dept .env> --approve-quarantine "<fp1>,<fp2>" --apply with only the groups you approve, each spelled exactly as its group: line.

Undo a wrong merge: $M unmerge-languages --config <dept .env> --survivor-id <survivorId> (the survivor id is in the consolidation report; 07c, step 3). It works only before that department's Hub push (a push after a merge keys the records by the merged ids), before finalize-consolidation, and before retire.

L5

Stage 6: verify

For each department: catch up with a delta, then compare source and target (parity). Repeats up to 1 + parity-retries rounds.

  1. 1open-program
  2. 2provision
  3. 3preflight
  4. 4dry-run
  5. 5run
  6. 6verify
  7. 7hub-backfill
  8. 8finalize
  9. 9export
  10. 10retire
  11. 11census
asks first

What it does For each department not yet verified, a round is a delta (copies source rows added since the run; the source is only read) followed by parity. If parity fails, it runs another round, up to 1 + parity-retries (default 3 rounds). Each round:

  • freezes the source first (Delta: freezing this round's source high-water marks …). Parity compares both sides only up to that line. Rows the live source adds after the freeze are reported as pending (a warning), not failures; the next round or finalize's final delta takes them.
  • relinks responses to contacts that arrived after them (Phase 4, before parity).
  • if the department's initial load is not finished (E-DELTA-PLAN-OPEN-01: its run left an unfinished checkpoint or partition plan), runs run --resume once for that department and tries the delta again. It stops only if the delta is refused a second time.

Keys enter → confirm Runs delta per department (copies the source rows added since the run into the target) and may resume an interrupted run. with departments to verify (delta + parity) N → token / APPLY / y.

What you should see The step line verify · dept N (k of M), the phases of the delta, then the parity checks. At the end ✓ verify and every department verified yes. Rows that arrived after a round froze the source are pending, not missing; finalize's final delta takes them. The Lifecycle screen prints no line for them. From a shell, $M lifecycle prints dept N round R: parity passed (…) — N row(s) arrived after the round froze the source (…): pending, not missing; the final delta before finalize takes them.

screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Verify round for department 1 with the phase timeline at phase 4 and the Response table progress row
Verify progress: each round is a delta (phases 1–5) followed by parity; the timeline shows only this step's phases.
screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Parity phase of a verify round showing parity check progress 3 of 18
The parity part of a verify round. Rows the live source adds after the round froze it are reported as pending, not failures.

When verify stops

The screen says which department did not verify, each failing check with its meaning, where the report and last log are, and a yellow Next: line. This is the current text:

verify stopped — text from the current build (example check)
verify failed
verify stopped: 1 department(s) did not verify — their parity checks failed (the parity gate, not a crash):

dept 5 did not verify: 1 check(s) failed
  ✗ contact_target_extras — <title>: <k> migrated contact(s) the department no longer uses (ids: …) …
    fix: <remedy, when the check has one>
Report: reports/parity-<env>-<time>.html
Last log: .migrate/lifecycle/logs/<base>/verify-dept5-delta-<time>.log
Next: check the contact ids in the report; if the live source deleted or re-pointed their usage, [o] → accept contact_target_extras, then enter and confirm
screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Verify stopped because department 5 did not verify; three failing checks listed with meaning not recorded and a Next line
The current build reading a state file written by an earlier build: each check says meaning not recorded, and Next: says to press enter to verify again with this build. A verify run with this build shows ✗ <check> — <title>: <note> and a fix: line instead (the text block above).

Check → what to do

Failing check (or message)What it means → what to do
survey_channel_coverage (only this one)Some source surveys have no channel. If that is expected for this customer, press a (shows [x]), then enter and confirm. Once that stage has run, the acceptance stays for the rest of this lifecycle, finalize included (L2). Otherwise fix the source data first.
contact_target_extras (only this one)Migrated contacts the department no longer uses: the live source deleted or re-pointed their usage after migration, and a delta never removes a contact. Look up the ids from the report in the source. If that is what happened: o, ↓ three times to --accept-check contact_target_extras, enter (shows [x]), esc, then enter and confirm. Once a stage has run with it, it stays accepted for this lifecycle. Applied only up to 50 per department; more than 50 is the sign of another department's contacts written here: do not finalize; escalate (L9 escalation kit).
contact_count_parity (a contact is missing)A customer the department uses is not in the target. No delta creates it, and a reset would meet the same case again. Do not finalize and do not reset. Escalate with the ids and the report (L9 escalation kit).
response_contact_backfillResponses not linked to a contact that exists. Press enter: the next round's relink links them. If it stays: $M backfill-response-contact-attributes --client <dept env id> --config <dept .env>, then enter. If its fix line says no migrator step links them, decide the link by hand before cutover.
row-count:… above the target's highest idLate rows or an unread tail. Press enter: another delta reads them.
"meaning not recorded" / "earlier build"The results came from an older build. Press enter to verify again with this build.
E-DELTA-PLAN-OPEN-01The department's initial load (its run) is not finished. Handled by itself (one run --resume, then the delta again). If it says still refused … after run --resume, escalate with the log (L9 escalation kit).
E-DELTA-HWM-01The source's newest id is below what this environment already migrated. First check that the department's .env and department id are right. If they are, the source lost rows (restore or deletion). No flag gets past it. Do not finalize; escalate with the table, id and environment (L9 escalation kit).
anything elsereal gap: do what each check's fix: line says, or read its note in the report. enter re-runs delta + parity, which repairs only what a fix says a delta repairs.

Reading the HTML report on the box: less reports/parity-<env>-<time>.html, or copy it to your laptop with scp. After you act, press enter: only departments not yet verified run again.

screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Verify running again for department 5 after enter was pressed on the failure view
Pressing enter after a failed verify runs only the departments not yet verified (here dept 5, 4 of 4).

CLI (one department by hand)

bash
$$M delta --client <dept env id> --config <dept .env> --department N
$$M parity --client <dept env id> --config <dept .env> --department N # optional: the delta already ran parity and wrote the report
$$M lifecycle --from-config <base.env> --from-stage verify --until verify --accept-check survey_channel_coverage # only if that gap is expected
L6

Stage 7: hub-backfill and the Hub

Push each verified department's responses to the Hub (Superset / Power BI read from it). Skipped where no Hub is configured.

  1. 1open-program
  2. 2provision
  3. 3preflight
  4. 4dry-run
  5. 5run
  6. 6verify
  7. 7hub-backfill
  8. 8finalize
  9. 9export
  10. 10retire
  11. 11census
asks firstskipped without a Hub

Where the Hub settings go. HIVECFM_HUB_URL and HIVECFM_HUB_API_KEY are read from each department .env. Put them in the base config before provision and every department gets them. Added after provision: add both lines to each .env.<base id>-* file. A key set in the file wins, even when set empty. A key missing from the file is taken from the shell that started the TUI.

What it does Runs hub-backfill once per verified department and records pushed to the Hub at <time>. A department already pushed is skipped.

Keys enter → confirm Sends each department's finished responses to the Hub (external service). A re-push is safe only while the data is unchanged: … with departments to push to the Hub N. Departments with no Hub are named before the confirm: dept N will be skipped: Hub not configured in <cfg> …. When no department has a Hub, enter records the skip without a confirm.

What you should see ✓ hub-backfill and each row pushed to the Hub at …, or » hub-backfill (skipped) with Hub not configured in … — nothing pushed; set it and re-run: …. Skipped is not failed: the lifecycle goes on to finalize.

The Hub never updates a record

The Hub answers a record it already holds with 409 (duplicate) and keeps the old one. So: only verified departments are pushed; merge QUARANTINE groups before this stage (L4); and finalize pushes every pushed department once more after its final delta, so the last rows reach the Hub. After a QUARANTINE merge, any push adds a second copy. reset-client does not delete Hub records (L10).

If not

  • dept N is not verified — hub-backfill pushes only verified data …: finish verify first (L5).
  • dept N hub-backfill failed (exit 2). Full log: …: the Hub is unreachable, the key is rejected, or the department's environment id is not in the target's Environment table (E-HUB-ENVNF-01; check CLIENT_ENV in that department's .env). Fix it and press enter; pushed departments are skipped, the rest are sent again.
  • The Hub stays down. The client can wait (nothing is lost before finalize). If the cutover cannot wait, finalize without the Hub from a shell, with --until: $M lifecycle --from-config <base.env> --from-stage finalize --until finalize. From a shell the question is a plain [y/N] (L11); without --until one command would go on to export, retire and census. This works only while no department is pushed to the Hub: finalize pushes every pushed department again and stops if the Hub is down. Afterwards the screen keeps ▸ ✗ hub-backfill and [enter] run next stage (hub-backfill), and it never says Migration complete until the push is done. When the Hub is back, press enter: hub-backfill pushes, then the lifecycle goes on to export, retire and census as usual (L8). h does not help here: it re-runs only a skipped hub-backfill and answers [h] re-runs a SKIPPED hub-backfill; hub-backfill is failed here. The shell form of the push is $M lifecycle --from-config <base.env> --from-stage hub-backfill --until hub-backfill (works after retire too).
  • Skipped, but you want the push: set the two variables in each department .env, then press h on the Lifecycle screen (works before and after retire). If hub-backfill failed instead, h does nothing: see the bullet above.

At the end of a lifecycle with no push, the screen says in yellow: The Hub was NOT pushed, so Superset / Power BI show no pre-migration responses — hub-backfill was skipped: …, ending with the command that pushes it.

The screenshot of this end state is the last one in L8.

bash: push from a shell
$$M lifecycle --from-config <base.env> --from-stage hub-backfill --until hub-backfill # same as [h]; records the push
$$M hub-backfill --client <dept env id> --config <dept .env> # one department; not recorded in the lifecycle state
L7

Stage 8: finalize (the cutover moment)irreversible per department

Stop writes to the source, take the last rows, push them to the Hub, and close each department's staging.

  1. 1open-program
  2. 2provision
  3. 3preflight
  4. 4dry-run
  5. 5run
  6. 6verify
  7. 7hub-backfill
  8. 8finalize
  9. 9export
  10. 10retire
  11. 11census
preview, then asks
  1. Stop writes to the source. The cutover owner (L0) stops the legacy system from taking new responses. Finalize checks this; if the source is still taking writes it refuses.
  2. Press enter. The preview runs finalize-staging (no --apply) for every department and shows what it would purge. Nothing changes. The full preview of each department is in .migrate/lifecycle/logs/<base>/finalize-dept<N>-finalize-staging-<time>.log.
  3. Read the confirm: IRREVERSIBLE: finalize-staging --apply per department, after one final delta per department and a second Hub push for each department already pushed; a finalized department can no longer resume or take a delta. Yellow lines name departments with QUARANTINE groups still undecided and departments already pushed. Merge first if needed (L4), otherwise type the token / APPLY / y.
  4. It then runs four passes, in this order: (1) one final delta + parity for every department not yet finalized; (2) the live-tail check: if the source took rows after a final delta froze it, finalize stops here (below); (3) the Hub push again for every department that was pushed before; (4) per department, the finalize-staging preview, then finalize-staging --apply. A live-tail refusal, a failed parity or a failed Hub push in passes 1–3 leaves every department unfinalized. On the screen the step line names each child, e.g. finalize · dept 1 (1 of 4) · elapsed 0m41s · log …/finalize-dept1-delta-<time>.log. (A shell $M lifecycle also prints dept N: running a final delta before finalize — re-checks the source at cutover; the screen does not.)
screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Finalize preview listing per-department staging tables it would purge
Finalize first previews finalize-staging for every department. Nothing changes, and the confirm opens only if every preview succeeds. Each department's full preview is in .migrate/lifecycle/logs/<base>/finalize-dept<N>-finalize-staging-<time>.log. (Target host and user painted over.)
screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Finalize running its final delta for department 1 of 4 with hub-backfill shown as skipped
After the confirm, finalize runs one final delta and parity for every department (the cutover check), pushes the Hub again where it was pushed, and only then runs finalize-staging --apply.

What you should see ✓ finalize, every department finalized yes, ▸ on export.

If not

finalize refused on a live source — text from the current build
finalize failed
Reason: Not finalized: the source is still taking writes — dept 5: up to 1 row(s) (…) arrived after the final delta froze it (an upper bound: …). Finalizing now could leave them unmigrated for good (retire removes what a later delta needs). Stop writes to the source (cutover) and re-run: finalize runs another final delta first. Or accept leaving them behind with --accept-live-tail.
Next: press [o], set accept-live-tail → yes, then enter — or stop writes to the source (cutover) and press enter.
You seeWhat to do
Not finalized: the source is still taking writesBest: stop source writes and press enter (finalize runs another final delta). Only if the owner accepts losing those rows: o, ↓ four times to --accept-live-tail, enter (shows [x]), esc, enter. The finalize preview runs again, then the confirm (token / APPLY / y). The acceptance is recorded in the state file.
finalize stopped: … did not verifyThe final delta's parity failed. Nothing was finalized and the department is no longer verified. Follow the check table in L5, then press enter (finalize runs its final delta and parity again first).
dept N Hub push after the final delta failedNothing was finalized. Fix the Hub, run $M hub-backfill --client <dept env id> --config <dept .env> (safe to repeat), then press enter.
E-DELTA-HWM-01The source lost rows this environment migrated. Do not finalize; escalate (L5, L9 escalation kit).
Finalizing by hand skips the live-source check

$M finalize-staging --client <dept env id> --config <dept .env> [--apply] run outside the lifecycle does not run a final delta and does not check for new source rows. Use the lifecycle's finalize stage unless you have stopped the source and run the final delta and parity yourself.

CLI $M lifecycle --from-config <base.env> --from-stage finalize --until finalize --preview, then the same without --preview, keeping --until finalize (add --accept-live-tail only if accepted). From a shell the confirm is a plain [y/N] (L11). The DNS / application switch to the new platform is outside the migrator: do it after finalize, as agreed with the customer (08).

Stop here after finalize: go live first, retire later

Do not press enter on export / retire now. Next:

  1. Right before you switch traffic, record the cutover start (rollback, 10, needs it): CUTOVER_START=$(date -u +%Y-%m-%dT%H:%M:%SZ); echo "$CUTOVER_START" | tee -a ~/cutover-<client>.txt.
  2. Switch the application / DNS to the new platform and run the smoke test (08 Go Live).
  3. Wait out the rollback window: until the customer confirms that you will not roll back. Retire (L8) ends rollback for good.

Only then open Lifecycle again and press enter on export (L8).

L8

Stages 9–11: export · retire · censusretire is database-wide and irreversible

Save the provenance, remove every migration table and column from the database, and prove nothing is left.

  1. 1open-program
  2. 2provision
  3. 3preflight
  4. 4dry-run
  5. 5run
  6. 6verify
  7. 7hub-backfill
  8. 8finalize
  9. 9export
  10. 10retire
  11. 11census

Start L8 only after go-live and the rollback window (the stop box at the end of L7): retire ends rollback for good.

Stage 9 · exportstarts at once

What it does Writes the provenance columns (which source row became which target row) to ./provenance/<base id>/ with a manifest.json. Skipped if a manifest already exists there. Read-only on the database.

Keys enter (no confirm). You should see ✓ export.

Keep this directory (copy it off the box). After retire it is the only lineage record.

screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Export stage done, retire next; hub-backfill shown as skipped with the Hub-not-configured detail
Export wrote the provenance manifest that retire checks. A skipped hub-backfill keeps its detail and the exact re-run command.

Stage 10 · retirepreview, then prod tokenirreversible · database-wide

What it does Drops every migration-owned table (13 staging tables and 2 markers), the 10 provenance and tracking columns and their 6 indexes, for the whole database. It refuses unless every client that migrated into this database is finalized, and unless the manifest's counts match the live rows.

Keys enter → preview (the tables, columns, and the manifest match) → confirm with the prod token, whatever the tier:

retire confirm — text from the current build
IRREVERSIBLE, DATABASE-WIDE: drops every migration table and provenance column. QUARANTINE language groups not yet merged (Consolidate languages → [a], per department) can no longer be merged after this.
Tier PROD
Tier PROD: retire drops the migration tables and columns for the whole database, not one environment, so it always asks for the production token, even for this dev client.

Type STCBH-XXXX exactly as shown, then press enter.
> _
After retire

No rollback (E-PROV-01: the provenance columns are gone). No QUARANTINE merges. No delta. The only way back is L10 reset-client, before the customer goes live. The Hub push still works ([h] for a skipped hub-backfill, enter for a failed one, L6).

If not E-PROV-02 has two causes.

  • The manifest is missing or does not match the live rows, for example a delta ran after export. enter on export does not help: the lifecycle never re-runs a stage that is done or skipped. Export by hand instead: move the old export aside (mv provenance/<base id> provenance/<base id>.stale-$(date +%Y%m%d%H%M); export refuses to write over an existing manifest.json), run $M export-provenance --config <base.env> --out ./provenance/<base id>, then press enter on retire. Keep the moved-aside copy too.
  • The message says provenance changed during retirement: a run or delta wrote provenance while retire was dropping it. Nothing was dropped. Do not export again: find and stop that writer first (pgrep -af "dist/cli.js" on this box; on a shared database, ask the other client's operator), then press enter on retire.
  • A refusal naming a tenant that is not finalized: another client in the same database must be finalized first (L0).
screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
Retire stage done, census next
Retire has dropped every migration table and provenance column. From here, rollback and QUARANTINE merges are no longer possible.

Stage 11 · censusstarts at once · read-only

What it does Counts every migration-owned table, column and index still in the database, and must find zero. Read-only. enter, no confirm.

What you should see Migration complete: retired and census is zero. If a yellow The Hub was NOT pushed … line follows, see L6. If hub-backfill failed and was passed over from a shell (L6), the screen shows ▸ ✗ hub-backfill instead, and Migration complete appears only after that push.

If not Census prints each name it found. Collect the escalation kit (L9) with that output; do not drop anything by hand.

screenshot · STC-BH rehearsal (run 3), 2026-09-29/30
All stages done: Migration complete, retired and census is zero, with a yellow warning that the Hub was not pushed and the command to push it
The finished lifecycle. The yellow line appears because no department config named a Hub. Press [h] (or run the printed command) once HIVECFM_HUB_URL / HIVECFM_HUB_API_KEY are set in each department .env.
bash: the same three stages by hand
$$M export-provenance --config <base.env> --out ./provenance/<base id>
$$M retire-migration-program --config <base.env> --confirm --provenance-manifest ./provenance/<base id>/manifest.json # preview
$$M retire-migration-program --config <base.env> --confirm --provenance-manifest ./provenance/<base id>/manifest.json --apply
$$M census --config <base.env> --expect-zero
L9

Lifecycle troubleshooting

Find the text you see in the left column. Every row came from a real run.

You seeWhat it means → what to do
⚠ not yet verified — press [r] to re-check it, or enter again to select … anyway.The entry has not been checked in the last 24 hours, or its config changed. Press r, then enter. On a single entry r opens the Environment re-check screen (L1, step 3).
lifecycle is grey on the MenuRead its hint (L1, step 4).
Not started: an engine child started by another migrator process is still running …Another command is still writing. The message names it and how to stop it safely. Wait for it. Remove .migrate/live/<pid>.json only if that pid is not that command any more.
E-LIFECYCLE-LOCK-01 Another lifecycle is already running for this clientCheck the named pid: ps -p <pid> -o args=. A live lifecycle: wait, or kill -INT <pid>. If it names a stage command still running after its lifecycle died, kill -INT it only if the message says it stops gracefully; otherwise wait. rm <lock> only when both are gone (another host: check on that host).
E-LIFECYCLE-LOCK-02 Lifecycle lock could not be createdCannot write .migrate/lifecycle: permissions, a file in the way, or a full / read-only disk. Fix it, then enter.
stage <s> is running … enter is disabled until it finishesYour own stage is still running. Wait, or press r. If it names a pid on this host that is not a lifecycle any more, follow the line's own rm <lock> advice.
<stage> failed, then Reason: / Next: / Full log: (on the screen)A stage command failed. Read Reason, the red lines and Full log:, fix the cause, press enter. The lifecycle resumes at that stage. The screen shows <stage> failed (exit N) instead only when the launch saved nothing (a refusal such as E-LIFECYCLE-LOCK-01): read the red lines under it.
E-LIFECYCLE-STAGE-01: stage <s> — … (from a shell)The same failure from a shell $M lifecycle, followed by Full log:, the check or error lines and Next:; exit code 1. The Lifecycle screen never shows this code. Fix the cause and run the same command again.
E-LIFECYCLE-SCOPE-01First check the spelling: --from-config must be written exactly as the base entry's configFile in .migrate/targets.json (the CLI compares the text; use the absolute path). Otherwise no base entry matches the config, or its id has no letters or digits. Fix the base entry in targets.json (L0).
E-LIFECYCLE-ACCEPT-01Only survey_channel_coverage and contact_target_extras can be accepted. Fix any other failing check; never accept it.
The lifecycle saved no output for this failure; its last stderr lines:The child died without saving a reason. Read the red lines and the newest log in .migrate/lifecycle/logs/<base>/.
Warning, not the cause of the failure: N source channel name(s) have no channel mapping …Those channels were migrated as type web. If that is wrong, add each name to config/channel-mapping.<environmentId>.json with displayName equal to the source name. The next run or verify round fixes the type. Look for the real error elsewhere.
Provision is incomplete … / … left half-created …See L3, stage 2.
verify stopped … (any check)See the check table in L5.
E-DELTA-PLAN-OPEN-01 … still refused after run --resumeThe department's initial load (its run) is not finished: an unfinished checkpoint or partition plan, and the one run --resume the lifecycle tries did not finish it. Escalate with the log (escalation kit below); do not finalize.
E-DELTA-HWM-01Real divergence (source lost migrated rows, or a wrong --department/config). No flag gets past it. Escalate (kit below).
E-RUN-RESUME-01 Pre-existing rows without --resumeIn the lifecycle, press enter again (a stopped run is resumed). By hand: add --resume.
» hub-backfill · Hub not configured in …Skipped, not failed. Set the Hub variables and press h when wanted (L6).
dept N hub-backfill failed (exit 2)Fix the Hub and press enter, or finish without it and push later with enter on hub-backfill, not h (L6).
dept N is not verified — hub-backfill pushes only verified dataRun verify first.
Not finalized: the source is still taking writesStop source writes and press enter, or accept the live tail (L7).
That did not match. A new token was generated …Type the new token shown, exactly (capitals matter).
Proceed? [y/N] and enter does nothingPress y.
E-PROV-02 Provenance would be dropped without an exportTwo causes (L8). The manifest is missing or stale: move provenance/<base id> aside, run $M export-provenance --config <base.env> --out ./provenance/<base id> by hand (enter on export does not re-run it), then enter on retire. Or the message says provenance changed during retirement: a run or delta is writing; stop it, do not export again, then enter on retire.
census not zeroCollect the escalation kit (below) with the census output. Do not drop anything by hand.
quarantine ? on a departmentThe count was not recorded. Dry-run Consolidate languages for that department to see (L4).
A shell lifecycle sat waiting after a stageIt is waiting at a [y/N] question. Attach to its tmux window and answer. Do not add --yes to avoid the wait: it removes every question, finalize and retire included (L11). If a run must be unattended, stop it before finalize: --yes --until verify.
A department was provisioned by mistake (dry-run fails on it with boundary 0)No lifecycle step removes a provisioned department. Stop, collect the escalation kit (below) and wait for the owner (L4).
SSH droppedssh -t …, then tmux attach -t <client>. Never start a second TUI to see the screen.
Escalation kit: what to collect when this guide says "escalate"

You are offline, so collect everything the migration owner needs in one go, before you change anything else:

  • A support bundle: Dashboard → B (written to reports/support-bundle-*.json, with passwords scrubbed).
  • .migrate/lifecycle/<base id>.json (the state) and the whole .migrate/lifecycle/logs/<base id>/ directory.
  • The newest reports/parity-*.html and reports/consolidation-*.md of the department concerned.
  • .migrate/targets.json, and the output of $M lifecycle --from-config <base.env> --status.
  • A photo or copy of the screen, and the last keys you pressed.

Pack them, for example tar -czf escalation-<client>-$(date +%Y%m%d-%H%M).tgz .migrate/lifecycle .migrate/targets.json reports/support-bundle-* reports/parity-* reports/consolidation-*, and copy the file off the box. Never add a .env file: they hold the passwords. Logs name hosts and databases; send them only to the migration owner.

Safe to leave: until finalize (L7) the client can wait for days at any stage. The source stays live and is only read, nothing is lost, and the next verify round or finalize's final delta catches up. While you wait for an answer, do not finalize, retire or reset.

Screens with no current-build screenshot yet

These screens are shown in this guide as text copied from the current build, not as pictures. If you run a migration, capture each one (crop the terminal title bar; paint over any host, user, IP or password) so the next version of this guide can show it:

  • Environments: the Client — <client> (N depts) row and its status line (L1).
  • Main menu: the lifecycle row with its hint (L1).
  • The Lifecycle screen before the first stage, with the [d] and [a] rows (L2).
  • The [o] options panel (L2).
  • The three confirm dialogs: dev/local Proceed? [y/N], uat APPLY, prod token (L2).
  • The stages open-program, provision (preview and confirm), preflight, dry-run and run (L3, L4).
  • The hub-backfill confirm (L6).
  • The current verify failure view, the finalize live-tail refusal and the retire token prompt (L5, L7, L8). The run-3 pictures of these showed older text.
L10

Reset a client and migrate againdestructive · pre-go-live only

reset-client returns a retired client to how it was before the migration, so the lifecycle can run again. CLI only.

Use it only before the customer goes live

It deletes the migrated surveys, responses and contacts and what the migration created in every environment of the client, deletes the department projects, restores the anchor project's name, and archives the department registry entries. It cannot leave an environment out. It refuses when it finds the customer's own data (contacts older than the migration, or anything created after retire). While the program is still open (before retire) it refuses: see Start over before retire below.

  1. Run it from the directory where the lifecycle ran (packages/migrator). It reads .migrate/lifecycle/<base id>.json for when the migration started and ended. Without that file, pass --cutoff <UTC time the first run started> and --upper-cutoff <UTC time retire --apply ran>, taken from those commands' logs. Never use a row's own time. Write <base.env> exactly as the base entry's configFile in .migrate/targets.json.
  2. Dry run: $M reset-client --from-config <base.env>. Read Organization, Environments, Cutoff, Upper bound, the steps, Protected (other organizations, …) and the Hub line. It ends DRY RUN — nothing was changed.
  3. Hub: if the Hub line says departments were pushed (or no lifecycle state exists), purge this client's records from the Hub before the apply (procedure below). Reset does not touch the Hub, and the re-migration's push would add every response again under new ids.
  4. Apply: $M reset-client --from-config <base.env> --apply --confirm-org "<exact organization name from the dry run>", plus --acknowledge-hub-push when the Hub line asked for it. Pass that flag only after the purge shows a count of 0, or when the owner has decided that the re-migration will not be pushed.
  5. Result: ✓ Registry: removed N department entries, moved M file(s) to .migrate/archive/reset-<time>. Base entry "<id>" kept. and Next: migrate lifecycle --from-config <base.env>. The lifecycle state was archived too, so the next lifecycle starts at open-program. In the TUI, Environments picks up the change when it opens (or [l]).
RefusalMeaning → what to do
E-RESET-STATE-01The client is not retired (migration tables or columns exist). Run $M census --config <base.env>, then see Start over before retire.
E-RESET-SCOPE-01First check that --from-config is written exactly as the base entry's configFile. Otherwise the scope is not safe: no record of the migration's start or end, contacts older than the migration, customer rows created after retire, or a project it cannot account for. Do not reset while the customer's own rows exist; the owner decides. Run it where the lifecycle ran, or give --cutoff/--upper-cutoff from the logs.
E-RESET-CONFIRM-01--confirm-org is missing or not the exact name (case-sensitive), or --acknowledge-hub-push is needed.
E-RESET-DRIFT-01Something changed since the dry run. Nothing was changed. Run the dry run again, compare, then apply.

Purge this client's records from the Hub

The migrator has no purge command; the Hub API has one. It deletes every Hub record of the client's organization (the Hub keys records by tenant_id, which is the organization id), so use it only before go-live, when the organization holds nothing but migrated data. The customer's Hub / analytics owner must agree first.

  1. Take the organization id from the reset dry run: Organization <name> (<organization id>).
  2. Get the Hub API address and the Hub server's own API key (its API_KEY setting) from whoever deployed the Hub. Call the Hub API itself, not the public gateway: the gateway does not route /v1/tenants/….
  3. Count, purge, then count again until it reads 0:
bash: purge one organization's Hub records (pre-go-live only)
$HUB=<hub api url>; KEY=<hub api key>; ORG=<organization id>
$curl -s -H "Authorization: Bearer $KEY" "$HUB/v1/feedback-records/count?tenant_id=$ORG" # before: {"count":N}
$curl -s -w '\n%{http_code}\n' -X DELETE -H "Authorization: Bearer $KEY" "$HUB/v1/tenants/$ORG/feedback-records" # 202, {"status":"accepted",…}
$curl -s -H "Authorization: Bearer $KEY" "$HUB/v1/feedback-records/count?tenant_id=$ORG" # repeat until {"count":0}
  • 202: accepted. The Hub's worker deletes in the background; repeat the count every minute or so.
  • 404 on the DELETE: this Hub build has no purge. Do not push the re-migration: leave HIVECFM_HUB_URL / HIVECFM_HUB_API_KEY out of the base config (so provision writes none into the department files; hub-backfill is then skipped), apply with --acknowledge-hub-push, and hand the Hub data decision to the migration owner.
  • 401: wrong key. The count does not go down after several minutes: the Hub's worker is not running; ask whoever runs the Hub.

Start over before retire

reset-client works only on a retired client (E-RESET-STATE-01 otherwise), and there is no supported procedure that resets a whole lifecycle client while its program is open. rollback (10) empties one environment, but it leaves the lifecycle state file (which still says run done, verified), the department projects, their registry entries and the anchor project's new name as they are, and the next lifecycle would not run those stages again. So:

  • The supported path is finalize (L7) → export → retire (L8) → reset-client (this section) → a new lifecycle, all before go-live: do not switch the customer's traffic.
  • When verify is what went wrong, that path is blocked too: finalize needs every department to pass its final parity. Stop, collect the escalation kit (L9) and ask the owner.
  • On a database shared with another client, retire refuses until every client there is finalized, so the path may be blocked. Stop and ask the owner; do not roll back environments by hand to get around it.
  • Until then the client can wait (L9, "Safe to leave").
L11

The same migration from a shell

lifecycle is the CLI behind the Lifecycle screen. Same state file, same stages, same order.

From a shell, finalize and retire ask only [y/N]

The production token, APPLY and the preview before each confirm exist only on the Lifecycle screen. From a shell every question is a plain … [y/N], and one y finalizes every department or retires the whole database. So: run finalize and retire from the TUI. When you run one stage from a shell, always pass --until <that stage> with --from-stage; without it the command goes on to the next stages, retire included. Never pass --yes to a range that reaches finalize: --yes removes every question.

<base.env> in every command below must be written exactly as the base entry's configFile in .migrate/targets.json (the absolute path). The CLI compares the text, so another spelling of the same file fails with E-LIFECYCLE-SCOPE-01.

bash: whole lifecycle in tmux (asks [y/N] before each writing stage)
$$M lifecycle --from-config <base.env> --departments 1,3,4,5
$$M lifecycle --from-config <base.env> # after a stop: the same command resumes
$$M lifecycle --from-config <base.env> --status # where it is; runs nothing
FlagRequiredDescriptionDefault
--from-config <path>REQThe client's base config. Its registry entry is the base entry.—
--departments <ids>optDepartments to provision, e.g. 1,3,4,5. Used by provision only.every department
--from-stage <stage>optStart at this stage. A stage already done or skipped is passed over, never re-run; the one exception is --from-stage hub-backfill, which re-runs a skipped hub-backfill. Use it with --until.next pending
--until <stage>optStop after this stage.census
--yesoptAsks nothing before open-program, provision, run, verify, hub-backfill, finalize, retire: no confirm at all, finalize and retire included. Use it only with --until on a stage before finalize (for example --yes --until verify).false
--accept-check <ids>optsurvey_channel_coverage and/or contact_target_extras only.none
--parity-retries <n>optExtra delta + parity rounds per department.2
--export-dir <dir>optWhere export writes. CLI only../provenance/<base id>
--skip-dry-runoptSkip the dry-run stage. Not recommended. CLI only.false
--max-workers <n>optForwarded to every department's run (parallel Phase 3). CLI only.serial
--approve-quarantine <fps>optQUARANTINE fingerprints for every department's run.none
--accept-live-tailoptLet finalize go ahead over rows the source took after its final delta. Recorded.false
--statusoptPrint the state and the next stage; run nothing. CLI only.false
--previewoptWith --from-stage S --until S for provision, finalize or retire: run only the preview.false

What each stage runs (the manual-path map)

StageCommand(s) the lifecycle runs
open-programopen-program --config <base.env>
provisionprovision-departments --client <anchor env> --config <base.env> --write-config --tier <base tier> --id-prefix <base id> [--departments …] (preview adds --dry-run)
preflightpreflight --client <dept env> --config <dept .env> --department N per department
dry-runrun --client <dept env> --config <dept .env> --department N --dry-run --consolidate-languages apply --skip-hub-backfill
runthe same without --dry-run (--resume added for a stopped department)
verifyper round, delta --client <dept env> --config <dept .env> --department N (the delta runs parity itself and writes the report); a separate parity with the same flags only when the delta wrote no report
hub-backfillhub-backfill --client <dept env> --config <dept .env>
finalizein four passes: a final delta (with its parity) for every unfinalized department; the live-tail check; hub-backfill again for each department pushed before; then per department finalize-staging --client <dept env> --config <dept .env> (preview) and the same with --apply
exportexport-provenance --config <base.env> --out ./provenance/<base id>
retireretire-migration-program --config <base.env> --confirm --provenance-manifest ./provenance/<base id>/manifest.json [--apply]
censuscensus --config <base.env> --expect-zero

Exit codes: 0 complete, or stopped at --until / after a --preview; 1 a stage failed, a question was declined (that stage goes back to pending), or a refusal such as E-LIFECYCLE-LOCK-01 (a failure is printed as E-LIFECYCLE-STAGE-01: stage <s> — <reason>, then Full log:, the check or error lines, and Next:); 130 stopped with Ctrl-C / kill -INT.

01 / 02Foundations
F1

What is the migrator?

Read this first. Sets context for everything that follows.

The HiveCFM migrator is a one-shot TypeScript CLI that moves a single legacy client from SQL Server (HiveCFMAppDB-* + HiveCFMSurveyDB-*) to the new PostgreSQL platform. It runs five phases (Lookups → Entities → Transactional → KPI → Validate) and is fully resumable. Kill it, restart, and it picks up where it left off.

It exists because we are retiring the legacy MSSQL backend while preserving every row, every survey response, every audit trail. Each client gets one migration. The same tool handles all known schema variants (StableRJB, ISTServiceEdge); an unknown schema aborts the preflight rather than guess.

The companion package @hivecfm/database ships five additive Prisma migrations (20260515000000 through 20260515000004) that prepare the target schema. Once those are applied, the migrator only adds data; it never alters schema at runtime.

F2

Who runs it & when

Operator profile plus the four lifecycle checkpoints.

The operator is a platform engineer with DDL + read/write access to both source MSSQL databases and the target PostgreSQL, plus REST credentials for the Superset analytics layer. Cutover runs are typically two-person: one driving, one watching the parity report.

WhenWhat happensWindow
T−7dBulk run. Lifecycle stages open-program → provision → preflight → dry-run → run → verify → hub-backfill (L3–L6) against the live legacy databases (read only). App stays live; users see no impact.Background, hours
T−0Cutover. Stop writes to the source, then the Lifecycle finalize stage (L7): for every department one final delta + parity, a second Hub push where pushed, then finalize; it refuses while the source still takes writes unless [o] accept-live-tail. Then switch the app / DNS and smoke test. Export, retire and census (L8) follow.1h target, 2h max (FR-019)
T+0…+4hRollback window. If smoke regresses, migrate rollback --cutover-start <T-0> replays PG writes back to MSSQL. Window closes at T+4h. Rollback needs the provenance columns: it works only before retire (after retire it refuses with E-PROV-01; the only way back is reset-client, pre-go-live). Do not retire until you are past this window.Hard cutoff (FR-023)
T+30dArchive close. Legacy MSSQL is read-only during this window for audit/historical lookup. Superset disconnects MSSQL the same day as cutover; the 30d window is for ad-hoc SQL only.Calendar reminder (FR-038/039)
F3

Glossary

The vocabulary the rest of this guide assumes.

variantA known shape of the legacy schema. Three are recognized: StableRJB (newer, has Touchpoint family), ISTServiceEdge (older, no Touchpoint), Custom (unknown, the migrator aborts).
legacyId / legacyGuidOptional nullable columns on target tables that hold the original MSSQL primary key. Fresh clients have NULL; migrated rows carry the source ID for traceability.
additivityEvery schema change is additive and nullable (FR-024). A fresh PostgreSQL client behaves identically before and after the migrator ships. Enforced by CI via fresh-client-e2e.test.ts.
idempotencyRe-running the migrator produces the same final state. Phases 1–2 use per-row ON CONFLICT(legacy_id) DO UPDATE; Phase 3 uses checkpoint + ON CONFLICT(legacy_id) DO NOTHING.
cutoverThe maintenance window where the client switches from legacy MSSQL to PostgreSQL. Target 1 hour; FR-019 hard maximum 2 hours.
deltaIncremental migration of rows changed since the T-7d bulk snapshot. Timestamp-based for StableRJB (uses LastModifiedDate); ID-based for ISTServiceEdge (uses max(ID)).
parityFive validation checks: row count, sample field, FK integrity, KPI aggregate, schema diff. Produces an HTML report with per-table pass/fail.
chunked copyPhase 3 strategy: write rows to a temp table via PostgreSQL COPY … FROM STDIN, then INSERT … SELECT … ON CONFLICT DO NOTHING. Atomic with checkpoint advance.
advisory lockPostgreSQL session-level lock the migrator acquires per (client, run). Prevents two concurrent migrations of the same client.
checkpointRow in _MigrationCheckpoint tracking the last successfully-written legacy_id per table. Resume reads this to skip already-done rows.
materialized viewmv_response_kpi_daily and mv_response_kpi_monthly pre-aggregate KPIs for fast dashboards. Refreshed via pg_cron (daily MV every 5 min; monthly nightly 02:00).
F4

Variant Decider

Three questions about your source MSSQL schema. Mirrors the classifier the CLI runs during preflight (src/source/variant-detector.ts).

Variant identification quiz

1

Does your source DB have a CFMTouchpoint table?

2

Does CFMSurveyInvitation have a LastModifiedDate column?

3

Does CFMResponseKPICache exist?

Answer the three questions above to identify your variant.

If preflight ever reports Custom for a client you believed to be StableRJB or ISTServiceEdge, do not pass --allow-resume or otherwise force the run. Escalate to the migrator maintainer; a Custom verdict means the schema scanner found a marker combination we have not validated.

F5

Dual MSSQL databases

Why HiveCFM has two source DBs, and how the migrator stitches them.

Every HiveCFM client ships with two SQL Server databases, by historical design:

  • HiveCFMAppDB-{variant}. Users, customer orgs, departments, surveys, touchpoints (the static-ish entities that change at human speed)
  • HiveCFMSurveyDB-{variant}. Invitations, responses, response answers (the high-volume transactional data)

The migrator reads both, normalizes into a single PostgreSQL target. Operators configure both connection strings (SOURCE_APP_DB + SOURCE_SURVEY_DB) but only one TARGET_PG_DATABASE:

  App DB        ┐
                  ├──→  @hivecfm/migrator  ──→  Postgres (single target)
  Survey DB     ┘
  

Phase 1 (Lookups) and most of Phase 2 (Entities) read App DB. Phase 3 (Transactional) reads Survey DB. Join points where Survey rows reference App rows (e.g. Invitation.SurveyId → Survey.Id) are resolved through the legacyId column the migrator adds during Phase 2.

F6

Pipeline deep-dive — 10 phases

What runs in each phase, what mode it uses, expected duration, and how it recovers if interrupted.

PHASE 1
Lookups
ContactAttributeKey (14 fixed), Channel (from used legacy channel IDs)
~2 min
›
PHASE 2
Entities
Users, Surveys, Contacts + ContactAttributes
~15 min
›
PHASE 3
Transactional
Responses (chunked COPY) + ResponseAnswer (staging table, created on demand)
~2 hrs
›
PHASE 4
KPI
Refresh materialized views (daily + monthly aggregates)
~10 min
›
PHASE 5
Parity
Row-count validation, spot-check, generate HTML report
~5 min

Each phase is fully idempotent. Kill the process mid-flight and the next run resumes from the last committed checkpoint, never re-inserting a row twice.

This is the original 5-phase core (still exactly what --phase <1-5> selects). migrate run now also auto-runs several more phases around it, each skippable with its own flag: Phase 2.5 repair-surveys (--skip-repair), Phase 2.6 audiences (--skip-audiences), structure + response-data backfill at the end of Phase 4 (--skip-structure-backfill), targeting backfill after Phase 5 (--skip-targeting-backfill), language consolidation at the end, which by default applies the AUTO_MERGE groups (--consolidate-languages <apply|ask|report|skip>, default apply), and Phase 6 Hub backfill (--skip-hub-backfill). The lifecycle runs every department with --consolidate-languages apply --skip-hub-backfill and pushes to the Hub in its own stage (L6). See Command Reference → migrate run for the full flag set.

PhaseModeSmall (<10k)Medium (10k–500k)Large (500k+)Recover
1 · Lookupsper-row upsert<30s<1m<2m--phase=1 --resume
2 · Entitiesper-row upsert1–3m5–15m20–40m--phase=2 --resume
3 · Transactionalchunked COPY + ON CONFLICT3–10m30m–2h2–6h--phase=3 --resume
4 · KPIcompute + MV refresh1–2m5–10m15–30m--phase=4 --resume
5 · Validateread-only checks<1m2–5m5–15m--phase=5 (re-runs free)

Implementation lives in packages/migrator/src/pipeline/phase-{1..5}-*.ts. Phase 3 is the only phase where chunk size (--chunk-size=N, default 500) materially changes wall-clock time.

F7

Idempotency model

Why re-running the migrator is always safe, and what guarantees it.

The tool uses a hybrid idempotency strategy: per-row upsert for the small lookup and entity tables, and a chunked COPY pattern with a UNIQUE constraint for the millions-of-rows transactional tables. Both paths key on legacyId (or legacyGuid for GUID PKs).

Phases 1–2 (lookups + entities)

Each row is upserted individually. Cheap, naturally idempotent, no checkpoint overhead.

sql
INSERT INTO "SurveyType" (id, name, "legacyId", "environmentId", ...)
VALUES (cuid(), 'NPS', 123, 'client-x', ...)
ON CONFLICT ("legacyId") DO UPDATE
  SET name = EXCLUDED.name, "updatedAt" = NOW();

Phase 3 (transactional, millions of rows)

The chunked-COPY pattern from src/idempotency/chunked-copy.ts: data write + checkpoint advance succeed or fail together. The UNIQUE("legacyId") constraint plus ON CONFLICT DO NOTHING is the double safety net that lets the checkpoint be slightly wrong without corrupting state.

sql
BEGIN;
  CREATE TEMP TABLE tmp_Response (LIKE "Response" EXCLUDING GENERATED);
  COPY tmp_Response (...) FROM STDIN;

  INSERT INTO "Response" (...)
  SELECT ... FROM tmp_Response
  ON CONFLICT ("legacyId") DO NOTHING;

  UPDATE "_MigrationCheckpoint"
     SET last_legacy_id = $LAST, rows_processed = rows_processed + $N
   WHERE table_name = 'Response' AND environment_id = $CLIENT;
COMMIT;
FailureWhat actually happens
Kill mid-chunkTransaction rolls back, checkpoint unchanged, resume re-reads same range. No dupes (ON CONFLICT silently skips any partial inserts that did commit before crash).
Checkpoint advanced past actual writesRe-encountered rows hit the UNIQUE constraint, ON CONFLICT DO NOTHING. Silent skip, no error.
Re-run after successCheckpoint marks the table complete. Phase 3 reads 0 source rows and writes 0 target rows.
Network drop mid-COPYThe TEMP table is session-scoped: dropped automatically. Checkpoint unchanged. Resume re-streams the same chunk.
F8

Schema additivity invariant

The contract that lets the migrator ship without breaking fresh clients.

FR-024: every schema change introduced by the migrator must be additive and nullable. No DROP COLUMN, no ALTER TYPE, no ADD NOT NULL. New tables and columns either default to NULL or are populated only when a migrated row provides a value.

Why this matters. A fresh PostgreSQL client signs up tomorrow. They never run the migrator. Their Response row has legacyId = NULL, touchpointId = NULL, kpiScores = {...}. The app code reads it identically to a migrated row that has legacyId = 12345. There is no if (isMigrated) branch anywhere in the application code, and no middleware filters by legacyId IS NULL.

How it's enforced. A CI guardrail (apps/web/tests/integration/fresh-client-e2e.test.ts) runs a full signup → survey → response → dashboard scenario before and after every schema change. User-visible output must be bit-identical. Any change that requires a non-null new column or alters existing behavior for fresh rows fails the test.

Materialized views follow the same rule: mv_response_kpi_daily includes is_archived as a dimension, not as a WHERE filter, so reports can opt in or out per query without losing historical aggregates.

F8b

New models & how data moves

Which tables the migrator adds and why, what the schema looks like before and after, and how one row travels from MSSQL into Postgres.

(a) Two kinds of tables — don't confuse them

The migrator introduces tables in two completely different senses. They look similar (both are "tables", both hold rows) but they have nothing to do with each other:

Permanent new modelsTemp / scratch table
ExampleContact, Channel, Response (+ new columns)tmp_Response
Created bythe 5 Prisma migrations — once, up frontthe migrator — per chunk, at runtime
Lifetimeforever (part of the live app)one transaction (ON COMMIT DROP)
Purposegive legacy data a permanent homeload fast + dedupe safely
Holds data?yes — the final resting placeyes — but only ~chunk-size rows for a split second

So, to answer the common question directly: the new models are permanent. The temp table is a separate, throwaway loading dock that rows pass through on their way into the permanent tables. We do not keep data "as temp" in any lasting sense.

Safety: never drop the permanent models after a migration thinking they were temporary — they hold the client's entire migrated dataset. Only tmp_* tables are disposable, and Postgres drops those itself at COMMIT.

(b) What models were added — and what happened to them since

Migration 20260515000000 originally created 10 brand-new tables, on top of new nullable columns on three existing platform tables (Response, User, Survey). That was the whole picture for three months. It no longer is.

Three cleanup migrations landed 2026-08-20 – 2026-08-24 and dropped 7 of these 10 tables

Live-verified 2026-08-31 against the shared hivecfm Postgres server (to_regclass() on all 7 names → NULL): Touchpoint, TouchpointType, SurveyTouchpoint, SurveyTouchpointType, Department, CustomerOrg, Invitation, SurveyChannel, LegacySurveyKind — gone. ResponseAnswer was dropped in the same pass but, unlike the others, was given a runtime creator four days later and now exists as a staging table again (not the same thing — see the callout after the table). Treat the "why it exists" column below as historical design rationale for a fresh read of migration 20260515000000's intent, and the "status now" column as the only thing worth relying on operationally — on any database that has run db:migrate:deploy through 20260824120000, the "why" tables simply are not there to query.

TableWhy it was added (2026-05)Status now (2026-08-31, live-verified)
TouchpointRegion→branch→counter hierarchy. Home for legacy CFMTouchpoint.Dropped 2026-08-24 (20260824120000). 0 rows, 0 application readers; Response.touchpoint_id was NULL on 1,556,974/1,556,974 rows.
TouchpointTypeClassifies touchpoints. From CFMTouchpointType.Dropped 2026-08-24, same migration & evidence as Touchpoint.
SurveyTouchpointM2M bridge, surveys↔touchpoints. Mirrors CFMTouchpointBrg.Dropped 2026-08-20 (20260820000000). 0 rows on every environment checked — no migrator transform or product query ever wrote/read it.
SurveyTouchpointTypeM2M bridge, surveys↔touchpoint types.Dropped 2026-08-20, same migration & evidence.
DepartmentOrganisational departments. From CFMDepartment.Dropped 2026-08-24. Held 2 rows; both names were written onto Survey.legacy_extras.DepartmentName before the drop, so they aren't lost — just relocated. Don't confuse this with department-scoped migration, which is a live, current feature (see 03b Provision departments) — that feature reads the legacy MSSQL CFMDepartment table directly, never this dropped Postgres one.
CustomerOrgCustomer organisations. From CFMCustomerOrg.Dropped 2026-08-24 (20260824000000). 0 rows — the ISTServiceEdgeOld source variant has no CFMCustomerOrg table at all.
InvitationSurvey invitations. From CFMSurveyInvitation. Was the join bridge from responses back to the sending agent.Dropped 2026-08-24 — this was the single largest table in the database (1,556,966 rows, 3,514 MB). Proven a bijective subset of Response first (0 invitations without a matching Response; only 3 late-arriving Responses without one), then dropped. See subsection (d) for what replaced it.
ResponseAnswerIndividual answers within a response. From CFMSurveyResponseAnswer.Dropped 2026-08-24 (164,452 rows, fully consumed by Phase 4 first — see (d)), then given a runtime creator on 2026-08-28. It is no longer a permanent model: it's one of 8 STAGING_TABLES, created on demand by migrator code and eventually dropped for good. Full explanation: 11b Program retirement & staging-table lifecycle.
SurveyChannelDelivery channels per survey. From CFMSurveyChannel.Dropped 2026-08-24 (20260824000000). 0 rows by design on this source variant — CFMSurveyChannel has no SurveyID here, so channel data reaches Hive via the Channel table instead (added in v0.6 — see Channel & contact mapping).
LegacySurveyKindPreserved the legacy survey-kind taxonomy.Dropped 2026-08-24. Held 10 lookup rows; names were written onto Survey.legacy_extras.SurveyTypeName before the drop, same pattern as Department above.
So what tells you "invitation" vs. "response" now that Invitation is gone?

Response.answered_questions_count = 0 (apps/web/lib/response/utils.ts:37–42). A response with zero answered questions is what the old Invitation row used to represent; the product already used this discriminator before the drop, which is exactly why the table had zero application readers to begin with.

Existing platform tables that were not recreated — they only received additive columns, and some of those were removed again in the same cleanup:

TableColumns added by the migrator, originallyStill present 2026-08-31
Responsetouchpoint_id (FK→Touchpoint, denormalized), legacy trio, archived_at, kpiScores, 4 generated KPI columns.Everything except touchpoint_id (dropped 2026-08-24, step 6 of 20260824120000, once its FK target no longer existed). legacy_guid is now the sole surviving invitation identity; legacy_extras is the sole copy of the former AgentID/InteractionID/SourceID/SendMethodID/Status fields — both kept deliberately, for business data, not for parity/rollback.
Usertouchpoint_id, allow_undefined_touchpoints, legacy trio.Only legacy_id / legacy_extras remain. touchpoint_id and allow_undefined_touchpoints were dropped 2026-08-24 alongside Response.touchpoint_id; legacy_guid was dropped separately, same day, by 20260824000000 (0 of 40 rows had ever been populated — transform/user.ts wrote NULL unconditionally).
Surveylegacy trio only.Only legacy_id / legacy_extras. legacy_guid was dropped 2026-08-24 by 20260824000000 (same reason as User.legacy_guid: 0 of 12 rows populated, identity carried by legacy_id + legacy_extras instead).

(c) What the schema looks like today — and the DDL that got it here

A fresh platform Response row and a migrated one still share the same table; the migrator's surviving columns are simply NULL for fresh clients. This is the current shape (Genesys/CCaaS columns collapsed for readability) — note there is no touchpoint_id anymore:

  Response  — current (fresh-client columns + surviving migrator columns)
  ├─ id · createdAt · updatedAt · finished
  ├─ surveyId · contactId · endingId · displayId
  ├─ data · variables · ttc · meta · contactAttributes   (jsonb)
  ├─ kpiScores (jsonb) · answered_questions_count
  ├─ singleUseId · language
  ├─ genesys_* CCaaS context  (12 cols)
  ├─ surveyDeliveryChannel · isNegativeResponse · expiredAt
  ├─ legacy_id BIGINT UNIQUE · legacy_guid · legacy_extras (jsonb)   ← migrator, kept
  ├─ archived_at TIMESTAMPTZ                                            ← migrator, kept
  └─ csat_score · ces_score · nps_score · fcr_score   GENERATED ← migrator, kept

  Removed 2026-08-24: touchpoint_id (FK→Touchpoint, now-deleted table)
Original DDL (2026-05) — ALTER TABLE / CREATE TABLE for the tables this section now documents as dropped
sql
-- 20260515000000 - additive columns on the existing Response table (touchpoint_id since dropped)
ALTER TABLE "Response"
  ADD COLUMN IF NOT EXISTS "touchpoint_id" TEXT,       -- dropped 2026-08-24
  ADD COLUMN IF NOT EXISTS "legacy_id"     BIGINT,
  ADD COLUMN IF NOT EXISTS "legacy_guid"   TEXT,
  ADD COLUMN IF NOT EXISTS "legacy_extras" JSONB,
  ADD COLUMN IF NOT EXISTS "archived_at"   TIMESTAMPTZ,
  ADD COLUMN IF NOT EXISTS "kpiScores"     JSONB NOT NULL DEFAULT '{}';

-- 20260515000001 - generated KPI columns (read-only; auto-derived from kpiScores), still live
ALTER TABLE "Response"
  ADD COLUMN IF NOT EXISTS csat_score NUMERIC GENERATED ALWAYS AS ((("kpiScores"->>'csatScore')::numeric)) STORED,
  ADD COLUMN IF NOT EXISTS ces_score  NUMERIC GENERATED ALWAYS AS ((("kpiScores"->>'cesScore')::numeric))  STORED,
  ADD COLUMN IF NOT EXISTS nps_score  NUMERIC GENERATED ALWAYS AS ((("kpiScores"->>'npsScore')::numeric))  STORED,
  ADD COLUMN IF NOT EXISTS fcr_score  NUMERIC GENERATED ALWAYS AS ((("kpiScores"->>'fcrScore')::numeric))  STORED;

-- The Touchpoint home (self-referencing tree), table no longer exists, kept here for archaeology only
CREATE TABLE "Touchpoint" (
  "id" TEXT NOT NULL, "name" TEXT NOT NULL, "latin_name" TEXT, "code" TEXT NOT NULL,
  "legacy_id" INTEGER, "legacy_guid" TEXT, "legacy_extras" JSONB,
  "parent_id" TEXT, "type_id" TEXT, "environment_id" TEXT NOT NULL,
  "archived_at" TIMESTAMPTZ, "metadata" JSONB NOT NULL DEFAULT '{}',
  "created_at" TIMESTAMPTZ NOT NULL DEFAULT NOW(), "updated_at" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  CONSTRAINT "Touchpoint_pkey" PRIMARY KEY ("id")
);
Retirement DDL (2026-08-24, 20260824120000) — the exact statements that dropped the 7 forbidden-list tables + Touchpoint/Department/LegacySurveyKind
sql
-- Step 0 - preserve the names BEFORE dropping the lookups they came from
UPDATE "Survey" s SET legacy_extras = s.legacy_extras || jsonb_build_object('DepartmentName', d.name)
  FROM "Department" d WHERE d.environment_id = s."environmentId"
  AND d.legacy_id = (s.legacy_extras->>'DepartmentID')::bigint;
UPDATE "Survey" s SET legacy_extras = s.legacy_extras || jsonb_build_object('SurveyTypeName', k.name)
  FROM "LegacySurveyKind" k WHERE k.environment_id = s."environmentId"
  AND k.legacy_id = (s.legacy_extras->>'SurveyTypeID')::bigint;

-- Steps 1-7, dependency-first, no CASCADE (an unmeasured dependency fails loudly instead of
-- silently taking a dependent object with it)
DROP MATERIALIZED VIEW IF EXISTS mv_response_kpi_daily;    -- grouped on touchpoint_id; recreated below without it
DROP MATERIALIZED VIEW IF EXISTS mv_response_kpi_monthly;
DROP TABLE IF EXISTS "ResponseAnswer";                     -- 164,452 rows, fully consumed by Phase 4 first
DROP TABLE IF EXISTS "Invitation";                         -- 1,556,966 rows, proven bijective with Response first
DROP TABLE IF EXISTS merge_archive;
DROP TABLE IF EXISTS survey_merge_archive;
DROP TABLE IF EXISTS duplicate_placeholder_archive;
DROP TABLE IF EXISTS "_MigrationCheckpoint";
DROP TABLE IF EXISTS "_MigrationBoundary";
DROP TABLE IF EXISTS "_MigrationAuditLog";
ALTER TABLE "Response" DROP COLUMN IF EXISTS "touchpoint_id";
ALTER TABLE "User" DROP COLUMN IF EXISTS "touchpoint_id";
ALTER TABLE "User" DROP COLUMN IF EXISTS "allow_undefined_touchpoints";
DROP TABLE IF EXISTS "Touchpoint";
DROP TABLE IF EXISTS "TouchpointType";
DROP TABLE IF EXISTS "Department";
DROP TABLE IF EXISTS "LegacySurveyKind";

-- Step 8 - the KPI rollups are recreated, same names (so any pg_cron schedule keeps working),
-- just without the touchpoint_id GROUP BY column.

Full evidence (row-level bijection proof for Invitation, value-level multiset comparison for ResponseAnswer) is in the migration file itself: packages/database/migration/20260824120000_drop_migration_machinery_and_redundant_legacy_tables/migration.sql.

(d) How one row moves today — and what "merged" means now

The original 4-table denormalization walk (Response → Invitation → Agent (User) → Touchpoint) described in earlier versions of this guide no longer runs — all three of those tables are gone (subsection b). This is the current path, current as of the hivecfm-core-consolidation commit in the hero banner above:

  1. Read. The migrator streams CFMSurveyResponse rows from HiveCFMSurveyDB-* in --chunk-size batches (default 500).
  2. Transform. Each source row is mapped to target columns. The source PK is copied into legacy_id; the source GUID into legacy_guid; unmapped source columns are stashed in legacy_extras (nothing is silently dropped) — this is what makes legacy_guid/legacy_extras the sole surviving invitation identity now that Invitation itself is gone.
  3. Stage. The batch is COPY-ed (TSV) into the throwaway tmp_Response table — the loading dock from subsection (a).
  4. Land + dedupe. INSERT … SELECT … FROM tmp_Response ON CONFLICT ("legacy_id") DO NOTHING moves rows into the permanent Response. Any row already present (from a prior interrupted run) is silently skipped.
  5. Checkpoint. _MigrationCheckpoint advances in the same transaction, so data + progress commit together. tmp_Response is dropped at COMMIT. (_MigrationCheckpoint itself is one of the 8 STAGING_TABLES — see the callout below.)
  6. Answer projection (Phase 4). ensureResponseAnswerTable() creates the ResponseAnswer staging table on demand if it doesn't exist, then backfill-survey-structure.ts projects each answer's legacy_extras onto the corresponding Response.data key. Response.data is the permanent, product-facing copy; ResponseAnswer is scratch that outlives one transaction (unlike tmp_Response) only until this tenant is finalized.
  7. Score (Phase 4). kpiScores is computed by the live app's KPI logic; the generated columns (csat_score…) then populate automatically.

"Merged" now means: (1) two source databases (App DB + Survey DB) are normalised into one Postgres target, and (2) per-answer detail is projected forward into Response.data so nothing downstream needs a join against a table that may not exist by the time anyone reads it.

Why ResponseAnswer can vanish and reappear, and eventually vanish for good

ResponseAnswer and 7 sibling tables are staging tables: created on demand by migrator code (never by a Prisma migration — a build-time test, migration-folder-no-staging-drops.test.ts, fails the build if one ever tries), purged per-tenant when that tenant is finalized, and dropped for good, database-wide, only when the whole migration program is retired. That two-step lifecycle — and the incident that made it necessary — is its own section: 11b Program retirement & staging-table lifecycle.

text
CFMSurveyResponse (MSSQL)
        |  read (streamed, chunked)
        v
   transform  (legacy_id / legacy_guid / legacy_extras, the sole surviving invitation identity)
        |  COPY (TSV)
        v
   tmp_Response  (TEMP, ON COMMIT DROP)
        |  INSERT ... SELECT ... ON CONFLICT (legacy_id) DO NOTHING
        v
   Response  (PERMANENT)  +  _MigrationCheckpoint advance   -- one transaction --
        |
        v  Phase 4: ensureResponseAnswerTable() creates ResponseAnswer on demand (staging, not permanent)
   ResponseAnswer.legacy_extras  --backfill-survey-structure.ts-->  Response.data  (projection)

(e) The partitioned data plane — for tenants at 100M rows and above

Everything above describes the serial path, and it is still exactly what runs when no budget flag is given. A 200M-row tenant needs more, and the flags below turn it on. They are optional by design: the source is live during the window and other tenants share the target, so parallelism is something an operator enables with a measurement in hand, never something a run starts doing on its own.

Three separate controls, and the common mistake is treating them as one. They answer different questions and neither derives from the other:

  1. The plan — which rows, in which ranges. Sized toward --partition-target-rows (default 500,000) from sampled row density, not by dividing the id space: a legacy key space has gaps and clusters, so equal id widths hold wildly unequal row counts. Capped at 512 partitions per table.
  2. The pool — how many partitions run at once. --max-workers, default 1 (serial). It also bounds source connections, target connections and memory simultaneously.
  3. The governor — how hard to push, given what the databases are feeling. --max-source-load (default 8 concurrent requests) and --max-target-load (default 24 active backends + lock waiters). Throttling starts at 90% of the ceiling, so the ceiling is not reached rather than reacted to.

--max-workers 8 with a source ceiling of 2 is a coherent configuration: eight partitions ready to run, throttled to what the live source can take. Deriving one number from the other is the error.

Preflight refuses; it does not warn. migrate preflight projects the run against the agreed window at the standard configuration and against a published four-dimension infrastructure floor (target write throughput, source read throughput, network throughput, connection headroom). A dimension with no measurement is not a passing one. If fitting the window would need hand-tuning, the standard configuration has failed its own requirement — and the cheapest place to learn that is the command line, not hour six. An explicit override is available and is recorded with the projection it overrode, so an attempted window stays distinguishable afterwards from one that was projected to fit.

Catch-up no longer takes --since. The floor is the per-entity boundary the bulk load recorded in _MigrationBoundary — the row id it actually stopped at — UNIONed with everything changed after the recorded source clock. Both halves are needed: the id catches new rows, and the clock catches a row that committed late under a lower id, or was edited below the line. Neither an id cursor nor a wall-clock value closes that window alone, and a row it misses is skipped permanently while every row count still reconciles. --since survives only to widen the id half; a timestamp, or an id above the boundary, is refused.

One schema change, and it leaves with its table. The whole feature adds _MigrationCheckpoint.partition_key and nothing else — no new table, no new column on a table the product keeps. Retirement still reaches zero migration-owned objects, because the column lives on a table retirement already drops.

Operator detail: packages/migrator/docs/200m-data-plane-runbook.md (ramp procedure, abort criteria, resume, cutover) and 200m-data-plane-minimum-spec.md (the floor, and the temporary scale-up with its verified revert).

F9

Variant detection algorithm

The classifier the CLI runs at preflight. Source: src/source/variant-detector.ts:16-46.

The detector probes three schema markers in the source HiveCFMAppDB-* and HiveCFMSurveyDB-*. The combination uniquely identifies one of three variants. There is no override flag; an unknown combination aborts with exit code 3 (FR-016).

CFMTouchpoint tableLastModifiedDate columnCFMResponseKPICache tableVariantDelta strategy
presentpresentpresentStableRJBtimestamp
absent(any)absentISTServiceEdgeid
any other combinationCustomabort (exit 3)

If you ever see a Custom verdict for a client you believed to be one of the known variants, do not pass --allow-resume or force a run. The schema has drifted in a way the tool has not been validated against; escalate with the full preflight output. The same logic backs the interactive Decider above.

03 / 04 / 05Setup
01

Prerequisitesrequired

Confirm all of these before touching any client data.

For a customer migration, use the full on-site checklist in L0 Before you go on site (tmux, ssh -t, ≥80 columns, a built dist/, the base entry's real tier). The items below are the platform prerequisites.

MSSQL read-only access only

The migrator never writes to the source MSSQL databases. It only reads. Even so, use a read-only SQL login; never SA credentials.

01b

Known gotchas on a fresh envread first

Eight things that historically blocked first-time runs on a brand-new EC2/laptop. All fixed at source on AG-migration ≥ commit 3076a01e1 (both are ancestors of fix/noref-tui-run3-operator-defects @ 4d6f7fe8e, so a current checkout has them). If you are on that commit or newer, only items 1, 4, and 6 still require operator-side action (items 6 and 8 are also auto-handled since commit af4b48920).

First, make sure your branch has the fixes

Run git log --oneline AG-migration | head -10 and confirm you see these six commits. If any are missing, git pull origin AG-migration:

  • 3076a01e1 — fix(email): close NPS Column tag outside the map iteration
  • 5d2fa1059 — fix(db): add @default(cuid()) to 8 migrator lookup models
  • 4fa0fd258 — fix(migrator): VariantDetector recognizes ISTServiceEdgeOld
  • 7595aa93a — fix(license): re-sync dev keypair between activation script and embedded public key
  • 5b3a52fb0 — fix(auth): make signup resilient to license-signing failure
  • da681292c — fix(db): add 10 migrator model definitions to schema.prisma
  • 9b983fcd6 — fix(migrator): preserve real email + password on user upsert re-run (never overwrite with synthetic)
  • af4b48920 — fix(migrator): auto-activate dev licenses + auto-discover CLIENT_ENV after migrate run

Expected: all eight SHA prefixes appear in git log. If missing: the gotcha that commit fixes will re-bite you. Search hint: if you cannot pull (network/auth issue), git fetch origin AG-migration first; if the branch was rebased, git reset --hard origin/AG-migration (only on a clean working tree).

1. Workspace packages must be built before anything

Symptom: Module not found: Can't resolve '@hivecfm/cache' or similar, either at pnpm dev or during pnpm db:migrate:dev. Why: sibling workspace packages have main: "dist/index.js" but their dist/ doesn't exist until built. Fix:

pnpm install
pnpm -r --filter './packages/*' build

Expected: last line reads Done with no ERR_. Verify: ls packages/cache/dist/index.js packages/logger/dist/index.js both exist. If error ENOSPC: EBS volume is full — resize (see Prerequisites). Search hint: Module not found + the missing @hivecfm/<name> tells you which package's dist/ is missing.

2. db:migrate:dev wipes the migrations/ directory

Symptom: after running pnpm --filter @hivecfm/database db:migrate:dev the migrator-owned migrations are missing from packages/database/migrations/ and the migrator's columns don't exist on Response/Survey/User in Postgres. Why: the custom migration runner does rm -rf migrations/* at the start, then copies migrations from migration/ (singular) one at a time — but the migrator-owned migrations live ONLY in migrations/ (plural), so they get permanently wiped. Fix: after db:migrate:dev completes, restore + apply:

git restore packages/database/migrations/
pnpm --filter @hivecfm/database exec dotenv -e ../../.env -- prisma migrate deploy

Expected: All migrations have been successfully applied., except 20260515000004_add_pg_cron_mv_refresh, which fails with schema "cron" does not exist (see item 3). Verify: docker exec hivecfm-postgres psql -U postgres -d hivecfm -c "SELECT column_name FROM information_schema.columns WHERE table_name='Response' AND column_name IN ('legacy_id','legacy_guid','legacy_extras') ORDER BY 1;" returns 3 rows. Don't use a table-existence check here: Touchpoint, Invitation, Department, CustomerOrg, SurveyChannel, and LegacySurveyKind are no longer part of the schema at all (dropped 2026-08-20/24, removed from schema.prisma, see F8b New models), so a correct, fully-migrated database returns 0 rows for any of them; that's expected, not a failure.

3. pg_cron extension is not in the pgvector/pgvector:pg17 image

Symptom: migration 20260515000004_add_pg_cron_mv_refresh fails with ERROR: schema "cron" does not exist. Why: the docker image used for Postgres does not bundle pg_cron. Fix: the migration only schedules an automatic materialized-view refresh — non-essential. Mark it applied so Prisma stops re-trying:

pnpm --filter @hivecfm/database exec dotenv -e ../../.env -- prisma migrate resolve --rolled-back 20260515000004_add_pg_cron_mv_refresh
pnpm --filter @hivecfm/database exec dotenv -e ../../.env -- prisma migrate resolve --applied 20260515000004_add_pg_cron_mv_refresh

Expected: Migration 20260515000004_add_pg_cron_mv_refresh marked as applied. If you ever need pg_cron for real: switch the image to a Postgres distribution that bundles it (Citus image, or build a custom image).

4. Dev license activation — handled automatically by migrate run

Symptom (historical): after migration, a "License Required — No license found for this organization" wall appeared despite a successful migrate run. The app-level check (getEnterpriseLicense in apps/web/modules/ee/license-check/lib/license.ts) is hardcoded to return active: true on the current build — but the migrator also creates new orgs during Phase 2, and those orgs briefly had no tenant_license row until the manual script ran.

Current behavior (auto, commit af4b48920): at the end of every successful migrate run, the migrator calls activateDevLicenses() internally. It inserts a signed dev license (valid 2024–2030) for every Organization in the target DB via ON CONFLICT (organization_id) DO UPDATE — idempotent, safe to run multiple times. The "License Required" screen will not appear after a fresh migration.

# No-op on current build — migrate run handles this automatically.
# Run manually only if you are NOT using migrate run (e.g. bare Prisma seed):
node scripts/activate-dev-licenses.mjs

If the license wall still appears after migrate run: check the run output for License activation: N org(s) licensed (dev licenses, valid to 2030). — if that line is missing, run the script above manually. If you see License signature verification FAILED — license tampered in the app logs: pull af4b48920 or newer which re-paired the embedded keypair.

5. "No workspace found" after login — now auto-repaired

Symptom: login lands on "No workspace found / Please contact your administrator to get access to a workspace." Why this happened: the signup action made three Prisma calls in sequence (createUser → createOrganization → createMembership). If any step threw — e.g. sendVerificationEmail failed because SMTP wasn't configured — the action aborted, leaving a partial row in the DB. A retry showed an error because the email already existed; the user had an account with no org and no way to recover.

Current behavior (auto-repair, no manual action needed):

If you are already stuck in this state (user has account but no org): navigate to http://<host>:3000/setup/organization/no-workspace while logged in — the page auto-repairs and redirects to the dashboard. If on a pre-1fc406f build, INSERT the missing Membership row manually:

docker exec hivecfm-postgres psql -U postgres -d hivecfm -c \
  "INSERT INTO \"Membership\" (\"organizationId\", \"userId\", role, accepted)
   SELECT o.id, u.id, 'owner', true
   FROM \"Organization\" o, \"User\" u
   WHERE u.email = '<your-email>'
     AND NOT EXISTS (SELECT 1 FROM \"Membership\" WHERE \"userId\" = u.id);"

Expected: INSERT 0 1. Refresh browser → lands on dashboard.

6. CLIENT_ENV in migrator .env is a literal Environment.id — but auto-discovered if wrong

Symptom (if set incorrectly): migrator logs a WARN like CLIENT_ENV 'ist-staging' not found — auto-discovered environment 'cmq8j66490015oigeitht0m87', or Phase 2 fails with Foreign key constraint violated: Survey_environmentId_fkey on a very old commit. Why: the .env.example shows CLIENT_ENV=ist-serviceedge as if it were a label, but the correct value is the CUID primary key of the target Environment row.

Auto-discovery (commit af4b48920): at startup, migrate run validates CLIENT_ENV against the Environment table. If not found (e.g. after a DB reset where the CUID changed), it automatically uses the first production environment it finds — migration proceeds without operator action. A WARN line is emitted; set the correct id to silence it.

To set the correct id (recommended — silences the warning and makes intent explicit):

docker exec hivecfm-postgres psql -U postgres -d hivecfm -tAc \
  "SELECT id || ' [' || type || ']' FROM \"Environment\" WHERE \"projectId\" IN
     (SELECT id FROM \"Project\" WHERE name = '<your-project-name>');"

Expected: one or more lines like cmpjx0yug000boiezjj412h8x [production]. Copy the id (without the bracketed type) into packages/migrator/.env as CLIENT_ENV=<id>. Verify: migrate preflight --client=<id> shows Target empty (or --allow-resume set) ✓. If auto-discovery fired and you want to confirm it landed in the right env: check the migrated survey count — SELECT COUNT(*) FROM "Survey" WHERE "environmentId" = '<discovered-id>'.

7. Post-DB-reset sequence — correct order for a clean dev box

After prisma migrate reset (or a full Docker volume wipe), the DB is empty. The migrator needs at least one org and environment before it can write anything. Do these steps in order:

  1. Start the Hive web app — pnpm dev, or on EC2: sudo systemctl start hivecfm-web.
  2. Sign up once — open http://<host>:3000/auth/signup and create a new account. The app auto-creates an Organization and its default Project + Production/Development Environments. No need to run activate-dev-licenses.mjs — the license is hardcoded active on the current build (see gotcha 4 above). If SMTP isn't configured, the verification email fails silently (non-blocking since commit 5c41baf) — log in directly. Multi-department source: give the project a neutral name (not any CFMDepartment.Name), see 06. If this stack has a Hub and you need Hub-side tenant features, restart the hivecfm-core container after signup: an organization created by UI signup is only registered as a Hub tenant at container start. Phase 6 / hub-backfill does not need that registration (see 07a).
  3. Get the Environment id — optional since commit af4b48920: migrate run auto-discovers the production environment if CLIENT_ENV doesn't match. To silence the discovery WARN and be explicit, run the query in gotcha 6 above (or read the id from the Hive UI URL bar: /environments/<id>/surveys — an environment id, the production environment of your signup project, not an organization id) and paste it into packages/migrator/.env as CLIENT_ENV=<id>.
  4. Run preflight — node dist/cli.js preflight from packages/migrator/. All checks should be green.
  5. Run the migrator — node dist/cli.js run.

If signup shows an error and you end up on "No workspace found": stay logged in and navigate to http://<host>:3000/setup/organization/no-workspace — the page auto-repairs the missing org and redirects to the dashboard (commit 1fc406f). Then continue from step 3.

8. Re-running migrate run does not overwrite real email or password

Symptom (historical, commit older than 9b983fcd6): after a re-run, the admin user could no longer log in — their email had been replaced with a synthetic value like ahmed-genidy-1009@imported.local and their password reset to null. Why: the user upsert in Phase 2 (packages/migrator/src/pipeline/phase-2-entities.ts) used ON CONFLICT DO UPDATE with email and password in the update clause. A source row with no Email column (IST-old variant) triggered email synthesis, and the synthetic value overwrote the real credential on every re-run.

Current behavior (commit 9b983fcd6): email and password are excluded from the update: clause entirely. The first insert sets them; subsequent re-runs only update name, isActive, and touchpointId. A manually-set password (e.g. via bcrypt reset) survives re-migration cleanly.

Verify after re-run:

docker exec hivecfm-postgres psql -U postgres -d hivecfm -c \
  "SELECT email, password IS NOT NULL AS has_password FROM \"User\" WHERE email = '<admin-email>';"

Expected: email is the real address you signed up with, has_password is t. If email is synthetic (ends in @imported.local): you're on an older commit — pull 9b983fcd6 or newer and reset the email manually via psql or the Hive UI profile page. Search hint: look for @imported.local suffix in the User.email column.

01c

Channel & Contact mappingv0.6+

Starting with v0.6, the migrator populates the Hive Channel and Contact tabs directly from source data (23 channel names across 7 ChannelType buckets; 252,232 CFMCustomer rows). Two pieces sometimes need operator attention before the run completes cleanly.

Channel mapping — default + per-env override

The default map at packages/migrator/config/channel-mapping.json covers the 33 known channel names from the reference IST-old source. During migrate preflight, the migrator checks every distinct channel name found in CFMCustomerSurvey.ChannelID against the map and reports one of:

✓ channel_mapping_coverage: All 23 used channel names have an exact mapping
⚠ channel_mapping_coverage: 2 channel names rely on suffix fallback. Add to config/channel-mapping.<environmentId>.json to silence: New Channel, NEW CHANNEL 2
Suffix fallback means "best-guess only"

The fallback rules match keywords like whatsapp, voice, email, etc. in the raw name and assign the likeliest ChannelType. Names such as "New Channel" or "NEW CHANNEL 2" contain no keyword, so they fall through to type: "web" with a warn-once log entry. That assignment may be wrong for your data. Create an override file to lock in the correct type.

Fix (per-env override): create the file packages/migrator/config/channel-mapping.<environmentId>.json — substitute the actual environmentId value you use in .env as CLIENT_ENV (e.g. cmpjx0yug000boiezjj412h8x). Contents follow the same JSON schema as the default map:

{
  "New Channel":    { "type": "web",   "displayName": "New Channel" },
  "NEW CHANNEL 2":  { "type": "voice", "displayName": "New Channel 2 Voice" }
}

Expected: on re-run, migrate preflight reports ✓ channel_mapping_coverage: All N used channel names have an exact mapping with no suffix-fallback warning.

Verify (after the full run):

docker exec hivecfm-postgres psql -U postgres -d hivecfm -c \
  "SELECT type, COUNT(*) FROM \"Channel\" WHERE \"environmentId\" = '<environmentId>' GROUP BY type ORDER BY 2 DESC;"

Expected: rows for each of the 7 ChannelType buckets (email, sms, whatsapp, voice, mobile, web, link) with non-zero counts. Replace <environmentId> with the actual value from CLIENT_ENV in your .env file.

If error Cannot find module '…/config/channel-mapping…': confirm the override file is under packages/migrator/config/, not packages/migrator/src/config/. The module resolves relative to the compiled dist/ directory one level up from src/.

Search hint: the warn-once log line reads [channel] no mapping for "…", defaulting to web — grep the run log for [channel] to find all unmapped names in one shot.

Contact migration — dedup signal + row count check

Every CFMCustomer row becomes one Contact record with up to 14 attributes (name, email, phone, birthDate, gender, etc.). Phase 2 streams all rows in configurable chunks (default 5 000 rows/chunk). The preflight dedup signal line shows the raw volume and signals whether email/phone collisions might cause issues:

ℹ customer_dedup_signal: CFMCustomer: 252,232 rows · Distinct emails=187,401 · Distinct phones=192,008

The numbers above come from the reference live source and are the baseline to verify against. Your source may differ; the key thing is the count is non-zero and plausible relative to the source system's known customer base.

How dedup works

Contacts are keyed by (environmentId, legacyId) — the CFMCustomer.ID primary key — so a re-run is safe (duplicates are skipped via skipDuplicates: true). Email and phone collisions within the source are kept as-is because the original system stored them that way; they do not block the migration.

If the preflight row count looks wrong (e.g. shows 0): the migrator queries SELECT COUNT(*) FROM CFMCustomer on the source. Verify directly:

sqlcmd -S <MSSQL_HOST> -U <MSSQL_USER> -P <MSSQL_PASSWORD> -d <SURVEY_DB> \
  -Q "SELECT COUNT(*) FROM CFMCustomer"

Expected: a positive integer matching what the migrator logs. If 0: either the table is empty in this environment, or the migrator login lacks SELECT on CFMCustomer — grant it: GRANT SELECT ON CFMCustomer TO <login>.

Verify (after the full run):

docker exec hivecfm-postgres psql -U postgres -d hivecfm -c \
  "SELECT COUNT(*) FROM \"Contact\" WHERE \"environmentId\" = '<environmentId>';"

Expected: the count matches the source CFMCustomer row total. Open the Hive UI → Contact tab; real customer names and emails should appear. If the count is lower: check the run log for skipDuplicates info — a prior partial run may have left stale rows; run migrate rollback --client <environmentId> to clear the env and re-run from scratch.

Search hint: Phase 2 progress logs print progress: N/252232 every 50 000 rows — if the run hangs, grep for the last progress line to see how far it got.

Contact UI parity (2026-05-26)

The Contacts list now defaults to Name · CIC · Phone · Email · Language columns, matching old HiveCFMRJB. To bring back First Name / Last Name / User ID columns, click the table's settings icon (top right) and toggle them on. Search now ranks by match quality — typing Marwa shows Marwa Ashour first instead of Sultan Al Marwan.

01d

Audiences & Segmentsv0.8+

Starting with v0.8, migrate run includes a new Phase 2.6 (Audiences) that converts 92 legacy CFMCustomerList records and ~10 in-use CFMSegmentCode values into native Hive Segment objects, materializes list-membership as ContactAttribute flags, and translates CFMSurveyCustomersFilter rows into per-survey segment filters. This section covers every audience-related command.

SMS/phone sending is out of scope

Only ~102 of 252 000 migrated contacts carry an email address; the remaining contacts are phone-only. Audience targeting (segment picker in campaigns and surveys) works for all contacts, but sending via SMS or phone requires a separate SMS-provider integration project and is not handled by this migration.

1. Full run — audiences included by default

Phase 2.6 runs automatically as part of migrate run. No extra flag is required. Use --skip-audiences only if you want to defer audience migration to a later run.

1

Run the full migration (includes audiences)

Standard full migration. Phase 2.6 runs between Phase 2 (Entities) and Phase 3 (Transactional).

bash · packages/migrator
$$M run --client=<environmentId>
ExpectedPhase 2.6 log lines: CustomerList: 92 lists · Segments: 92 customer-list segments · Segments: ~10 CRM-code segments · Membership: inserted ~2807767 list attributes (orphans N skipped)
VerifyIn the Hive app, open any survey or campaign → click the segment picker → the 92 customer-list segments and the CRM-code segments should appear in the list. Then open any contact → its Responses tab should show historical response entries.
If column "legacy_kind" does not existThe transient tracking columns were dropped by a prior finalize-audiences call. Re-run $M run; Phase 2.6 re-adds the columns automatically via ADD COLUMN IF NOT EXISTS before inserting any data.

2. Re-run only audiences

If you need to re-migrate only the audience/segment layer without touching other phases (e.g., after a partial failure or a source-data correction), use the standalone audiences command.

2

Dry-run audiences (no writes)

Validates source data and prints a plan. Safe to run at any time.

bash · packages/migrator
$$M audiences --client=<environmentId>
ExpectedDry-run output: lists source counts (CFMCustomerList: 92, CFMSegmentCode: N in-use, CFMCustomerListBrg: ~2807767) and the plan, but writes nothing. Exit code 0.
VerifySegment and ContactAttribute counts in the target DB remain unchanged after this call.
If error ECONNREFUSEDCheck your .env: TARGET_PG_HOST, TARGET_PG_PORT, and CLIENT_ENV must be set correctly.
3

Apply audiences (write)

Runs Phase 2.6 in isolation — idempotent, safe to re-run.

bash · packages/migrator
$$M audiences --client=<environmentId> --apply
ExpectedSame log lines as step 1: Segments: 92 customer-list segments, Segments: ~10 CRM-code segments, Membership: inserted ~2807767 list attributes (orphans N skipped). Exit code 0.
VerifyQuery Hive DB: SELECT COUNT(*) FROM "Segment" WHERE "environmentId" = '<environmentId>'; — should show 100+ rows. Open the segment picker in a survey; migrated audiences appear.
If duplicate key value violates unique constraintA prior partial run left some segments. --apply is idempotent — the upsert uses @@unique([environmentId, title]) and ON CONFLICT DO NOTHING for memberships. Re-run safely; the duplicate will be silently skipped.
If column "legacy_kind" does not existfinalize-audiences was called before this run. Phase 2.6 adds the columns automatically; re-run this command.

3. Per-contact response history report

4

Generate contact-history report

Produces a CSV + HTML report showing each contact's response history. Useful for QA and for client hand-off evidence.

bash · packages/migrator
$$M report contact-history --client=<environmentId>
ExpectedTwo files written: ./reports/contact-history-<environmentId>-<timestamp>.csv and ./reports/contact-history-<environmentId>-<timestamp>.html. Log prints: Report written: N contacts, M responses.
VerifyOpen the CSV in a spreadsheet or text editor. Columns include contactId, email, responseCount, lastResponseAt. Rows with responseCount > 0 confirm that Response.contactId backfill is working. The HTML report renders the same data in a browser-friendly table.
If report is empty (0 contacts)Either contacts have not been migrated yet (run Phase 2 first via migrate run), or Response.contactId was not backfilled (Phase 3 must also be complete). Check _MigrationCheckpoint to confirm completed_at is set for both Contact and Response.

4. Finalize — drop tracking columns (run once at project end)

The transient legacy_id and legacy_kind columns on Segment persist across runs and rollbacks during the migration project (keep-by-default policy). Drop them only when you are certain the project is finished and you will not need to roll back.

Run AFTER any rollbacks you might need

Once the tracking columns are dropped, rollback --audiences can no longer identify audience-created segments by legacy_kind. Run finalize only after you are sure no audience rollback will be needed.

5

Finalize audiences (drop tracking columns)

One-shot cleanup at the very end of the migration project.

bash · packages/migrator
$$M finalize-audiences --client=<environmentId> --drop-tracking
ExpectedLog: Dropped columns legacy_id, legacy_kind from "Segment". Exit code 0.
VerifyConnect to the target PG and run: \d "Segment" — the legacy_id and legacy_kind columns must no longer appear in the output.
NoteThe segments themselves remain intact — only the two tracking columns are removed. This is a non-destructive DDL operation on the Segment table.
If column "legacy_id" does not existThe columns were already dropped (either by a prior finalize call or by migrate run --drop-tracking). This is safe to ignore — the final state is already correct.

5. Rollback audiences

Removes only audience-related data: Segment rows where legacy_kind is customer_list or segment_code, all ContactAttribute rows with keys matching the list_ prefix, and the crmSegmentCode/crmSegmentName attribute key rows. Contacts and Responses are left untouched.

list_ prefix namespace caveat

Rollback identifies audience-owned ContactAttribute keys by the list_ prefix. If you ever introduce a non-audience attribute key whose name begins with list_, it would be swept by rollback. As of v0.8 no such key exists — the only list_* keys are the ones created by Phase 2.6.

6

Roll back audience data only

Removes segments + membership attributes. Leaves contacts, responses, and channels intact.

bash · packages/migrator
$$M rollback --client=<environmentId> --audiences
ExpectedLog: Rolled back: N customer-list segments, M CRM-code segments, K list_* attributes deleted. The legacy_id/legacy_kind columns are left in place (they are dropped only by finalize-audiences).
VerifyQuery: SELECT COUNT(*) FROM "Segment" WHERE "environmentId" = '<environmentId>'; should drop to 0 (or match any non-audience segments that existed before the migration). Open the Hive segment picker — no migrated audiences should appear.
If "legacy_kind" does not existThe tracking columns were already dropped by finalize-audiences --drop-tracking. Rollback cannot identify audience segments by legacy_kind. If you still need to remove audience data manually, delete segments by title pattern (e.g., WHERE title LIKE 'List: %' OR title LIKE 'CRM: %') and delete ContactAttribute rows via the list_-prefixed key join.
02

Install & Builddeveloper · online only

Eight commands, one per card. Run each in order, copy its own button, wait for the expected output before moving on.

Not for an offline customer site

This section builds the migrator from source. It needs the network (git fetch, pnpm install, npm install -g pnpm) and is written for a developer workstation (Windows + WSL paths). At an offline customer site, do not follow it: bring a prebuilt migrator and check it as in L0, Bring the migrator to an offline box.

Windows 10 users · use WSL Ubuntu, not PowerShell

All pnpm and node commands run inside WSL Ubuntu. Open it by typing wsl in PowerShell, or use Windows Terminal → Ubuntu tab. Your Windows drives are mounted at /mnt/c/, /mnt/f/, etc.

1

Open WSL Ubuntu (Windows only)

Skip this step on macOS or Linux. From PowerShell, drop into your WSL shell.

powershell · Windows host
PS>wsl
ExpectedPrompt changes to user@host:/mnt/c/…$
If it failsRun wsl --install -d Ubuntu first, reboot, then retry.
2

Enter the repository

Adjust the path to wherever you cloned. The example assumes F:\ISt\HiveFormbricks\hivecfm-core on Windows.

bash · WSL
$cd /mnt/f/ISt/HiveFormbricks/hivecfm-core
ExpectedNo output, prompt now ends with hivecfm-core$
VerifyRun ls package.json, should print the file name.
3

Switch to the migrator branch

Default clones land on main, which doesn't have the migrator yet. You need AG-migration — the single migrator branch on the remote as of 2026-09-10. Skip this step if you already see it in git branch --show-current.

bash · WSL
$git fetch origin && git checkout AG-migration && git pull origin AG-migration
Expected"Switched to a new branch 'AG-migration'" + "Already up to date."
VerifyRun test -f packages/migrator/package.json && echo present, must print present. (Older guide versions checked grep -c '^model Touchpoint' schema.prisma — that model was removed from the schema on 2026-08-24 along with the live table; it's gone on this branch too now, so it's no longer a valid marker. See F8b New models.)
WhyThe migrator package (packages/migrator) and its CLI only exist on this branch.
4

Install workspace dependencies

Run from the repo root. pnpm picks up every workspace under packages/ and apps/.

bash · hivecfm-core/
$pnpm install
Expected"Progress: resolved … reused … downloaded …" then "Done in …s", ~60s first run, ~5s thereafter.
If it failscommand not found: pnpm → run sudo npm install -g pnpm@9, open a new WSL tab.
If EPERMEPERM: operation not permitted, futime. WSL2 can't pass futime through DrvFs. The repo is on a Windows mount (/mnt/f/...). Move it to the WSL ext4 home filesystem and reinstall there: rsync -a --exclude=node_modules --exclude=.next --exclude=dist /mnt/f/path/to/hivecfm-core/ ~/hivecfm-core/ && cd ~/hivecfm-core && pnpm install. Native ext4 is also ~10× faster.
5

Generate the Prisma client

Reads packages/database/schema.prisma and writes typed accessors to node_modules/.prisma/client. The migrator's TypeScript depends on these types.

bash · hivecfm-core/
$pnpm --filter @hivecfm/database generate
Expected✓ Generated Prisma Client (v6.x) to ./../../node_modules/@prisma/client
VerifyRun ls node_modules/.prisma/client/index.d.ts, it must print the file. (Older versions of this guide grepped that file for touchpoint:. That model is gone from the schema, so the count is 0 on a correct build.)
6

Export DATABASE_URL for this shell

Prisma's db:migrate:deploy needs to know where Postgres lives. Without this, the next step silently no-ops.

bash · WSL
$export DATABASE_URL="postgresql://postgres:postgres@localhost:5432/hivecfm"
ExpectedNo output. The variable is now set for this shell only.
VerifyConfirm it points at THIS client's DB before any schema write: psql "$DATABASE_URL" -c '\conninfo' → the database / host / port must be exactly this client's target. The next step writes the schema; a wrong URL changes whatever database it hits.
PortNever assume 5432. A colleague's stack on the same box may already own it — check docker compose … ps / your host-ports override for the real port (rehearsal stacks landed on 5442, 5415, …) and put that in the URL. Defaulting to 5432 once nearly sent 1.8M rows into the wrong database. A second stack on the same box needs more than a new port: the base compose file fixes container_name, network and volume names, and -p ignores all three. Use an override with a top-level name:, a container_name for every service, network and volume name:s, and ports: !override bound to 127.0.0.1 (compose v2.24+). Without it the second project silently shares the first one's containers and volumes.
PersistTo survive shell restarts, add the line to ~/.bashrc.
7

Build the database package, then apply the schema — db:migrate:deploy, then check it

The migration runner is a compiled Node script (dist/scripts/apply-migrations.js), so the database package must be built before the deploy script can find it. It replays every Prisma migration (idempotent, safe to re-run). The Verify below is the authority for this step, not the command itself — run it every time, on every checkout.

On this build the migrator's provenance columns (legacy_id / legacy_guid / legacy_extras on Response, Survey, Contact, User) and its staging tables are not part of the product schema. They are migration-owned: migration 20260925120000_hand_provenance_columns_to_migrator drops unused ones on a fresh database, open-program creates the lease, the first run creates the columns and tables under it, and retire removes them. So a correct schema has none of them before the migration starts. Older versions of this guide checked for Response.legacy_id / touchpoint_id and fell back to db:push; both are wrong on this build.

bash · hivecfm-core/
$pnpm --filter @hivecfm/database build
$pnpm --filter @hivecfm/database db:migrate:deploy
# then run the Verify below. Never db:push a database that holds, or will hold, a migration.
Expecteddeploy: "X migrations found … All migrations have been successfully applied."
If "no script""None of the selected packages has a migrate:deploy script", you dropped the db: prefix. The script is db:migrate:deploy, namespaced under db: like every other database script.
If silentNo output = DATABASE_URL not exported (re-do step 6) or Docker postgres not running (run docker compose -f docker-compose.yml -f docker-compose.host-ports.yml up -d).
If P1001"Can't reach database server at localhost:5432". Docker isn't exposing the port. Use the docker-compose.host-ports.yml override.
If "pull access denied for minio/mc"Docker Hub no longer serves minio/minio or minio/mc, so docker compose up stops before it creates any container, Postgres included. Point the minio and minio-init services at quay.io/minio/minio:latest and quay.io/minio/mc:latest in a compose override. See Troubleshooting “pull access denied for minio/mc”.
If P3018"schema 'cron' does not exist", migration 20260515000004_add_pg_cron_mv_refresh calls cron.schedule(...), but the stock pgvector/pgvector:pg17 image doesn't ship pg_cron. For local/dev, mark it applied and continue (KPI MVs are queryable, just no auto-refresh): pnpm --filter @hivecfm/database exec prisma migrate resolve --applied 20260515000004_add_pg_cron_mv_refresh && pnpm --filter @hivecfm/database exec prisma migrate deploy. For production parity, install pg_cron inside the container, see the troubleshooting card below.
VerifyRun it every time: psql "$DATABASE_URL" -c "SELECT migration_name FROM _prisma_migrations WHERE migration_name LIKE '20260925120000%' AND finished_at IS NOT NULL;" must return 1 row (20260925120000_hand_provenance_columns_to_migrator). 0 rows: the deploy did not reach this build's migrations; re-check DATABASE_URL (step 6) and run the deploy again. Do not use db:push to make up for it.
Migration objectsWhat "good" looks like for the lease, psql "$DATABASE_URL" -c "SELECT to_regclass('public._migrator_program_lease');": empty on a fresh database; _migrator_program_lease from open-program (L3) until retire; empty again after retire (L8). _MigrationCheckpoint and the legacy_* columns follow the same rule, created by the first run. $M census --config <base.env> (read-only, takes no lease) lists every migration-owned object it finds: none before open-program and none after retire.
If P2022"The column … does not exist" means the migrator and the product schema come from different builds, or the schema went to a different database than DATABASE_URL points at. Do not db:push (it runs --accept-data-loss and can drop migration-owned objects). Stop and get matching builds.
8

Typecheck, then build the migrator CLI

Typecheck first, if types are clean, the migrator's runtime contract matches the Prisma client. Then build, which produces dist/cli.js. Without the build dist/cli.js does not exist, so every $M … command in this guide fails ($M is node --import tsx dist/cli.js; it never uses the migrate bin).

bash · hivecfm-core/
$pnpm --filter @hivecfm/migrator typecheck
$pnpm --filter @hivecfm/migrator build
ExpectedTypecheck silent (exit 0). Build prints "CLI Build start" → "CLI ⚡️ Build success in <Xms>" and writes packages/migrator/dist/cli.js.
VerifyRun ls packages/migrator/dist/cli.js, the file must exist. Then, from packages/migrator, node --import tsx dist/cli.js --help should print the CLI's command list (lifecycle and reset-client included).
If "legacyId does not exist"You're on the wrong branch or the Prisma client is stale. Re-do steps 3 + 5.
If "no script: migrate""None of the selected packages has a migrate script", you used pnpm --filter @hivecfm/migrator migrate …. migrate is a bin, not a script. Do not use pnpm for it. From packages/migrator run $M preflight …, where M="node --import tsx dist/cli.js" (see 02).
How to invoke the migrator CLI

The migrator is a built bin, not a pnpm script. After a one-time cd packages/migrator && pnpm build (produces dist/cli.js), invoke it from inside the package as node --import tsx dist/cli.js <cmd> (reads .env from the current folder), or from repo root as node --import tsx packages/migrator/dist/cli.js <cmd>. --import tsx is required: the build keeps @hivecfm/database external (TypeScript-only), so plain node dist/cli.js dies with ERR_UNKNOWN_FILE_EXTENSION (".ts"). The shorter node dist/cli.js … blocks in this guide need export NODE_OPTIONS=--import=tsx in the shell first; run-all-departments requires that form (see 06), because its child processes inherit the environment but not --import. You do not need both. pnpm --filter @hivecfm/migrator migrate does not work, migrate is a bin, not a script.

03

Configure .envrequired

One config file per client. Five short steps. Each card below has its own copy button.

Multi-department clients: this is the base config

For the lifecycle this file is the client's base config (<base.env>). Provision copies it into one .env.<base id>-<dept>-<name> per department and never overwrites an existing file. So put everything the departments need here before provision, including HIVECFM_HUB_URL and HIVECFM_HUB_API_KEY when the customer uses the Hub. Anything added after provision must be added to each department file too. chmod 600 the base file and every generated file: they hold the source and target passwords. Invoke every command as $M = node --import tsx dist/cli.js from packages/migrator (L0).

1

Find the target Environment ID

The migrator writes into an existing Environment row. Sign up + create an org in the app first (browser at http://<host>:3000/auth/signup), then run the query below. Note: every signup creates two environments per project, one development and one production. Almost always pick the production row for a real client migration. If the source has more than one department, give the project a neutral name at signup, one that is not any legacy CFMDepartment.Name (e.g. <Client> migration anchor): provision-departments renames it to the first (lowest-id) department it provisions, and refuses if the name belongs to another department.

bash · hivecfm-core/
$psql "host=<TARGET_PG_HOST> port=<TARGET_PG_PORT> dbname=<TARGET_PG_DATABASE> user=<TARGET_PG_USER> sslmode=require" -c 'SELECT e.id AS env_id, e.type AS env_type, p.name AS project, o.name AS organization, e.created_at FROM "Environment" e JOIN "Project" p ON p.id = e."projectId" JOIN "Organization" o ON o.id = p."organizationId" ORDER BY e.created_at;'
ConnectFill in the target's host, port, database and user (card B below); psql asks for the password. Use sslmode=disable when TARGET_PG_SSL is false. On a developer's local Docker stack the same query runs as docker compose exec postgres psql -U postgres -d hivecfm -c '…'.
ExpectedA table with two rows per org: one env_type=development, one env_type=production. Each env_id is a 25-char cuid (e.g. cmpecd9hb000bqs01s7li9z68). Copy the production id.
VerifyThe organization column should show the name you typed at signup. If it says HiveCFM or any name you don't recognize, you're looking at a seed-data org, not your real account.
If "column name does not exist"You ran the legacy SELECT id, name FROM "Environment" form. Environment has no name column, names live on Organization. Use the joined query above. The same applies to camelCase column names: created_at is snake_case in the DB despite being createdAt in Prisma.
If emptyNo rows means signup hasn't happened yet (or TRUNCATE CASCADE wiped the chain). Open http://<host>:3000/auth/signup, create an account + org, then re-run. Note: the License-Required screen blocks UI access, run node scripts/activate-dev-licenses.mjs from the repo root after signup, then refresh.
If multiple orgsIf the query returns rows for multiple organizations, pick the production env whose organization column matches the org you typed during YOUR signup. Cross-check membership: SELECT u.email, o.name FROM "User" u JOIN "Membership" m ON m."userId"=u.id JOIN "Organization" o ON o.id=m."organizationId";, your email should appear next to the org name.
2

Copy the .env template

One file per client. Name it after the client so you can keep multiple side-by-side.

bash · hivecfm-core/
$cp packages/migrator/.env.example packages/migrator/.env.ist-serviceedge
ExpectedNo output. ls packages/migrator/.env* now lists the new file.
Why namedPass it later with --config=packages/migrator/.env.ist-serviceedge. Use .env.stable-rjb, .env.acme-corp, etc. for other clients.
3

Open the file and fill in every value

Use nano (simplest), code (VS Code), or any editor. Five groups of variables; reference cards are below.

bash · hivecfm-core/
$nano packages/migrator/.env.ist-serviceedge
Save in nanoCtrl+O, Enter, then Ctrl+X.
VS CodeReplace nano with code if you have the WSL extension installed.

.env variable groups · paste into the file above

Editing .env values without opening an editor

To change a single variable in place, no nano, no vim, use sed -i with an anchored pattern. The ^ anchors to start-of-line so you can never accidentally edit a different variable:

bash · hivecfm-core/
# Pattern: replace one variable value, leave the rest of the file untouched
sed -i 's/^CLIENT_ENV=.*/CLIENT_ENV=<new-cuid>/' packages/migrator/.env.ist-serviceedge
# Verify the change before re-running anything
grep CLIENT_ENV packages/migrator/.env.ist-serviceedge

Works for any .env variable, just swap the name on both sides of the pattern: sed -i 's/^TARGET_PG_PORT=.*/TARGET_PG_PORT=5432/' <file>. If the variable doesn't exist yet (vs. updating an existing one), sed silently no-ops, confirm with grep and append the line with echo '<KEY>=<val>' >> <file> if missing.

A · Source MSSQL (read-only)
SOURCE_MSSQL_HOST=<source host or IP>
SOURCE_MSSQL_PORT=1433
SOURCE_MSSQL_USER=<readonly-sql-login>
SOURCE_MSSQL_PASSWORD=<password>
SOURCE_APP_DB=<source app database, e.g. HiveCFMAppDB-<Client>>
SOURCE_SURVEY_DB=<source survey database, e.g. HiveCFMSurveyDB-<Client>>
SOURCE_MSSQL_ENCRYPT=true # optional — omit unless server requires explicit encrypt=false
SOURCE_MSSQL_TRUST_CERT=false # secure default. Set =true only for self-signed-cert dev boxes (never in production).
B · Target PostgreSQL (the customer's product database)
TARGET_PG_HOST=<target host> # a developer's local Docker stack: localhost
TARGET_PG_PORT=5432 # local dev stacks often map to 5415; check docker compose port postgres 5432
TARGET_PG_DATABASE=<target database> # local Docker stack: hivecfm
TARGET_PG_USER=<target user> # local Docker stack: postgres
TARGET_PG_PASSWORD=<password>
TARGET_PG_SSL=<true | no-verify | false>

TARGET_PG_SSL: true (also 1, require, verify) = TLS with the server certificate verified; no-verify (or insecure) = TLS without verifying the certificate; false (also 0, disable) = no TLS. Not set = no TLS, unless PGSSLMODE is set in the shell. Ask the customer's DBA which one the server needs; a managed cloud database needs true. Get the host, port, database, user and password from the same person.

C · Client identity (paste id from step 1)
CLIENT_ENV=<paste-environment-cuid-here> # 25-char cuid like cmpa6qyqp0008p301k7mdo311. NOT a slug like ist-serviceedge

The rule: pick the env id your operator account can actually log into. Two valid setups exist:

  • Real client install (production target): you signed up through the UI and got a fresh cuid like cmpa6qyqp0008p301k7mdo311, use that. Do NOT paste clseedenvprod000000000, clseedenvdev000000000, or any clseed* id; those are dev-seed envs that no real signup user belongs to. Rows would land in a phantom environment.
  • Local/EC2 dev validation: you're logged in as the seed admin (created by pnpm db:seed / activate-dev-licenses.mjs). In that case the seed env clseedenvprod000000000 is the right target, that's where your seed admin has membership.

If you're not sure which case applies, run this query and pick the env whose project's "organizationId" matches an org your logged-in user is a member of: SELECT u.email, e.id AS env_id, o.name AS org FROM "User" u JOIN "Membership" m ON m."userId"=u.id JOIN "Organization" o ON o.id=m."organizationId" JOIN "Project" p ON p."organizationId"=o.id JOIN "Environment" e ON e."projectId"=p.id ORDER BY u.email; Naming clarification: --client takes the same Environment.id cuid as CLIENT_ENV (the id in /environments/<id>/surveys), not a slug and not an organization id. You may omit --client only on run, parity, delta and rollback, which fall back to the config's CLIENT_ENV; preflight, hub-backfill, audiences, consolidate-languages and finalize-consolidation check the client before the config is read, so they need --client or an exported CLIENT_ENV.

E · Hub (optional; put it here before provision)
HIVECFM_HUB_URL=<hub url>
HIVECFM_HUB_API_KEY=<hub api key>

Both or neither. Leave both out when the customer has no Hub: hub-backfill is then skipped, not failed (L6). The URL is the Hub API address this box can reach; the key is issued by whoever deployed the customer's Hub (it is the Hub's API key; ask them, it is not in the product UI). Provision copies this file into every department .env and never overwrites an existing one, so a Hub added after provision must be added to each department file too (L0).

D · Superset (optional) v0.2
SUPERSET_BASE_URL=https://analytics.hivecfm.com
SUPERSET_USERNAME=<admin-user>
SUPERSET_PASSWORD=<password>
3b

Verify the .env file actually contains what you typed

Before testing connectivity, print the file and visually confirm every value. Old templates of .env.example shipped with wrong defaults (port 5433, db hivecfm_ist_serviceedge, user hivecfm) that don't match the canonical Docker stack. If you copied an older template, preflight will fail with "ping returned false" without telling you which field is wrong.

bash · hivecfm-core/
$cat packages/migrator/.env.ist-serviceedge
Required values TARGET_PG_* and TARGET_PG_SSL: exactly what the customer's DBA gave you (a developer's local Docker stack: localhost, 5432 or 5415, hivecfm, postgres / postgres) · CLIENT_ENV=<25-char cuid> (e.g. cmpecd9hb000bqs01s7li9z68, NOT a slug)
If a value is wrongFix it in place without opening an editor, see the "Editing .env values without opening an editor" admonition above. Example: sed -i 's/^TARGET_PG_PORT=.*/TARGET_PG_PORT=5432/' packages/migrator/.env.ist-serviceedge, then grep TARGET_PG_PORT packages/migrator/.env.ist-serviceedge to confirm.
Sanity test, does PG actually accept this combination?Run a one-line ping against your exact values: PGPASSWORD=$(grep ^TARGET_PG_PASSWORD packages/migrator/.env.ist-serviceedge | cut -d= -f2) psql "host=$(grep ^TARGET_PG_HOST packages/migrator/.env.ist-serviceedge | cut -d= -f2) port=$(grep ^TARGET_PG_PORT packages/migrator/.env.ist-serviceedge | cut -d= -f2) dbname=$(grep ^TARGET_PG_DATABASE packages/migrator/.env.ist-serviceedge | cut -d= -f2) user=$(grep ^TARGET_PG_USER packages/migrator/.env.ist-serviceedge | cut -d= -f2)" -c 'SELECT 1' (when TARGET_PG_SSL is true, add sslmode=require inside the quotes). If it returns 1, your four PG values are right. If it errors, the error message names the wrong field directly (e.g. "database ... does not exist").
4

Validate the config with preflight

Preflight is fully read-only and surfaces every connection or permission issue in under 30 seconds. If this passes, every command in this guide will work.

bash · packages/migrator/
$cd packages/migrator && node --import tsx dist/cli.js preflight --client=<env-id> --config=.env.ist-serviceedge
Expected"Preflight passed. Ready to migrate."
If MSSQL failsVPN/firewall blocking 1433. Test directly: nc -zv $SOURCE_MSSQL_HOST 1433.
If PG "ping returned false"One or more of the four TARGET_PG_* values doesn't match your running container. The preflight check is a generic "can pg.connect succeed?", it can't tell you which field is wrong. Run the Sanity test command from Step 3b above; its error message will name the bad field. Common gotchas: (a) Port mismatch, canonical stack is 5432; only the laptop's docker-compose.host-ports.yml override maps to 5415. Confirm with docker compose port postgres 5432. (b) Wrong DB name, the container creates one DB named hivecfm; per-client schema is partitioned by environmentId, not by separate databases. (c) Wrong user, only postgres exists by default; no hivecfm role unless you created it. (d) Container stopped, docker compose up -d postgres.
If env missing"Environment ID not found", your CLIENT_ENV doesn't match any row. Re-run step 1 query, copy the exact id.
Multiple clients

Repeat steps 2-4 with a new file per client: .env.stable-rjb, .env.acme-corp. The tool never reads a global .env by default, you must pass --config or export the variables yourself.

5

Make every command env-portable

Stop relying on export DATABASE_URL=..., it dies with each shell. Use a file Prisma auto-loads, and switch files per environment with dotenv-cli. One file per target (local, staging, prod, per-client).

bash · workspace root
# 1. Create packages/database/.env for your default (local) target
printf 'DATABASE_URL=postgresql://postgres:postgres@localhost:5415/hivecfm\n' > packages/database/.env
 
# 2. Install dotenv-cli once for picking a different file on demand
pnpm add -Dw dotenv-cli
 
# 3. Keep one file per environment (gitignored)
ls packages/database/.env*
# .env → local (5415)
# .env.staging → staging host
# .env.acme → on-prem client

Now any Prisma command runs against any environment by pointing at the matching file:

bash · workspace root
# Local (no flag. Prisma auto-loads packages/database/.env)
pnpm --filter @hivecfm/database exec prisma migrate deploy
 
# Any other env, wrap with dotenv-cli
pnpm dlx dotenv-cli -e packages/database/.env.staging -- \
  pnpm --filter @hivecfm/database exec prisma migrate deploy
Why filesSurvives shell restart, version-controllable as .env.name.example, easy to diff between environments, no risk of running a staging command in a forgotten dev terminal.
gitignoreMake sure packages/**/.env and packages/**/.env.* are in .gitignore (the workspace root one already covers this). Commit only the .env.example templates.
Migrator runsThe migrator CLI has its own equivalent: --config=packages/migrator/.env.<client>. Use that for preflight, run, delta, parity, rollback.
DDL vs runtimeSome packages honor MIGRATE_DATABASE_URL first, falling back to DATABASE_URL. Use this when you want migrations to run as a privileged role but the app to connect as a low-priv role. Put both in the same .env.
03b

Provision departmentsadvanced · the lifecycle runs this for you

Skip this whole section if the source tenant is a single department: go straight to Run with the TUI or 04 Preflight with no --department flag, and every later step below still applies unchanged. This section only matters when one legacy MSSQL source (one CFMDepartment table with more than one row) needs to land as more than one HiveCFM tenant: one Environment per department, each migrated and finalized independently.

Manual step: confirm this command exists in your build first

TUI equivalent: Lifecycle [d] + the provision stage (L3), which passes --tier <base entry tier> and --id-prefix <base entry id> itself. Use this section only to provision by hand. provision-departments and department-scoping (--department) are on fix/noref-tui-run3-operator-defects @ 4d6f7fe8e. What still needs checking is the build on the box you are on, which is a separate artifact from the branch — a stale packages/migrator/dist/ is the usual cause of "command not found" here. Run node --import tsx dist/cli.js provision-departments --help before relying on anything below; if commander doesn't recognize the command, rebuild (pnpm --filter @hivecfm/migrator build) rather than assuming the feature is missing.

The only migrator command that creates tenancy

migrate provision-departments is deliberately separate from migrate run, which refuses to write into an Environment that doesn't already exist. That refusal is what stops a mistyped --client from silently manufacturing a new tenant mid-run. Creating the Project + Environment is a distinct, one-time, up-front decision, made by a human reading this command's dry-run output, not an automatic side effect of running a migration.

What it does: for each legacy department, create-or-reuse one Project with its own Environment, and print the department→CLIENT_ENV map you'll need for every later step.

bash
$node --import tsx dist/cli.js provision-departments --client <anchor-env-id> --config .env.<client>-base --write-config --dry-run # preview first
$node --import tsx dist/cli.js provision-departments --client <anchor-env-id> --config .env.<client>-base --write-config
FlagDescriptionDefault
--clientREQTarget anchor Environment.id (25-char cuid): the production environment of the signup project, i.e. the id in the Hive UI URL /environments/<id>/surveys. It is an environment id, not an organization id. The organization is derived from it, and the first (lowest-id) department provisioned reuses (and renames) its project (see 06).CLIENT_ENV
--dry-runoptReport what would be created without writingfalse
--departmentsoptComma-separated legacy department ids to provision. Use to exclude an empty department (0 surveys and 0 customer_surveys, e.g. an intermediate node in a flattened ParentID hierarchy with no surveys of its own) from getting its own Environment. A department with a customer_surveys count of 0 fails Phase 3 (boundary 0) and stops run-all-departments, but exclude it only if its surveys count is 0 too: leaving out a department that has surveys drops its survey definitions. Report surveys > 0 with 0 customer surveys to the migration owner as a blocker; see 06 for the count query.every department the source reports
--configoptBase .env (source + target credentials, CLIENT_ENV). Generated department files copy it.$ENV_FILE, else ./.env
--write-configoptWrite one .env.<id>-<slug> per department plus its .migrate/targets.json entry. Existing files are never overwritten. The files hold the source and target passwords and get default permissions: chmod 600 them.false
--tieroptTier recorded on generated registry entries (local|dev|uat|prod). The lifecycle passes the base entry's tier, so a customer base entry must carry its real tier (usually prod).dev
--id-prefixoptNamespace the generated registry ids and .env files, e.g. stcbh turns 1-main-department into stcbh-1-main-department. Needed when a second client shares the registry. The lifecycle passes the base entry id (lower-cased, letters/digits/-).none
What you do with the printed map

Each printed department gives you a legacy department id and a target Environment.id (CUID). From here, every migration command for that department takes both: --client stays pointed at the department's target Environment (or its config file), and the new --department <id> flag scopes the pipeline to that department's surveys, plus the contacts, responses, and answers reached through them. With --write-config each department is registered in .migrate/targets.json automatically; Environments re-reads the file when it opens and on [l], and the Lifecycle screen re-reads it after every stage.

--department is accepted by run, delta, and parity. It must be the same value across all three for one department's migration — a parity or delta run without it treats the target as if it received the whole tenant, and reports a count mismatch that isn't real (verbatim warning from both commands' own --help text).

06 / 07 / 07aOperation
UI

TUI: single-environment flowadvanced

For a customer migration use the Lifecycle screen instead (L1–L11). This section documents the older single-environment flow of the same TUI (Dashboard r: Preflight → Plan & dry-run → Confirm → Run monitor → Completion), which runs one environment at a time. Use it only to re-run one environment by hand. It runs the same engine as the numbered CLI steps 04–07.

The four stages, always in this order:

  1. Check — read-only preflight. Writes nothing.
  2. Rehearse — a dry-run that simulates the entire migration. Writes nothing.
  3. Run — the one step that writes real data, and only after you type a confirmation word.
  4. Verify — parity: compares source vs target row counts.

You can stop after any stage. Stages 1–2 are completely safe to explore on any environment.

Not the golden path any more. The Main menu lists 24 operations

The golden path is Menu → lifecycle (one stage per enter, 11 stages; L2). The Main menu (enter on the Dashboard) lists 24 operations under an <N> operations header, in groups: Assess, Migrate (lifecycle is here), Targeting & structure, Audiences, Hub, Danger, Superset, Environments & settings. Rows that cannot run for the current selection are grey and say why. The Command palette opens with g or :. ? opens a fixed "Global keys" list, and some keys on it (/, l, tab, M) do nothing.

Still CLI only: reset-client, export-provenance, census, verify-revert, project-legacy-hidden-fields, and lifecycle with --status, --export-dir, --skip-dry-run or --max-workers. The Lifecycle screen runs export, retire (with --provenance-manifest) and census itself; the separate Migration program screen cannot pass --provenance-manifest, so a retire from that screen refuses (E-PROV-02) on a database with provenance.

Hard requirements — why the UI "won't start"

The full-screen UI only launches with all of: a real TTY (connect with ssh -t — a one-shot ssh host '…' has none), a terminal ≥ 80 columns (tput cols), no CI env var, and no --no-ui. Miss one and it silently degrades to the line-by-line CLI. It also needs node --import tsx: the built CLI keeps @hivecfm/database external (TypeScript-only), so plain node dist/cli.js throws ERR_MODULE_NOT_FOUND, or on current builds ERR_UNKNOWN_FILE_EXTENSION for a packages/database/types/*.ts file. The TUI adds --import tsx to its own child processes, including All departments; the CLI run-all-departments does not (see 06). Always run it inside tmux so a dropped SSH session never kills a live migration.

bash: launch over SSH
$ssh -t <user>@<server-host> # -t forces a real TTY
$tmux new -s migrate # survives disconnects
$cd packages/migrator # so .migrate/targets.json + .env resolve
$node --import tsx dist/cli.js ui
If SSH times out — confirmed live, September 2026

Some jumpboxes' network security groups only admit a specific, rotating operator IP on port 22. From an unallowlisted IP, ssh -t <user>@<server-host> hangs and fails with ssh: connect to host … port 22: Connection timed out — not a credentials or hostname problem.

$ ssh -i ~/.ssh/<key> <user>@<server-host>
ssh: connect to host <server-host> port 22: Connection timed out

Fix: ask whoever owns that VM's resource group to add or refresh your current public IP in its NSG's inbound SSH rule. There is no working fallback that reaches the TUI — az vm run-command can reach the box, but it is one-shot and non-interactive (no TTY, no persistent stdin), so it cannot satisfy the TUI's own TTY requirement above. Use it only for one-off read-only or scripted checks, never to run ui. Direct, allowlisted SSH is the only path to the TUI.

If your SSH session drops mid-run — reattach, do not restart (confirmed live, September 2026)

Closing your terminal or losing the network (client_loop: send disconnect: Connection reset) does not stop a run started inside tmux — it keeps going on the server. Never re-type the run command to "get the screen back": that starts a second run against the same environment. Reconnect and reattach instead.

bash: get back to a running migration
$ssh -t <user>@<server-host> # if it times out, see the NSG note above
$tmux ls # your session name, e.g. dept1
$tmux attach -t <session> # back to the live screen
$tmux attach -r -t <session> # read-only: your keys can never reach the run

If tmux ls does not list the session, check whether the process is still alive before doing anything else:

$ ps -eo pid,etime,time,cmd | grep "dist/cli.js" | grep -v grep
$ tail -3 ~/run-<name>.log | cut -c1-300

Still listed → it is running; watch its log (below). Not listed, and the log has no run_end → it died; re-run the same command with --resume, which continues from the last checkpoint. Run twice a minute apart, a climbing TIME column proves it is working, not hung.

Do not type or scroll in the run's own window

Arrow keys and mouse-wheel scrolls in the window of a CLI run started in a shell are sent to that process as input and show up as ^[[C^[[C. The default language mode is apply, which never asks a question, so this junk is harmless there; it only matters with --consolidate-languages ask, which the TUI and the lifecycle never pass.

To scroll safely press Ctrl+b then [ (tmux scroll mode — arrows and PgUp now go to tmux, not the run), and q to leave. Or watch from a second window instead.

bash: watch progress from a second tmux window
#Ctrl+b then c opens a new window · Ctrl+b then 0 / 1 switches
$tail -f ~/run-<name>.log | grep --line-buffered -v heartbeat | cut -c1-250
$grep -v heartbeat ~/run-<name>.log | tail -4 | cut -c1-300 # one-shot "where is it now"

This only works if the run was started with its output saved — always launch CLI runs as … run … --json 2>&1 | tee ~/run-<name>.log.

A screen of nothing but {"evt":"heartbeat"} lines means one of two things. The heartbeat fires every 30 s no matter what, so it proves the process is alive — not that it is moving. It is usually in a phase that reports no row progress (the language-merge apply and the in-run parity check are silent for long stretches). Run the one-shot command above to see the last real line. A run started with --consolidate-languages ask in a terminal can also be waiting at its Apply … [y/N] question; the default apply never asks.

Environment registry — what populates the picker

The picker reads .migrate/targets.json relative to where you launch (hence the cd above). Each entry maps a friendly slug to the same .env you built in 03 Configure and the target Environment.id CUID (the value passed as --client). Environments re-reads the file each time it opens and on [l]. A file it cannot read keeps the old list and shows ✗ targets.json could not be re-read — showing the list from <time>.: fix the JSON, then [l].

{
  "environments": [
    {
      "id": "ist-serviceedge",
      "label": "IST ServiceEdge (dev)",
      "tier": "dev",
      "configFile": ".env.ist-serviceedge",
      "environmentId": "cmq9ij4310004pc01tzlxlqjh"
    }
  ]
}

To keep a provisioned department out of run-all-departments (for example an empty one, see 06), back up this file and delete that department's entry. The sequencer has no department filter of its own. That only lets you re-run run-all-departments while nothing has been written: once a real run has written rows for an earlier department, a re-run is refused by its own preflight gate (Target not empty), so run each remaining department on its own instead (run --client <env> --config .env.<dept> --department N, with --resume for a department that already wrote rows), as the E-RUN-PHASE-FAIL-01 message says.

Step by step — what to press, what you see

  1. Pick your client. You start on the Dashboard — on a first launch every field reads unknown because nothing is selected yet:
    no environment selected
    Variant unknown    engine unknown
    
    Active run   none
    Resume   none
    Last run   none
    
    Health   target PG unknown   source MSSQL unknown   Hub unknown
    
    [enter]menu [r]run [s]status [v]verify [B]bundle [e]env [N]notif [?]help
    Press e → the Environments list opens.
    • If your client is already listed (it reads from .migrate/targets.json — see the schema above): highlight it with ↑/↓ and press Enter. A second Enter is needed only on a row marked ⚠ unverified (⚠ not yet verified — press [r] to re-check it, or enter again to select <label> anyway.); prefer r, whose result is saved in .migrate/registry-status.json and restored for 24 h. A multi-department client shows one row, Client — <client> (N depts); Enter on it selects the client for lifecycle, and this single-environment flow needs one department: [x], then Enter on the department. Press Esc to return to the Dashboard.
    • On a fresh checkout the list is empty — this is the normal starting state, not an error:
      tier  label                    env-id       status
      
      No environments registered. Press n to add one.
      
      [enter] select [n] new [e] edit [r] re-check [d] details
      Press n and fill in id, label, tier, configFile (the absolute path to your .env from 03 Configure) and environmentId (the target Environment.id CUID). The editor writes no .env file: create it first. t runs SELECT 1 FROM "Environment" WHERE id=$1 through that file, so it needs a cuid-shaped environmentId and a configFile with a full TARGET_PG_* block. s saves once t passed. Hand-editing .migrate/targets.json works too; press [l] in Environments to reload it (no restart needed).
  2. Stage 1 · Check. Press r. The Preflight screen runs the checks it can do without spawning the engine — env-id, target connectivity, target-empty — and marks the rest deferred, not skipped:
    0  Environment id resolves in target PG   PASS
    1  Source MSSQL connectivity              not checked
    2  Target PostgreSQL connectivity         PASS
    5  Target empty (or --resume)             PASS
    ...
    8 source/hub/variant checks deferred to the engine — [p] to proceed
    The non-destructive dry-run on the next screen runs these checks.
    
    0 blockers · 0 warnings
    0 blockers with checks still marked deferred is the expected, normal result — press p to proceed. Nothing is written at this stage.
  3. Stage 2 · Rehearse. Preflight hands you to the Plan & dry-run screen — this is where the 8 deferred checks (source read, variant detection, schema) actually run, alongside a full simulation:
    Impact (no writes yet)
    No dry-run yet — press enter to run.
    
    Phase plan [space]=skip toggle
    1    Lookups                run  (core, not toggleable)
    2    Entities               run  (core, not toggleable)
    2.5  Repair                 run
    2.6  Audiences              run
    3    Transactional          run  (core, not toggleable)
    4    Post-process KPI/MV    run  (core, not toggleable)
    4.5  Structure backfill     run
    5    Validate / parity      run  (core, not toggleable)
    5.5  Targeting backfill     run
    6    Hub backfill           run
    
    [enter] run dry-run   [space] toggle skip   [P] single-phase
    Press Enter to run it — it simulates the whole migration and writes nothing. While it runs, the screen shows Running dry-run… m:ss · Phase <n>: <name> and a row count per table. [space] toggles any non-core phase off first if you only need a partial rehearsal; [P] opens a single-phase picker to isolate just one phase instead of the whole plan. When it finishes clean, the "proceed" option unlocks.
  4. Stage 3 · Run (the only write). After a clean dry-run, press p. The Confirm screen depends on the tier: prod shows Type <TOKEN> exactly as shown, then press enter. (case-sensitive; a wrong attempt makes a new token); uat asks you to type APPLY; dev/local shows Proceed? [y/N]: press y (enter does nothing there). [tab] on the confirm cycles the language mode (apply → report → skip; default apply). This is the first and only moment real data is written. The Run monitor opens and streams each phase live.
  5. Stage 4 · Verify. The Completion screen's keys do nothing except esc. Press esc to the Dashboard, then v → Parity compares source and target and flags any mismatch.

The only keys you need

KeyWhat it does
eOpen Environments — pick your client
rStart the flow: Check → Rehearse → Run
↑ ↓Move the highlight
EnterChoose / run the highlighted item
pProceed on the Dry-run screen · on the Run monitor it sends one SIGINT (a graceful stop) and opens the Pause overlay. Every key on that overlay only closes it: [K][K] does not force-kill and [R] does not resume. Its resume hint leaves out --config and --department: add them.
EscGo back one screen · on the Run monitor, detach (the run keeps going). On the Lifecycle screen esc is refused while a stage runs; use ←.
vVerify (Parity)
sResume / status — only if a run stopped
g or :Command palette
?A fixed "Global keys" overlay (some keys listed there do nothing)
qQuit. If a child is running it asks for a second q (or Ctrl+C), then quits; the detached child keeps running.

Ctrl-C is not a pause: it arms a quit, and the detached run never receives it. Use p to stop gracefully or Esc to detach.

One destructive point

Everything up to the confirm token is non-destructive — Preflight and Dry-run only probe connectivity and a create/drop scratch table. The first write to PostgreSQL happens when you confirm the Run — the exact write that 06 Run Migration performs from the CLI. You can walk right up to that line on any environment.

Known issues in this build (branch fix/noref-tui-run3-operator-defects)
  • Preflight: [enter] proceed stays (blocked) because the TUI runs only 3 of the 12 checks; use p (proceed anyway). The full gate is the CLI preflight.
  • Plan & dry-run: the single-phase selection ([P]) cannot be cleared; leave and re-enter the screen.
  • Confirm: on dev/local, enter does nothing; press y.
  • Pause overlay: every key only closes it (see the key table).
  • Completion: [P], [H], [o] and [enter] do nothing; only esc. Rows and artifacts are always empty. The Hub hint prints the environment label, not its id: use the id.
  • Resume / status: the checkpoint table always shows an error; [R] works.
  • Dashboard: version, variant, health and last run always read unknown / none.
  • Environment editor: writes no template .env; exists ✓ only means the field is filled; editing a department entry resets tenancy to single and drops its department binding.
  • Rollback screen: the dry-run impact list is always empty; run rollback … --dry-run in a shell to see it.
  • No typed confirm: Consolidate languages, Audiences and Finalize targeting apply on the second enter; Delta and Hub backfill start on the first.
  • Migration program screen: after open-program it says Report-only run passed — [a] --apply is now available for open-program. Ignore it; the lease was taken.
Resume after a disconnect or stop

If SSH drops mid-run, the migration is still alive inside tmux: reconnect and tmux attach -t migrate to land back on the live monitor — do not relaunch the TUI (that starts a second instance). If a run actually stopped, resume it from the Dashboard's Resume / status screen (press s, then R) or with the CLI node --import tsx dist/cli.js run --resume --client <cuid> --config <.env> [--department N]. At launch, the Startup check finds an interrupted run in _MigrationCheckpoint and offers [R] Resume; it does not move on by itself (press N or esc).

The Run monitor screen — confirmed live, September 2026

Once you confirm the real run, the Run monitor shows a phase checklist, a per-table progress line, and a scrolling log, all live. (The screens below are from an earlier build; the legend now reads » skipped (did not need to run).)

Right after you confirm, before any phase starts:

Run monitor

○1 Lkp ○2 Ent ○2.5 Rep ○2.6 Aud ○3 Txn
○4 KPI ○4.5 Str ○5 Parity ○5.5 Tgt ○6 Hub
legend  ✓ done  ● active  ○ pending  ♪ skipped  ✗ failed

Overall  ▱▱▱▱▱▱▱▱▱▱ 0/10 done · 10 pending

Tables
(no table progress reported yet)

Log
Filter: all  autoscroll: ON (space=pause)
(no lines)

a/e/w filter · / search · n/N jump · space pause/resume · x raw/pretty · c copy · d error-details
p pause · tab pane · d detail · l log · esc detach (safe)

ZainBH-Local · Idle · no run · 00:06 · poll 2s

Every phase starts as ○ pending — that includes the phases you never toggled off, like 2.5 Rep and 6 Hub. ○ pending here is not a warning; it just means "not reached yet."

A minute or so in, with a phase actually moving rows, the log fills in and the status bar starts tracking a live checkpoint:

  Variant detected: ISTServiceEdgeOld — CFMSurveyQuestionResponse (typed-union parent) exists and CFMSurveyResponse (unified) is absent — matches ISTServiceEdgeOld schema.
  Adapter: ISTServiceEdgeOld (responseStrategy=typed-union)
  Department scope: WHOLE TENANT (no --department given)
  Phase 1/5: Lookups
    ContactAttributeKey: upserting 18 fixed keys
    Channel: 4 unique rows (from 4 legacy IDs)
    SegmentCode: loaded 57 CRM segment codes
    Department: 2 read from [CFMDepartment] — 1="Main Department", 2="Zain Bahrain"
  ⚠[memory] memory rule not measurable: global.gc is not exposed, so heapUsed at each phase
  boundary includes uncollected garbage and cannot be held to the post-Phase-1 baseline +
  256.0 MiB. Samples (including rss) are still recorded. To measure the rule, start the
  migrator with node --expose-gc.
  Phase 2/5: Entities
    Contact: streaming 310926 CFMCustomer rows
      Contact progress: 50000/310926

ZainBH-Local · Idle · ckpt Contact@8506 · 00:36 · poll 2s

What the memory warning means: it is informational, not an error. The migrator measures its own memory at each phase boundary to catch a runaway leak, but that check only holds if a garbage collection just ran — otherwise leftover garbage inflates the number and produces false alarms. Forcing a GC pass requires Node's --expose-gc flag, which the TUI does not set by default. Without it, the tool still records memory samples (visible in --json output) — it just doesn't enforce the pass/fail budget on them. Nothing to act on; it never affects what gets migrated.

The status bar's ckpt Contact@8506 is the live resume point — if the run stopped right there, --resume would continue from legacy id 8506, not from zero.

Reading a phase transition in the log

Inside Phase 3 (Transactional), several sub-steps run back to back with no separate phase banner between them — the only signal one finished and the next started is the log itself changing subject. Confirmed live against dev.hivecfm.io (2026-09-15), ResponseAnswer finishing and UnansweredInvitationResponse starting immediately after:

  ✓ ResponseAnswer (typed-union): 167060 rows written, 0 already present (read 167060)
  [CFMSurveyInvitation]: paging by [GUID] (uniqueidentifier) via PK_CFMSurveyInvitation (nonclustered, unique, NOT NULL) — [ID] is not the key of any usable index on this source
  UnansweredInvitationResponse: --chunk-size 500 is below the advised 5000 for a [GUID] keyset read. ...
  Unanswered invitations: 38952 answered GUIDs recorded in _MigrationAnsweredGuid (CFMCustomerSurvey through id 52659)

The tell: a line starting with ✓ and a final row count is always that sub-step's completion summary. The very next line naming a different table (here, [CFMSurveyInvitation] choosing its page key) is the next sub-step beginning — there's no blank line or banner between them, so read the log by table name, not by whitespace.

The All departments screen — one row, every department

Manual path; the Lifecycle screen replaces it. A legacy source with more than one department migrates into one environment per department. Select the client row Client — <client> (N depts) in Environments (enter only selects it), then Main menu → run-all-departments opens the plan below. It runs each department in turn, and every department still writes only its own environment. Unlike the lifecycle, it has no verify, Hub, finalize or retire stages.

All departments — Zain - BH (My Project)
Source config .env.zain-base · each department runs into its OWN environment

Department 1 of 2: Main Department (dept 1)  dept 1 → cmtsbhsb7000ej101ut7o0pzc  (.env.1-main-department)
Department 2 of 2: Zain Bahrain (dept 2)     dept 2 → cmua0y12p000dc1bx61i23gxf  (.env.2-zain-bahrain)

Options
  [h] skip Hub backfill     ON   (push after consolidation — the report lists each hub-backfill)
  [c] consolidate languages apply
  [d] dry-run               OFF
  [o] open-program          ON   (opens the migration lease)
  [f] continue on failure   OFF
  A configured Hub that cannot be reached fails every department's preflight, whatever [h] says.
  Dry run of this exact plan passed this session: no

Child run budget [t]
  all default — no --max-workers, so every department runs SERIAL: one partition at a time, the certified path and the slow one.

Child commands, in order (the sequencer stops the gate before any run on a failure)
  open-program --config .env.1-main-department --json
  open-program --config .env.2-zain-bahrain --json
  preflight --client cmtsbhsb7000ej101ut7o0pzc --config .env.1-main-department --department 1 --json
  preflight --client cmua0y12p000dc1bx61i23gxf --config .env.2-zain-bahrain --department 2 --json
  run --client cmtsbhsb7000ej101ut7o0pzc --config .env.1-main-department --department 1 --consolidate-languages apply --skip-hub-backfill --json
  run --client cmua0y12p000dc1bx61i23gxf --config .env.2-zain-bahrain --department 2 --consolidate-languages apply --skip-hub-backfill --json
  CLI equivalent: migrate run-all-departments --from-config .env.zain-base --open-program --consolidate-languages apply --skip-hub-backfill

[enter] confirm & run  [p] provision / preview  [h][c][d][o][f] options  [t] budget  [esc] back

Read the child-command list before pressing anything else. It is not a summary — it is the exact argv each child receives, and the CLI equivalent line is the single command that does the same thing from a shell. A department pointed at the wrong environment or config shows up here, before anything is written.

The gate runs first, for every department: open-program, then preflight --department N for all of them, before the first run writes a row. A problem that would stop department 2 therefore surfaces before department 1 has touched anything, and a gate failure stops the whole sequence with nothing migrated.

What to press:

  • [p] only when the departments are not listed yet — it previews, then creates, one environment per department and writes their config files. Departments already listed means this is done.
  • [t] sets the child run budget. Left alone, every department runs serial — the certified path, and the slow one. Setting --max-workers runs the partitioned plane instead: faster, but the connection pools do not yet size themselves from the worker count, so treat such a run as “it completed”, never as a benchmark.
  • [h] keep skip-Hub ON for any environment that has Hub settings. Phase 6 pushes before language consolidation, so an in-run push sends ids that consolidation later merges away, and a second push cannot correct them. Push afterwards with hub-backfill per department — the completion report lists the exact commands.
  • [enter] confirms and runs. This is the destructive point; a confirmation screen follows.

“Dry run of this exact plan passed this session: no” is a statement about this session, not a warning. On a dev-tier entry the dry run is optional; on production it is required before the confirmation screen will let you commit. A dry run of a large department costs about as long as the run itself, which is why it is usually skipped deliberately on dev.

While it runs you get the normal Run monitor, one department at a time, with a Department k of M header. esc detaches safely and the run keeps going — the run also survives the UI being killed. Stopping is per department: it signals the one in flight and does not start the remaining ones.

Reading the Completion screen

DATA COMPLETE · Hub push pending — this is NOT a data failure · exit 2
run #run-1789462675572 · env ZainBH-Local

✓1 Lkp ✓2 Ent ○2.5 Rep ○2.6 Aud ✓3 Txn
✓4 KPI ○4.5 Str ✓5 Parity ○5.5 Tgt ○6 Hub
legend  ✓ done  ● active  ○ pending  ♪ skipped  ✗ failed

Verification
Parity (in-run)   informational only — run does NOT gate on it
Parity (gate)     NOT RUN -> press P for `migrate parity` (exit 2 on fail)

Data COMPLETE · Hub push pending. Fix: re-run `migrate hub-backfill --client ZainBH-Local`
— it is idempotent and external-only. Do NOT roll back.

Next steps
1 [H] re-run hub-backfill (idempotent) — clears Hub pending
[P] parity gate  [H] re-run hub-backfill  [o] open artifact  [enter] recommended  esc back
Reaching this screen is not the finish line

Read the banner literally, top to bottom:

  • DATA COMPLETE — every row that should have migrated, did. This part is done and correct.
  • exit 2 — the process's exit code, and it does not mean the data failed. It means the full lifecycle (data + Hub push) did not finish. On a Hub-less environment like this local bench, that's the expected outcome every time.
  • Phases that did not need to run show » skipped (did not need to run) in the current build (the capture above is from an earlier one).
  • Parity gate says NOT RUN — the in-run parity check is informational only. [P], [H], [o] and [enter] do nothing on this screen; only esc works. Press esc, then v on the Dashboard to run the real gate.

Actually finishing, in order: (1) Dashboard v for the parity gate — this is the real pass/fail check; (2) if this environment has a Hub, run $M hub-backfill --client <env id> --config <.env> (the hint on screen prints the label; use the id). A re-push is safe only while the data is unchanged: the Hub answers records it holds with 409 and never updates them. If there is no Hub (as here), this step is correctly skipped.

Completion screen: only esc works

The legend now separates » skipped (did not need to run) from ○ pending. The action keys on this screen ([P], [H], [o], [enter]) are still not wired: use the reading order above.

UI-b

History: STC-BH run 2 (manual path)superseded by L0–L11

STC-BH (4 departments) was first migrated on 2026-09-26 by hand: TUI Migration program → Run all departments with [p] and [d] → per-department delta + parity from a shell → finalize-staging → export-provenance → retire-migration-program → census. Run 3 (2026-09-28/30) did the same client through the Lifecycle screen, which now does every one of those steps.

Use the Lifecycle sections for any multi-department client:

  • Base config and base entry: L0. Register the real tier (usually prod): it becomes the tier of every department entry and of every confirm; retire always asks for the prod token.
  • Department list and provision: L3 ([d], then the provision stage). Department entries get the base id as prefix (--id-prefix, e.g. stcbh-1-main-department), so two clients with a "Main Department" no longer collide.
  • Dry-run, run and QUARANTINE merges: L4. Verify (delta + parity, with automatic recovery from E-DELTA-PLAN-OPEN-01): L5. Hub: L6. Finalize: L7. Export, retire and census, all from the TUI: L8.

Two run-2 findings that no longer apply: the contact-count check that timed out on dept 5 is now two set differences read in 100,000-id ranges (contact_count_parity and contact_target_extras), and "rows beyond the boundary" on a live source are now pending warnings, not failures (07).

04

Preflight Checkrequired

Read-only. Validates both databases, detects schema variant, estimates row counts and duration. No data is written. The lifecycle runs this once per department in its preflight stage (L3): $M preflight --client <dept env> --config <dept .env> --department N.

Before you run

The migrator CLI is the bin packages/migrator/dist/cli.js, not a pnpm script, it must exist before this command resolves. Install Step 8 already builds it as part of the first-time setup; if you skipped that or pulled new migrator source since, rebuild now:

bash · hivecfm-core/
$pnpm --filter @hivecfm/migrator build

Confirm ls packages/migrator/dist/cli.js prints the file before continuing.

Rule: after updating code on a migration host, always regenerate the Prisma client and rebuild before running anything — pnpm --filter @hivecfm/database generate && pnpm --filter @hivecfm/migrator build. A schema pulled without regenerating leaves the client silently out of date; see Troubleshooting · language consolidation reports "0 merged".

bash · hivecfm-core/
$$M preflight --client <env-id> --config <.env> [--department N]

What preflight checks:

  • MSSQL connectivity (AppDB and SurveyDB)
  • PostgreSQL connectivity and migration version
  • Required tables present in source (CFMUser, CFMSurveyResponse, etc.)
  • Schema variant detection: StableRJB or ISTServiceEdge
  • Row count estimates per table
  • Advisory lock availability (confirms no other migration is running)
  • Target environment ID exists
expected output
HiveCFM Migrator v0.1.0
Preflight: ist-serviceedge

✓ MSSQL AppDB connected         (HiveCFMAppDB-ISTServiceEdge)
✓ MSSQL SurveyDB connected      (HiveCFMSurveyDB-ISTServiceEdge)
✓ PostgreSQL connected          (hivecfm_ist_serviceedge)
✓ Migrations current            (20260826020000)
✓ Variant detected              ISTServiceEdge
✓ Advisory lock available
✓ Environment ID found          env_xxxxxxxxxx

Row estimates
  CFMUser                12,847
  CFMSurveyResponse     341,092
  CFMSurveyInvitation    87,441
  CFMTouchpoint              —   (not present in ISTServiceEdge)

Estimated duration: ~2h 20min

Preflight passed. Ready to migrate.
If preflight reports ✗, match the exact line

Preflight emits one ✓ or ✗ line per check. Find the failing line below and apply the inline fix. Every other ✓ line means that check passed; you only need to fix the ✗ ones. Re-run preflight after each fix.

Failure line Cause & fix
✗ Source MSSQL connectivity MSSQL host unreachable on port 1433. Test directly: nc -zv $SOURCE_MSSQL_HOST 1433. If timeout → VPN/firewall. If "connection refused" → wrong host/port in .env. If TLS error → set SOURCE_MSSQL_TRUST_CERT=true in .env (self-signed cert opt-in; v0.10+ default is secure). Never set this in production.
✗ Target PostgreSQL connectivity Postgres unreachable on the configured host/port. Confirm exposed port: docker compose port postgres 5432 (laptop dev maps to 5415, EC2 default 5432). Update TARGET_PG_PORT in .env.<client> to match. If container stopped: docker compose up -d postgres. If P1001: see troubleshooting card "P1001" below.
✗ Source read permission · no VariantAdapter matched this schema The schema doesn't match either StableRJB or ISTServiceEdge markers. Do not pass --allow-resume or any force flag. The schema has drifted in a way the tool isn't validated against. Run the Variant Decider for offline triage and escalate with the full preflight output.
✗ Target write+DDL permission · canCreateTempTable=false, canRunDDL=false The PG user lacks DDL rights. The migrator creates temp tables and indexes during Phase 3. Either grant: GRANT CREATE, USAGE ON SCHEMA public TO <user>; and ALTER USER <user> CREATEDB;, or switch TARGET_PG_USER to postgres.
✗ Target not empty · N legacy rows already in Response; use --allow-resume to continue Fresh-client guardrail tripped, the target already holds legacy_id-tagged rows from a prior run. Two valid paths: (a) Resume the prior migration (idempotent): re-run preflight as $M preflight --client <c> --config <f> --allow-resume, then proceed to $M run with --resume (note the different flag). (b) Restart fresh: never TRUNCATE (on a customer or shared target it wipes every organization). While the program is open, roll back this one environment: $M rollback --client <c> --config <f> --dry-run, then without --dry-run (10). For a retired client use reset-client (L10). Investigate the row source first; you may be about to discard work.
✗ Disk space · Only X GB free, need Y GB Free space on the PG volume is below the estimated need (~2× source DB size for COPY + temp). Expand the PG volume: on EC2, aws ec2 modify-volume --volume-id <id> --size <new> then sudo growpart /dev/nvme0n1 1 && sudo resize2fs /dev/nvme0n1p1; on laptop dev, expand the Docker volume. Re-run preflight.
BLOCKER: lines (other than the rows above) Usually missing required tables in the source. Resolve each one before proceeding. Warnings (missing optional columns) are safe to continue, they'll be noted in the parity report.

For deeper diagnostics on any of the rows above, Ctrl-F the Troubleshooting section for the exact error string. Flag-name gotcha: preflight uses --allow-resume to bypass the empty-target guard; migrate run uses --resume to continue from a checkpoint. Different names, related behavior.

expected output: failure case
HiveCFM Migrator v0.1.0
Preflight: stable-rjb

✓ MSSQL AppDB connected         (HiveCFMAppDB-StableRJB)
✓ MSSQL SurveyDB connected      (HiveCFMSurveyDB-StableRJB)
✗ FAIL PostgreSQL connectivity       password authentication failed for user "migrator_rw"
✗ FAIL Migrations current            20260515000004 not applied (last applied: 20260514103022)
✗ FAIL Advisory lock                 held by PID 14823 (started 47 min ago)

Preflight FAILED — 3 blockers.

Remediate top-down: fix the PG credentials (or rotate them), then apply pending Prisma migrations (pnpm --filter @hivecfm/database build && pnpm --filter @hivecfm/database db:migrate:deploy), then kill the stale advisory lock holder (SELECT pg_terminate_backend(14823);). Re-run preflight after each step.

04b · Open the migration program required once per database

Preflight is read-only, so it cannot grant anything. Between preflight and your first run against a database that has never been migrated into, you must open the migration lease:

bash · hivecfm-core/
$$M open-program --config <base.env>
Expected"Migration program OPEN on host:port/db — migration program opened by `migrate open-program`."
VerifySELECT * FROM "_migrator_program_lease"; returns exactly one row.
If already open"A migration program is already open … Nothing to do." Exit 0. Safe to re-run; it is idempotent.
Skipping this fails fast — before anything is written

migrate run never opens the lease itself, by design: permission to write migration-owned schema into a customer database must not be a side effect of a command happening to run. It does, however, ask for the lease up front — before Phase 1 writes a single row (shouldAssertProgramOpen / assertProgramOpen in cli/run.ts). On a database that has never been migrated into, a lease-less run therefore refuses immediately with E-LEASE-01, exit 1, and writes nothing at all. Recovery is the plain command with no flags: migrate open-program, then migrate run — no --resume, because there is nothing to resume. The dry-run and --phase 5 paths are exempt (neither writes, so neither needs permission). Preflight still only WARNs about the missing lease; it does not block — it is read-only diagnostics and cannot grant anything — so a passing preflight is not a statement that run will proceed. Read the warning.

On builds before 9a5c77aa4: the refusal on a fresh database says "RETIRED"

This applies only if your deployed dist/ predates 9a5c77aa4 — the branch is fixed, but a box can still be running an older build, which is the common case right after a fix lands. How to tell without reading git: on a fixed build the refusal arrives before any Phase 1 output; on an older one you will see lookups, surveys and contacts scroll past first. If in doubt, rebuild: pnpm --filter @hivecfm/migrator build.

On those older builds the lease was enforced only at the first call that creates migration-owned schema — Phase 2.6's addSegmentTracking, or Phase 3's DDL bootstrap under --skip-audiences. Both run after Phase 2 has written Survey rows carrying legacy_id, and before any staging table exists. assertProgramOpen classifies from exactly those three facts — no lease, migrated data present, zero staging tables — which is also precisely what a genuinely retired database looks like. So you got E-LEASE-02: "this database holds migrated data, has no open migration lease, and has no migration staging tables left. That is a RETIRED migration program." — about a database nobody had ever migrated into, with Phases 1–2.5 already written.

And the obvious recovery was refused too. The refusal did not change the state, so a bare open-program diagnosed the same retired verdict and refused in turn. The working sequence on an older build is migrate open-program --reopen-after-retirement --confirm, then migrate run --resume — and the lease note it writes reads "re-opened after retirement" for a retirement that never happened, so do not let a later reader take that as evidence this database was once retired. Re-run preflight if unsure: check 12 prints the remedy for the state it actually sees.

Why this could not be fixed by diagnosing better: retirement drops all fifteen MIGRATION_OWNED_TABLES (13 staging tables and both markers) — so a retired database and a mid-run lease-less one are schema-identical. Any signal able to separate them would have to survive retirement, which is the permanent footprint the lease exists to remove. Asking before the first write sidesteps it: at that moment nothing carries a legacy_id, so the answer is unambiguously never-opened.

A passing dry-run still does not prove the lease exists. Dry runs are exempt from the gate on every build — they write nothing, and the TUI's dry-run runner rejects any non-zero exit, so refusing there would make a rehearsal impossible on a fresh database. migrate run --dry-run succeeding on a lease-less database is expected, not reassurance.

The two escape flags are not interchangeable, and each is refused in the other's state — the wrong one tells you your diagnosis was wrong rather than doing something adjacent:

Database stateWhat to passWhat happens otherwise
never-opened — no lease, no migration-owned tablesNothing. The ordinary path takes no flag on purpose: making the common case ceremonial is how flags stop being read.—
open — lease already presentNothing.No-op, exit 0.
active-unleased — a migration predating the lease is already running (staging tables present, no lease)--adopt-active-program. Adoption writes the lease and changes nothing else: no staging table created, dropped or modified, no tenant state touched.Refuses without the flag. --reopen-after-retirement is refused here too — retirement never ran, so the flag's own name would be saying something untrue.
retired — retire-migration-program dropped everything on purpose--reopen-after-retirement --confirm. Deliberately noisy, because it reverses a permanent database-wide decision a human made with --confirm.Refuses without both. --adopt-active-program is refused here: there is nothing active to adopt. --confirm alone is never sufficient for anything — it is the flag operators are most practised at adding, so it must not be the one that decides.

open-program is the one command with no --client: the lease is database-wide, not per-tenant. It reads its target from --config (or the ambient TARGET_PG_* vars) and every message it prints names the database it actually connected to, not the one you believe you configured.

05

Dry Runoptional

Runs the full pipeline logic without committing any data. Reads from MSSQL, transforms, but rolls back all target transactions. Takes the same time as a real run.

bash
$$M run --client <env-id> --config <.env> [--department N] --dry-run

Dry run is optional but strongly recommended for the first migration of each client. It surface transform errors (type mismatches, missing lookup keys, FK violations) without touching production data.

If dry run completes without errors, proceed to the real migration. If it reports errors, fix the transform or the source data first. The lifecycle's dry-run stage runs this per department with --consolidate-languages apply --skip-hub-backfill (L4).

06

Run Full Migrationadvanced · manual path

Writes data to PostgreSQL. For a customer migration the Lifecycle run stage does this for every department (L4). This section is the per-command reference for running by hand. The process is safe to interrupt; it resumes from the last checkpoint.

One department or several? The source decides — detect first

A legacy source with more than one department must migrate each department into its own environment. A plain run refuses an unscoped run on such a source (E-RUN-SCOPE-01), because it would put every department's rows into one environment. Use the two steps below instead: step 1 reads the department list from the source and creates or reuses one environment per department; step 2 runs every detected department, one after another, in a single command. A source with only one department uses the plain run further down this section.

Manual path: the order that worked in STC-BH run 2 (2026-09-21). Run 3 (2026-09-28/30) used the Lifecycle screen instead
  1. Sign up in the UI and give the project a neutral name (see below). Copy the production environment id from /environments/<id>/surveys.
  2. Put it in the base config (.env.<client>-base) as CLIENT_ENV.
  3. open-program, then preflight (04).
  4. Count surveys and customer surveys per department (query below). Leave out every department with 0 surveys and 0 customer surveys; report one with surveys but 0 customer surveys to the owner as a blocker.
  5. provision-departments --dry-run --write-config, read the map, then provision-departments --write-config (step 1).
  6. Check that the generated .env.* files read -rw------- (ls -l .env.*; provision writes them 0600).
  7. run-all-departments --open-program --dry-run, then run-all-departments --open-program (steps 2a and 2b, launched with NODE_OPTIONS=--import=tsx; this applies to run-all-departments only: the lifecycle adds --import tsx to its own children).
  8. parity --client <env> --config .env.<dept> --department N for each department (07).
An empty department cannot be migrated: count before you provision (confirmed live, 2026-09-21)

Phase 3 stops on a department whose scope holds no CFMCustomerSurvey row, in the dry run and in the real run. Dry run: [dry-run] runTypedUnionResponseAndAnswer: the source holds no CFMCustomerSurvey row in this run's scope (boundary 0), so a real run would have no Response parent to link any answer to. Check the source database and the --department value. Real run: runTypedUnionResponseAndAnswer: resolved 0 migrated Response rows from the target, so no ResponseAnswer parent can be linked and every answer would be silently skipped. Expected non-null Response.legacy_id values from the Response copy that just ran. Check that Phase 3 wrote Response to the intended database. run-all-departments then stops the whole sequence at that department with E-RUN-PHASE-FAIL-01. The typical case is an intermediate ParentID node with no surveys of its own: STC-BH department 2 STCBH is empty, and its children 4 and 5 hold the data. A department with 0 surveys needs no environment at all.

Before step 1, count per department on the source (read-only login), then leave out only the ids with 0 surveys and 0 customer surveys, via --departments <the other ids> (surveys > 0 with 0 customer surveys is a blocker to report, not an id to drop):

How to run it. Use any SQL client that reaches the source with the read-only login, connected to the survey database, for example sqlcmd -S <source host>,1433 -U <readonly login> -d <SOURCE_SURVEY_DB> (it asks for the password; add -C for a self-signed server certificate), or SSMS on the customer's side. First find the source type: SELECT OBJECT_ID('dbo.CFMDepartment'); in the survey database. A number: ISTServiceEdge type, everything is in the survey database (query 1). NULL: StableRJB type, the departments are in the app database (query 2). Preflight's Variant: … line confirms it later.

sql 1 · ISTServiceEdge type · run in <SOURCE_SURVEY_DB> (read-only)
SELECT d.ID, d.Name, d.ParentID,
(SELECT count(*) FROM CFMSurvey s WHERE s.DepartmentID = d.ID) AS surveys,
(SELECT count(*) FROM CFMCustomerSurvey cs JOIN CFMSurvey s ON s.ID = cs.SurveyID WHERE s.DepartmentID = d.ID) AS customer_surveys
FROM CFMDepartment d ORDER BY d.ID;
sql 2 · StableRJB type · run in <SOURCE_SURVEY_DB>, departments read from <SOURCE_APP_DB> (read-only)
SELECT d.ID, d.Name, d.ParentID,
(SELECT count(*) FROM dbo.CFMSurvey s WHERE s.DepartmentID = d.ID) AS surveys,
(SELECT count(*) FROM dbo.CFMSurveyResponse r JOIN dbo.CFMSurvey s ON s.ID = r.SurveyID WHERE s.DepartmentID = d.ID) AS responses
FROM [<SOURCE_APP_DB>].dbo.CFMDepartment d ORDER BY d.ID;

Replace <SOURCE_APP_DB> with the app database's name, keeping the square brackets. In query 2, responses takes the place of customer surveys: leave out a department with 0 surveys and 0 responses.

Already provisioned the empty one? run-all-departments has no department filter. Back up .migrate/targets.json (cp .migrate/targets.json .migrate/targets.json.bak) and delete that department's entry from it. Its project and environment stay, empty, which matches the source. Re-running run-all-departments after that works only if nothing was written yet. If a real run already wrote earlier departments, a re-run is refused by its own preflight gate (Target not empty): do not re-run it; run each remaining department on its own (run --client <env> --config .env.<dept> --department N, adding --resume for a department that already wrote rows), as the E-RUN-PHASE-FAIL-01 message says. On the lifecycle path none of this applies: the lifecycle has no step that drops a provisioned department, so stop and ask the owner (L4).

bash: step 1 — detect the departments (preview, then apply)
$cd packages/migrator && unset DATABASE_URL && export TARGET_PG_SSL=true
$node --import tsx dist/cli.js provision-departments --client <anchor-env-id> --config .env.<client>-base --write-config --tier <tier> --id-prefix <client> --dry-run
$node --import tsx dist/cli.js provision-departments --client <anchor-env-id> --config .env.<client>-base --write-config --tier <tier> --id-prefix <client>
$chmod 600 .env.<client>-base && ls -l .env.* # generated files are written 0600 (-rw-------); chmod 600 any that is not

The preview prints the department → environment map read from the source — one line per department, each marked reusing existing project, reusing project (renamed) or WOULD create. Check it before the second command. The apply writes one .env.<dept> per department and registers each in .migrate/targets.json. Each generated .env.<id>-<slug> copies the base config's source and target passwords and is written with mode 0600; check with ls -l (the last line above). On a re-run, “already exists — left untouched” for those files is expected and correct; such a file keeps its old mode, so chmod 600 it if ls -l shows otherwise. It refuses to rename a project whose environment already holds migrated rows.

The first department provisioned takes over the --client project: give it a neutral name at signup (confirmed live, 2026-09-21)

provision-departments reuses the project of the --client / CLIENT_ENV environment for the first department it provisions (the lowest id in --departments, or in the source when all are provisioned) and renames it to that department's name. The other departments get new projects, each with a production and a development environment. Before the rename it checks the project's current name, in --dry-run too. If that name belongs to any other legacy department, it refuses:

refusing to rename project <id> ("STCBH") to "Main Department" for department 1: "STCBH" is the name of department 2 in this source ... (E-RUN-SCOPE-01). Remedy: re-run with --client naming an environment that is not already a department's — the original anchor, or an empty one whose project has a neutral name. Nothing has been written.

What caused it live: the signup project was named STCBH, which is also STC-BH legacy department 2's name. Prevention: at signup, give the project a name no CFMDepartment.Name uses, e.g. <Client> migration anchor; it is renamed to the first department anyway. Fix after the fact: rename the (still empty) project to a neutral name, in the project settings in the UI or with the SQL below, and re-run. The second check still applies: the anchor environment must hold 0 migrated rows.

sql · target Postgres
UPDATE "Project" SET name = '<Client> migration anchor' WHERE id = '<project-id>' AND name = '<current-name>';
bash: step 2a — in tmux, rehearse every detected department (dry run)
$tmux new -s <client>-all # an SSH drop can no longer kill the run
$export NODE_OPTIONS=--import=tsx # inside tmux; every department child inherits it. No need to also pass --import tsx
$node dist/cli.js run-all-departments --from-config .env.<client>-base --open-program --dry-run 2>&1 | tee ~/run-all-<client>-dry.log
bash: step 2b — run every detected department (same tmux session, after the dry run passed)
$node dist/cli.js run-all-departments \
--from-config .env.<client>-base \
--open-program \
--consolidate-languages apply \
--skip-hub-backfill \
--max-workers 4 2>&1 | tee ~/run-all-<client>.log
$node dist/cli.js parity --client <env> --config .env.<dept> --department N # then once per department
--approve-quarantine / --fold-sibling-question now work directly on run and run-all-departments (migrator commit 914d42d15)

The fold no longer needs a second command. Step 2b's own run-all-departments invocation can carry --approve-quarantine and --fold-sibling-question straight through to whichever department's consolidation actually has that fingerprint — this is now the primary, recommended form. A fold fingerprint that matches no consolidation group in a given department is a logged no-op there, not a failure, so one flag meant for only one department never stops a multi-department run. The standalone consolidate-languages command further below still refuses on the same typo — it has only one department's report to match against, so nothing else could explain a miss.

bash — real command, Zain run-all-departments 2026-09-22 (2 departments; fold applied to department 2's Social EN/AR quarantine group)
$node dist/cli.js run-all-departments --from-config .env.zain-base --open-program \
--consolidate-languages apply --skip-hub-backfill --max-workers 4 \
--approve-quarantine "social survey|2" \
--fold-sibling-question "social survey|2:ar:4->4,5,6"

Repair path — standalone consolidate-languages, per department

Use this only for QUARANTINE groups the run did not approve, when a run's consolidation was skipped (--consolidate-languages skip or report, or a department that failed before reaching it), or to re-run after the fact — it is not the normal path. Always pass --config with the department's own .env.

bash: repair — approve a QUARANTINE language merge with an operator-approved fold, one department at a time
$node dist/cli.js consolidate-languages --client <env> --config .env.<dept> --apply \
--approve-quarantine "social survey|2" \
--fold-sibling-question "social survey|2:ar:4->4,5,6" # real Zain example: Arabic Q4 fills English Q4/Q5/Q6
Launch run-all-departments with NODE_OPTIONS, not --import tsx (confirmed live, 2026-09-21)

run-all-departments starts each department as a new node dist/cli.js … process. The --import tsx you typed is not passed on to those children, so node --import tsx dist/cli.js run-all-departments … kills every child at startup with TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for …/packages/database/types/survey-follow-up.ts. The parent then reports E-RUN-ALL-PREFLIGHT-01: open-program via .env.1-<dept> (exit 1), … with --open-program, or E-RUN-ALL-PREFLIGHT-01: preflight dept N (exit 1), … without it. Nothing is written.

Fix: the children do inherit the environment. Inside the tmux session run export NODE_OPTIONS=--import=tsx, then launch plain node dist/cli.js run-all-departments …; a second --import tsx is not needed. Single commands (run, preflight, provision-departments) work with node --import tsx dist/cli.js. The TUI's All departments screen is not affected: it adds --import tsx to each child itself.

What scrolls past, in order:

  1. Running N department(s) in sequence — the detected list, each with its environment.
  2. The gate: open-program, then preflight --department N for every department, before any row is written. A problem that would stop the last department surfaces before the first one starts; a gate failure stops everything with nothing migrated (E-RUN-ALL-PREFLIGHT-01).
  3. Each department's own run: Phases 1–5, then the language consolidation. In Phase 3 the log names the plan, e.g. UnansweredInvitationResponse: 4 partitions, 4 workers.
  4. All N department(s) completed. A department failure stops the sequence (add --continue-on-failure to carry on) and names the department; recover that one alone with run --client <env> --config .env.<dept> --department N --resume.

What each flag is for:

  • --from-config — runs only the departments generated from this client's base config. Required when the registry also holds another client's departments, and harmless otherwise.
  • --open-program — opens the migration lease (idempotent; “Nothing to do” when already open).
  • --consolidate-languages apply — merges each survey's language copies at the end without prompting, so an unattended run never waits at a [y/N].
  • --approve-quarantine — commits the named QUARANTINE-bucket group(s) too (fingerprint match), same as on the standalone command; a fingerprint with no matching group in a given department just logs a no-op there.
  • --fold-sibling-question — repeatable, only valid alongside --approve-quarantine for the same fingerprint; supplies a sibling-language question's own text for named survivor slots so that language isn't left disabled. See 07c for the syntax.
  • --skip-hub-backfill — keep it. The in-run Hub push happens before language consolidation, so it would send response ids that consolidation merges away, and a second push cannot correct them. Push afterwards, per department: hub-backfill --client <env> --config .env.<dept>.
  • --max-workers 4 — runs Phase 3's largest table as 4 partitions at once. Leave it out and every department runs serial (the certified default).
Workers: measured on Zain-BH, September 2026 — read before raising the number

Department 2 (311,990 contacts, 1,595,798 responses) on the dev server: serial 1:00:00, 4 workers 39m16s. Phase 3 went from 21m55s to 9m08s (4 partitions at 930–960 rows/s each). Phase 2 is a single stream whatever the worker count (about 7½ minutes for 312k contacts), and the language consolidation at the end is single-stream too (about 20 minutes for 1.26M re-pointed responses) — it is now the longest part of the run.

The database CPU peaked at 96% during Phase 3 with 4 workers on that Burstable server, so more workers would not come free there. The connection pools do not yet size themselves from the worker count, so treat a worker run's time as “it completed”, not as a scaling benchmark.

Measured — full run-all-departments + fold, Zain-BH, 2026-09-22

The real command above (2 departments, --max-workers 4, source ~1.6M responses / 312k contacts, target Azure Postgres 17): 47m20s wall clock for the whole run-all-departments.

  • Department 1 (6 IVR surveys, 80 responses): about 4 minutes including preflight.
  • Department 2 (9 surveys, 1,597,317 responses, 312,156 contacts): 43m00s — Phase 1 lookups ~1m, Phase 2 entities ~6m, Phase 3 transactional ~10m30s, Phase 4 post-process ~22m30s, Phase 5 parity ~3m.

Language consolidation with the fold, run separately via the repair path below: 19m48s, almost all of it re-pointing the merged Call Center SMS pair's 1,257,679 responses.

Parity result for this run: 23 pass, 2 warn, 0 fail.

Measured figures for this dataset and this server — not a guarantee for a different client; see the worker-scaling note above for what changes with more/fewer workers.

Dry-run timing: budget for the unanswered-invitation lookup

The dry run of STC-BH's Consumer department (43,446 responses, 112,924 invitations read) took about 30 minutes on XIC-DEV-Machine-001 (2026-09-21). Most of that was the unanswered-invitation “answered lookup”: each statement scans CFMCustomerSurvey, because the source has no index on InvitationGUID. Budget a department's dry run accordingly before scheduling the real run.

Starting again from empty

A completed department cannot simply be re-run: preflight refuses a non-empty target, and that refusal is what stops a second run doubling the data. While the program is open (before retire), roll back one environment with $M rollback --client <env> --config .env.<dept> --dry-run, read it, then without --dry-run (10). After retire, reset the whole client with $M reset-client --from-config <base.env> (dry run), then --apply --confirm-org "<org>" (L10): it deletes the migrated rows and the department projects, restores the anchor project name, and archives the department entries, their .env files and the lifecycle state to .migrate/archive/reset-<time>/. It refuses unless the database census is zero.

bash
$$M run --client <env-id> --config <.env> # single-department source
If the process is killed

Simply re-run the same command with --resume. The checkpoint table records the last committed legacy_id per table. Migration continues from exactly that point.

bash: resume after interruption
$$M run --client <env-id> --config <.env> [--department N] --resume
bash: run a single phase only
$$M run --client <env-id> --config <.env> --phase 3

The progress bar shows rows processed per chunk (default 500). Large clients (CFMSurveyResponse rows above 500k) can take 4-6 hours for Phase 3. This is expected.

Concurrent locks. Only one migration per client environment runs at a time. A second invocation will immediately exit with "advisory lock held by another process."

v0.4+ — post-migration phases run automatically

As of v0.4, all post-migration steps (status mapping, timestamp restoration, structure + answer projection, and targeting backfill) run automatically at the end of migrate run. No additional scripts are required after the pipeline completes. See 07a Post-migration backfill for what runs automatically, manual re-run options, and recovery from a failed auto-run.

Performance tuning

The default --chunk-size=500 is balanced for typical office connectivity. Tune up or down based on bottleneck:

  • --chunk-size=1000: same-region VPN, fast PG, >200 Mbps. Cuts Phase 3 wall-clock by ~30%.
  • --chunk-size=500: default. Office VPN / colocated dev DB.
  • --chunk-size=100: slow network (residential, transit VPN), or memory-constrained workstation. Slower but smaller commits.

If Node OOMs during Phase 3, retry with NODE_OPTIONS="--import=tsx --max-old-space-size=4096" in front of the command and drop chunk size by half. Keep --import=tsx in it: a bare NODE_OPTIONS=--max-old-space-size=4096 prefix replaces an exported NODE_OPTIONS=--import=tsx, and the command dies with ERR_UNKNOWN_FILE_EXTENSION.

Inspect progress without interrupting

From any Postgres client, peek at the checkpoint table while the migration runs:

SELECT table_name, last_legacy_id, rows_processed, completed_at
FROM "_MigrationCheckpoint"
WHERE environment_id = '<client-env-id>'
ORDER BY started_at;

completed_at = NULL means the table is still in flight. The migrator commits checkpoint advances inside the same transaction as the data writes, so the number you read is always consistent.

Watch a run live over SSH

When the migration was started detached (nohup … &) on a remote box, these attach to it from your workstation. Both are read-only: the run is detached, so closing the SSH session — or Ctrl-C in it — cannot kill the migration.

Live progress feed — the human-readable per-phase ticker:

ssh -t -i <key.pem> <user>@<host> "tail -f ~/AG/run.err"

Numbers instead of prose — refreshes a counts/checkpoint report every 30s:

ssh -t -i <key.pem> <user>@<host> "watch -n 30 bash /tmp/track2.sh"

Plain shell to poke around by hand:

ssh -t -i <key.pem> <user>@<host>

Worked example (XIC-DEV rehearsal box, 2026-09-20):

ssh -t -i C:\Users\<you>\.ssh\XIC-DEV-Machine-001.pem ubuntu@63.181.26.135 "tail -f ~/AG/run.err"
  • -t is not optional for these. It forces a TTY, which is what tail -f, watch and any password prompt need; without it watch exits immediately.
  • Check the host octet-by-octet. A truncated address (…26.13 instead of …26.135) is a different machine, not an error — you can land on someone else's box and read the wrong run.
  • Paths are whatever the run used. ~/AG/run.err and ~/AG/run.ndjson are this rehearsal's; substitute your own. run.ndjson is the machine-readable event stream — grep phase_done it for per-phase durations and row counts.
  • /tmp/track2.sh is a helper script, not something the migrator ships. Write your own, or read _MigrationCheckpoint directly with the query above.
FlagDescriptionDefault
--clientREQClient environment identifier (the cuid in CLIENT_ENV in .env)CLIENT_ENV
--configoptPath to the .env file for this client (for a department: its own .env)reads env vars
--dry-runoptRun without committing any writesfalse
--resumeoptSkip guard check for non-empty target, resume from checkpointfalse
--phaseoptRun only a specific phase (1–5)all
--chunk-sizeoptRows per COPY batch. Lower for slow connections.500
--migrate-usersoptWrite legacy User/Membership rows. Off by default since b9b107b77 — see the callout below.false
--consolidate-languages <mode>optapply merges the AUTO_MERGE groups without asking; ask asks y/N on an interactive terminal (report-only elsewhere); report writes the report and merges nothing; skip writes no report. QUARANTINE groups merge only when named on --approve-quarantine; UNMERGEABLE never. Ignored (report only) on --dry-run. --consolidate-languages-apply and --skip-consolidate-languages are older aliases for apply and skip. See 07c.apply
--departmentoptMigrate only this legacy department (required on a multi-department source).whole tenant
--max-workersoptPhase 3 partitions at once. Other budget flags: --partition-target-rows, --audience-partition-target-rows, --max-source-load, --max-target-load, --placeholder-writer, --membership-writer.serial
Legacy users are opt-in now, for any client (migrator commit b9b107b77)

run and run-all-departments no longer write legacy User/Membership rows by default — new customers create their own accounts in HiveCFM. Pass --migrate-users (also toggleable in the TUI run panel) to restore the old behaviour unchanged. The source rows are still read either way, so the User: N rows log line and its fail-closed read guard are unaffected; the log now says the rows were read and not migrated.

Why: the migrated operators were unusable logins. On the live Zain dev target all 16 carried synthetic <name>-<legacyId>@<environmentId>.imported.local addresses, a null password and zero Account rows — none had ever signed in — and every re-run recreated them. They existed only to hold a Membership.

If this environment was migrated before this change, those users are still there. Remove them with a scoped delete — a user is safe to delete only if it carries a legacy_id and its only organization is the one being cleaned; deleting the User cascades its Membership. Never delete a user without a legacy_id (a real operator) or one that also belongs to another organization (a shared real person). On the dev target this removed exactly 16 users and their 16 memberships, leaving the 5 real operators and 56 other clients' migrated users untouched: Works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact.

-- Preview first — every row here is what the delete below would remove
docker exec hivecfm-postgres psql -U postgres -d hivecfm -c \
  "SELECT u.id, u.email, u.legacy_id FROM \"User\" u
     JOIN \"Membership\" m ON m.\"userId\" = u.id
    WHERE u.legacy_id IS NOT NULL
      AND m.\"organizationId\" = '<org-id-being-cleaned>'
      AND (SELECT count(*) FROM \"Membership\" m2 WHERE m2.\"userId\" = u.id) = 1;"

-- Deleting User cascades its (sole) Membership row
docker exec hivecfm-postgres psql -U postgres -d hivecfm -c \
  "DELETE FROM \"User\" u
    USING \"Membership\" m
    WHERE m.\"userId\" = u.id
      AND u.legacy_id IS NOT NULL
      AND m.\"organizationId\" = '<org-id-being-cleaned>'
      AND (SELECT count(*) FROM \"Membership\" m2 WHERE m2.\"userId\" = u.id) = 1;"
--dry-run really does write nothing now

It did not always. Until 2026-07-27 the dev-licence activation at the end of run sat outside the dry-run branch, so --dry-run — the command the TUI itself uses as its safety gate before unlocking Proceed — rewrote every organisation's tenant_license row in the target database with the repo-committed dev key. On a target shared by two clients that destroyed the other client's portal entitlements and freed their license_uid from the unique index.

Fixed in af0e7f761: the activation now runs only on a real migration, is scoped through Environment → Project → Organization to the environment being migrated, and refuses to overwrite any licence whose signature does not verify against the dev key — i.e. it never touches a portal-issued licence. If you are on an older checkout, do not point --dry-run at a database that holds another client's data.

07

Verify Parityrequired

Compares row counts between MSSQL and PostgreSQL and generates an HTML report. Run this after migration completes, and any time you want a status snapshot.

bash
$$M parity --client <env-id> --config <.env> [--department N] # --department must match the run's
expected output
Parity report: ist-serviceedge

  Table                        Source        Target        Status
  ───────────────────────────────────────────────────────────────
  CFMUser -> User                12,847        12,847        PASS
  CFMSurveyResponse -> Response 341,092       341,092        PASS
  CFMCustomer -> Contact        252,372       252,372        PASS
  channel_count_parity                -             -        PASS
  response_contact_backfill           -             -        PASS

  All checks passed. Report: reports/parity-<env>-<timestamp>.html

Table names shown here changed 2026-08-24: CFMSurveyInvitation, CFMCustomerOrg, and CFMDepartment no longer have a target-side counterpart to compare against (F8b New models), so they no longer appear as parity rows.

Surveys3 / 3
Responses3,179 / 3,179
ResponseAnswer4,371 / 4,371
KPI avg drift±0.000
FK orphans0
Schema diffempty
Parity passed: now find your data in the UI

Parity confirms rows landed in Postgres, but which environment they landed in is determined by CLIENT_ENV in your .env.<client> file. If you point the UI at the wrong env, the page is blank and there's no error, silent failure. Run this one-line sanity check, then build your URL from its output: Works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact.

bash · hivecfm-core/
$docker compose exec postgres psql -U postgres -d hivecfm -c 'SELECT "environmentId", COUNT(*) AS surveys FROM "Survey" WHERE legacy_id IS NOT NULL GROUP BY "environmentId";'

Expected: exactly one row whose environmentId matches the CLIENT_ENV in your .env.<client>. Copy that id and open: http://<host>:3000/environments/<that-id>/surveys. You should see all your migrated surveys with status badges, response counts, and human-readable dates.

Observation What it means & what to do
Query returns clseedenvprod000000000 (or any other clseed* id) Your CLIENT_ENV is pointed at a seed-data environment from packages/database/src/seed/constants.ts, not the real org you signed up with. The migrated rows are technically in PG but invisible to your real user. Fix: re-query for the real env id (SELECT id, "organizationId" FROM "Environment" ORDER BY "createdAt"), update CLIENT_ENV in .env.<client>. Rows are not moved between environments: migrator inserts skip rows that already exist (ON CONFLICT DO NOTHING). Roll back the wrong environment ($M rollback --client <wrong id> --config <.env> --dry-run, then without --dry-run; 10), then run into the right one.
Query returns an env id, but visiting /environments/<id>/surveys redirects to /auth/login or 403 You're signed in as a user who doesn't belong to that env's org. Log out, sign in with the email that owns the org (the one you created during signup), then revisit the URL. If you forgot which account owns it: SELECT u.email, o.name FROM "User" u JOIN "Membership" m ON m."userId"=u.id JOIN "Organization" o ON o.id=m."organizationId" JOIN "Project" p ON p."organizationId"=o.id JOIN "Environment" e ON e."projectId"=p.id WHERE e.id='<env-id>';
Query returns 0 rows or "relation does not exist" Migration never wrote anything to Survey, or the table doesn't exist yet. Re-check that migrate run printed Survey: N rows in Phase 2 (not 0 rows — skipped). If 0, the source DB query found no surveys, verify SOURCE_SURVEY_DB in .env.<client>.
Query returns multiple env ids (e.g., 2 with rows) A prior migration ran with a different CLIENT_ENV and you didn't truncate before changing it. Decide which env should own the rows, then either truncate the wrong one (DELETE FROM "Survey" WHERE "environmentId"='<wrong-id>' AND legacy_id IS NOT NULL;) or roll back the wrong environment with $M rollback --client <wrong-id> --config <.env> (10).

The naming gotcha: CLIENT_ENV looks like it should hold a slug like ist-serviceedge, but it's actually the target environment cuid (e.g., cmpa6qyqp0008p301k7mdo311). The --client CLI flag takes the same cuid, not a slug: a --client that differs from the config's CLIENT_ENV is refused with E-CLI-ARG-01. Keep CLIENT_ENV = cuid, and pass that same cuid to --client. hub-backfill (like preflight) checks the client before reading the config, so it needs --client or an exported CLIENT_ENV; only run, parity, delta and rollback may omit it.

A migrated survey's public link can't be opened anonymously — that's expected

Visiting a migrated Zain survey's /s/<id> link directly returns "Survey requires identification / This survey can only be taken via a personal invitation link" — migrated surveys require identification. Verify a migrated survey either through a real personal invitation link, or by replaying the stored survey row in a local player harness; a bare anonymous /s/<id> visit is not a valid test.

If parity fails: check → action

Do not proceed to cutover until parity passes. On the lifecycle path, verify runs delta + parity for you and shows each failing check with its fix (L5).

CheckWhat to do
row-count:… in the windowA real gap at or below the frozen line. Run $M delta … --department N and parity again; if it stays, read _MigrationAuditLog for transform errors and escalate.
row-count WARN: rows above the frozen linePending, not missing: the next delta (or finalize's final delta) takes them. No action.
contact_count_parity (missing contact)Escalate with the ids and the report. Do not reset, do not finalize.
contact_target_extrasCheck the ids in the source; if the live source deleted or re-pointed their usage, accept it (at most 50 per department): --accept-check contact_target_extras on the lifecycle.
response_contact_backfillAnother delta relinks them, or $M backfill-response-contact-attributes --client <env> --config <.env>, then parity again.
survey_channel_coverageSource surveys with no channel. Accept only if expected (--accept-check survey_channel_coverage, TUI [a]).
interrupted run (incomplete checkpoint)$M run --client <env> --config <.env> [--department N] --resume.
How to read the HTML parity report

The HTML report is saved to reports/parity-<client>-<timestamp>.html, next to a sidecar file the lifecycle reads. Read it on the box with less, or copy it off with scp. It has one section per check:

  • Row count. After a delta round, both sides are compared only up to the source line that round froze (Parity window: the latest round froze the source at …). A gap at or below the line FAILS. Rows above it are a WARN (pending): the live source took them after the freeze, and the next delta takes them. With no frozen line (no delta yet, or a StableRJB source) the old strict boundary applies.
  • Contacts. Two checks in department mode: contact_count_parity (every department customer at or below the line is a Contact; a missing one FAILS and can never be accepted) and contact_target_extras (every migrated contact is still a department customer; one the department no longer uses FAILS, and can be accepted up to 50 per department). Native contacts (no legacy id) are reported, never compared.
  • Response ↔ contact link (response_contact_backfill). Every run and typed-union delta relinks responses to contacts that arrived after them at the start of Phase 4, so this usually clears on the next round.
  • Sample field. 1000 random rows compared field-by-field; tolerance 0 for text/IDs, ±0.001 for numeric KPI fields.
  • FK integrity. Zero orphans required on every FK. Any orphan blocks cutover.
  • KPI aggregate. CSAT/CES/NPS/FCR averages per survey, tolerance ±0.001.
  • Schema diff. Listing of every non-additive change between source and target (should always be empty for v0.1.0).

Spot-check methodology: pick the 3 highest-volume tables and 1 random sample of 10 row IDs from the sample-field check; open both source and target rows side-by-side to manually verify the migrator did not silently truncate or re-encode a value.

07a

Post-migration backfillautomatic (v0.4+)

As of v0.4, all post-migration steps (status mapping, timestamp restoration, structure + answer projection, and targeting backfill) run automatically at the end of migrate run — Phase 2.5 (Repair) fires after Phase 2, and Phase 4 (Post-process) now includes the structure + Response.data projection plus the targeting backfill. Operators no longer need to remember any post-migration scripts. The legacy .cjs scripts and new migrate <subcommand> entry points remain available as manual re-run / debug paths — useful when a single phase needs to be re-run after a hotfix or when investigating a parity issue in isolation.

What runs automatically during migrate run (v0.4+)

Relink first. Every run and every typed-union delta starts Phase 4 by linking migrated responses that have no contactId to the Contact of the same customer when that contact arrived later (relinked N response(s) to contacts created after them …). $M backfill-response-contact-attributes --client <env> --config <.env> runs the same relink, then the contact-attribute snapshot, as a standalone repair. After retire it cannot relink (relink skipped: the provenance column(s) … are absent).

Inside migrate run, after Phase 2 entities are written, Phase 2.5 repairs Survey.status and Survey.created_at / updated_at from the source MSSQL. After Phase 3 transactional + Phase 4 KPI/MV refresh, the structure backfill builds Survey.blocks from CFMSurveyQuestion + CFMQChoice and projects ResponseAnswer.legacy_extras → Response.data. Finally, the targeting backfill creates a private Segment + one SurveyTrigger per App-type survey. All four steps are idempotent (safe to re-run via the manual entry points below).

Manual re-run / override (rarely needed)

Use these when an auto-run failed and you fixed the underlying issue, OR when you want to re-run just one phase in isolation. All idempotent.

$M repair-surveys --client <env> --config <.env>                        # Phase 2.5 manual re-run
$M backfill-survey-structure --client <env> --config <.env>             # Phase 4 structure + answers manual re-run
$M finalize-targeting --client <env> --config <.env> --apply            # Phase 4 targeting backfill manual re-run
$M backfill-response-contact-attributes --client <env> --config <.env>  # relink + contact-attribute snapshot

# Legacy entry points (shims forwarding to the subcommands above) — still work for runbook compatibility:
node scripts/repair-survey-status.cjs
node scripts/repair-survey-timestamps.cjs
node scripts/backfill-survey-structure-and-answers.cjs
node scripts/backfill-survey-targeting-and-triggers.cjs --apply
Recovery from partial migration

If migrate run crashed mid-pipeline (e.g. unhandled rejection in Phase 3, network blip), the _MigrationCheckpoint table may have stale completion markers for tables that were truncated. v0.4 auto-detects this — CheckpointAccessor.upsert() probes the target table; if empty but the checkpoint says completed, the checkpoint is reset inline. No operator action needed in the typical case.

If a resume still misbehaves, do not delete checkpoint rows by hand (that loses the resume point; see Troubleshooting → Partial checkpoint after a crash). Re-run $M run --client <env> --config <.env> [--department N] --resume, and if it still fails, roll back that environment (10) and run it again.

Symptoms diagnostic — if you see one of these in the editor, the corresponding auto-run failed and needs manual re-run:

Symptom Fix
Editor Settings tab throws "Invalid segment"; Save disabled $M finalize-targeting --client <env> --config <.env> --apply
Summary tab blank (no question cards, no response counts) $M backfill-survey-structure --client <env> --config <.env>
Survey list shows wrong status (all "Draft") or today's date for created_at $M repair-surveys --client <env> --config <.env>

Verify the auto-run completed correctly. Expected: every survey has non-zero q_count + b_count, status is one of {inProgress, completed, draft, paused}, created_at matches the real MSSQL date: Works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact.

bash · hivecfm-core/
$docker compose exec postgres psql -U postgres -d hivecfm -c 'SELECT id, name, status, jsonb_array_length(questions) AS q_count, array_length(blocks, 1) AS b_count, created_at::date FROM "Survey" WHERE legacy_id IS NOT NULL ORDER BY legacy_id;'
Not a migration bug: missing “Preview” button on the surveys list

The Preview action in the survey-row dropdown only renders for type='link' surveys (upstream Formbricks gate at survey-dropdown-menu.tsx:188: survey.type === "link" && survey.status !== "draft"). HiveCFM customer surveys land as type='app', so Preview never appears on the list. This is intentional — do not investigate as a migration regression.

HiveCFM Hub backfill automatic (Phase 6)

As of v0.5, Hub backfill auto-runs as Phase 6 of migrate run when HIVECFM_HUB_URL and HIVECFM_HUB_API_KEY are set. When unconfigured, the phase emits a critical banner and migrate run exits with code 2 (signal-not-failure — Phases 1–5 still completed). Use --skip-hub-backfill to suppress the banner for clients without Hub (the lifecycle always does, and pushes in its own hub-backfill stage, L6). Manual re-run: $M hub-backfill --client <env> --config <.env>. A re-push is safe only while the data is unchanged: the Hub answers records it already holds with 409 and never updates them, and after a QUARANTINE merge a re-push adds duplicates.

Hub tenants are organizations; a UI-signup organization is registered only when the container starts. The core container's apps/web/scripts/docker/next-start.sh registers every existing Organization with the Hub (POST /v1/tenants) when hivecfm-core starts, so an organization created by UI signup after that is not registered until the container restarts. An organization created through the management API (POST /api/v1/management/tenants) is registered with the Hub at creation. Phase 6 / hub-backfill does not depend on that registration: Hub feedback_records has no foreign key to a tenant table. If you need Hub-side tenant features, restart hivecfm-core after signup.

Status: v0.5 (current) — all five post-migration steps (Phase 2.5 Repair, Phase 4 Structure + Targeting, Phase 6 Hub backfill) auto-run during migrate run. Use --skip-repair, --skip-structure-backfill, --skip-targeting-backfill, or --skip-hub-backfill on the CLI to disable individual phases for debugging. Plan reference: docs/superpowers/plans/2026-05-21-migrator-hub-backfill-phase6.md.

Classic web surveys with skip logic — one page, not one question per page

A legacy "classic" (DisplayMode 1) survey on the web channel that carries skip logic is migrated as one block (one Hive page) whose jumpToElement rules branch between its own questions, instead of one question per page. Verified against the real survey player, three differences from the legacy system are documented here rather than worked around:

Voice/IVR, popup, kiosk, in-chat, WhatsApp, in-app and embedded-popup surveys are unchanged: the old system rendered those one question at a time regardless of DisplayMode, so today's one-question-per-page migration output for them already matches legacy. The channel is resolved from the legacy SurveyTypeID / CFMSurveyType catalog, never guessed from traffic — see Troubleshooting · E-STRUCT-CHANNEL-01 for what happens when it can't be resolved.

07b

Manual spot-check (OLD ↔ NEW)verification

Parity (step 07) is the authoritative proof, but stakeholders often want to eyeball a single value or the five head-line counts by hand. Run the OLD query against the legacy MSSQL and the NEW query against Postgres, then confirm they match. Every query is self-contained — copy, run, compare. Reference numbers shown are from the StableRJB migration (env cmpjx0yug…); your own counts will differ, but OLD must equal NEW.

Which database is which

OLD (source of truth): legacy SQL Server at <source host>:1433. For the ISTServiceEdgeOld variant the customer & survey tables live in the Survey DB (e.g. HiveCFMSurveyDBStableRJB), not the App DB — querying CFMCustomer in the App DB throws Invalid object name 'CFMCustomer'. Run OLD queries in Superset → SQL Lab (pick the Survey-DB connection) or in SSMS / sqlcmd. If your SQL Lab connection already defaults to the Survey DB you can drop the [HiveCFMSurveyDB<client>].[dbo]. prefix.

NEW (target): the migrated Postgres. Enter psql with docker compose exec postgres psql -U postgres -d hivecfm, then paste the SQL. Replace the \set env value with your target environment cuid (the CLIENT_ENV from .env.<client>).

A · Head-line count reconciliation

Five numbers must match one-for-one. Surveys & questions on the NEW side are filtered to legacy_id IS NOT NULL so an app-created survey doesn't inflate the total. Works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact.

SQL · OLD legacy (Survey DB) · Superset SQL Lab / SSMS
SELECT COUNT(*) AS contacts  FROM CFMCustomer;               -- expect 252,372
SELECT COUNT(*) AS surveys   FROM CFMSurvey;                 -- expect 692
SELECT COUNT(*) AS questions FROM CFMSurveyQuestion;         -- expect 3,531
SELECT COUNT(*) AS responses FROM CFMCustomerSurvey;         -- expect 1,087
SELECT COUNT(*) AS answers   FROM CFMSurveyQuestionResponse; -- expect 3,161
SQL · NEW Postgres · paste into psql
\set env 'cmpjx0yug000boiezjj412h8x'   -- replace with your CLIENT_ENV
SELECT count(*) AS contacts  FROM "Contact"  WHERE "environmentId"=:'env';
SELECT count(*) AS surveys   FROM "Survey"   WHERE "environmentId"=:'env' AND "legacy_id" IS NOT NULL;
SELECT count(*) AS responses FROM "Response" r
  JOIN "Survey" s ON s.id=r."surveyId" WHERE s."environmentId"=:'env';
SELECT count(*) AS answers   FROM "ResponseAnswer" ra
  JOIN "Response" r ON r.id=ra.response_id
  JOIN "Survey"   s ON s.id=r."surveyId" WHERE s."environmentId"=:'env';
SELECT count(*) AS questions FROM "Survey" s
  CROSS JOIN LATERAL unnest(s.blocks) AS b(block)
  CROSS JOIN LATERAL jsonb_array_elements(coalesce(b.block->'elements','[]'::jsonb)) AS e(elem)
  WHERE s."environmentId"=:'env' AND s."legacy_id" IS NOT NULL;
Entity OLD table (legacy) NEW table (Postgres) StableRJB ref
ContactsCFMCustomerContact252,372
SurveysCFMSurveySurvey (legacy_id ≠ null)692
QuestionsCFMSurveyQuestionSurvey.blocks[].elements[]3,531
ResponsesCFMCustomerSurveyResponse1,087
AnswersCFMSurveyQuestionResponseResponseAnswer3,161

Verify: each OLD number equals its NEW number. Expected drift: NEW Survey total may read one higher (e.g. 693) than OLD CFMSurvey (692) — that extra row is a native app-created survey with legacy_id IS NULL; the legacy_id ≠ null filter above removes it. If a migrated count is short: see step 07 — re-run parity, check _MigrationAuditLog for the last legacy_id, resume with --resume --phase=3. Invitations (0 vs 2,448) and touchpoints (0 vs 498) are intentionally skipped for this variant — not a count failure.

B · Single-record spot-check

Pick any value a stakeholder recognises — here a phone number, 502987999 — and prove the same record exists on both sides. The NEW Contact.legacy_id equals the OLD CFMCustomer.ID; that's the join key. Works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact.

SQL · OLD legacy (Survey DB)
SELECT ID, Name, Phone, CustomerIdentifier, UserCIC, BirthDate, Gender, IsAnonymous, Email
FROM   [HiveCFMSurveyDBStableRJB].[dbo].[CFMCustomer]
WHERE  Phone = '502987999'
ORDER  BY ID;
SQL · NEW Postgres · paste into psql
SELECT c."legacy_id", ak.key, ca.value
FROM   "Contact" c
JOIN   "ContactAttribute"    ca ON ca."contactId" = c.id
JOIN   "ContactAttributeKey" ak ON ak.id = ca."attributeKeyId"
WHERE  c.id IN (SELECT "contactId" FROM "ContactAttribute" WHERE value = '502987999')
ORDER  BY c."legacy_id", ak.key;
NEW attribute key OLD column (CFMCustomer)
Contact.legacy_idID
name / firstName / lastNameName (split on first space)
phoneNumberPhone
userIdCustomerIdentifier
userCICUserCIC
birthDate · gender · isAnonymousBirthDate · Gender · IsAnonymous
emailEmail (NULL → attribute omitted)

Expected for 502987999: 5 rows OLD and 5 contacts NEW, with the same legacy IDs 62162, 82713, 142411, 201940, 261514, all named Ahlam Almarwani. The phone repeats because the legacy CRM holds five separate customer records for the same person; the migrator preserves them 1:1 by ID — it does not merge. Confirm the leading-zero UserCIC = 0000000006320271 survived as a string (not coerced to 6320271) — that's the classic silent-corruption trap.

C · Question-type fidelity

Legacy CFMSurveyQuestion.QuestionTypeID (named in CFMQuestionType.TypeName) maps to a Formbricks element type per backfill-survey-structure.ts. Run both distributions and reconcile against the table. Works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact.

SQL · OLD legacy (Survey DB)
SELECT qt.ID, qt.TypeName, COUNT(*) AS cnt
FROM   CFMSurveyQuestion q
JOIN   CFMQuestionType  qt ON qt.ID = q.QuestionTypeID
GROUP  BY qt.ID, qt.TypeName
ORDER  BY qt.ID;
SQL · NEW Postgres · paste into psql
\set env 'cmpjx0yug000boiezjj412h8x'   -- replace with your CLIENT_ENV
SELECT e.elem->>'type' AS type, count(*) AS cnt
FROM   "Survey" s
CROSS JOIN LATERAL unnest(s.blocks) AS b(block)
CROSS JOIN LATERAL jsonb_array_elements(coalesce(b.block->'elements','[]'::jsonb)) AS e(elem)
WHERE  s."environmentId"=:'env' AND s."legacy_id" IS NOT NULL
GROUP  BY 1 ORDER BY 2 DESC;
NEW type Legacy QuestionTypeID (TypeName) OLD = NEW
nps8 (nps)629
rating6 (slide), 7 (star), 16 (emoji), 19 (csat), 21 (ces), 22 (numcsat), 23 (numces)1,470
multipleChoiceSingle3 (twochoices), 4 (list), 15 (singleCh), 18 (imgSingle), 20 (fcr)678
multipleChoiceMulti2 (mcq), 17 (imgMcq)283
openText5 (date), 9 (txtinput), 10 (numinput), 11 (emailinput), 12 (teleinput), 13 (postinput), 14 (urlinput), 24 (thumbsfcr), 25 (thumbscsat), 26 (thumbsces)471
Total3,531

Verify: the NEW distribution equals nps 629 / rating 1,470 / multipleChoiceSingle 678 / multipleChoiceMulti 283 / openText 471 (sum 3,531). Documented, expected mappings (not bugs): the three thumbs* types (24/25/26) and date (5) have no Formbricks equivalent and fall through to openText via the default branch; rating.scale/range (star/smiley/number, 1–10) is derived from CFMSurveyQuestion.Scale. If a type total is off: re-run the structure backfill (step 07a) — it rebuilds Survey.blocks idempotently from the legacy questions.

If OLD ≠ NEW

A genuine mismatch (after excluding the documented gaps above) means rows are missing or in the wrong environment. Do not proceed to cutover. Re-run step 07 parity for the authoritative table-by-table verdict, confirm CLIENT_ENV points at the right environment cuid (step 07's env sanity check), then resume the affected phase with --resume. Re-run this spot-check until OLD = NEW.

07c

Language consolidation

Merge per-language survey siblings into a single multi-language Hive survey. Reversible.

The base migrate run imports each legacy language variant as its own survey (1:1 import — no data loss). This step identifies groups of surveys that are the same instrument in different languages (matched by name stem, not structure), merges them into one multi-language Hive survey with a language switcher, and re-points all historical responses to the merged survivor. Merging is reversible via unmerge-languages until the separate, irreversible finalize step (Step 4) runs.

run already merged the AUTO_MERGE groups: this section is for QUARANTINE

The default --consolidate-languages mode is apply, and the lifecycle run stage passes apply: the run merges AUTO_MERGE groups itself. Come here only for QUARANTINE groups (or to re-run). Do it per department, before hub-backfill (a merge after a Hub push re-keys records, and any later push adds duplicates) and before retire (after retire nothing can be merged). The Lifecycle quarantine count is not updated by a merge here. TUI: select the department (Environments → [x] on the client row → the department), Menu → consolidate-languages: the first enter is a dry run; [a] arms the QUARANTINE fingerprints from that dry run; the second enter applies with no typed confirm; [b] options; [p] does nothing (read the report with less reports/consolidation-<env>-*.md). See L4.

migrate run can now do the AUTO_MERGE part for you

Since 2026-07-27, run always writes the consolidation report and then decides what to do about it rather than just telling you to come back later:

ContextBehaviour
default (--consolidate-languages apply)commits AUTO_MERGE without asking, in any context
--consolidate-languages asky/N on an interactive terminal; report only in a pipe, CI or the TUI
--consolidate-languages reportwrites the report, merges nothing
--consolidate-languages skipno report at all (--skip-consolidate-languages is an alias)
--dry-runreport only, whatever else was passed

QUARANTINE could not be committed from run before — as of migrator commit 914d42d15, passing --approve-quarantine (and, per group, --fold-sibling-question) to run or run-all-departments commits that fingerprint too, in the same command; see 06 · step 2b for the real Zain invocation. UNMERGEABLE still never merges. The standalone command below is now the QUARANTINE / repair path — used for QUARANTINE groups the run did not approve, when a run's consolidation was skipped (skip or report mode, or a department that failed before reaching it), or to re-run after the fact. Run it per department with that department's --client and --config.

Why it asks rather than simply doing it: unlike the additive post-phases, this merge is a fingerprint-matched heuristic that archives the donor and re-points every one of its responses. Response totals are conserved whether the match was right or wrong, so a bad merge appears in no row count — the report is the only place it is visible. On the ZainBahrain validation run 3 of 5 groups were safe to merge unattended and 2 were not.

Step 1 — Dry run (inspect decisions, no writes)

shell
$M consolidate-languages --client <dept env id> --config <dept .env>
ExpectedPrints a report with 3 decision buckets: AUTO_MERGE (committed on --apply), QUARANTINE (needs --approve-quarantine), UNMERGEABLE (never committed — left as separate surveys). No DB writes.
Identity & survivorSiblings are grouped by NAME STEM + DepartmentID (language token stripped), not by structure. The survivor is the UNION-MAXIMAL member (most questions, tie → en) — not always the English row. Whoever has the most questions can hold default-key text for all of them, which is what makes the merge representable at all.
Three axes, three decisionsContent coverage decides SurveyLanguage.enabled only. Alignment confidence decides AUTO_MERGE vs QUARANTINE. Response-bearing loss decides UNMERGEABLE. They never cross: a low-confidence pairing never silently flips a language's serving state.
AUTO_MERGEEvery question pairs unambiguously — OR a sibling covers FEWER questions (gaps written as code:"", that language attached enabled:false, reported as "N matched, M unmatched" — never "translated": alignment compares shape, not meaning) — OR a sibling holds a question the survivor lacks but it carries NO responses (merge proceeds with a warning; the gate for that loss moves to Step 4).
An ambiguous pairing (two positions share a signature, so order — not evidence — picked it) also does not block the merge when the guessed position holds no responses: that language's text is simply withheld there (legacyExtras.unplacedTranslations), never guessed.
QUARANTINEAn ambiguous pairing whose guessed position HOLDS responses (approving would file real answers under the wrong question) — or discarded branching/required-ness differs on a paired position (the survivor's rule is kept, the sibling's dropped). Approve with --approve-quarantine <key> after reading the per-question title lines in the report.
UNMERGEABLENo question in common with the survivor at all; a language code repeats in the group (not translations); or a sibling holds a question the survivor lacks AND it carries responses — merging would leave those answers keyed to a question that doesn't exist. No flag commits an UNMERGEABLE group.

Step 2 — Apply (commit AUTO_MERGE + approved QUARANTINE groups)

shell
$M consolidate-languages --client <dept env id> --config <dept .env> --apply \
  --approve-quarantine "<group-key-1>,<group-key-2>"
ExpectedFor each committed group: assembles per-position i18n blocks (withholding any unjustifiable guessed text), sets SurveyLanguage.default/enabled per the coverage rule, turns on showLanguageSwitch only when >1 language ends up complete, re-points sibling responses to the survivor, archives originals (status:"draft" + legacyExtras.mergedIntoSurveyId +, where relevant, unfoldedQuestions/unplacedTranslations). Prints N merged · M responses re-pointed.
Disabled languageA language attached with incomplete coverage is enabled:false — it STOPS being served until someone finishes the missing translations in the editor. If that language is currently live, tell the client before applying.
VerifyOpen the survivor in Hive admin → no validation error on load → language dropdown lists only the merged languages → switching language shows the right text on the right question (not the previous language's text bleeding through) → response total for the environment is unchanged.
If ZSurvey validation failedThe assembled survivor failed the Hive schema check; the message names the exact field + language (seen live: an ending card with only English text; a null welcomeCard). The group is skipped, not committed. Fix the named field on the survivor in the editor, then re-run.
--fold-sibling-questionRepeatable, and only valid together with --approve-quarantine for the same fingerprint: --fold-sibling-question "<fingerprint>:<languageCode>:<siblingPos>-><survivorPos>[,<survivorPos>…]" (1-based question positions). Makes the named sibling-language question's own text fill the listed survivor slots — nothing is invented and nothing is machine-translated. If a survivor field can't be filled from the sibling, the group is reported incomplete and that language is left disabled, same outcome as an unapproved QUARANTINE group.

Real example — Zain Social EN/AR:

shell
$M consolidate-languages --client <dept env id> --config <dept .env> --apply \
  --approve-quarantine "social survey|2" \
  --fold-sibling-question "social survey|2:ar:4->4,5,6"

The Arabic survey's single general follow-up question (position 4) supplies the Arabic text for the English survey's three branch-specific follow-ups (positions 4, 5, 6), so Arabic stays selectable.

Step 3 — Unmerge (reverse a merge, if needed — before Step 4 only)

shell
# Get the survivorId from the dry-run report, then:
$M unmerge-languages --config <dept .env> --survivor-id <survivorId>
ExpectedRestores survivor blocks/welcomeCard/endings/name from the structural snapshot, re-points all responses back to their original sibling surveys with original language, restores each sibling to its pre-merge status, drops the survivor's extra SurveyLanguage rows, turns showLanguageSwitch off.
Once Step 4 has runUnmerge can no longer reverse that merge — the sibling rows it needs are deleted. Do not run Step 4 until the merges it covers are verified.

Step 4 — Finalize (permanently delete merge remnants — IRREVERSIBLE)

Only run once the merges above are verified

This step permanently deletes the archived sibling surveys. Until it runs they still render in the survey list, inflate the "Draft" counter, and consume the client's licensed survey quota — but they are still there, and unmerge-languages still works. After this step, it doesn't.

shell
$M finalize-consolidation --client <dept env id> --config <dept .env>
Expected (dry run)Lists each remnant that would be deleted with its response count. No writes.
Two fail-closed guards1) A remnant still holding RESPONSES refuses the whole run — it would be the only copy of that data. No override, ever.
2) A remnant stamped legacyExtras.unfoldedQuestions (a question the survivor never received) also refuses the whole run, printing each question's wording so it is recoverable from the log — author it on the survivor and re-merge, or override with --accept-question-loss (destroys those questions permanently).
unplacedTranslationsNot a refusal — the question survives on the survivor, only one language's wording for it was withheld (Step 1/2's ambiguity rule). Finalize WARNS and prints the text so it can be re-applied by hand, then proceeds.
shell
$M finalize-consolidation --client <dept env id> --config <dept .env> --apply
ExpectedDeletes every remnant that passed both guards. Prints deleted N merge remnant(s). Reload the survey dashboard — the archived rows are gone, Draft count drops, response total is unchanged.
If exit 1Nothing was deleted — fails closed for the WHOLE run rather than half-finalizing. Read the named remnant(s) and reason (responses vs. unfolded questions) before retrying.
07d

Quiz score backfill

Stamp historical quizScore from legacy TotalSurveyScore; enable native Hive scoring on quiz surveys.

128 surveys in StableRJB use IsQuizeMode=1. The migrator maps their question weights (QScore), choice scores (ChoiceScore), and max possible score (MaxScore) onto native Hive scoring fields during migrate run. This step then backfills Response.quizScore for all pre-existing responses from the legacy TotalSurveyScore column.

Check before use: backfill-quiz-scoring is not a registered command on this branch

The 30 top-level commands on fix/noref-tui-run3-operator-defects @ 4d6f7fe8e do not include backfill-quiz-scoring, so the commands below fail with an unknown-command error on this build. Run $M --help on the box; if it is not listed, do not improvise a replacement: report it to the migration owner.

Additive schema — apply the Prisma migration first

The scoring columns are added by a Prisma migration. Apply it once on a fresh target before running the backfill:

shell
cd packages/migrator
pnpm prisma migrate deploy

Dry run (gap report)

shell
$M backfill-quiz-scoring --client <env> --config <.env> --dry-run
ExpectedPrints count of responses that would be stamped. Should report 0 missing scores if migrate run already completed Phase 3 (responses backfilled).

Apply

shell
$M backfill-quiz-scoring --client <env> --config <.env>
ExpectedStamps Response.quizScore from legacyExtras.totalSurveyScore for all responses in quiz surveys. Prints stamped count.
VerifyRun $M parity --client <env> --config <.env> — the quiz_score_parity row should show PASS (or WARN if a small % of legacy rows had NULL TotalSurveyScore).
If quiz_score_parity shows WARNExpected when some legacy responses have TotalSurveyScore IS NULL (partial quiz submissions). WARN means <5% gap — acceptable. FAIL (≥5% gap) requires investigation: check Response.legacyExtras.totalSurveyScore on a sample of affected rows.
New responses score automatically

After the backfill, any new response submitted through Hive on a quiz survey will have quizScore computed on submit using the migrated scoreWeight/score fields. The score algorithm is a 1:1 port of the legacy C# ScoreCalculator. DEFERRED: the back-office editor UI for adjusting per-question weights and per-choice scores is tracked as task #49 — existing weights migrated from legacy are correct, just not yet editable in the UI.

08 / 09 / 10 / 11Cutover
08

Go Live: Cutover Checklistdanger

The maintenance window. Target: under 1 hour. MSSQL stays read-only for 30 days afterward.

Parallel-run strategy. The full bulk migration happens 7 days before cutover (T-7d), with the legacy app still live. During that week, users keep writing to MSSQL; Postgres accumulates a snapshot. At T-0 the legacy app is set read-only (operator action, outside this tool), then the lifecycle's finalize stage runs one final delta per department that picks up the rows written since verify, in minutes. This is what keeps the user-visible window under an hour even for clients with 500k+ responses.

Why DNS-flip is last. Read-only freeze stops new MSSQL writes. Finalize's final delta + parity confirm Postgres is current. Only then does the DNS / load-balancer change route user traffic to the new platform. If parity or smoke fail, the DNS still points at MSSQL and you have not gone live. The rollback path is only needed if traffic has been served from PG.

T−60min
Preflight
T−7d
Bulk migration (legacy still live)
T−0
Read-only freezeDeltaParityDNS flipSmoke test
T+30d
MSSQL read-only retention
T–60 min
Ready check

On the Lifecycle screen every stage up to hub-backfill is ✓ or » and every department reads verified yes ($M lifecycle --from-config <base.env> --status). QUARANTINE groups are merged (L4).

T–0: Maintenance window open
Stop writes to the source

The cutover owner sets the legacy application read-only (outside this tool).

T+5 min
Lifecycle finalize

Press enter on finalize (L7): preview, confirm, then for every department one final delta + parity, a second Hub push where pushed, and finalize-staging --apply. If it refuses with Not finalized: the source is still taking writes, the source is not stopped: stop it and press enter again (or, only if accepted, [o] accept-live-tail). A parity failure here is handled as in L5.

T+15 min
Switch traffic to PostgreSQL

First record the cutover start, which rollback needs: CUTOVER_START=$(date -u +%Y-%m-%dT%H:%M:%SZ). Then point the client's app / DNS at the new platform (outside this tool). Redeploy.

T+20 min
Smoke test

Load the client's survey list, open a recent response, verify KPI widgets show data.

Before retire
Delete the merge remnants

The run merged each language pair by itself (--consolidate-languages defaults to apply), but the archived sibling surveys are still there as draft rows — they render in the client's survey list, inflate the Draft counter and consume the licensed survey count. Nothing in run or in the lifecycle deletes them: Step 4 — Finalize is the only thing that does, and it is never run for you. Dry-run it first; it refuses the whole run if any remnant still holds responses. It must run before retire — retire drops Survey.legacy_extras, the column finalize-consolidation reads to find remnants, so afterwards it aborts on the provenance-columns check and those drafts can no longer be removed by the tool at all.

After the rollback window
Export · retire · census

Once you are sure you will not roll back (10 works only before retire), run the export, retire and census stages (L8). Retire is database-wide and irreversible.

T+30 days
Decommission MSSQL

After 30 days with no rollback events, the source MSSQL is decommissioned. The 4-hour rollback window expires after cutover; from that point, only the 30-day read-only window applies.

Finalizing by hand does not check the live source

finalize-staging and retire-migration-program run outside the lifecycle do not run a final delta and do not check for rows the source took after verify. Only the lifecycle's finalize stage does. On the manual path, stop source writes, run $M delta … --department N and $M parity … --department N for every department yourself, then finalize.

Save the cutover timestamp

You will need CUTOVER_START if you need to rollback. Write it down or save it to a shared doc before closing the maintenance window.

09

Delta Sync

Copy the source rows added since the run into the target, per department. The lifecycle runs it in every verify round and in finalize.

On the lifecycle path you do not run this by hand

Every verify round and finalize's final delta run exactly this command per department (L5, L7). Run it by hand only on the manual path.

bash: catch up one department (the normal form)
$$M delta --client <dept env id> --config <dept .env> --department N
$$M parity --client <dept env id> --config <dept .env> --department N # optional: the delta already ran parity and wrote the report
  • --since is normally omitted. The floor is the per-entity boundary the run recorded. Pass --since <UTC ISO time> (or a bare id with --strategy id) only to re-read an older window on purpose.
  • --department and --config are required for a department, and must be the same values its run used. Without --department a delta on a multi-department source is refused (E-DELTA-SCOPE-01) and writes nothing; pass the same --department the run used.
  • Frozen lines. A typed-union (ISTServiceEdge) delta first freezes the source (Delta: freezing this round's source high-water marks …); the following parity compares up to those lines and reports newer rows as pending.
  • Relink. It links responses to contacts that arrived after them (Phase 4).
  • E-DELTA-PLAN-OPEN-01 (the initial load is not finished): run $M run --client … --config … --department N --resume with the same --max-workers as the original run, then the delta again. The lifecycle does this by itself once.
  • E-DELTA-HWM-01 (the source's newest id is below what this environment already migrated): check --department and --config first. If they are right, the source lost rows (restore, deletion, or a survey moved department). It is a real divergence; no flag gets past it. Do not finalize; escalate.
  • A StableRJB delta reads WHERE LastModifiedDate > @since and freezes no line, so its parity keeps the strict boundary.
10

Emergency Rollbackdanger

Reverses new writes made to MSSQL during the cutover window. The 4-hour window is a hard limit. The command refuses after that.

Only while the migration program is open (before retire)

rollback needs the provenance columns to tell migrated rows from native ones. Retire drops them, so after retire it refuses with E-PROV-01. For a retired client the only way back is reset-client (L10), before go-live. Modes: full teardown of one environment (no --cutover-start), --audiences (audience artifacts only), and cutover replay (--cutover-start <ISO>, within 4 hours). The TUI Rollback screen has the same three modes ([1] [2] [3], [p] dry-run, [x] confirm), but its dry-run impact list is always empty: run $M rollback --client <env> --config <.env> --dry-run in a shell to see what it would do.

Use only within 4 hours of cutover

After 4 hours the rollback command exits with refused: cutover window expired. This is intentional. Data written to Postgres after the window cannot be safely reverse-replayed without a full audit.

Show emergency procedure Reveals the rollback command, scope, and step-by-step procedure. Only expand if you are within the 4-hour window and have a confirmed regression.
bash
$$M rollback --client <env-id> --config <.env> --cutover-start <CUTOVER_START, UTC ISO> --dry-run
$$M rollback --client <env-id> --config <.env> --cutover-start <CUTOVER_START, UTC ISO>
Run with --dry-run first

Always preview the replay scope before writing. Adding --dry-run to the command above prints exactly which rows would be inserted into MSSQL and which would be flagged as conflicts. No side effects.

Why 4 hours?

FR-023. The replay logic in packages/migrator/src/reverse/replay-cutover-window.ts reads every Postgres row written between --cutover-start and now, then INSERTs/UPDATEs back into MSSQL. The 4-hour cap bounds the scope so that the worst-case replay completes in <30 min (FR-022) and so that schemas don't have time to drift on either side.

Recoverable scope

  • Rows in Response (joined against Survey) written between T-0 and the rollback moment. (Older guide versions also listed ResponseAnswer and Invitation here — checked against packages/migrator/src/reverse/replay-cutover-window.ts directly: it only ever touches Response/Survey. Invitation no longer exists as of 2026-08-24 anyway — see F8b New models.)
  • For rows with a legacy_id: conflict logged (conservative; does not overwrite MSSQL).
  • For new rows (no legacy_id): inserted into MSSQL SurveyDB, Postgres legacy_id updated.
  • NOT reversed: schema changes (the additive Prisma migrations stay), materialized view refreshes, KPI computations.

What's lost after 4 hours

The ability to bulk-replay back to MSSQL. Manual data extraction is still possible (SELECT from PG, INSERT to MSSQL via hand-written SQL), but the tool will refuse. The MSSQL retention is also why 30-day archive matters separately from rollback; it preserves the source data even after the rollback window closes.

Procedure

  1. Run with --dry-run, confirm the row counts look right.
  2. Run without --dry-run (sample stdout: Replayed 1,204 rows; 3 conflicts logged; window 47 min of 240 min remaining).
  3. Flip DNS / DATABASE_URL back to MSSQL.
  4. Redeploy the app pointing at MSSQL.
  5. Smoke-test the rollback (open a recent response, file a fresh ticket in your tracker noting the rollback timestamp).
11

30-day MSSQL archive

Distinct from rollback. Audit/historical lookup only. Not a sync mechanism.

After cutover, the legacy MSSQL instance stays online in read-only mode for 30 days (FR-038). Superset disconnects from MSSQL the same day as cutover (FR-039); the 30-day window is for ad-hoc operator SQL and audit lookups, not for end-user dashboards.

This is independent of the FR-023 rollback window. Rollback closes at T+4h (and is impossible after retire); the archive stays accessible for the full 30 days. A Hub push ([h] on the Lifecycle screen, or hub-backfill) still works after retire. No automatic sync happens during this period. Any writes to Postgres do not flow back, and any reads from MSSQL are stale by definition.

calendar reminder template
Subject: Decommission MSSQL for <client> — 30-day archive close

Pre-checks:
  [ ] Latest parity report still passes
  [ ] No production reads from MSSQL in the last 7 days (check VPC flow logs)
  [ ] No open support tickets referencing legacy data

Actions:
  [ ] Final SQL dump archived to S3 bucket: s3://hivecfm-archives/<client>-final.bak
  [ ] Power down MSSQL instance (do not delete VM for 60 days)
  [ ] Update internal runbook: <client> is fully on Postgres
  [ ] Notify support team
11b

Program retirement & staging-table lifecyclereference · irreversible · database-wide

On the lifecycle path, the verify → hub-backfill → finalize → export → retire → census stages do everything below, with the final delta, the Hub re-push, the live-tail guard and a preview before each irreversible stage (L7, L8). This section is the reference for what finalize-staging and retire-migration-program do, why they exist as two separate commands, and the incident that made the split necessary. Read this before finalizing your first tenant on a shared database, not after your second tenant gets blocked by your first.

Manual step: confirm this is in your deployed build first

This subsystem is on fix/noref-tui-run3-operator-defects @ 4d6f7fe8e. What still needs checking is the build on the box: run $M retire-migration-program --help and $M lifecycle --help before relying on anything below.

The incident this fixes

On 2026-08-24, three Prisma migrations authored for Zain-BH's closeout ran against the shared hivecfm database (full detail: F8b New models). Two of them dropped 7 tables the migrator's own phases depend on. Less than a week later, STC-BH tried to migrate into the same database: Phase 3 crashed immediately, because ResponseAnswer, which Phase 3 unconditionally requires, no longer existed.

Why this was structural, not a one-off mistake: the finalize command that ran during Zain-BH's closeout was database-scoped. Finalizing any one tenant dropped every staging table, locking out every future tenant, by design of the wrong scope. The fix below splits "this one tenant is done" from "the entire migration program is retired forever" into two separate, independently-gated commands.

The table below is a dated snapshot, not current state

These are the values observed live on 2026-08-31, before the lease redesign. They are kept because they are the evidence that the 2026-08-24 incident was real and live, not merely documented. Read them as history: the last row's _migrator_finalized no longer exists anywhere in the code — see The lease model below for what replaced it. Re-probe your own database rather than trusting this table for anything operational.

Checked live 2026-08-31 (Container Apps Job, to_regclass())Result
The 7 tables the 2026-08-24 incident dropped (Invitation, Department, Touchpoint, TouchpointType, LegacySurveyKind, CustomerOrg, SurveyChannel)All 7 confirmed absent. The incident is real and live, not just documented.
Response.answered_questions_count columnConfirmed present. The current invitation/response discriminator (subsection F8b) is live.
6 of 8 STAGING_TABLES (ResponseAnswer, merge_archive, survey_merge_archive, _MigrationCheckpoint, _MigrationAuditLog, duplicate_placeholder_archive)All 6 present, recreated on demand by ordinary migrator phase code since the drop, exactly as the staging-table model below predicts.
2 of 8 STAGING_TABLES (_MigrationBoundary, _MigrationDeferred)Absent. Both have runtime creators too (idempotency/boundary-store.ts, idempotency/deferred-store.ts); no phase that calls them has run on this database since 2026-08-24. Not evidence of a problem, they're only created when their specific phase runs.
_migrator_finalized (the program-wide retirement tombstone that existed in the 2026-08-31 design)Absent — and now obsolete. It was replaced by _migrator_program_lease, which inverts the polarity; the row is left here only so the shape of the old design is legible. Nothing creates or reads _migrator_finalized on the current branch.
_migrator_tenant_finalized (per-tenant marker)Present. Worth asking about before your first finalize-staging --apply against this database: its existence isn't proof the full gated command set is wired into whatever build is actually deployed there, only that something already created this one table.

The lease model replaced the two-marker model

The 2026-08-31 design used a tombstone: _migrator_finalized meant "this database is retired," and its presence blocked future runs. A tombstone has to live forever by construction — deleting it silently restores permission — so "leave zero migration-owned tables behind" was unreachable, and the old checklist below ended at "2 tables above the pre-migration baseline."

That polarity is now inverted. _migrator_program_lease is a lease: its presence is the permission to create migration-owned schema. Absence already means "refuse," so nothing has to survive retirement, and a retired database is left with exactly zero migration-owned tables (the two transient Segment columns are a separate lifecycle — see below). Source: packages/migrator/src/target/program-lease.ts, packages/migrator/src/target/staging-guard.ts.

_migrator_program_lease_migrator_tenant_finalized
Answers"Migration-owned schema is permitted in this database""This tenant is done"
Created bymigrate open-program — and nothing else. Not run, not preflight, not a Prisma migration (04b)migrate finalize-staging --client <env> --apply
ScopeThe whole database (one row only, CHECK (id = true))One environment_id (PK column, one row per tenant)
What it gatesEverything that creates schema: ensureStagingTable and markTenantFinalized both refuse without it — with E-LEASE-01, -02 or -03 depending on the state it diagnoses (Gate 0 below)Nothing automatically: a record, and the input to Gate 3
Drops any table?No. retire-migration-program drops tables; the lease is one of the things it dropsNo, never
Dropped bymigrate retire-migration-program --apply --confirm, in the same transaction as the 13 staging tables and the 10 migration-owned columnsSame command, same transaction
Reversible?Yes, deliberately: migrate open-program --reopen-after-retirement --confirmNot via CLI today, see recovery note below

The full footprint is one exported constant, MIGRATION_OWNED_TABLES in packages/migrator/src/target/migration-tables.ts: the 13 STAGING_TABLES plus these 2 markers, 15 tables in all. All fifteen may only be dropped by retire-migration-program, which drops every one of them in a single transaction and writes nothing afterwards — the lease last, through the module that owns it, so no window exists where the tables are gone but the permission record survives. Two transient columns are covered too, by a separate list: MIGRATION_OWNED_COLUMNS (src/target/migration-tables.ts) enumerates Segment.legacy_id and Segment.legacy_kind, added by Phase 2.6. They cannot be members of MIGRATION_OWNED_TABLES because Segment is a product table that must survive retirement — only the columns are migration-owned. Retirement drops them itself, in its own transaction, so zero footprint does not depend on anyone remembering a second command. finalize-audiences --drop-tracking (or run --drop-tracking) remains the way to remove them earlier, before retirement: they are kept by default so migrate rollback can still identify audience Segments by legacy_kind, and note it drops them for every environment in the database, not just yours. A Prisma migration in packages/database/migration/ that DROP TABLEs any of the ten breaks every future legacy migration into that database — this happened once, on 2026-08-24, and tests/unit/migration-folder-no-staging-drops.test.ts now fails the build if it happens again.

The provenance columns are migration-owned too since 2026-09-26 · AG-migration bb98b273e

Constitution v2.0.0 (Principle XI) turned the legacy_* provenance columns into temporary state, like the Segment.legacy_* pair above. There are eight of them: Response.legacy_id, legacy_guid and legacy_extras; Survey.legacy_id and legacy_extras; Contact.legacy_id; User.legacy_id and legacy_extras. They have 6 indexes.

schema.prisma no longer declares any of them. The migrator creates them at runtime while the program is open: the first real run or delta adds whichever are missing, under the lease, with a 5 s lock timeout and CREATE INDEX CONCURRENTLY. Retirement drops them. MIGRATION_OWNED_COLUMNS now lists 10 columns (these 8 plus the Segment pair), and MIGRATION_OWNED_INDEXES lists the 6 indexes. The staging list has also grown since the table above was written: the source of truth is STAGING_TABLES / MIGRATION_OWNED_TABLES in src/target/migration-tables.ts, not the counts in this section.

What survives retirement is the product's own data. Status, SourceID (as SourceCode) and SendMethodID are written into the response's Hidden Fields (Response.data) as rows are inserted. Phase 4 and migrate project-legacy-hidden-fields backfill any rows migrated before that mapping existed, and they never overwrite a key that is already set. The column lineage itself survives only in the export artifact written by migrate export-provenance. Once retired, that export is the only link from a migrated row back to its source row. Keep it.

CodeWhen retirement refusesWhat to do
E-PROV-01A command that needs the provenance columns found them absent (for example rollback, or audiences --apply).The database is retired or was never migrated. Nothing was written.
E-PROV-02Provenance is populated, and there is neither a matching --provenance-manifest (per-table counts and database name) nor --discard-provenance. Also raised when the in-transaction re-count grew ("provenance changed during retirement").Run export-provenance, then pass its manifest.json. If the counts changed during retirement, stop the concurrent writer and re-run. Nothing was dropped.
E-PROV-03preflight, run or the TUI found an environment with data but no provenance. That is a retired tenant.Migrate into a new environment. Re-migrating would duplicate every row.
E-PROV-04Status, SourceID or SendMethodID are not yet in Hidden Fields, or a hidden field conflicts while --discard-provenance is set.Run project-legacy-hidden-fields --client <env> for each environment, re-check parity, then retry. --discard-provenance never bypasses this.
E-PROV-05The advisory lock or LOCK TABLE hit the 5 s lock_timeout.A migrator or writer is active. Retry when it is idle. Nothing was dropped.

Retirement with provenance, step by step

  1. Verify: parity passes for every environment, including legacy_extras_hidden_field_coverage. If the source is live, run one migrate delta first so the row counts close.
  2. Finalize each tenant: finalize-staging --client <env> --config <dept .env> --apply. Outside the lifecycle this does not run a final delta or check for rows the live source took after verify: stop source writes and run delta + parity per department first.
  3. Export: migrate --config <cfg> export-provenance --out <new empty dir>. It is read-only and takes no lease. It writes gzipped NDJSON per table plus manifest.json with row counts and sha256. It refuses a directory that already holds an export. Do not start another delta between the export and step 5, or the counts will no longer match.
  4. Dry run: retire-migration-program --confirm --provenance-manifest <dir>/manifest.json. It must say the manifest matches and that neither E-PROV-02 nor E-PROV-04 would refuse. Ignore its "estimated export size" on builds older than bb98b273e, which under-counted.
  5. Retire: the same command with --apply. One transaction runs SET LOCAL lock_timeout, then the advisory lock, then LOCK TABLE … SHARE ROW EXCLUSIVE, then the re-count, then every DROP. Product writes to Response, Survey, Contact and User wait until the commit; reads continue.
  6. Prove zero: migrate --config <cfg> census --expect-zero. It is read-only and takes no lease. It exits 1 unless tables, columns, indexes, stray relations and dev licences are all zero.

A database that reads "never-opened" but still has columns. The migrator tells retired from fresh by Survey.legacy_id. After you wipe every migrated tenant, no survey carries it any more, but other organisations' Users can still hold legacy_id. As of 4961dfdb7, retire-migration-program handles this: if no lease and no staging table exist, it runs the same gated completion (export check, Hidden-Fields check, lock and re-count, DROP) with no lease. If staging tables exist it refuses with the active-unleased message. If nothing migration-owned is left, it says there is nothing to retire.

Fresh databases and the handover migration. Prisma migration 20260925120000_hand_provenance_columns_to_migrator drops a table's provenance columns only when three things hold: no lease exists, no staging table exists, and every value in those columns is NULL. It never removes populated data. A populated or open database keeps its columns until retirement.

Proven end to end on dev, 2026-09-26

This was run on dev hivecfm, Zain-BH environments only, with every step timed through scripts/rehearsal/lifecycle.sh:

  • wipe both tenants (d2: 10m26s);
  • retire the leftover columns, then census = 0;
  • open-program, then provision;
  • run --dry-run against the column-less target (no 42703);
  • run-all-departments (1h24m50s);
  • census during the run: the 8 columns and 6 indexes appeared at runtime;
  • one delta, after which parity passed in both departments;
  • finalize, export (1,916,847 rows), retire (24s);
  • census --expect-zero returned rc 0.

Evidence: docs/post-migration-architecture-audit/provenance-lifecycle-rehearsal-2026-09-26.md.

Per-table purge vs. keep-forever, on finalize-staging

Finalizing one tenant purges that tenant's rows from 9 of the 13 staging tables. The other 4 are kept for every tenant until retirement. All 13 stay in the schema, for every tenant, until retire-migration-program runs.

Purged (per-tenant DELETE)Kept forever (until program retirement)
ResponseAnswer: fully consumed by Phase 4, nothing reads it after structure backfill_MigrationBoundary: read-consistency checkpoint, a future delta-after-finalize needs this line
merge_archive: undo record for an already-verified language merge_MigrationCheckpoint: resumability plus audit record of when this tenant's run happened
survey_merge_archive: same, for structural consolidation_MigrationAuditLog: append-only audit trail, permanent by design
_MigrationDeferred (keyed by client_env, not environment_id): rows parked for a later pass, all must be resolved first (Gate 2)duplicate_placeholder_archive: tombstone of which response superseded which, a structural decision record, not scratch
_MigrationAnsweredGuid, _MigrationPlaceholderStage, _MigrationMembershipStage, _MigrationMembershipOrder, _MigrationPlaceholderOrder: per-run working tables of the unanswered-invitation and membership writers—

The four hard safety gates

These are what make "finalizing one tenant cannot disable another tenant's future migration" a provable property, not just a policy. Gate 0 is new with the lease; the numbering below matches the order they fire in.

  1. Gate 0, at first schema creation, database-wide (the lease). Every call that would create migration-owned schema goes through assertProgramOpen (target/program-lease.ts) first, and it diagnoses one of four states from the database itself rather than trusting a flag. open → proceed. never-opened (no lease, no migrated data, no staging tables) → E-LEASE-01: run migrate open-program. retired (migrated data, no lease, no staging tables) → E-LEASE-02: the schema was dropped on purpose and must not come back; use a clean database, or reverse it deliberately with --reopen-after-retirement --confirm. active-unleased (migrated data and staging tables, no lease — a pre-lease build) → E-LEASE-03: adopt it with --adopt-active-program. That third/fourth distinction is the whole point: staging tables and the lease are dropped together in one transaction, so staging still being present proves retirement never ran, and an active database can never be misreported as retired. Every one of these refusals names the database it actually connected to and states "Nothing has been written." Since 9a5c77aa4, migrate run asks Gate 0 before Phase 1 writes (cli/run.ts), so a fresh database answers never-opened and gets E-LEASE-01 — the code whose remedy actually works — with nothing written. On older builds the question was asked later, after Phase 2 had written Surveys with legacy_id, which matches retired and printed E-LEASE-02 on a database that was never migrated. If that is what you are seeing, your dist/ predates the fix: 04b.
  2. Gate 1, pre-run, per tenant. Before migrate run or migrate delta writes for a client: does _migrator_tenant_finalized already hold a row for this environment_id? If yes, refuses with E-TENANT-FINAL-01 (assertTenantNotFinalized, target/staging-guard.ts). Idempotency does not cover this: ON CONFLICT DO NOTHING protects rows that already exist, whereas a delta exists precisely to add rows that do not. A --dry-run is always allowed and is the safe way to see what a re-run would do. Caveat worth knowing: when the marker table is absent entirely the guard logs "guard NOT ARMED" and continues — absence of the table is not read as "finalized".
  3. Gate 2, pre-finalize, per tenant. Before finalize-staging --apply commits: four refusals, each scoped to THIS environment_id only. (1) An incomplete _MigrationCheckpoint row (a phase stopped mid-way). (2) Unresolved _MigrationDeferred rows. (3) No Survey in this environment carries a legacy_id (almost certainly the wrong environment). (4) A Survey has a legacy_id but Phase 4 never finished (purging ResponseAnswer now would make those surveys unrepairable). None can be overridden with a flag.
  4. Gate 3, pre-retirement, program-wide. Before retire-migration-program --apply --confirm drops anything: every environment_id that ever appeared in _MigrationCheckpoint must also appear in _migrator_tenant_finalized, or it refuses and names which tenants are missing. Also refuses if _MigrationCheckpoint itself is missing or unreadable. Absence is never read as "zero tenants, safe to proceed," because that table is exactly what the 2026-08-24 incident dropped, so a database in that state cannot prove Gate 3 either way. --confirm exists separately from this gate: the database can refuse based on facts it holds, but only a human can decide whether any future tenant will ever need this database again.
Danger: retire-migration-program alone, or with only --apply, is a REFUSAL, not a dry-run

The pipeline checks --confirm before it checks --apply. A bare invocation, or --apply without --confirm, exits 1 with a refusal; it does not fall through to a harmless report. Only --confirm (with or without --apply) reaches the dry-run/apply branch. To preview what would be dropped, run retire-migration-program --confirm (no --apply). To actually drop, run retire-migration-program --apply --confirm.

Operators' checklist

  1. After a tenant's migration is complete and verified (parity passes): migrate finalize-staging --client <env> (no --apply) to preview the purge. If it looks right, add --apply. This purges 9 tables for that tenant only and never blocks any other tenant.
  2. Before program retirement (rare, typically only after the last tenant that will ever use this database is finalized): confirm the business decision first (will any future tenant migrate into this database? if yes, do not retire). Then retire-migration-program --confirm (no --apply) to preview: it lists any tenant that's migrated but isn't finalized yet, and refuses if the list is non-empty. Once clean, retire-migration-program --apply --confirm.
  3. After retirement: all 13 STAGING_TABLES and both marker tables are gone — 15 tables, the 10 migration-owned columns and their 6 indexes, in one transaction — zero migration-owned objects left, with nothing further to remember. (Running finalize-audiences --drop-tracking beforehand is still fine, and is how you drop those columns early; it is no longer a prerequisite for a clean finish.) (The older design left 2 permanent tombstone tables behind; that is what the lease removed. Nothing needs to survive, because absence of the lease already means "refuse".) A re-opened database is a deliberate, recorded reversal, not a side effect: migrate open-program --reopen-after-retirement --confirm.
Re-opening a finalized tenant

No CLI command does this today. clearTenantFinalized() (packages/migrator/src/target/staging-guard.ts) exists only as an exported function used by tests. Re-opening means running its SQL by hand: DELETE FROM "_migrator_tenant_finalized" WHERE environment_id = '<env>'. This only works if the program hasn't been retired (tables still exist): _MigrationBoundary and _MigrationCheckpoint were never purged, so migrate delta can run again afterward.

,Reference

Command Reference

30 top-level commands on fix/noref-tui-run3-operator-defects @ 4d6f7fe8e (29 working plus the superset stub group). Invoke each as $M <command>, with M="node --import tsx dist/cli.js" in packages/migrator. lifecycle, reset-client and run-all-departments take --from-config and no --client. open-program, export-provenance, retire-migration-program and census are database-wide and take only --config. verify-revert takes neither. The rest take --client and --config.

Exit codes, across the whole CLI

One table, because the per-command lines below only list the codes that command can emit. Anything scripting the migrator should branch on these:

CodeMeansWhat to do
0Success, and — since the E-P5-PARITY-SILENT-01 trust-fix — parity-verified. run.ts now tracks parityPassed from Phase 5 and raises the exit code, so a 0 from run does mean Phase 5's counts reconciled.Nothing. Three cases where a 0 carries no parity claim: (a) a run with --phase, or with Phase 5 skipped, never computed parity; (b) a --dry-run — its parity always "fails" (real source counts against an empty target) and the code deliberately does not raise the exit for it (E-P5-PARITY-DRYRUN-01), because forcing a non-zero there would mean a rehearsal on a first migration could never be signed off; (c) a build predating the trust-fix, which exited 0 on a real parity FAIL. If you are unsure which you have, run migrate parity and read its exit code.
1A phase or environment failure: a refused gate (E-LEASE-01/02/03, E-TENANT-FINAL-01), a bad .env, a missing target environment, a preflight blocker. Also a run that finished with required stages incomplete, or with responses written but unscored.Read the error code, apply its operator fix, re-run. These are recoverable by construction; nothing was half-written for a gate refusal.
2Connectivity failure, a refused DDL bootstrap, a parity FAIL (from run's own Phase 5 or from standalone migrate parity), or a Phase 6 Hub problem after an otherwise-good migration.Distinguish by the last line printed. On a parity FAIL the data is written but NOT verified — read the parity report before treating the run as usable. A Hub-only 2 means the migration data is fine and only the Hub push needs re-running (migrate hub-backfill).
3Source schema variant is Custom — neither StableRJB nor ISTServiceEdge.Stop. See F4 Variant Decider; the transform layer has no mapping for a third shape.
130SIGINT/SIGTERM at a phase boundary — a deliberate, clean interrupt.Safe to resume: migrate run --resume. Checkpoints advance inside the same transaction as each COPY, so no chunk is half-applied.
migrate lifecycle The whole client migration, one stage after another, resumable (recommended) ›

The CLI behind the TUI Lifecycle screen: open-program → provision → preflight → dry-run → run → verify → hub-backfill → finalize → export → retire → census. State in .migrate/lifecycle/<base id>.json; re-run the same command to resume. Takes --from-config, not --client. Full guide: L0–L11.

FlagDescriptionDefault
--from-config <path>REQThe client's base config; its registry entry is the base entry—
--departments <ids>optDepartments to provision (provision only)every department
--from-stage / --until <stage>optStart at / stop after this stage. --from-stage hub-backfill is the only way to re-run a skipped hub-backfillnext pending / census
--yesoptDo not ask before open-program, provision, run, verify, hub-backfill, finalize, retire. Only with --until on a stage before finalize: from a shell the questions are the only guard (L11).false
--accept-check <ids>optsurvey_channel_coverage, contact_target_extras only (the latter up to 50 per department)none
--parity-retries <n>optExtra delta + parity rounds per department in verify2
--export-dir <dir>optWhere export-provenance writes./provenance/<base id>
--skip-dry-runoptSkip the dry-run stage (not recommended)false
--max-workers <n>optForwarded to every department's runserial
--approve-quarantine <fps>optForwarded to every department's runnone
--accept-live-tailoptLet finalize go ahead over rows the source took after its final delta (recorded in the state)false
--statusoptPrint the state and the next stage; run nothingfalse
--previewoptWith --from-stage S --until S (provision, finalize, retire): run only the previewfalse

Exit codes: 0 complete or stopped at --until, 1 a stage failed (E-LIFECYCLE-STAGE-01, or a refusal such as E-LIFECYCLE-LOCK-01), 130 interrupted.

migrate reset-client Return a RETIRED client to its pre-migration state (destructive, pre-go-live) ›

Deletes the migrated surveys, responses and contacts in every environment of the client, deletes the department projects, restores the anchor project name and archives the department entries, their .env files and the lifecycle state to .migrate/archive/reset-<time>/. Dry run unless --apply. Refuses unless the database census is zero, and refuses when it finds the customer's own rows. Run it where the lifecycle ran. See L10.

FlagDescriptionDefault
--from-config <path>REQThe client's base config—
--applyoptCommit the resetfalse (dry run)
--confirm-org <name>optRequired with --apply: the exact organization name the dry run prints—
--acknowledge-hub-pushoptRequired with --apply when the Hub may hold this client's responses; purge them firstfalse
--cutoff <iso>optWhen the migration started, if no lifecycle state records it (from the first run's log)lifecycle open-program stamp
--upper-cutoff <iso>optWhen the migration ended (retire --apply), if no lifecycle state records itlifecycle retire stamp
--anchor-name <name>optName to restore on the anchor projectrecorded name
--project <id>optAdd a department project whose entry is gone (repeatable)—
--keep-registryoptDo not archive the department entries and .env filesfalse

Refusals: E-RESET-STATE-01, E-RESET-SCOPE-01, E-RESET-CONFIRM-01, E-RESET-DRIFT-01 (L10).

migrate backfill-response-contact-attributes Relink responses to late contacts, then snapshot contact attributes ›

Links migrated responses with no contactId to the Contact of the same customer in the same environment (never overwriting a link), then snapshots each response's contact attributes. Idempotent. The repair the response_contact_backfill parity check names; every run and typed-union delta runs the relink at the start of Phase 4. After retire it cannot relink.

FlagDescriptionDefault
--clientREQEnvironment id (global flag)CLIENT_ENV
--configoptThe environment's .envenv vars
migrate verify-revert Check that infrastructure raised for a migration came back down ›

Read-only. Compares current values against the baseline preflight captured before a scale-up and names every dimension still raised. CLI only.

FlagDescriptionDefault
--report <path>REQRun report holding the preflight baseline—
--observed <dimension=value…>REQCurrent value per dimension, e.g. "target vCPU=8 vCPU"; every baseline dimension must be supplied—
migrate preflight Read-only validation and schema detection ›
FlagDescriptionDefault
--clientREQClient environment ID,
--configoptPath to .env config fileenv vars
--verboseoptShow full column-level scan resultsfalse
--allow-resumeoptSkip "target non-empty" blockerfalse

Exit codes: 0 all clear, 1 blockers found, 2 warnings only

A missing migration lease is a WARN here, not a blocker — preflight is read-only and cannot grant permission. Do not read a passing preflight as "ready to run" on a fresh database; run open-program next (04b).

migrate open-program Create the migration lease — required once per database ›

The only command that creates _migrator_program_lease, the permission to put migration-owned schema into a database. Never a side effect of run, on purpose: schema must not appear because a command happened to run. Database-wide, so it takes no --client. Idempotent — a second invocation on an open program is a no-op, exit 0. Full decision table at 04b.

FlagDescriptionDefault
--configoptPath to .env config file (target read from TARGET_PG_*)env vars
--adopt-active-programoptAdopt a migration already running without a lease (staging tables present). Writes the lease and changes nothing else. Refused on a retired database, so it can never become a quiet way to undo a retirement.false
--reopen-after-retirementoptDeliberately re-open a RETIRED database. Refused on an active one — reaching for it there means the state was misdiagnosed. Requires --confirm.false
--confirmoptRequired with --reopen-after-retirement. Never sufficient alone for anything: it is the flag operators are most practised at adding, so it must not be the one that decides.false

Exit codes: 0 opened, adopted, re-opened, or already open; 1 refused (the message names the state it diagnosed and the flag that state actually calls for)

migrate run Full migration pipeline — 10 phases ›
FlagDescriptionDefault
--clientREQClient environment ID,
--configoptPath to .env config fileenv vars
--dry-runoptSimulate without writingfalse
--resumeoptResume from checkpointfalse
--phaseoptRun only phase N (1–5). Selects from the original 5-phase core only — the auto-run phases (2.5, 2.6, 4.5, 5.5, 6) are not addressable this way; skip them with the --skip-* flags below instead.all
--chunk-sizeoptRows per COPY batch500
--departmentoptMigrate ONLY this legacy department id's surveys, plus reached contacts/responses/answers. Get the id from provision-departments (see 03b).whole tenant
--allow-env-discoveryoptIf CLIENT_ENV is absent from the target, adopt its only production environmentfalse
--migrate-usersoptWrite legacy User/Membership rows (restores the pre-b9b107b77 behaviour). Off by default: those rows are still read for the User: N rows telemetry either way, only the write is gated. See 06 Run Full Migration.false
--skip-targeting-backfilloptDon't auto-run targeting backfill after Phase 5false
--skip-repairoptDon't auto-run Phase 2.5 (repair survey status/timestamps)false
--skip-structure-backfilloptDon't auto-run structure + response-data backfill at end of Phase 4false
--skip-hub-backfilloptDon't auto-run Phase 6 (Hub push) at end of pipelinefalse
--skip-audiencesoptSkip Phase 2.6 (customer lists / CRM codes → Segments)false
--drop-trackingoptAfter a successful run, drop the transient Segment tracking columnsfalse
--consolidate-languages <mode>optapply|ask|report|skip: apply merges AUTO_MERGE groups without asking; ask prompts only on an interactive terminal; report merges nothing; skip writes no report. --consolidate-languages-apply / --skip-consolidate-languages are aliases for apply / skip.apply
--max-workers <n>optPhase 3 partitions at once (target pool max(10, n+6)). Also: --partition-target-rows, --audience-partition-target-rows, --max-source-load, --max-target-load, --placeholder-writer, --membership-writer.serial
--whole-tenant-into-one-envoptDeliberately put every department of a multi-department source into one environment (otherwise refused, E-RUN-SCOPE-01).false
--approve-quarantineoptComma-separated quarantine fingerprints to also commit during the in-run consolidation. Added 914d42d15 — previously only the standalone consolidate-languages command accepted it. UNMERGEABLE still never commits.,
--fold-sibling-questionoptRepeatable; valid only with --approve-quarantine for the same fingerprint. Added 914d42d15. See 07c for the syntax.,

Exit codes: 0 success and parity passed, 1 fatal error (or a required stage left incomplete), 2 parity FAIL — or Phase 6 Hub push failed after an otherwise-good migration, 130 interrupted (SIGINT/SIGTERM); safe to resume. Corrected 2026-09-10: this card previously said "parity failure is silently ignored". That was true before the E-P5-PARITY-SILENT-01 trust-fix; run.ts now wires parityPassed into the exit code. (The entry still carrying exitCode: 0 in errors/catalog.ts is stale metadata describing the original defect, not current behaviour.)

migrate parity Row-count validation + HTML report ›
FlagDescriptionDefault
--clientREQClient environment ID,
--configoptPath to .env config fileenv vars
--departmentoptThe department the run being validated was scoped to. Must match the run's --department, otherwise every source count is tenant-wide against a single-department target and reports a deficit that isn't real. (See 03b.)whole tenant

Exit codes: 0 all pass, 2 parity failures

migrate delta Catch up one environment from its recorded boundary (verify rounds and finalize run it) ›
FlagDescriptionDefault
--clientREQClient environment ID,
--sinceoptNormally omitted: the floor is the per-entity boundary the run recorded. An ISO 8601 timestamp, or a bare row id under --strategy id, re-reads an older window on purpose.recorded boundary
--configoptPath to .env config fileenv vars
--strategyopttimestamp or idauto-detected
--departmentoptDrain only this legacy department's new rows. Must match the original run's --department: without it a delta reads every department's post-boundary rows into whichever environment it was pointed at, silently mixing tenants. (See 03b.)whole tenant
--chunk-sizeoptRows per read chunk500
--max-duplicate-deletionsoptCeiling for the automatic duplicate-placeholder repair; a count above it skips the repair100
migrate rollback Reverse new writes back to MSSQL (4-hour window) ›
FlagDescriptionDefault
--clientREQClient environment ID,
--cutover-startoptISO 8601 timestamp when cutover began. Omit to run cleanup only, without replay.,
--dry-runoptPreview replay scope without writingfalse
--audiencesoptRoll back ONLY the v0.8 audience artifacts (segments + list_/crmSegment attributes), leaving contacts intactfalse
--configoptPath to .env config fileenv vars

Exit codes: 0 success, 1 refused (window expired) or error

migrate provision-departments Create one Project + Environment per legacy department ›

The lifecycle's provision stage runs it (see L3; manual: 03b). The only migrator command that creates tenancy, deliberately separate from run, which refuses a target environment that doesn't already exist (that's what stops a mistyped target from manufacturing a tenant). Prints the department→CLIENT_ENV map to feed into run --department, delta --department, and parity --department.

FlagDescriptionDefault
--clientREQTarget anchor Environment.id (the id in /environments/<id>/surveys, not an organization id). The organization is derived from it, and the first (lowest-id) department provisioned reuses and renames its project.CLIENT_ENV
--dry-runoptReport what would be created without writingfalse
--departmentsoptComma-separated legacy department ids to provision. Use to exclude an empty department (e.g. a parent node in a flattened hierarchy with no surveys of its own).every department the source reports
--configoptBase .env (source + target credentials, CLIENT_ENV). Generated department files copy it.$ENV_FILE, else ./.env
--write-configoptWrite one .env.<id>-<slug> per department plus its .migrate/targets.json entry. Existing files are never overwritten. The files hold the source and target passwords and get default permissions: chmod 600 them.false
--tieroptTier recorded on generated registry entries (local|dev|uat|prod). The lifecycle passes the base entry's tier.dev
--id-prefix <prefix>optNamespace generated registry ids and .env files (stcbh → stcbh-1-main-department). The lifecycle passes the base entry id.none
migrate run-all-departments Run every provisioned department in sequence, one environment each ›

Reads the department entries provision-departments --write-config put in .migrate/targets.json and runs the same commands an operator would type (see 06), in this order: open-program first (only with --open-program, once per distinct config), then preflight --department N for every department, and only then run --department N for each department in turn. Launch it as export NODE_OPTIONS=--import=tsx, then plain node dist/cli.js run-all-departments …: each child is spawned as node dist/cli.js and does not get the parent's --import tsx. There is no department filter: it runs every registry entry generated from --from-config.

FlagDescriptionDefault
--from-configoptRun only the entries generated from this base config. Required when the registry holds more than one client's departments.all entries (refused if the registry holds more than one client's)
--open-programoptRun open-program (idempotent) through each department's config before the preflightsfalse
--dry-runoptPass --dry-run to every child runfalse
--continue-on-failureoptKeep going after a department failsfalse (stop)
--skip-preflightoptDo not run preflight --department N for every department before the first runfalse
--migrate-usersoptForwarded to every child run. Write legacy User/Membership rows (restores the pre-b9b107b77 behaviour). See 06 Run Full Migration.false
--consolidate-languagesoptForwarded to every child run (e.g. apply)child's own
--approve-quarantineoptForwarded to every child run. Comma-separated quarantine fingerprints to commit; a fingerprint that matches no group in a given department is a logged no-op there, not a failure. Added 914d42d15.,
--fold-sibling-questionoptForwarded to every child run. Repeatable; valid only with --approve-quarantine for the same fingerprint. Added 914d42d15. See 07c for the syntax.,
--skip-hub-backfilloptForwarded to every child run. Keep it on and push per department afterwards.false
--max-workersoptForwarded to every child run. The other budget flags (--chunk-size, --partition-target-rows, …) are forwarded the same way.serial

Refusals: E-RUN-ALL-PREFLIGHT-01 (a gate child failed, nothing migrated; the lease may already be open), E-RUN-PHASE-FAIL-01 (a department's run failed or was stopped), E-RUN-SCOPE-01 (registry refused).

migrate finalize-targeting Backfill missing Segment + SurveyTrigger rows for App surveys ›
FlagDescriptionDefault
--clientREQClient environment ID,
--applyoptWrite rowsfalse (dry-run)
--reportoptPath to write report JSONbackfill-targeting-report.json
--trigger-nameoptName for the auto-created ActionClass,
--trigger-keyoptKey for the auto-created ActionClass,

Runs automatically after Phase 5 during migrate run unless --skip-targeting-backfill. See 07a Post-migration backfill.

migrate audiences Customer lists + CRM segment codes → native Segments (Phase 2.6) ›
FlagDescriptionDefault
--clientREQClient environment ID,
--applyoptWrite segments and attributes idempotentlyfalse (dry-run)

Full detail: Audiences & segments.

migrate finalize-audiences Drop the transient Segment tracking columns (one-shot, project-end) ›
FlagDescriptionDefault
--drop-trackingoptDrop Segment.legacy_id/legacy_kind. Run once at the end of the migration project, after any rollback --audiences calls you might need.false (no-op)
migrate repair-surveys Fix Survey.status + created_at/updated_at by re-reading source MSSQL ›

No flags beyond the global --client/--config. Writes on invoke, no apply gate.

migrate backfill-survey-structure Build Survey.blocks + project Response.data from ResponseAnswer ›

No flags beyond the global --client/--config. Writes on invoke, idempotent on re-run. This is the command that reads the ResponseAnswer staging table (see F8b New models): it must run, or be allowed to auto-run inside migrate run, before that tenant is finalized.

migrate backfill-survey-hidden-fields Declare per-invitation context as Survey.hiddenFields ›

Merged on AG-migration. Derives hidden fields (agent, customer, InteractionType, invitation timestamp) per survey from the Response.data keys that actually carry values. Target-only, idempotent, no schema change, no Response rewrites.

FlagDescriptionDefault
--dry-runoptReport what would change without writingfalse

Hidden field id renamed: DispoCode → InteractionType (migrator commit b9b107b77). Only the name changes — the id in Survey.hiddenFields.fieldIds and the key inside Response.data. Source is unchanged: CFMDispCode.DispCode, reached via row.DispCodeID. “InteractionType” is what the legacy product calls this concept. Unrelated despite the shared word, and untouched by this rename: Survey.legacy_extras.InteractionType and the CFMDispCodeGroupBrg bridge that distinguishes Bot from Agent sibling surveys — different derivation, different column.

The rename is not retroactive — and a re-run does not fix it

An environment migrated under the old id keeps it. Re-running does not fix it: a re-run declares InteractionType alongside the stale DispoCode rather than replacing it, and never renames keys on responses that were not re-migrated. Fixing an existing environment takes one transaction, and both statements must run together, or a survey will declare a key its responses do not use.

Check first — there may be nothing to do:

SELECT count(*) FROM "Survey" WHERE "hiddenFields"->'fieldIds' @> '["DispoCode"]';
SELECT count(*) FROM "Response" WHERE data ? 'DispoCode';

Both were 0 database-wide on the dev target, because that source carries no DispCode values at all.

If either count is non-zero, remediate in one transaction (scope it per environment unless every tenant in that database is meant to change, batch the Response update on a large table, and verify afterwards that both DispoCode counts are 0 and the InteractionType counts match what they were):

BEGIN;
UPDATE "Survey"
   SET "hiddenFields" = jsonb_set("hiddenFields", '{fieldIds}',
         (SELECT jsonb_agg(CASE WHEN v = '"DispoCode"'::jsonb THEN '"InteractionType"'::jsonb ELSE v END)
            FROM jsonb_array_elements("hiddenFields"->'fieldIds') v))
 WHERE "hiddenFields"->'fieldIds' @> '["DispoCode"]';
UPDATE "Response"
   SET data = (data - 'DispoCode') || jsonb_build_object('InteractionType', data->'DispoCode')
 WHERE data ? 'DispoCode';
COMMIT;
migrate consolidate-languages Merge migrated language-sibling surveys into one multi-language survivor ›
FlagDescriptionDefault
--clientREQClient environment ID,
--applyoptCommit the merge: AUTO_MERGE groups commit unattended, QUARANTINE only with --approve-quarantine, UNMERGEABLE neverfalse (dry-run report)
--approve-quarantineoptComma-separated quarantine fingerprints to also commit,
--fold-sibling-questionoptRepeatable. Valid only with --approve-quarantine for the same fingerprint: <fingerprint>:<languageCode>:<siblingPos>-><survivorPos>[,<survivorPos>…] (1-based positions). Fills the listed survivor slots with the sibling question's own text — never invented or machine-translated; an unfillable field leaves that language disabled.,
--repoint-batch-sizeoptResponses per re-point transaction batchcapped, see CLI help

Full detail, including Step 4 finalize: 07c Language consolidation.

migrate unmerge-languages Reverse a committed language merge for one survivor survey ›
FlagDescriptionDefault
--survivor-idREQThe survivorId of the merged survey to un-merge,

Writes immediately on invoke, restores archived Responses, reactivates sibling surveys, removes extra SurveyLanguage rows. No --client/--apply gate.

migrate finalize-consolidation Permanently delete sibling surveys archived by consolidate-languages ›

IRREVERSIBLE. Ends unmerge-languages for those merges. Refuses to delete any remnant that still holds responses, or a question the survivor never received.

FlagDescriptionDefault
--clientREQClient environment ID,
--applyoptCommit the deletionfalse (dry-run)
--accept-question-lossoptDelete remnants holding questions absent from the survivor, destroying those questions (TUI key [u])false
--accept-missing-archiveoptGo ahead when the merge archive for a remnant is missing (TUI key [m])false
migrate hub-backfill Phase 6: POST historical finished Responses to HiveCFM Hub ›
FlagDescriptionDefault
--clientREQClient environment ID,
--batch-sizeoptRows per PG batch100
--concurrencyoptParallel Hub POSTs per batch8

Records the Hub already holds come back 409 (a duplicate) and are never updated, so a re-push is safe only while the data is unchanged; after a QUARANTINE merge it adds duplicates. Runs at the end of migrate run unless --skip-hub-backfill (the lifecycle always skips it there and pushes in its hub-backfill stage). Missing Hub config exits 2 with a critical banner. The TUI Hub backfill screen defaults to 200 / 4, not 100 / 8. Works after retire.

migrate report contact-history Per-contact response history export (CSV + HTML) ›

No flags beyond the global --client/--config. Requires Phase 3 complete (Response.contactId populated). Writes ./reports/contact-history-<client>-<ts>.csv and .html.

migrate finalize-staging Per-tenant: purge this tenant's rows from shared staging tables ›

Purges ONE tenant's rows from 9 of the 13 migration-only staging tables and marks that tenant finalized. Run outside the lifecycle it does not run a final delta or check for new source rows; the lifecycle's finalize stage does (L7). Does not drop any table: other tenants can still migrate afterward. Refuses on that tenant's incomplete checkpoints, unresolved deferred rows, or an environment that was never migrated.

FlagDescriptionDefault
--clientREQClient environment ID (via global flag, resolved by resolveClientIdentity),
--applyoptCommit the purge and set this tenant's markerfalse (dry-run)

Full detail, gates, and deployment status: 11b Program retirement & staging-table lifecycle.

migrate retire-migration-program PERMANENT, DATABASE-WIDE: drop all 15 migration-owned tables, 10 columns and 6 indexes ›

Drops all 15 MIGRATION_OWNED_TABLES — the 13 staging tables plus _migrator_tenant_finalized and the _migrator_program_lease itself — (its --help text still says "11": stale) — in one transaction, the lease last, leaving zero migration-owned tables. Also drops Segment.legacy_id/legacy_kind (the MIGRATION_OWNED_COLUMNS list) in the same transaction, so a retired database keeps no migration-owned columns either; finalize-audiences --drop-tracking is now only for removing them earlier. Refuses unless every tenant that has ever migrated through this database is already finalized. Never part of any single tenant's workflow, use finalize-staging for that. A bare invocation, or --apply without --confirm, is a hard refusal (exit 1), not a harmless dry-run report. Only --confirm (with or without --apply) reaches the report/apply branch.

FlagDescriptionDefault
--applyoptCommit the drop (also requires --confirm)false (report only)
--confirmoptRequired even for a dry-run report: explicit human sign-off that no future tenant will use this databasefalse
--provenance-manifest <file>optmanifest.json from export-provenance. Its per-table counts and database name must match the live populated provenance (E-PROV-02).,
--discard-provenanceoptDrop populated provenance WITHOUT an export: permanent loss of lineage. Never bypasses E-PROV-04, and is refused while any hidden field conflicts.false

Also drops the 8 provenance columns and 6 indexes (MIGRATION_OWNED_COLUMNS / MIGRATION_OWNED_INDEXES). The lifecycle retire stage passes --provenance-manifest ./provenance/<base id>/manifest.json itself; the TUI Migration program screen cannot, so use the Lifecycle screen or this CLI. The dry run predicts E-PROV-02 and E-PROV-04. It removes leftover columns from an already-retired database, and (since 4961dfdb7) from a never-opened one that has no staging tables. Full detail, gates and the E-PROV codes: 11b · provenance columns and 11b Program retirement & staging-table lifecycle.

migrate export-provenance Read-only: export the provenance columns before retirement drops them ›

Streams each provenance table to <table>.ndjson.gz and writes manifest.json with the database name, exportedAt, and per table {rows, file, sha256}. It hashes while it writes, so memory stays bounded. It takes no lease and writes nothing to the database. It refuses a directory that already holds any export file, and on failure it removes only the files it wrote. The result is a point-in-time snapshot: a later write makes retirement refuse on a mismatch (the safe direction).

FlagDescriptionDefault
--out <dir>REQOutput directory. It is created if missing, and must not already contain an export.,

After retirement this artifact is the only lineage from migrated rows back to the source. Store it somewhere safe.

migrate census Read-only: count every migration-owned object still in the database ›

Counts and names the migration-owned tables, columns and indexes (flagging invalid indexes), plus migrator-shaped stray relations and dev-signed tenant_license rows. The indexes and sequences of registered tables are not strays. It takes no lease and writes nothing.

FlagDescriptionDefault
--expect-zerooptExit 1 unless every count is zero. Use it as the last step of retirement.false
migrate project-legacy-hidden-fields Copy Status / SourceID / SendMethodID from legacy_extras into Hidden Fields ›

A recovery or backfill for responses migrated before these keys were mapped at insert time. It only fills keys missing from Response.data and never overwrites one the product or a user already set. It is safe to repeat. Phase 4 runs the same projection, and retirement's E-PROV-04 gate checks its coverage. CLI only.

FlagDescriptionDefault
--clientREQEnvironment to project (global flag),
--dry-runoptReport coverage (source / present / missing / conflicting per key) without writingfalse
migrate superset * Dashboard re-pointing toolkit v0.2 · not yet implemented ›

Four subcommands are wired in the CLI surface but currently print Command not yet implemented. They ship in v0.2:

SubcommandPlanned behavior
superset inventoryExport all Superset dashboards, datasets, charts, RLS rules to a JSON snapshot
superset rewriteAuto-convert MSSQL SQL → PostgreSQL across all chart queries (14 known patterns)
superset parityRun every chart against both DBs and diff results before cutover
superset cutoverAtomic API swap: enable PG, disable MSSQL connection

Until v0.2, repoint dashboards manually in Superset Settings → Database Connections.

File Paths

Source paths are relative to the repo root (<checkout>). Runtime paths are relative to <checkout>/packages/migrator, where you start the TUI and every command.

Runtime path (packages/migrator)What it holds
.migrate/targets.jsonThe environment registry: the base entry and every department entry.
.migrate/registry-status.jsonSaved Environments re-check results (0600; restored for 24 h).
.migrate/live/<pid>.jsonOne record per running engine child; used to refuse a second writer.
.migrate/lifecycle/<base id>.jsonLifecycle state (stages, departments, accepted checks, Hub push times).
.migrate/lifecycle/<base id>.lockHeld while a lifecycle runs (E-LIFECYCLE-LOCK-01).
.migrate/lifecycle/logs/<base id>/<stage>[-dept<N>]-<command>-<time>.log, mode 0600, never pruned.
.migrate/archive/reset-<time>/What reset-client archived (department entries, .env files, lifecycle state).
reports/parity-<env>-<time>.html (+ sidecar), consolidation-<env>-<time>.md, contact-history and support bundles.
provenance/<base id>/The provenance export and manifest.json retire checks. Keep it.
.env.<base id>-<dept>-<name>Department configs written by provision (chmod 600).
config/channel-mapping[.<envId>].jsonChannel type mapping (dist/config/ in a built install).
<checkout>/ ├── packages/ │ ├── migrator/ ← the CLI package (run everything from here) │ │ ├── dist/cli.js ← built CLI: node --import tsx dist/cli.js │ │ ├── src/ │ │ │ ├── cli/ │ │ │ │ ├── program.ts ← every command is registered here (commander) │ │ │ │ ├── lifecycle/ ← migrate lifecycle: stages, run-lifecycle, lock, parity gate │ │ │ │ ├── run.ts · delta.ts · parity.ts · preflight.ts · rollback.ts │ │ │ │ ├── provision-departments.ts · run-all-departments.ts │ │ │ │ └── reset-client.ts · census.ts · export-provenance.ts · retire-migration-program.ts │ │ │ ├── pipeline/ ← phases 1–5, relink-response-contacts, finalize-staging, reset-client │ │ │ ├── ui/ ← the TUI (screens/Lifecycle.tsx, EnvPicker.tsx, MainMenu.tsx …) │ │ │ ├── target/ ← migration-tables.ts (the owned tables/columns), program-lease.ts │ │ │ ├── errors/ ← catalog.ts (every E-… code) │ │ │ ├── transform/ · source/ · idempotency/ · reverse/ │ │ └── tests/ ← unit, ui, integration projects (Vitest) │ └── database/ │ ├── schema.prisma │ └── migration/ ← applied Prisma migrations (singular directory)
Operational tables in Postgres

_MigrationCheckpoint: one row per (client, table), tracks last committed legacy_id.
_MigrationAuditLog: append-only log of every migration run, phase timings, row counts.
These are 2 of the 13 staging tables (15 migration-owned tables with the lease and the tenant marker); retire drops them all (11b). _MigrationVariant was dropped on 2026-08-20 and no longer exists.

Troubleshooting

Common errors and how to fix them. Filter by error text or keyword. For anything the Lifecycle screen shows, start with L9 Lifecycle troubleshooting.

No entries match. Try a shorter keyword.
advisory lock held by another process ›

Another migration, delta or finalize-targeting --apply for this environment holds its lock. Find the holder and wait for it (or stop it with kill -INT <pid> if it is a run, which stops at its next safe point). A dead process's lock is released by PostgreSQL when its connection closes, so there is nothing to unlock by hand; pg_advisory_unlock_all() only releases locks held by your own session and cannot free another one. Lifecycle problems (E-LIFECYCLE-LOCK-01 and the rest) are in L9.

bash / sql: find the holder
$pgrep -af "dist/cli.js (run|delta|finalize-targeting|lifecycle)"
SELECT pid, application_name, state, query_start FROM pg_stat_activity WHERE pid IN (SELECT pid FROM pg_locks WHERE locktype = 'advisory');
Target not empty. N legacy rows already in Response; use --allow-resume to continue ›

The target Response table already has rows with legacy_id set, the fresh-client guardrail. Flag-name gotcha: preflight uses --allow-resume (skips the empty-target check); migrate run uses --resume (resumes from the checkpoint table). Different flags for different commands, the migrator will reject the wrong one.

Resume an interrupted prior migration (idempotent, safe):

bash · hivecfm-core/
$$M preflight --client <c> --config <f> --allow-resume
$$M run --client <c> --config <f> --resume

Restart fresh, only if the existing rows are unwanted. Never TRUNCATE product tables: on a customer or shared target that wipes every organization. While the program is open, remove one environment's migrated rows with $M rollback --client <c> --config <f> --dry-run, then without --dry-run (10). After retire, use $M reset-client --from-config <base.env> (L10).

Do not touch the migration-only staging tables by hand either (ResponseAnswer, _MigrationCheckpoint, _MigrationAuditLog, etc, see 11b Program retirement): they are created on demand by migrator code and only retire-migration-program may drop them. If the row counts are unexpected and you did not run a prior migration on this DB, stop and investigate, you may be looking at someone else's in-progress work or the wrong target database.

GENERATED column error in COPY ›

The InsertableColumnsCache queries information_schema.columns to filter out GENERATED ALWAYS columns (csat_score, ces_score, etc.). If Postgres doesn't have information_schema access, grant it:

sql · Postgres
GRANT SELECT ON information_schema.columns TO <pg-user>;
Parity FAIL: rowsOnlyInSource = N ›

N rows exist in MSSQL that are not in Postgres. Most common causes:

  • Migration was interrupted mid-chunk. Run migrate run --resume
  • New rows inserted to MSSQL after migration. Run $M delta --client <env> --config <.env> --department N (no --since: the recorded boundary is the floor), then parity. On the lifecycle path press enter on verify, which runs delta + parity again (L5).
  • Rows filtered by a transform error. Check _MigrationAuditLog for error entries
Connection timeout to source MSSQL ›

Usually network. Verify VPN, firewall, and that the SQL Server listens on TCP 1433 (not just shared memory). Drop --chunk-size to 100. Smaller commits reset the connection more often, which masks intermittent drops. If timeouts persist, run migrate preflight separately and watch its own connectivity check fail or pass.

Node OOM during Phase 3 ›

Increase the V8 heap and reduce chunk size:

bash
NODE_OPTIONS="--import=tsx --max-old-space-size=4096" node packages/migrator/dist/cli.js run --client=<c> --resume --chunk-size=250
Partial checkpoint after a crash ›

Inspect _MigrationCheckpoint for the affected table. If completed_at IS NULL, the table is mid-migration; just run with --resume. Do not manually DELETE FROM _MigrationCheckpoint: that loses your resume point. If you must restart from scratch, roll the environment back with $M rollback --client <env> --config <.env> (dry run first), which removes its migrated rows and checkpoints together; never delete checkpoint or product rows by hand.

Preflight passes, run fails on disk space ›

Target Postgres ran out of space during Phase 3 COPY. Required ~2× source DB size plus temp space for chunks. Expand the PG volume, then rerun with --resume. Preflight does a sanity-check on free space but not on growth during the run.

Sample-field parity mismatch but row counts match ›

Counts agree but specific field values diverge. Almost always a transform bug: character encoding (CP-1252 vs UTF-8), timezone (CET vs UTC), or a numeric rounding step. Capture the sample row IDs from the parity HTML report and file a migrator issue with: variant, table name, the 3-5 row IDs, and a SELECT of those rows from both source and target.

MSSQL goes read-only mid-run ›

The migrator errors cleanly and leaves the checkpoint untouched. Once MSSQL is back, migrate run --resume picks up where it stopped. Check the audit log to confirm the last successful chunk:

sql
SELECT phase, table_name, started_at, completed_at, error
FROM "_MigrationAuditLog"
WHERE environment_id = '<client>'
ORDER BY started_at DESC LIMIT 10;
P3018: schema "cron" does not exist (pg_cron missing) ›

Migration 20260515000004_add_pg_cron_mv_refresh calls cron.schedule(...). Stock Postgres Docker images do not ship the pg_cron extension, so the migration aborts with P3018. Pick a path:

A. Skip for local/dev testing. KPI materialized views remain queryable; you just lose the auto-refresh schedule:

bash
pnpm --filter @hivecfm/database exec prisma migrate resolve --applied 20260515000004_add_pg_cron_mv_refresh
pnpm --filter @hivecfm/database exec prisma migrate deploy

Refresh MVs manually when needed:

sql · Postgres
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_response_kpi_daily;
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_response_kpi_monthly;

B. Install pg_cron (production parity). Either swap the image to citusdata/postgres_15_pgcron, or inside the container:

bash · inside postgres container
apt-get update && apt-get install -y postgresql-15-cron
echo "shared_preload_libraries = 'pg_cron'" >> /var/lib/postgresql/data/postgresql.conf
echo "cron.database_name = 'hivecfm'"      >> /var/lib/postgresql/data/postgresql.conf
# then restart the container and:
psql -U postgres -d hivecfm -c 'CREATE EXTENSION IF NOT EXISTS pg_cron;'
EPERM: operation not permitted, futime (WSL on /mnt/*) ›

WSL2 cannot pass the Linux futime syscall through DrvFs to NTFS-mounted Windows drives, so pnpm install from /mnt/c/... or /mnt/f/... fails with EPERM. Move the repo to the WSL ext4 home filesystem and reinstall there:

bash · WSL
rsync -a --exclude=node_modules --exclude=.next --exclude=dist /mnt/f/path/to/hivecfm-core/ ~/hivecfm-core/
cd ~/hivecfm-core && pnpm install

Disk I/O on native ext4 is also ~10× faster than DrvFs. Treat the WSL copy as authoritative; sync changes back to Windows only if a Windows-side editor needs them.

"None of the selected packages has a migrate:deploy script" ›

The workspace namespaces every database script under db:. The script is db:migrate:deploy, not migrate:deploy. It runs a compiled apply-migrations.js, so the database package must be built first:

bash
pnpm --filter @hivecfm/database build
pnpm --filter @hivecfm/database db:migrate:deploy

Then run the Step 7 Verify: the _prisma_migrations SELECT for 20260925120000% must return 1 row. On this build the legacy_* provenance columns are migration-owned and absent before the migration starts; do not check for them, and do not db:push.

The script reads MIGRATE_DATABASE_URL first and falls back to DATABASE_URL. Useful when DDL credentials differ from runtime credentials (e.g., a privileged role for migrations, a low-priv role for the app).

For one-off local runs, skip the build and call Prisma directly:

bash
pnpm --filter @hivecfm/database exec prisma migrate deploy
Cannot find module ./dist/scripts/apply-migrations.js ›

The db:migrate:deploy script invokes a compiled Node entry point. If dist/ is missing, build the database package:

bash
pnpm --filter @hivecfm/database build

Or bypass the workspace script entirely and call Prisma directly, no build required:

bash
pnpm --filter @hivecfm/database exec prisma migrate deploy
P1001: Can't reach database server at localhost:5432 ›

Prisma is trying the default Postgres port 5432 but your local Postgres is exposed on a different host port. HiveCFM dev stacks commonly map to a non-default port (e.g., 5415) to avoid colliding with a host-installed Postgres. Verify the published port, then export DATABASE_URL before re-running:

bash
docker compose ps postgres
export DATABASE_URL="postgresql://postgres:postgres@localhost:5415/hivecfm"
pnpm --filter @hivecfm/database exec prisma migrate deploy

If db:migrate:deploy still fails, set MIGRATE_DATABASE_URL too (the script prefers it over DATABASE_URL), or unset it so the fallback wins.

P1001 in a new terminal (worked yesterday, broken today) ›

Two causes, both common after a laptop reboot or a new shell:

  1. Docker Postgres isn't running. Containers don't auto-restart unless configured. Bring it up:
bash · hivecfm-core/
docker compose ps postgres
docker compose up -d postgres
docker compose logs --tail=20 postgres # wait for "ready to accept connections"
  1. export DATABASE_URL died with the previous shell. Environment variables don't persist across terminal sessions. Replace exports with a .env file Prisma auto-loads, see 03 Configure · Step 5 "Make every command env-portable" for the recommended pattern.

Quick recovery without the file setup:

bash
export DATABASE_URL="postgresql://postgres:postgres@localhost:5415/hivecfm"
pnpm --filter @hivecfm/database exec prisma migrate status
provision-departments: refusing to rename project … is the name of department N in this source (E-RUN-SCOPE-01) ›

The anchor project (the project of --client / CLIENT_ENV) already carries another legacy department's name, usually because it got the client's name at signup. Nothing was written, even in --dry-run. Rename the empty project to a neutral name (UI project settings, or the UPDATE "Project" in 06) and re-run provision-departments --dry-run. The anchor environment must also hold 0 migrated rows.

pull access denied for minio/mc, repository does not exist or may require docker login ›

Docker Hub no longer serves the minio/minio and minio/mc images. docker compose up aborts before it creates any container, so Postgres never starts either. Use the same images from quay.io (verified 2026-09-21: pull succeeds, container healthy). Put this in an override file, e.g. docker-compose.minio-quay.yml:

yaml · docker-compose.minio-quay.yml
services:
minio:
image: quay.io/minio/minio:latest
minio-init:
image: quay.io/minio/mc:latest
bash · hivecfm-core/
docker compose -f docker-compose.yml -f docker-compose.host-ports.yml -f docker-compose.minio-quay.yml up -d
docker compose -f docker-compose.yml -f docker-compose.host-ports.yml -f docker-compose.minio-quay.yml ps # minio should report healthy
classic survey has skip logic but its legacy survey type can't be resolved (E-STRUCT-CHANNEL-01) ›

Raised when a classic (DisplayMode 1) survey with skip logic can't have its legacy survey type resolved — Survey.legacy_extras.SurveyTypeID is missing, or there is no matching row for it in the source CFMSurveyType catalog. The legacy type is what decides whether the survey migrates as one page or one-question-per-page (see 07a · Classic web surveys with skip logic), so an unresolved type is refused rather than guessed — unknown is never treated as web.

Fix: check the survey's SurveyTypeID in the source database and confirm it has a matching row in CFMSurveyType. Correct the source data (or the type map), then re-run.

language consolidation reports "0 merged" and every merge is skipped with a showSurveyEveryDays Zod error (stale generated Prisma client) ›

Symptom: the migration completes and parity passes, but EVERY language merge is skipped with a warning like merge skipped for survivor <id>: [{"code":"invalid_type","expected":"number","received":"undefined","path":["showSurveyEveryDays"]}], and the summary reads Language consolidation APPLIED: 0 merged. Cost a full 43-minute run to diagnose live, 2026-09-22.

Cause: the machine's GENERATED Prisma client is older than packages/database/schema.prisma, so prisma.survey.findUnique returns the survivor row without the newer column, and the survey shape gate (ZSurvey, which requires the key even though it is nullable) rejects the assembled survey. This happens whenever the schema is updated by patch/pull without regenerating the client.

Fix: run pnpm --filter @hivecfm/database generate, rebuild the migrator (pnpm build in packages/migrator), confirm the column is present in node_modules/.prisma/client/schema.prisma, then re-run consolidation with the repair command (06 · step 2 / 07c).

Migrations explained

The seven Prisma migrations that originally prepared the target schema (2026-05, renumbered 2026-07-27) were additive and nullable per FR-024, no DROP, TRUNCATE or DELETE anywhere in that set. That's no longer true of the migration history as a whole: four later migrations (2026-08-20 through 2026-08-26) deliberately drop tables and columns once the one-time customer migration is finished and verified. Both groups are listed below; see F8b New models for the full evidence behind the second group.

The first seven were renumbered on 2026-07-27. These files previously lived in packages/database/migrations/ (plural), gitignored scratch that the migration runner deletes with rm -rf on every run, so db:migrate:deploy never applied them. Commit 883fc6b03 moved them into the applied migration/ directory (singular) as 20260727000000..6, timestamped after 20260726120000_tenant_license_portal_fields so they sort last on installations that already carry the development history. They are fully idempotent (IF NOT EXISTS on tables and indexes, and the 19 foreign keys guarded on pg_constraint), so they are safe to apply to a target previously patched by hand with db:push.

MigrationWhat it addsReversible?
20260727000000
add_legacy_columns_and_touchpoint
was 20260515000000
Touchpoint family (Touchpoint, TouchpointType, SurveyTouchpoint, SurveyTouchpointType) + lookups (SurveyChannel) + legacyId/legacyGuid/legacyExtras nullable columns on every core table. All of this was dropped 2026-08-20/24, see the retirement group below.Was additive; superseded by the drops below.
20260727000001
add_response_generated_columns
was 20260515000001
Four GENERATED ALWAYS AS columns on Response: csat_score, ces_score, nps_score, fcr_score (extracted from kpiScores JSON). Partial indexes on non-archived rows.Pure read-side; no behavior change for inserts. Still live.
20260727000002
add_kpi_materialized_views
was 20260515000002
mv_response_kpi_daily + mv_response_kpi_monthly, each with is_archived as a dimension (not a filter).Still live, though recreated 2026-08-24 without the touchpoint_id grouping column (see below).
20260727000003
add_migrator_operational_tables
was 20260515000003
_MigrationCheckpoint, _MigrationAuditLog, _MigrationVariant. None has a Prisma model, so db:push cannot create them: this migration is the only thing that does._MigrationVariant dropped 2026-08-20 (0 rows, never populated). The other two dropped-then-made-staging 2026-08-24, see below.
20260727000004
add_pg_cron_mv_refresh
was 20260515000004
Two pg_cron jobs: daily MV refresh every 5 min; monthly MV refresh nightly at 02:00. Guarded by a pg_extension check, so it is a clean no-op where pg_cron is absent. If an older checkout fails with P3018: schema "cron" does not exist, mark it applied with prisma migrate resolve --applied <name> (see Troubleshooting).Cron jobs are no-ops if the MVs are empty. Still live.
20260727000005
reconcile_schema_drift
was 20260516000000
Response.is_negative_response and Survey.closeTheLoop, declared in schema.prisma but created by no earlier migration.Additive with safe defaults. Still live.
20260727000006
add_contact_legacy_id
was 20260525000000
Contact.legacy_id + a unique index on (environmentId, legacy_id) so contacts upsert by their original integer PK without colliding across environments.Nullable column; no effect on existing rows. Still live.

Retirement group (2026-08-20 – 2026-08-26) — deliberately not additive

Authored for Zain-BH's closeout on the shared hivecfm database once that customer's migration was finished and parity-verified. Full evidence and current live status: F8b New models and 11b Program retirement.

MigrationWhat it dropsReversible?
20260820000000
drop_unused_migration_scaffold_tables
SurveyTouchpoint, SurveyTouchpointType, _MigrationVariant: 0 rows on every environment checked, never read by any migrator transform or product query.No, DROP TABLE, no data backup (none held data).
20260824000000
zainbh_cleanup_drop_empty_migration_objects
SurveyChannel, CustomerOrg, _MigrationDeferred (all 0 rows); Survey.legacy_guid, User.legacy_guid (0 populated); Segment.legacy_id/legacy_kind (0 populated for this client).No, irreversible by design; every dropped object was measured empty first.
20260824120000
drop_migration_machinery_and_redundant_legacy_tables
Invitation (1,556,966 rows, proven bijective with Response first), ResponseAnswer (164,452 rows, fully consumed by Phase 4 first), Touchpoint/TouchpointType/Department/LegacySurveyKind (0/0/2/10 rows; names preserved onto Survey.legacy_extras first), merge_archive/survey_merge_archive/duplicate_placeholder_archive, _MigrationCheckpoint/_MigrationBoundary/_MigrationAuditLog, Response.touchpoint_id, User.touchpoint_id/allow_undefined_touchpoints. Recreates both KPI materialized views without the touchpoint_id grouping column.No, by explicit no-rollback directive. The two largest tables (Invitation, ResponseAnswer) are proven derivable from Response/Response.data rather than dumped.
20260826020000
restore_responseanswer_staging
Nothing, intentional no-op. Originally written to recreate ResponseAnswer, superseded before deploy by a runtime creator (ensureResponseAnswerTable()) that keeps table creation inside the staging-guard chokepoint. Never applied to the live hivecfm database (absent from its _prisma_migrations ledger).N/A, no-op.

FR Index

The functional requirements referenced throughout this guide, with one-line summaries.

FR-016Unknown-variant abort. Preflight exits with code 3 if the schema scanner reports Custom. No --allow-resume override. Referenced in: Variant Decider, Variant detection algorithm.
FR-019Cutover window cap. Target maintenance window 1 hour, hard maximum 2 hours. Referenced in: Lifecycle, Cutover Checklist.
FR-022Rollback completes in < 30 min. Worst-case replay bound that drives the FR-023 window length. Referenced in: Emergency Rollback.
FR-0234-hour rollback window. Hard cap after cutover start; the rollback command refuses replays beyond this point. Referenced in: Lifecycle, Emergency Rollback.
FR-024Schema additivity. Every new column is nullable; no ALTER TYPE, DROP COLUMN, or ADD NOT NULL. Enforced by fresh-client-e2e.test.ts. Referenced in: Schema additivity, Migrations explained.
FR-026Soft-deleted rows migrate. Archived legacy rows are preserved with is_archived = true; MVs treat archive as a dimension, not a filter. Referenced in: FAQ.
FR-03830-day MSSQL retention. Source DBs stay online read-only for 30 days after cutover. Referenced in: Lifecycle, 30-day archive.
FR-039Superset disconnect at T-0. Analytics layer cuts over the same day; the 30-day window is for ad-hoc operator SQL only. Referenced in: Lifecycle, 30-day archive.

FAQ

Questions teammates have actually asked.

Can I run preflight multiple times?

Yes. It's fully read-only. Run it as often as you want, including from a shared CI environment for visibility.

How long does Phase 3 take for 500k responses?

2–6 hours, depending on network latency and chunk size. Same region + --chunk-size=1000 is the fast end; cross-region transit VPN + default chunk size is the slow end. Watch _MigrationCheckpoint.rows_processed for live throughput.

What if MSSQL goes down mid-run?

The process errors cleanly. Once MSSQL is restored, migrate run --resume picks up from the last committed checkpoint. No dupes, no manual cleanup.

Can I migrate two clients in parallel from the same workstation?

Yes. Use separate .env.<client> files and separate target Postgres databases. The advisory lock is per environment_id, so two different clients don't contend. CPU and network may; tune chunk size accordingly.

Where does the Variant Decider get its logic?

Directly from packages/migrator/src/source/variant-detector.ts:16-46. The CLI runs the same three schema probes during preflight; the widget mirrors them for offline planning.

Is there a command to query the migration audit log?

Not yet. There's no migrate history command (an earlier guide version described one as a planned v0.2 feature; it was never built). Query _MigrationAuditLog directly instead: SELECT phase, table_name, started_at, completed_at, rows_processed, error FROM "_MigrationAuditLog" WHERE environment_id = '<client-id>' ORDER BY started_at DESC LIMIT 50; Remember it's one of the 13 staging tables (11b Program retirement), so it may be empty or briefly absent on a database whose migration program isn't in progress.

Can I reset a client and migrate it again?

Only a retired client that has not gone live: $M reset-client --from-config <base.env> (dry run), then --apply --confirm-org "<org>". Run it where the lifecycle ran. It refuses when it finds the customer's own data. Purge the client's Hub records first. Before retire, use rollback for one environment instead. See L10.

The Lifecycle finished but says "The Hub was NOT pushed". What now?

No department config named a Hub, so hub-backfill was skipped. Add HIVECFM_HUB_URL and HIVECFM_HUB_API_KEY to each department .env, then press [h] on the Lifecycle screen (or $M lifecycle --from-config <base.env> --from-stage hub-backfill --until hub-backfill). It works after retire. If hub-backfill failed (not skipped) and was passed over from a shell, [h] does nothing and the screen never says Migration complete: press enter on hub-backfill, or run the same shell command. See L6.

What does "quarantine ?" mean on a department row?

The department's last run did not record how many QUARANTINE language groups it left undecided (for example, the run predates this build). It is unknown, not zero. Dry-run Consolidate languages for that department to see its pending groups, and merge them before hub-backfill and before retire. See L4.

Should I migrate archived (soft-deleted) rows?

Yes (FR-026). They're preserved with is_archived = true. The materialized views include is_archived as a dimension, so reports can include or exclude them per query without losing the historical aggregate.

How do I file a bug against the migrator?

Open an issue in the hivecfm-core repo. Always include: the variant verdict, the affected client's environment_id, the parity report (or relevant SQL output), and the last 20 lines of _MigrationAuditLog for that client.